From fcd05aa51f1e1f3903661baaa76d97501d136e52 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 2 Nov 2026 16:33:33 -0600 Subject: [PATCH 1/2] =?UTF-8?q?id:=20session.checkpoint=20event=20kind=20?= =?UTF-8?q?=E2=80=94=20session=20header=20+=20segment=20checkpoint=20(#379?= =?UTF-8?q?4)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Phase 1 of the #2036 protocol v1: a session.checkpoint ChainExt event kind carrying SessionHeader/SegmentCheckpoint (canonical-CBOR via the signed header), golden vectors, validation in ChainExt::validate (segment/predecessor monotonicity shape, participant and purpose bounds, time bounds), CheckpointPolicy defaults (256 events / 2s), and an event_store waiting-pool round-trip test. Refs #3794, #2036. --- pkgs/id/src/attestation.rs | 2 + pkgs/id/src/chain.rs | 124 ++++++++++ pkgs/id/src/currency.rs | 2 + pkgs/id/src/event_store/ingest.rs | 59 +++++ pkgs/id/src/event_store/mod.rs | 1 + pkgs/id/src/event_store/sync.rs | 4 + pkgs/id/src/idset.rs | 1 + pkgs/id/src/lib.rs | 1 + pkgs/id/src/local_events.rs | 2 + pkgs/id/src/log_sync.rs | 2 + pkgs/id/src/session_checkpoint.rs | 370 ++++++++++++++++++++++++++++++ pkgs/id/src/store_traits.rs | 1 + pkgs/id/src/world/signed.rs | 1 + 13 files changed, 570 insertions(+) create mode 100644 pkgs/id/src/session_checkpoint.rs diff --git a/pkgs/id/src/attestation.rs b/pkgs/id/src/attestation.rs index 40160d95a2..7ff76b6694 100644 --- a/pkgs/id/src/attestation.rs +++ b/pkgs/id/src/attestation.rs @@ -179,6 +179,7 @@ pub fn sign_genesis( removes: None, note: None, link: None, + checkpoint: None, }, )?) } @@ -210,6 +211,7 @@ pub fn sign_claim( removes: None, note: None, link: None, + checkpoint: None, }, )?) } diff --git a/pkgs/id/src/chain.rs b/pkgs/id/src/chain.rs index dbb22b4dab..58fab2f728 100644 --- a/pkgs/id/src/chain.rs +++ b/pkgs/id/src/chain.rs @@ -25,6 +25,7 @@ use unicode_normalization::is_nfc; use crate::documents::{DocumentRef, is_document_kind, is_removal_kind}; use crate::note_links::{NoteLinkOp, check_note_link_op, is_note_link_kind}; use crate::notes::{NoteOp, check_note_op, is_note_kind}; +use crate::session_checkpoint::{SessionCheckpoint, check_session_checkpoint, is_checkpoint_kind}; use crate::tag_claims::{TagOp, check_op, is_tag_kind}; /// The domain tag every `ChainExt` carries, so this header type cannot be @@ -125,6 +126,11 @@ pub struct ChainExt { /// It is the link body (#3816): signed with the header, so an event carries /// its whole link operation, and sync needs no separate body. pub link: Option, + /// The session checkpoint of a `session.checkpoint`, and `None` for every + /// other kind. It is the checkpoint body (#3794): the session header and + /// the segment this checkpoint closes, signed with the header, so an + /// event carries its whole checkpoint, and sync needs no separate body. + pub checkpoint: Option, } /// The wire form of [`ChainExt`]: the same fields, plus the domain tag. Keys @@ -147,6 +153,8 @@ struct Wire { note: Option, #[serde(default, skip_serializing_if = "Option::is_none")] link: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + checkpoint: Option, } impl From for Wire { @@ -161,6 +169,7 @@ impl From for Wire { removes: ext.removes, note: ext.note, link: ext.link, + checkpoint: ext.checkpoint, } } } @@ -181,6 +190,7 @@ impl TryFrom for ChainExt { removes: wire.removes, note: wire.note, link: wire.link, + checkpoint: wire.checkpoint, }; ext.validate()?; Ok(ext) @@ -201,6 +211,8 @@ impl ChainExt { /// carry none. A removal kind must name the document it removes, and any /// other kind must name none. A removal carries no tag and no document, as /// any kind that is not a tag or a document kind must not. + /// A session checkpoint kind must carry a session checkpoint that passes + /// [`check_session_checkpoint`], and any other kind must carry none. pub fn validate(&self) -> Result<(), ChainError> { if self.after.len() > MAX_AFTER { return Err(ChainError::TooManyAfter(self.after.len())); @@ -308,6 +320,25 @@ impl ChainExt { .map_err(|err| ChainError::Extension(err.to_string()))?; } } + match (is_checkpoint_kind(&self.kind), &self.checkpoint) { + (false, None) => {} + (false, Some(_)) => { + return Err(ChainError::Extension(format!( + "kind {:?} carries a session checkpoint", + self.kind + ))); + } + (true, None) => { + return Err(ChainError::Extension(format!( + "kind {:?} needs its session checkpoint", + self.kind + ))); + } + (true, Some(checkpoint)) => { + check_session_checkpoint(&self.kind, checkpoint) + .map_err(|err| ChainError::Extension(err.to_string()))?; + } + } Ok(()) } } @@ -462,9 +493,21 @@ mod tests { removes: None, note: None, link: None, + checkpoint: None, } } + fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|byte| format!("{byte:02x}")).collect() + } + + fn unhex(text: &str) -> Vec { + (0..text.len()) + .step_by(2) + .map(|i| u8::from_str_radix(&text[i..i + 2], 16).unwrap()) + .collect() + } + /// `count` distinct hashes: the digests of the counters `0..count`. fn distinct(count: usize) -> Vec { (0..count).map(|n| Hash::digest(n.to_le_bytes())).collect() @@ -750,6 +793,85 @@ mod tests { assert!(decode(&event.bytes[..cut]).is_err(), "cut at {cut}"); } } + + /// A `session.checkpoint` event from fixed values, for the golden vector + /// below: the test key's session, two participants, segment 0 with an + /// audit blob. + fn checkpoint_event() -> Event { + use crate::session_checkpoint::{MacScope, SegmentCheckpoint, SessionHeader}; + + let author = key(); + let other = SigningKey::from_bytes(&[7; 32]); + sign( + &author, + 0, + None, + None, + ChainExt { + kind: "session.checkpoint".to_owned(), + group: None, + after: Vec::new(), + tag: None, + document: None, + removes: None, + note: None, + link: None, + checkpoint: Some(SessionCheckpoint { + header: SessionHeader { + session_id: hash(1), + purpose: "collab editing".to_owned(), + participants: vec![author.verifying_key(), other.verifying_key()], + started_ms: 1_000, + nonce: hash(2), + mac_key_commitment: hash(3), + mac_scope: MacScope::PerParticipant, + }, + segment: SegmentCheckpoint { + segment_seq: 0, + prev_checkpoint: None, + root: hash(4), + event_count: 256, + start_ms: 1_000, + end_ms: 2_800, + audit_blob: Some(hash(5)), + }, + }), + }, + ) + .unwrap() + } + + #[test] + fn test_session_checkpoint_golden_vector_is_pinned() { + const BYTES: &str = "8601582003a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b8584044bc9d648ffd9e02e2aab846e028b4581a49c4832be635ddacc2a5d3bd31f59a3395c4e85090336563040c8e24cc60bf15ce1a6e987d6ac474f99ac1cb93c50d0000a5646b696e647273657373696f6e2e636865636b706f696e74656166746572806567726f7570f666646f6d61696e6c69642e6576656e74732e76316a636865636b706f696e74a266686561646572a7656e6f6e63655820ab13bedf42e84bae0f7c62c7dd6a8ada571e8829bed6ea558217f0361b5e25d067707572706f73656e636f6c6c61622065646974696e67696d61635f73636f70656e5065725061727469636970616e746a73657373696f6e5f6964582048fc721fbbc172e0925fa27af1671de225ba927134802998b10a1568a188652b6a737461727465645f6d731903e86c7061727469636970616e747382582003a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b85820ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c726d61635f6b65795f636f6d6d69746d656e745820e1e0e81d6ea39b0cf8b86ffd440921011f57400cbc3f76a8a171906a9b8d7505677365676d656e74a764726f6f7458200c389a743e34fda435fbd575bb889dbc0d3e66b9f9d81e00be33b7188509e7eb66656e645f6d73190af06873746172745f6d731903e86a61756469745f626c6f62582084cb40e74f0e856bb4bb91233e3cb74113533dca78a74f36f59edaa41895c9466b6576656e745f636f756e741901006b7365676d656e745f736571006f707265765f636865636b706f696e74f6"; + const ID: &str = "4f6c1d23b5b47657e5e5a4d39da727c2613b8cfc00af23453934f44749845fa7"; + + let event = checkpoint_event(); + assert_eq!(hex(&event.bytes), BYTES); + assert_eq!(event.id.to_hex(), ID); + assert_eq!(decode(&unhex(BYTES)).unwrap(), event); + } + + #[test] + fn test_a_checkpoint_kind_without_its_checkpoint_is_refused() { + let err = sign( + &key(), + 0, + None, + None, + ext("session.checkpoint", None, Vec::new()), + ) + .unwrap_err(); + assert!(err.to_string().contains("session checkpoint"), "{err}"); + } + + #[test] + fn test_a_checkpoint_on_another_kind_is_refused() { + let mut ext = checkpoint_event().header.extensions.clone(); + ext.kind = "message".to_owned(); + let err = sign(&key(), 0, None, None, ext).unwrap_err(); + assert!(err.to_string().contains("session checkpoint"), "{err}"); + } } #[cfg(test)] @@ -941,6 +1063,7 @@ mod golden { removes: None, note: None, link: None, + checkpoint: None, }, ) .unwrap(); @@ -959,6 +1082,7 @@ mod golden { removes: None, note: None, link: None, + checkpoint: None, }, ) .unwrap(); diff --git a/pkgs/id/src/currency.rs b/pkgs/id/src/currency.rs index c6ec56affe..3a9bbefe41 100644 --- a/pkgs/id/src/currency.rs +++ b/pkgs/id/src/currency.rs @@ -332,6 +332,7 @@ pub fn sign_authorisation( removes: None, note: None, link: None, + checkpoint: None, }, )?) } @@ -363,6 +364,7 @@ pub fn sign_revoke( removes: None, note: None, link: None, + checkpoint: None, }, )?) } diff --git a/pkgs/id/src/event_store/ingest.rs b/pkgs/id/src/event_store/ingest.rs index c638c86535..ce2fc75ec2 100644 --- a/pkgs/id/src/event_store/ingest.rs +++ b/pkgs/id/src/event_store/ingest.rs @@ -1109,6 +1109,7 @@ mod tests { removes: None, note: None, link: None, + checkpoint: None, }; sign(key, seq, backlink, None, ext).unwrap() } @@ -1480,6 +1481,62 @@ mod tests { store.check_invariants().unwrap(); } + /// A `session.checkpoint` event (#3794) is an ordinary verified event to + /// the store: it waits for an `after` hash it names like any other kind, + /// is released by that event's arrival, and reads back byte for byte. + #[test] + fn test_a_session_checkpoint_waits_and_round_trips() { + use crate::session_checkpoint::{ + MacScope, SegmentCheckpoint, SessionCheckpoint, SessionHeader, + }; + + let (_dir, mut store) = open(); + let x = key(21); + let y = key(22); + let x0 = event(&x, 0, None, Vec::new(), "x"); + let ext = ChainExt { + kind: "session.checkpoint".to_owned(), + group: None, + after: vec![x0.id], + tag: None, + document: None, + removes: None, + note: None, + link: None, + checkpoint: Some(SessionCheckpoint { + header: SessionHeader { + session_id: Hash::digest(b"session"), + purpose: "collab editing".to_owned(), + participants: vec![y.verifying_key()], + started_ms: 1_000, + nonce: Hash::digest(b"nonce"), + mac_key_commitment: Hash::digest(b"mac key"), + mac_scope: MacScope::Shared, + }, + segment: SegmentCheckpoint { + segment_seq: 0, + prev_checkpoint: None, + root: Hash::digest(b"root"), + event_count: 3, + start_ms: 1_000, + end_ms: 1_500, + audit_blob: None, + }, + }), + }; + let y0 = sign(&y, 0, None, None, ext).unwrap(); + assert_eq!(ingest(&mut store, &y0), Ingest::Waiting { id: y0.id }); + assert_eq!( + ingest(&mut store, &x0), + Ingest::Accepted { + id: x0.id, + released: vec![y0.id], + } + ); + assert_eq!(store.event(&author(&y), 0).unwrap(), Some(y0)); + store.check_invariants().unwrap(); + } + #[test] fn test_an_after_hash_naming_a_voided_event_is_applied() { let (_dir, mut store) = open(); @@ -1673,6 +1730,7 @@ mod tests { removes: None, note: None, link: None, + checkpoint: None, }; sign(&signer, seq, backlink, None, ext).unwrap() }; @@ -1707,6 +1765,7 @@ mod tests { removes: None, note: None, link: None, + checkpoint: None, }; let event = sign(key, seq, backlink, Some(&body), ext).unwrap(); (event, body) diff --git a/pkgs/id/src/event_store/mod.rs b/pkgs/id/src/event_store/mod.rs index 64598b241c..b5676ee560 100644 --- a/pkgs/id/src/event_store/mod.rs +++ b/pkgs/id/src/event_store/mod.rs @@ -1384,6 +1384,7 @@ mod tests { removes: None, note: None, link: None, + checkpoint: None, } } diff --git a/pkgs/id/src/event_store/sync.rs b/pkgs/id/src/event_store/sync.rs index 7e408ef3db..ac829e86d3 100644 --- a/pkgs/id/src/event_store/sync.rs +++ b/pkgs/id/src/event_store/sync.rs @@ -855,6 +855,7 @@ mod tests { removes: None, note: None, link: None, + checkpoint: None, }; events.push(chain::sign(&key, seq, backlink, Some(body), ext).unwrap()); } @@ -1109,6 +1110,7 @@ mod tests { removes: None, note: None, link: None, + checkpoint: None, }, ) .unwrap(); @@ -1153,6 +1155,7 @@ mod tests { removes: None, note: None, link: None, + checkpoint: None, }, ) .unwrap(); @@ -1201,6 +1204,7 @@ mod tests { removes: None, note: None, link: None, + checkpoint: None, }, ) .unwrap(); diff --git a/pkgs/id/src/idset.rs b/pkgs/id/src/idset.rs index f18ffcf785..f579629f7d 100644 --- a/pkgs/id/src/idset.rs +++ b/pkgs/id/src/idset.rs @@ -761,6 +761,7 @@ mod tests { removes: None, note: None, link: None, + checkpoint: None, }, ) .unwrap(); diff --git a/pkgs/id/src/lib.rs b/pkgs/id/src/lib.rs index 80fdeb22dd..3bee965a8d 100644 --- a/pkgs/id/src/lib.rs +++ b/pkgs/id/src/lib.rs @@ -218,6 +218,7 @@ pub mod sandbox; pub mod search; #[cfg(feature = "world")] pub mod seitan; +pub mod session_checkpoint; #[cfg(feature = "world")] pub mod server_config; #[cfg(feature = "world")] diff --git a/pkgs/id/src/local_events.rs b/pkgs/id/src/local_events.rs index 377efe2fda..ef9dd592c7 100644 --- a/pkgs/id/src/local_events.rs +++ b/pkgs/id/src/local_events.rs @@ -711,6 +711,7 @@ impl LocalEvents { removes, note, link: None, + checkpoint: None, }; let event = sign(&self.key, chain.next_seq, chain.head, None, ext)?; match self.store.ingest(&event.bytes, now_ms())? { @@ -968,6 +969,7 @@ mod tests { parents: vec![id(223)], }), link: None, + checkpoint: None, }, ) .unwrap(); diff --git a/pkgs/id/src/log_sync.rs b/pkgs/id/src/log_sync.rs index 5e63fae61a..ecb08c8001 100644 --- a/pkgs/id/src/log_sync.rs +++ b/pkgs/id/src/log_sync.rs @@ -702,6 +702,7 @@ mod tests { removes: None, note: None, link: None, + checkpoint: None, }; events.push(sign(signer, seq, backlink, None, ext).unwrap()); } @@ -1207,6 +1208,7 @@ mod tests { removes: None, note: None, link: None, + checkpoint: None, }; let rival = sign(alice, 1, Some(honest[0].id), None, rival_ext).unwrap(); assert!(matches!( diff --git a/pkgs/id/src/session_checkpoint.rs b/pkgs/id/src/session_checkpoint.rs new file mode 100644 index 0000000000..2d7b9c8a00 --- /dev/null +++ b/pkgs/id/src/session_checkpoint.rs @@ -0,0 +1,370 @@ +//! Session headers and segment checkpoints as signed events: phase 1 of the +//! #2036 messaging/relay protocol v1 (#3794), per the design record on #2036 +//! (`doc/2026-11-01_design_id2036.md`, §4.3 and the phase table in §6) and the +//! residue fields of the #2034 investigation (§5/§7). +//! +//! Live session traffic itself stays out of the durable graph: frames are +//! MAC-authenticated and ephemeral. What the graph carries is the durable +//! contract every later phase builds on — one ordinary signed event kind, +//! `session.checkpoint`, whose header extension carries a [`SessionHeader`] +//! and a [`SegmentCheckpoint`] together. +//! +//! The header is the session's signed-once binding: a fresh session ID, its +//! purpose, the participant set, its start time and nonce, and a commitment +//! to the MAC key. The MAC secret itself is never published — the header +//! carries only `mac_key_commitment`, a hash of the key material — and +//! `mac_scope` states explicitly whether one key authenticates every +//! participant's frames or each participant has their own key. Key +//! derivation is the header author's business; rotation is a new session +//! with a new header, never an edit to this one. +//! +//! A checkpoint closes one ordered segment of the session: it names its +//! immediate predecessor checkpoint (so a gap in the segment chain is +//! detectable), a root over the ordered segment, the number of frames it +//! covers, and the segment's time bounds. A checkpoint attests only to the +//! signer's ordered segment commitment and endpoint state — never to +//! per-frame timing, and never to what every participant saw. The optional +//! audit-blob reference names retained audit material by hash; the blob is +//! not part of the event and may expire under the retention policy without +//! altering the signed checkpoint (#2036 §4.5/§5 rule 8). + +use std::collections::HashSet; + +use p2panda_core::{Hash, VerifyingKey}; +use serde::{Deserialize, Serialize}; +use unicode_normalization::is_nfc; + +/// The kind of a `session.checkpoint` event, as the header's `kind` names it. +pub const CHECKPOINT_KIND: &str = "session.checkpoint"; + +/// The most bytes a session's purpose may have. The purpose is text inside +/// the header, and the header decoder declares text at most 512 bytes long; +/// a purpose stays well under that. +pub const MAX_PURPOSE_BYTES: usize = 256; + +/// The most participants one session header may name. +pub const MAX_PARTICIPANTS: usize = 64; + +/// The default segment size, in frames, at which the session owner signs a +/// checkpoint (#2036 §4.3). A default, not a protocol constant: a session +/// may configure its own limit in the `WorldLimits` style. +pub const DEFAULT_CHECKPOINT_EVENT_LIMIT: u64 = 256; + +/// The default segment age, in milliseconds, at which the session owner +/// signs a checkpoint, whichever of the two defaults comes first. +pub const DEFAULT_CHECKPOINT_INTERVAL_MS: u64 = 2_000; + +/// When a session signs a checkpoint: at `event_limit` frames or +/// `interval_ms` milliseconds, whichever comes first, and at explicit +/// commit/blur/end. Both limits are configurable per session; the defaults +/// are the #2036 values. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct CheckpointPolicy { + /// Frames per segment before a checkpoint is due. + pub event_limit: u64, + /// Milliseconds per segment before a checkpoint is due. + pub interval_ms: u64, +} + +impl Default for CheckpointPolicy { + fn default() -> Self { + Self { + event_limit: DEFAULT_CHECKPOINT_EVENT_LIMIT, + interval_ms: DEFAULT_CHECKPOINT_INTERVAL_MS, + } + } +} + +/// Whose MAC key authenticates a participant's frames. The scope is part of +/// the signed header, so every participant can tell which key a frame's MAC +/// must verify under before checking it. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum MacScope { + /// One MAC key for the whole session, committed once in the header. + /// Every participant holds it, so a valid MAC proves a participant sent + /// the frame, not which one. + Shared, + /// One MAC key per participant, each committed in the header author's + /// derivation from the session secret. A valid MAC under a participant's + /// key attributes the frame to that participant. + PerParticipant, +} + +/// The signed-once binding of a live session: who may speak, about what, +/// from when, and under which MAC key commitment. Carried inside every +/// `session.checkpoint` event of the session, so the binding travels with +/// the checkpoints that rely on it and needs no separate event kind. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct SessionHeader { + /// The session's fresh ID. Distinct from every event ID: it names the + /// live session the checkpoints close segments of. + pub session_id: Hash, + /// What the session is for, as its author wrote it: non-empty, NFC, and + /// at most [`MAX_PURPOSE_BYTES`] bytes. + pub purpose: String, + /// The participants allowed to send frames in this session: at least + /// one, at most [`MAX_PARTICIPANTS`], none repeated. + pub participants: Vec, + /// When the session started, in milliseconds since the Unix epoch. + pub started_ms: u64, + /// A fresh nonce for this session, committed by hash. Together with + /// `session_id` it makes the header un-replayable across sessions. + pub nonce: Hash, + /// A commitment to the MAC key material: a hash of the key, never the + /// key itself. A receiver who holds the key checks it against this + /// commitment before trusting any frame's MAC. + pub mac_key_commitment: Hash, + /// Which key authenticates a participant's frames (see [`MacScope`]). + pub mac_scope: MacScope, +} + +/// One closed segment of a session: the residue a compacted segment leaves +/// behind (#2034 §5/§7). The checkpoint event that carries it is signed by +/// the session owner; its signature is the event's own, so no signature +/// field is repeated here. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct SegmentCheckpoint { + /// The segment's number within the session, counting from 0. Strictly + /// increasing along the checkpoint chain: each checkpoint's number is + /// its predecessor's plus one (the chain is verified by following + /// `prev_checkpoint`, whose own number the receiver checks). + pub segment_seq: u64, + /// The event ID of the previous `session.checkpoint` of this session, + /// and `None` for segment 0 and only segment 0. A missing predecessor + /// is a detectable gap, never a silent restart. + pub prev_checkpoint: Option, + /// A root over the ordered segment: a hash committing to every frame + /// of the segment in order. + pub root: Hash, + /// How many frames the segment holds. + pub event_count: u64, + /// When the segment's first frame was sent, in milliseconds since the + /// Unix epoch: never before the session's `started_ms`. + pub start_ms: u64, + /// When the segment's last frame was sent, in milliseconds since the + /// Unix epoch: never before `start_ms`. + pub end_ms: u64, + /// The retained audit material for this segment, named by hash, when + /// the session's retention policy keeps any. The blob is not part of + /// the event; its later expiry does not alter the signed checkpoint. + pub audit_blob: Option, +} + +/// What a `session.checkpoint` event carries: the session's header and the +/// segment this checkpoint closes. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct SessionCheckpoint { + /// The session's signed header (see [`SessionHeader`]). + pub header: SessionHeader, + /// The segment this checkpoint closes (see [`SegmentCheckpoint`]). + pub segment: SegmentCheckpoint, +} + +/// Why a session checkpoint was refused. +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +pub enum CheckpointError { + /// The payload is not the one the event's kind names. + #[error("a {kind:?} event carries the wrong session checkpoint payload")] + KindMismatch { + /// The kind of the event. + kind: String, + }, + /// A field breaks a limit or a shape rule. + #[error("{0}")] + Field(String), +} + +/// Whether `kind` is the session checkpoint kind, so its event carries a +/// session checkpoint payload. +#[must_use] +pub fn is_checkpoint_kind(kind: &str) -> bool { + kind == CHECKPOINT_KIND +} + +/// Checks a session checkpoint payload against the kind of the event that +/// carries it. +/// +/// # Errors +/// +/// Returns [`CheckpointError::KindMismatch`] when the carrying event's kind +/// is not [`CHECKPOINT_KIND`]. Returns [`CheckpointError::Field`] when the +/// purpose is empty, not NFC, or over [`MAX_PURPOSE_BYTES`]; when the +/// participant set is empty, over [`MAX_PARTICIPANTS`], or names one +/// participant twice; when segment 0 names a predecessor or a later +/// segment names none; or when the segment's time bounds run backwards or +/// start before the session did. +pub fn check_session_checkpoint( + kind: &str, + checkpoint: &SessionCheckpoint, +) -> Result<(), CheckpointError> { + if kind != CHECKPOINT_KIND { + return Err(CheckpointError::KindMismatch { + kind: kind.to_owned(), + }); + } + let header = &checkpoint.header; + if header.purpose.is_empty() { + return Err(CheckpointError::Field( + "a session purpose is not empty".to_owned(), + )); + } + if header.purpose.len() > MAX_PURPOSE_BYTES { + return Err(CheckpointError::Field(format!( + "a session purpose is {} bytes, it may be at most {MAX_PURPOSE_BYTES}", + header.purpose.len() + ))); + } + if !is_nfc(&header.purpose) { + return Err(CheckpointError::Field( + "a session purpose is not NFC".to_owned(), + )); + } + if header.participants.is_empty() { + return Err(CheckpointError::Field( + "a session names at least one participant".to_owned(), + )); + } + if header.participants.len() > MAX_PARTICIPANTS { + return Err(CheckpointError::Field(format!( + "a session names {} participants, it may name at most {MAX_PARTICIPANTS}", + header.participants.len() + ))); + } + let mut seen = HashSet::with_capacity(header.participants.len()); + if !header + .participants + .iter() + .all(|participant| seen.insert(participant.as_bytes().to_vec())) + { + return Err(CheckpointError::Field( + "a session names a participant twice".to_owned(), + )); + } + let segment = &checkpoint.segment; + match (segment.segment_seq, segment.prev_checkpoint) { + (0, Some(_)) => { + return Err(CheckpointError::Field( + "segment 0 names no previous checkpoint".to_owned(), + )); + } + (seq, None) if seq > 0 => { + return Err(CheckpointError::Field( + "a segment after segment 0 names its previous checkpoint".to_owned(), + )); + } + _ => {} + } + if segment.start_ms < header.started_ms { + return Err(CheckpointError::Field( + "a segment starts before its session".to_owned(), + )); + } + if segment.end_ms < segment.start_ms { + return Err(CheckpointError::Field( + "a segment ends before it starts".to_owned(), + )); + } + Ok(()) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use p2panda_core::SigningKey; + + use super::*; + + fn participant(n: u8) -> VerifyingKey { + SigningKey::from_bytes(&[n; 32]).verifying_key() + } + + fn checkpoint() -> SessionCheckpoint { + SessionCheckpoint { + header: SessionHeader { + session_id: Hash::digest(b"session"), + purpose: "collab editing".to_owned(), + participants: vec![participant(1), participant(2)], + started_ms: 1_000, + nonce: Hash::digest(b"nonce"), + mac_key_commitment: Hash::digest(b"mac key"), + mac_scope: MacScope::PerParticipant, + }, + segment: SegmentCheckpoint { + segment_seq: 0, + prev_checkpoint: None, + root: Hash::digest(b"root"), + event_count: 256, + start_ms: 1_000, + end_ms: 2_800, + audit_blob: None, + }, + } + } + + #[test] + fn a_well_formed_checkpoint_passes() { + check_session_checkpoint(CHECKPOINT_KIND, &checkpoint()).unwrap(); + let mut later = checkpoint(); + later.segment.segment_seq = 1; + later.segment.prev_checkpoint = Some(Hash::digest(b"previous")); + check_session_checkpoint(CHECKPOINT_KIND, &later).unwrap(); + } + + #[test] + fn the_checkpoint_policy_defaults_are_the_design_values() { + let policy = CheckpointPolicy::default(); + assert_eq!(policy.event_limit, 256); + assert_eq!(policy.interval_ms, 2_000); + } + + #[test] + fn a_checkpoint_under_another_kind_is_refused() { + assert!(matches!( + check_session_checkpoint("message", &checkpoint()), + Err(CheckpointError::KindMismatch { .. }) + )); + } + + #[test] + fn segment_zero_with_a_predecessor_is_refused() { + let mut bad = checkpoint(); + bad.segment.prev_checkpoint = Some(Hash::digest(b"previous")); + assert!(check_session_checkpoint(CHECKPOINT_KIND, &bad).is_err()); + } + + #[test] + fn a_later_segment_without_a_predecessor_is_refused() { + let mut bad = checkpoint(); + bad.segment.segment_seq = 3; + assert!(check_session_checkpoint(CHECKPOINT_KIND, &bad).is_err()); + } + + #[test] + fn a_duplicate_participant_is_refused() { + let mut bad = checkpoint(); + bad.header.participants.push(participant(1)); + assert!(check_session_checkpoint(CHECKPOINT_KIND, &bad).is_err()); + } + + #[test] + fn an_empty_participant_set_is_refused() { + let mut bad = checkpoint(); + bad.header.participants.clear(); + assert!(check_session_checkpoint(CHECKPOINT_KIND, &bad).is_err()); + } + + #[test] + fn a_segment_ending_before_it_starts_is_refused() { + let mut bad = checkpoint(); + bad.segment.end_ms = bad.segment.start_ms - 1; + assert!(check_session_checkpoint(CHECKPOINT_KIND, &bad).is_err()); + } + + #[test] + fn a_segment_starting_before_the_session_is_refused() { + let mut bad = checkpoint(); + bad.segment.start_ms = bad.header.started_ms - 1; + bad.segment.end_ms = bad.segment.start_ms; + assert!(check_session_checkpoint(CHECKPOINT_KIND, &bad).is_err()); + } +} diff --git a/pkgs/id/src/store_traits.rs b/pkgs/id/src/store_traits.rs index d5890345f7..0862012b31 100644 --- a/pkgs/id/src/store_traits.rs +++ b/pkgs/id/src/store_traits.rs @@ -788,6 +788,7 @@ mod tests { removes: None, note: None, link: None, + checkpoint: None, }; sign(signer, seq, backlink, body, ext).unwrap() } diff --git a/pkgs/id/src/world/signed.rs b/pkgs/id/src/world/signed.rs index 9231029f38..5d46ada7f0 100644 --- a/pkgs/id/src/world/signed.rs +++ b/pkgs/id/src/world/signed.rs @@ -85,6 +85,7 @@ pub fn sign_move( removes: None, note: None, link: None, + checkpoint: None, }, ) } From 1965ad317f40321f4db22563d0e0ebf3c7d15f7d Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 2 Nov 2026 16:54:57 -0600 Subject: [PATCH 2/2] id: verify session checkpoint predecessors in the event store (#3794) Codex review finding on the phase-1 PR: the shape check alone let a checkpoint naming any stored event (or a segment-skipping predecessor) apply. decide_in now treats prev_checkpoint as a dependency: absent, the checkpoint waits and is released by the predecessor's arrival; stored, it must be the same author's checkpoint carrying the same session header at the previous segment number, else the checkpoint is refused as malformed; a fork proof header predecessor parks it. Tests: wait/release, segment skip refused, foreign predecessor refused. --- pkgs/id/src/event_store/ingest.rs | 150 ++++++++++++++++++++++++++++++ 1 file changed, 150 insertions(+) diff --git a/pkgs/id/src/event_store/ingest.rs b/pkgs/id/src/event_store/ingest.rs index ce2fc75ec2..0881cde023 100644 --- a/pkgs/id/src/event_store/ingest.rs +++ b/pkgs/id/src/event_store/ingest.rs @@ -59,6 +59,12 @@ //! not present, so an event of another author that names a voided event still applies. This is //! the Phase 1 rule. It has no membership or authority model to void by, so authority-based //! voiding (decision 1) replaces it in Phase 2 (P2.3). + +//! A session checkpoint's is a dependency of the same kind (#3794): the +//! checkpoint waits while the predecessor is absent, and a stored predecessor is verified — +//! the same author's checkpoint, the same session header, the previous segment number — +//! before the checkpoint may apply. A predecessor that fails the verification refuses the +//! checkpoint as malformed. //! //! Held events count too. Two held events at one sequence number are a fork, though //! neither is applied. Held events are rows on disk, so a restart keeps them, and a conflict @@ -816,6 +822,39 @@ fn decide_in( // proof header is present but never stored, so it is parked too: waiting for it would wait on // a dependency that is already present. let mut waits = missing_deps(txn, &event.header.extensions.after)?; + // A session checkpoint names its predecessor checkpoint (#3794), and the predecessor is + // a dependency like an `after` hash: absent, the checkpoint waits for it; present only + // as a fork proof header, it can never link, so the checkpoint is parked. A stored + // predecessor must be this author's checkpoint carrying the same session header (the + // session's signed-once binding) at the previous segment number — anything else is a + // broken segment chain, and the checkpoint is refused. + if let Some(checkpoint) = &event.header.extensions.checkpoint { + if let Some(prev_id) = checkpoint.segment.prev_checkpoint { + match stored_by_id(txn, &prev_id)? { + Some(prev) => { + let predecessor = author_of(&prev) == author + && prev + .header + .extensions + .checkpoint + .as_ref() + .is_some_and(|prev_checkpoint| { + prev_checkpoint.header == checkpoint.header + && prev_checkpoint.segment.segment_seq + 1 + == checkpoint.segment.segment_seq + }); + if !predecessor { + return Ok(Decision::Refuse(Refusal::Malformed( + "a session checkpoint's prev_checkpoint is not the previous segment's checkpoint of the same session" + .to_owned(), + ))); + } + } + None if is_present(txn, &prev_id)? => return Ok(Decision::Park), + None => waits.push(prev_id), + } + } + } if seq > 0 { let linked = match event.header.backlink { Some(backlink) => { @@ -1034,6 +1073,18 @@ fn stored_event( .ok_or_else(|| corrupt("an applied sequence number has no stored event")) } +/// The stored event with this ID, applied or voided, if there is one. Reads the `hashes` +/// index for the event's position, then the event at that position. +fn stored_by_id(txn: &WriteTransaction, id: &Hash) -> Result, StoreError> { + let hashes = txn.open_table(HASHES)?; + let Some(position) = hashes.get(id.as_bytes().as_slice())? else { + return Ok(None); + }; + let events = txn.open_table(EVENTS)?; + let row = events.get(position.value())?; + row.map(|row| decode_stored(row.value())).transpose() +} + /// The `after` hashes that are not present yet. fn missing_deps(txn: &WriteTransaction, after: &[Hash]) -> Result, StoreError> { let mut missing = Vec::new(); @@ -1537,6 +1588,105 @@ mod tests { store.check_invariants().unwrap(); } + /// A signed `session.checkpoint` event for `key` at chain position `seq`: + /// segment `segment_seq` of one fixed session, naming `prev` as its + /// predecessor checkpoint. + fn checkpoint_event( + key: &SigningKey, + seq: SeqNum, + backlink: Option, + segment_seq: u64, + prev: Option, + ) -> Event { + use crate::session_checkpoint::{ + MacScope, SegmentCheckpoint, SessionCheckpoint, SessionHeader, + }; + + let ext = ChainExt { + kind: "session.checkpoint".to_owned(), + group: None, + after: Vec::new(), + tag: None, + document: None, + removes: None, + note: None, + link: None, + checkpoint: Some(SessionCheckpoint { + header: SessionHeader { + session_id: Hash::digest(b"session"), + purpose: "collab editing".to_owned(), + participants: vec![key.verifying_key()], + started_ms: 1_000, + nonce: Hash::digest(b"nonce"), + mac_key_commitment: Hash::digest(b"mac key"), + mac_scope: MacScope::Shared, + }, + segment: SegmentCheckpoint { + segment_seq, + prev_checkpoint: prev, + root: Hash::digest(b"root"), + event_count: 3, + start_ms: 1_000, + end_ms: 1_500, + audit_blob: None, + }, + }), + }; + sign(key, seq, backlink, None, ext).unwrap() + } + + /// The verifier walk for checkpoints (#3794): a checkpoint whose + /// predecessor is not yet stored waits for it and is released by its + /// arrival, exactly like an `after` dependency. + #[test] + fn test_a_checkpoint_waits_for_its_predecessor() { + let (_dir, mut store) = open(); + let y = key(23); + let seg0 = checkpoint_event(&y, 0, None, 0, None); + let seg1 = checkpoint_event(&y, 1, Some(seg0.id), 1, Some(seg0.id)); + assert_eq!(ingest(&mut store, &seg1), Ingest::Waiting { id: seg1.id }); + assert_eq!( + ingest(&mut store, &seg0), + Ingest::Accepted { + id: seg0.id, + released: vec![seg1.id], + } + ); + store.check_invariants().unwrap(); + } + + /// A checkpoint that skips a segment — its predecessor is segment 0 but + /// it claims segment 3 — is refused, not applied. + #[test] + fn test_a_checkpoint_that_skips_a_segment_is_refused() { + let (_dir, mut store) = open(); + let y = key(24); + let seg0 = checkpoint_event(&y, 0, None, 0, None); + ingest(&mut store, &seg0); + let seg3 = checkpoint_event(&y, 1, Some(seg0.id), 3, Some(seg0.id)); + assert!(matches!( + ingest(&mut store, &seg3), + Ingest::Refused(Refusal::Malformed(_)) + )); + store.check_invariants().unwrap(); + } + + /// A checkpoint whose `prev_checkpoint` names an event that is not a + /// checkpoint of the same session is refused. + #[test] + fn test_a_checkpoint_naming_a_foreign_predecessor_is_refused() { + let (_dir, mut store) = open(); + let y = key(25); + let plain = event(&y, 0, None, Vec::new(), "message"); + ingest(&mut store, &plain); + let seg1 = checkpoint_event(&y, 1, Some(plain.id), 1, Some(plain.id)); + assert!(matches!( + ingest(&mut store, &seg1), + Ingest::Refused(Refusal::Malformed(_)) + )); + store.check_invariants().unwrap(); + } + #[test] fn test_an_after_hash_naming_a_voided_event_is_applied() { let (_dir, mut store) = open();