interplane.Get Omega
Read in your language

synapse

A component of the AienOS ecosystem.

Brought by drakestapleton

branch main Branches Tags History

synapse / crates / synapse-store / src / codec.rs

1570 lines · 54336 bytes Raw Blame History
1//! Binary canonical codec v2 for WAL records and checkpoints (ADR 0003 section 9, step A1).
2//!
3//! Scope: only the bytes inside WAL frames and the checkpoint file change. The changeset
4//! envelope, its signature bytes and every identity (`ChangesetId`, `BlobDigest`, frame
5//! digests) are unchanged; envelope v2 is a separate step (B1).
6//!
7//! Record layout: `CODEC_V2 (u8) | kind (u8, same as WalRecord::kind_byte) | body`.
8//! Primitives are fixed width and little endian: `u8`, `u16`, `u32`, `u64`; `usize` is
9//! written as `u64`; `bool` is one byte 0 or 1; `Option` is a tag byte 0 or 1 then the
10//! value; strings and byte strings are `u32 length | bytes` (strings must be UTF-8);
11//! sequences are `u32 count | items`; fixed arrays (`[u8; 32]`, `GitOid`) are raw bytes.
12//! There is exactly one encoding per logical record: any other tag value, trailing byte,
13//! invalid UTF-8, or out-of-order checkpoint key is refused, so decode then encode gives
14//! the input bytes back.
15//!
16//! Untrusted input: every length and count is checked against the bytes that remain and
17//! against the caller's cap before anything is allocated, so a frame that declares a
18//! huge length is refused without allocating it.
19
20use super::*;
21use crate::git_bridge::{
22 GitBlobMapping, GitBridgeEntry, GitBridgeTarget, GitImportedCommit, GitImportedRefs,
23 GitImportedTag, GitTreeMapping,
24};
25use crate::seal::REVISION_SEAL_TAG;
26use synapse_auth::CapabilityLink;
27use synapse_core::{FileMode, GitOid, PathMutation, TreeDigest};
28
29/// Codec version byte that starts every binary record and checkpoint content.
30pub const CODEC_V2: u8 = 2;
31
32/// WAL frame header byte 7 (flags): set when the payload holds a binary v2 record.
33/// Zero means the v1 JSON record. Any other value is refused (`WalFlagsNonZero`).
34pub const WAL_FLAG_CODEC_V2: u8 = 0x01;
35
36/// Binary checkpoint file name inside the store root.
37pub const CHECKPOINT_V2_FILE: &str = "checkpoint.v2";
38/// Binary checkpoint magic.
39pub const CHECKPOINT_V2_MAGIC: [u8; 4] = *b"SCK2";
40/// Binary checkpoint format version.
41pub const CHECKPOINT_V2_VERSION: u16 = 2;
42/// Fixed header length of `checkpoint.v2` (everything before the content).
43pub const CHECKPOINT_V2_HEADER_LEN: usize = 216;
44/// Domain tag of the checkpoint content digest.
45pub const DOMAIN_CHECKPOINT_CONTENT_V2: &[u8] = b"SYNAPSE_CHECKPOINT_CONTENT_V2\0";
46/// Domain tag of the checkpoint root chain.
47pub const DOMAIN_CHECKPOINT_ROOT_V2: &[u8] = b"SYNAPSE_CHECKPOINT_ROOT_V2\0";
48/// Domain tag of `SynapseStore::state_root_digest` (unchanged from v1).
49pub const DOMAIN_STATE_ROOT_V1: &[u8] = b"SYNAPSE_STATE_ROOT_V1\0";
50
51/// Which encoding a WAL record payload uses (declared by the frame header flags).
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub enum RecordCodec {
54 /// v1: `serde_json` text (flags 0).
55 JsonV1,
56 /// v2: this module's binary canonical encoding (flags [`WAL_FLAG_CODEC_V2`]).
57 BinaryV2,
58}
59
60impl RecordCodec {
61 /// Frame header flags byte for this codec.
62 pub fn frame_flags(self) -> u8 {
63 match self {
64 Self::JsonV1 => 0,
65 Self::BinaryV2 => WAL_FLAG_CODEC_V2,
66 }
67 }
68
69 /// Codec declared by a frame header flags byte (`None` for any unknown value).
70 pub fn from_frame_flags(flags: u8) -> Option<Self> {
71 match flags {
72 0 => Some(Self::JsonV1),
73 WAL_FLAG_CODEC_V2 => Some(Self::BinaryV2),
74 _ => None,
75 }
76 }
77}
78
79/// Typed refusal from the binary decoder. `at` is the byte offset where it was found.
80#[derive(Debug, Clone, PartialEq, Eq)]
81pub enum CodecRefusal {
82 /// The input ends before a field: `need` more bytes were required.
83 Truncated { at: usize, need: usize },
84 /// A declared length or count needs more than the cap allows.
85 LengthOverCap { at: usize, declared: u64, cap: u64 },
86 /// Bytes remain after the last field.
87 TrailingBytes { at: usize, count: usize },
88 /// A tag byte (record kind, enum variant, bool, option) has no meaning.
89 UnknownTag {
90 at: usize,
91 field: &'static str,
92 tag: u8,
93 },
94 /// A string is not UTF-8.
95 InvalidUtf8 { at: usize },
96 /// The codec version byte is not [`CODEC_V2`].
97 VersionUnsupported { found: u8 },
98 /// Keys out of strict order (checkpoint maps), so a second encoding would exist.
99 NotCanonical { at: usize, field: &'static str },
100 /// A repository id fails `RepoId::new`.
101 InvalidRepoId { at: usize },
102 /// An embedded `synapse-core` encoding (envelope v2, chain path, marker) is refused
103 /// by its own decoder with `code`.
104 EmbeddedMalformed {
105 at: usize,
106 field: &'static str,
107 code: RefusalCode,
108 },
109}
110
111impl CodecRefusal {
112 /// Short stable name of the refusal kind.
113 pub fn kind(&self) -> &'static str {
114 match self {
115 Self::Truncated { .. } => "Truncated",
116 Self::LengthOverCap { .. } => "LengthOverCap",
117 Self::TrailingBytes { .. } => "TrailingBytes",
118 Self::UnknownTag { .. } => "UnknownTag",
119 Self::InvalidUtf8 { .. } => "InvalidUtf8",
120 Self::VersionUnsupported { .. } => "VersionUnsupported",
121 Self::NotCanonical { .. } => "NotCanonical",
122 Self::InvalidRepoId { .. } => "InvalidRepoId",
123 Self::EmbeddedMalformed { .. } => "EmbeddedMalformed",
124 }
125 }
126
127 /// The refusal as a `SynapseError` with `code`.
128 pub fn into_error(self, code: RefusalCode, context: &str) -> SynapseError {
129 SynapseError::new(code, format!("{context}: {} ({self:?})", self.kind()))
130 }
131}
132
133// ---------------------------------------------------------------------------------------
134// Writer
135// ---------------------------------------------------------------------------------------
136
137struct Writer(Vec<u8>);
138
139impl Writer {
140 fn u8(&mut self, v: u8) {
141 self.0.push(v);
142 }
143 fn u16(&mut self, v: u16) {
144 self.0.extend_from_slice(&v.to_le_bytes());
145 }
146 fn u32(&mut self, v: u32) {
147 self.0.extend_from_slice(&v.to_le_bytes());
148 }
149 fn u64(&mut self, v: u64) {
150 self.0.extend_from_slice(&v.to_le_bytes());
151 }
152 fn raw(&mut self, b: &[u8]) {
153 self.0.extend_from_slice(b);
154 }
155 fn bool(&mut self, v: bool) {
156 self.u8(u8::from(v));
157 }
158 fn len(&mut self, n: usize, what: &str) -> SynapseResult<()> {
159 let n = u32::try_from(n).map_err(|_| {
160 SynapseError::new(
161 RefusalCode::QuotaPayloadTooLarge,
162 format!("{what} exceeds the 32-bit length field"),
163 )
164 })?;
165 self.u32(n);
166 Ok(())
167 }
168 fn bytes(&mut self, b: &[u8], what: &str) -> SynapseResult<()> {
169 self.len(b.len(), what)?;
170 self.raw(b);
171 Ok(())
172 }
173 fn str(&mut self, s: &str, what: &str) -> SynapseResult<()> {
174 self.bytes(s.as_bytes(), what)
175 }
176 fn repo(&mut self, r: &RepoId) -> SynapseResult<()> {
177 // `RepoId` deserializes from JSON without validation; refuse here what the
178 // decoder would refuse, so every written record stays readable.
179 RepoId::new(r.as_str())?;
180 self.str(r.as_str(), "repository id")
181 }
182}
183
184fn put_attachment(w: &mut Writer, a: &EvidenceAttachment) -> SynapseResult<()> {
185 w.str(&a.gate_name, "gate name")?;
186 w.bool(a.passed);
187 w.raw(&a.artifact_digest);
188 w.str(&a.summary, "evidence summary")
189}
190
191fn put_attachments(w: &mut Writer, v: &[EvidenceAttachment]) -> SynapseResult<()> {
192 w.len(v.len(), "evidence count")?;
193 v.iter().try_for_each(|a| put_attachment(w, a))
194}
195
196fn put_envelope(w: &mut Writer, e: &ChangesetEnvelope) -> SynapseResult<()> {
197 w.u16(e.version);
198 w.repo(&e.repo_id)?;
199 w.raw(&e.base_git_oid.0);
200 w.len(e.parent_changesets.len(), "parent count")?;
201 for p in &e.parent_changesets {
202 w.raw(&p.0);
203 }
204 w.str(&e.author_did, "author did")?;
205 w.raw(&e.idempotency_key.0);
206 w.u64(e.created_at_ms);
207 w.str(&e.intent_summary, "intent summary")?;
208 w.len(e.mutations.len(), "mutation count")?;
209 for m in &e.mutations {
210 w.str(&m.path, "path")?;
211 match &m.op {
212 MutationOp::Upsert {
213 mode,
214 blob_digest,
215 size_bytes,
216 } => {
217 w.u8(1);
218 w.u8(mode.tag_byte());
219 w.raw(&blob_digest.0);
220 w.u64(*size_bytes);
221 }
222 MutationOp::Delete => w.u8(2),
223 }
224 }
225 put_attachments(w, &e.evidence_receipts)?;
226 w.bytes(&e.signature, "signature")
227}
228
229fn put_review(w: &mut Writer, r: &ReviewRecord) -> SynapseResult<()> {
230 w.str(&r.reviewer_did, "reviewer did")?;
231 w.bool(r.approved);
232 w.str(&r.comment, "review comment")?;
233 w.u64(r.recorded_at_ms);
234 Ok(())
235}
236
237fn put_projection(w: &mut Writer, p: &GitHubPullRequestProjection) -> SynapseResult<()> {
238 w.repo(&p.repo_id)?;
239 w.u64(p.pr_number);
240 w.raw(&p.changeset_id.0);
241 w.raw(&p.head_git_oid.0);
242 w.raw(&p.base_git_oid.0);
243 w.str(&p.pr_branch_ref, "branch ref")?;
244 w.str(&p.title, "title")?;
245 w.str(&p.body_markdown, "body")?;
246 w.raw(&p.evidence_summary_digest);
247 w.bool(p.github_merged);
248 Ok(())
249}
250
251fn put_canonical(w: &mut Writer, c: &RadicleCanonicalHead) -> SynapseResult<()> {
252 w.repo(&c.repo_id)?;
253 w.str(&c.default_branch, "default branch")?;
254 w.raw(&c.canonical_git_oid.0);
255 match &c.promoted_changeset_id {
256 Some(id) => {
257 w.u8(1);
258 w.raw(&id.0);
259 }
260 None => w.u8(0),
261 }
262 w.raw(&c.rad_id_commit_oid.0);
263 w.u64(c.threshold as u64);
264 w.len(c.verified_delegates.len(), "delegate count")?;
265 for d in &c.verified_delegates {
266 w.str(d, "delegate")?;
267 }
268 w.u64(c.verified_at_ms);
269 Ok(())
270}
271
272fn put_stored(w: &mut Writer, s: &StoredChangeset) -> SynapseResult<()> {
273 w.raw(&s.changeset_id.0);
274 w.u64(s.committed_seq.0);
275 put_envelope(w, &s.envelope)?;
276 put_attachments(w, &s.evaluations)?;
277 w.len(s.reviews.len(), "review count")?;
278 for r in &s.reviews {
279 put_review(w, r)?;
280 }
281 w.u64(s.lease_expires_at_ms);
282 Ok(())
283}
284
285/// Encode `record` with the binary canonical codec v2.
286pub fn encode_record(record: &WalRecord) -> SynapseResult<Vec<u8>> {
287 let mut w = Writer(Vec::with_capacity(256));
288 w.u8(CODEC_V2);
289 w.u8(record.kind_byte());
290 match record {
291 WalRecord::ChangesetIngest {
292 envelope,
293 changeset_id,
294 new_blobs,
295 } => {
296 put_envelope(&mut w, envelope)?;
297 w.raw(&changeset_id.0);
298 w.len(new_blobs.len(), "new blob count")?;
299 for b in new_blobs {
300 w.raw(&b.0);
301 }
302 }
303 WalRecord::EvaluationAttached {
304 changeset_id,
305 attachment,
306 } => {
307 w.raw(&changeset_id.0);
308 put_attachment(&mut w, attachment)?;
309 }
310 WalRecord::ReviewRecorded {
311 changeset_id,
312 review,
313 } => {
314 w.raw(&changeset_id.0);
315 put_review(&mut w, review)?;
316 }
317 WalRecord::GitProjected { projection } => put_projection(&mut w, projection)?,
318 WalRecord::CanonicalPromoted { canonical } => put_canonical(&mut w, canonical)?,
319 WalRecord::LeaseUpdated {
320 changeset_id,
321 lease_expires_at_ms,
322 } => {
323 w.raw(&changeset_id.0);
324 w.u64(*lease_expires_at_ms);
325 }
326 WalRecord::RevisionAdmitted {
327 envelope,
328 chain,
329 admitted_at_ms,
330 new_blobs,
331 seal,
332 } => {
333 w.bytes(&envelope.encode(), "envelope v2")?;
334 put_chain(&mut w, chain)?;
335 w.u64(*admitted_at_ms);
336 w.len(new_blobs.len(), "new blob count")?;
337 for b in new_blobs {
338 w.raw(&b.0);
339 }
340 put_seal(&mut w, seal);
341 }
342 WalRecord::ObsolescenceRecorded {
343 marker,
344 chain,
345 recorded_at_ms,
346 seal,
347 } => {
348 w.bytes(&marker.encode(), "obsolescence marker")?;
349 put_chain(&mut w, chain)?;
350 w.u64(*recorded_at_ms);
351 put_seal(&mut w, seal);
352 }
353 WalRecord::RevisionStateMoved {
354 state_move: m,
355 moved_at_ms,
356 seal,
357 } => {
358 w.repo(&m.repo_id)?;
359 w.raw(&m.changeset_id.0);
360 w.u8(m.to.tag_byte());
361 put_chain(&mut w, &m.chain)?;
362 w.u64(*moved_at_ms);
363 w.u64(m.signed_at_ms);
364 w.bytes(&m.leaf_link.encode(), "leaf link")?;
365 w.raw(&m.mover_key);
366 w.raw(&m.signature);
367 put_seal(&mut w, seal);
368 }
369 WalRecord::DerivedRevisionAdmitted {
370 derived,
371 chain,
372 admitted_at_ms,
373 seal,
374 } => {
375 w.bytes(&derived.encode(), "derived revision")?;
376 put_chain(&mut w, chain)?;
377 w.u64(*admitted_at_ms);
378 put_seal(&mut w, seal);
379 }
380 WalRecord::GitBridgeImported {
381 repo_id,
382 entry,
383 seal,
384 } => {
385 w.repo(repo_id)?;
386 put_git_bridge_entry(&mut w, entry)?;
387 put_seal(&mut w, seal);
388 }
389 }
390 Ok(w.0)
391}
392
393/// The body of a kind 10 record without its seal trailer, `repo_id | entry`: what the
394/// record digest (state root and seal chain) covers.
395pub(crate) fn git_bridge_body(repo_id: &RepoId, entry: &GitBridgeEntry) -> SynapseResult<Vec<u8>> {
396 let mut w = Writer(Vec::with_capacity(256));
397 w.repo(repo_id)?;
398 put_git_bridge_entry(&mut w, entry)?;
399 Ok(w.0)
400}
401
402fn put_git_target(w: &mut Writer, t: &GitBridgeTarget) {
403 match t {
404 GitBridgeTarget::Commit(c) => {
405 w.u8(1);
406 w.raw(&c.0);
407 }
408 GitBridgeTarget::Tree(d) => {
409 w.u8(2);
410 w.raw(&d.0);
411 }
412 GitBridgeTarget::Blob(b) => {
413 w.u8(3);
414 w.raw(&b.0);
415 }
416 GitBridgeTarget::Tag(o) => {
417 w.u8(4);
418 w.raw(&o.0);
419 }
420 }
421}
422
423/// `entry tag (u8) | body`: 1 objects `u32 n | (git oid [20] | blob [32] | size u64)* | u32 m
424/// | (git oid [20] | u32 len | tree node)*`; 2 commit `git oid | tree [32] | u32 n | parent
425/// [32]* | u32 len | headers`; 3 tag `git oid | target | u32 len | rest`; 4 refs `u32 n |
426/// (name | target)* | option head`. A target is `tag (u8) | [32]` (1 commit, 2 tree, 3 blob)
427/// or `4 | git oid [20]` (tag).
428fn put_git_bridge_entry(w: &mut Writer, e: &GitBridgeEntry) -> SynapseResult<()> {
429 w.u8(e.tag());
430 match e {
431 GitBridgeEntry::Objects { blobs, trees } => {
432 w.len(blobs.len(), "Git blob count")?;
433 for b in blobs {
434 w.raw(&b.git_oid.0);
435 w.raw(&b.blob.0);
436 w.u64(b.size_bytes);
437 }
438 w.len(trees.len(), "Git tree count")?;
439 for t in trees {
440 w.raw(&t.git_oid.0);
441 w.bytes(&t.node, "Git tree node")?;
442 }
443 }
444 GitBridgeEntry::Commit(c) => {
445 w.raw(&c.git_oid.0);
446 w.raw(&c.tree.0);
447 w.len(c.parents.len(), "Git parent count")?;
448 for p in &c.parents {
449 w.raw(&p.0);
450 }
451 w.bytes(&c.headers, "Git commit headers")?;
452 }
453 GitBridgeEntry::Tag(t) => {
454 w.raw(&t.git_oid.0);
455 put_git_target(w, &t.target);
456 w.bytes(&t.rest, "Git tag body")?;
457 }
458 GitBridgeEntry::Refs(r) => {
459 w.len(r.refs.len(), "Git reference count")?;
460 for (name, target) in &r.refs {
461 w.str(name, "Git reference name")?;
462 put_git_target(w, target);
463 }
464 match &r.head {
465 Some(h) => {
466 w.bool(true);
467 w.str(h, "Git HEAD")?;
468 }
469 None => w.bool(false),
470 }
471 }
472 }
473 Ok(())
474}
475
476/// The optional seal trailer of a revision record (issue #101): nothing when unsealed,
477/// else `1 u8 | server_key [32] | signature [64]`. Bytes after a body that do not open
478/// with the seal tag are refused as `TrailingBytes`.
479fn put_seal(w: &mut Writer, seal: &Option<RevisionSeal>) {
480 if let Some(seal) = seal {
481 w.u8(REVISION_SEAL_TAG);
482 w.raw(&seal.server_key);
483 w.raw(&seal.signature);
484 }
485}
486
487fn get_seal(r: &mut Reader) -> Decoded<Option<RevisionSeal>> {
488 if r.remaining() == 0 {
489 return Ok(None);
490 }
491 // Anything after the body that is not a seal is trailing bytes, as before seals.
492 if r.buf[r.pos] != REVISION_SEAL_TAG {
493 return Err(CodecRefusal::TrailingBytes {
494 at: r.pos,
495 count: r.remaining(),
496 });
497 }
498 r.u8()?;
499 Ok(Some(RevisionSeal {
500 server_key: r.array()?,
501 signature: r.array()?,
502 }))
503}
504
505fn put_chain(w: &mut Writer, chain: &ChainPath) -> SynapseResult<()> {
506 let mut buf = Vec::with_capacity(1 + 32 * chain.links().len());
507 chain.encode_into(&mut buf);
508 w.bytes(&buf, "chain path")
509}
510
511// ---------------------------------------------------------------------------------------
512// Reader (untrusted input)
513// ---------------------------------------------------------------------------------------
514
515type Decoded<T> = Result<T, CodecRefusal>;
516
517struct Reader<'a> {
518 buf: &'a [u8],
519 pos: usize,
520 cap: u64,
521}
522
523impl<'a> Reader<'a> {
524 fn new(buf: &'a [u8], cap: u64) -> Self {
525 Self { buf, pos: 0, cap }
526 }
527
528 fn remaining(&self) -> usize {
529 self.buf.len() - self.pos
530 }
531
532 fn take(&mut self, n: usize) -> Decoded<&'a [u8]> {
533 if n > self.remaining() {
534 return Err(CodecRefusal::Truncated {
535 at: self.pos,
536 need: n - self.remaining(),
537 });
538 }
539 let s = &self.buf[self.pos..self.pos + n];
540 self.pos += n;
541 Ok(s)
542 }
543
544 fn array<const N: usize>(&mut self) -> Decoded<[u8; N]> {
545 let mut a = [0u8; N];
546 a.copy_from_slice(self.take(N)?);
547 Ok(a)
548 }
549
550 fn u8(&mut self) -> Decoded<u8> {
551 Ok(self.take(1)?[0])
552 }
553 fn u16(&mut self) -> Decoded<u16> {
554 Ok(u16::from_le_bytes(self.array()?))
555 }
556 fn u32(&mut self) -> Decoded<u32> {
557 Ok(u32::from_le_bytes(self.array()?))
558 }
559 fn u64(&mut self) -> Decoded<u64> {
560 Ok(u64::from_le_bytes(self.array()?))
561 }
562
563 fn tag(&mut self, field: &'static str, max: u8) -> Decoded<u8> {
564 let at = self.pos;
565 let t = self.u8()?;
566 if t > max {
567 return Err(CodecRefusal::UnknownTag { at, field, tag: t });
568 }
569 Ok(t)
570 }
571
572 fn bool(&mut self) -> Decoded<bool> {
573 Ok(self.tag("bool", 1)? == 1)
574 }
575
576 /// A `u32` length of a byte run: checked against the cap, then the input.
577 fn byte_len(&mut self) -> Decoded<usize> {
578 let at = self.pos;
579 let n = self.u32()?;
580 if u64::from(n) > self.cap {
581 return Err(CodecRefusal::LengthOverCap {
582 at,
583 declared: u64::from(n),
584 cap: self.cap,
585 });
586 }
587 let n = n as usize;
588 if n > self.remaining() {
589 return Err(CodecRefusal::Truncated {
590 at: self.pos,
591 need: n - self.remaining(),
592 });
593 }
594 Ok(n)
595 }
596
597 fn bytes(&mut self) -> Decoded<Vec<u8>> {
598 let n = self.byte_len()?;
599 Ok(self.take(n)?.to_vec())
600 }
601
602 fn str_slice(&mut self) -> Decoded<&'a str> {
603 let n = self.byte_len()?;
604 let at = self.pos;
605 std::str::from_utf8(self.take(n)?).map_err(|_| CodecRefusal::InvalidUtf8 { at })
606 }
607
608 fn string(&mut self) -> Decoded<String> {
609 Ok(self.str_slice()?.to_owned())
610 }
611
612 fn repo(&mut self) -> Decoded<RepoId> {
613 let at = self.pos;
614 let s = self.str_slice()?;
615 RepoId::new(s).map_err(|_| CodecRefusal::InvalidRepoId { at })
616 }
617
618 /// A `u32` element count. Each element takes at least `min_encoded` input bytes, so
619 /// the count is checked against the input before anything is reserved, and the
620 /// reservation (`count x size_of::<T>()`) against the cap.
621 fn vec<T>(&mut self, min_encoded: usize) -> Decoded<(usize, Vec<T>)> {
622 let at = self.pos;
623 let n = u64::from(self.u32()?);
624 let need = n.saturating_mul(min_encoded as u64);
625 let bytes = n.saturating_mul(std::mem::size_of::<T>() as u64);
626 if need > self.cap || bytes > self.cap {
627 return Err(CodecRefusal::LengthOverCap {
628 at,
629 declared: n,
630 cap: self.cap,
631 });
632 }
633 if need > self.remaining() as u64 {
634 return Err(CodecRefusal::Truncated {
635 at: self.pos,
636 need: (need - self.remaining() as u64) as usize,
637 });
638 }
639 Ok((n as usize, Vec::with_capacity(n as usize)))
640 }
641
642 /// A length-prefixed value in a `synapse-core` canonical encoding, decoded by `decode`.
643 fn embedded<T>(
644 &mut self,
645 field: &'static str,
646 decode: impl FnOnce(&[u8]) -> SynapseResult<T>,
647 ) -> Decoded<T> {
648 let at = self.pos;
649 let n = self.byte_len()?;
650 decode(self.take(n)?).map_err(|e| CodecRefusal::EmbeddedMalformed {
651 at,
652 field,
653 code: e.code,
654 })
655 }
656
657 fn finish(&self) -> Decoded<()> {
658 match self.remaining() {
659 0 => Ok(()),
660 count => Err(CodecRefusal::TrailingBytes {
661 at: self.pos,
662 count,
663 }),
664 }
665 }
666}
667
668const MIN_STR: usize = 4;
669const MIN_ATTACHMENT: usize = MIN_STR + 1 + 32 + MIN_STR;
670const MIN_MUTATION: usize = MIN_STR + 1;
671const MIN_REVIEW: usize = MIN_STR + 1 + MIN_STR + 8;
672
673fn get_attachment(r: &mut Reader) -> Decoded<EvidenceAttachment> {
674 Ok(EvidenceAttachment {
675 gate_name: r.string()?,
676 passed: r.bool()?,
677 artifact_digest: r.array()?,
678 summary: r.string()?,
679 })
680}
681
682fn get_attachments(r: &mut Reader) -> Decoded<Vec<EvidenceAttachment>> {
683 let (n, mut v) = r.vec(MIN_ATTACHMENT)?;
684 for _ in 0..n {
685 v.push(get_attachment(r)?);
686 }
687 Ok(v)
688}
689
690fn get_envelope(r: &mut Reader) -> Decoded<ChangesetEnvelope> {
691 let version = r.u16()?;
692 let repo_id = r.repo()?;
693 let base_git_oid = GitOid(r.array()?);
694 let (n, mut parent_changesets) = r.vec(32)?;
695 for _ in 0..n {
696 parent_changesets.push(ChangesetId(r.array()?));
697 }
698 let author_did = r.string()?;
699 let idempotency_key = IdempotencyKey(r.array()?);
700 let created_at_ms = r.u64()?;
701 let intent_summary = r.string()?;
702 let (n, mut mutations) = r.vec(MIN_MUTATION)?;
703 for _ in 0..n {
704 let path = r.string()?;
705 let op = match r.tag("mutation op", 2)? {
706 1 => {
707 let at = r.pos;
708 let mode = match r.u8()? {
709 1 => FileMode::Regular644,
710 2 => FileMode::Executable755,
711 3 => FileMode::Symlink120000,
712 tag => {
713 return Err(CodecRefusal::UnknownTag {
714 at,
715 field: "file mode",
716 tag,
717 })
718 }
719 };
720 MutationOp::Upsert {
721 mode,
722 blob_digest: BlobDigest(r.array()?),
723 size_bytes: r.u64()?,
724 }
725 }
726 2 => MutationOp::Delete,
727 tag => {
728 return Err(CodecRefusal::UnknownTag {
729 at: r.pos - 1,
730 field: "mutation op",
731 tag,
732 })
733 }
734 };
735 mutations.push(PathMutation { path, op });
736 }
737 let evidence_receipts = get_attachments(r)?;
738 let signature = r.bytes()?;
739 Ok(ChangesetEnvelope {
740 version,
741 repo_id,
742 base_git_oid,
743 parent_changesets,
744 author_did,
745 idempotency_key,
746 created_at_ms,
747 intent_summary,
748 mutations,
749 evidence_receipts,
750 signature,
751 })
752}
753
754fn get_review(r: &mut Reader) -> Decoded<ReviewRecord> {
755 Ok(ReviewRecord {
756 reviewer_did: r.string()?,
757 approved: r.bool()?,
758 comment: r.string()?,
759 recorded_at_ms: r.u64()?,
760 })
761}
762
763fn get_projection(r: &mut Reader) -> Decoded<GitHubPullRequestProjection> {
764 Ok(GitHubPullRequestProjection {
765 repo_id: r.repo()?,
766 pr_number: r.u64()?,
767 changeset_id: ChangesetId(r.array()?),
768 head_git_oid: GitOid(r.array()?),
769 base_git_oid: GitOid(r.array()?),
770 pr_branch_ref: r.string()?,
771 title: r.string()?,
772 body_markdown: r.string()?,
773 evidence_summary_digest: r.array()?,
774 github_merged: r.bool()?,
775 })
776}
777
778fn get_canonical(r: &mut Reader) -> Decoded<RadicleCanonicalHead> {
779 let repo_id = r.repo()?;
780 let default_branch = r.string()?;
781 let canonical_git_oid = GitOid(r.array()?);
782 let promoted_changeset_id = match r.tag("option", 1)? {
783 1 => Some(ChangesetId(r.array()?)),
784 _ => None,
785 };
786 let rad_id_commit_oid = GitOid(r.array()?);
787 let at = r.pos;
788 let threshold = usize::try_from(r.u64()?).map_err(|_| CodecRefusal::LengthOverCap {
789 at,
790 declared: u64::MAX,
791 cap: usize::MAX as u64,
792 })?;
793 let (n, mut verified_delegates) = r.vec(MIN_STR)?;
794 for _ in 0..n {
795 verified_delegates.push(r.string()?);
796 }
797 Ok(RadicleCanonicalHead {
798 repo_id,
799 default_branch,
800 canonical_git_oid,
801 promoted_changeset_id,
802 rad_id_commit_oid,
803 threshold,
804 verified_delegates,
805 verified_at_ms: r.u64()?,
806 })
807}
808
809fn get_stored(r: &mut Reader) -> Decoded<StoredChangeset> {
810 let changeset_id = ChangesetId(r.array()?);
811 let committed_seq = WalSeq(r.u64()?);
812 let envelope = get_envelope(r)?;
813 let evaluations = get_attachments(r)?;
814 let (n, mut reviews) = r.vec(MIN_REVIEW)?;
815 for _ in 0..n {
816 reviews.push(get_review(r)?);
817 }
818 Ok(StoredChangeset {
819 changeset_id,
820 committed_seq,
821 envelope,
822 evaluations,
823 reviews,
824 lease_expires_at_ms: r.u64()?,
825 })
826}
827
828fn get_version(r: &mut Reader) -> Decoded<()> {
829 match r.u8()? {
830 CODEC_V2 => Ok(()),
831 found => Err(CodecRefusal::VersionUnsupported { found }),
832 }
833}
834
835/// Decode a binary v2 record. `cap` bounds every declared length and every reservation.
836const MIN_GIT_TARGET: usize = 1 + 20;
837
838fn get_git_target(r: &mut Reader) -> Decoded<GitBridgeTarget> {
839 let at = r.pos;
840 Ok(match r.u8()? {
841 1 => GitBridgeTarget::Commit(ChangesetId(r.array()?)),
842 2 => GitBridgeTarget::Tree(TreeDigest(r.array()?)),
843 3 => GitBridgeTarget::Blob(BlobDigest(r.array()?)),
844 4 => GitBridgeTarget::Tag(GitOid(r.array()?)),
845 tag => {
846 return Err(CodecRefusal::UnknownTag {
847 at,
848 field: "Git bridge target",
849 tag,
850 })
851 }
852 })
853}
854
855fn get_git_bridge_entry(r: &mut Reader) -> Decoded<GitBridgeEntry> {
856 let at = r.pos;
857 Ok(match r.u8()? {
858 1 => {
859 let (n, mut blobs) = r.vec(20 + 32 + 8)?;
860 for _ in 0..n {
861 blobs.push(GitBlobMapping {
862 git_oid: GitOid(r.array()?),
863 blob: BlobDigest(r.array()?),
864 size_bytes: r.u64()?,
865 });
866 }
867 let (m, mut trees) = r.vec(20 + 4 + 4)?;
868 for _ in 0..m {
869 let git_oid = GitOid(r.array()?);
870 let node = r.embedded("Git tree node", |b| {
871 synapse_core::decode_tree_node(b).map(|_| b.to_vec())
872 })?;
873 trees.push(GitTreeMapping { git_oid, node });
874 }
875 GitBridgeEntry::Objects { blobs, trees }
876 }
877 2 => {
878 let git_oid = GitOid(r.array()?);
879 let tree = TreeDigest(r.array()?);
880 let (n, mut parents) = r.vec(32)?;
881 for _ in 0..n {
882 parents.push(ChangesetId(r.array()?));
883 }
884 let headers = r.bytes()?;
885 GitBridgeEntry::Commit(GitImportedCommit {
886 git_oid,
887 tree,
888 parents,
889 headers,
890 })
891 }
892 3 => GitBridgeEntry::Tag(GitImportedTag {
893 git_oid: GitOid(r.array()?),
894 target: get_git_target(r)?,
895 rest: r.bytes()?,
896 }),
897 4 => {
898 let (n, mut refs) = r.vec::<(String, GitBridgeTarget)>(MIN_STR + MIN_GIT_TARGET)?;
899 for _ in 0..n {
900 let name_at = r.pos;
901 let name = r.string()?;
902 if refs.last().is_some_and(|(p, _)| *p >= name) {
903 return Err(CodecRefusal::NotCanonical {
904 at: name_at,
905 field: "Git reference names",
906 });
907 }
908 refs.push((name, get_git_target(r)?));
909 }
910 let head = if r.bool()? { Some(r.string()?) } else { None };
911 GitBridgeEntry::Refs(GitImportedRefs { refs, head })
912 }
913 tag => {
914 return Err(CodecRefusal::UnknownTag {
915 at,
916 field: "Git bridge entry",
917 tag,
918 })
919 }
920 })
921}
922
923pub fn decode_record(bytes: &[u8], cap: u64) -> Result<WalRecord, CodecRefusal> {
924 let mut r = Reader::new(bytes, cap);
925 get_version(&mut r)?;
926 let at = r.pos;
927 let record = match r.u8()? {
928 1 => {
929 let envelope = get_envelope(&mut r)?;
930 let changeset_id = ChangesetId(r.array()?);
931 let (n, mut new_blobs) = r.vec(32)?;
932 for _ in 0..n {
933 new_blobs.push(BlobDigest(r.array()?));
934 }
935 WalRecord::ChangesetIngest {
936 envelope,
937 changeset_id,
938 new_blobs,
939 }
940 }
941 2 => WalRecord::EvaluationAttached {
942 changeset_id: ChangesetId(r.array()?),
943 attachment: get_attachment(&mut r)?,
944 },
945 3 => WalRecord::ReviewRecorded {
946 changeset_id: ChangesetId(r.array()?),
947 review: get_review(&mut r)?,
948 },
949 4 => WalRecord::GitProjected {
950 projection: get_projection(&mut r)?,
951 },
952 5 => WalRecord::CanonicalPromoted {
953 canonical: get_canonical(&mut r)?,
954 },
955 6 => WalRecord::LeaseUpdated {
956 changeset_id: ChangesetId(r.array()?),
957 lease_expires_at_ms: r.u64()?,
958 },
959 7 => {
960 let envelope = r.embedded("envelope v2", ChangesetEnvelopeV2::decode)?;
961 let chain = r.embedded("chain path", ChainPath::decode)?;
962 let admitted_at_ms = r.u64()?;
963 let (n, mut new_blobs) = r.vec(32)?;
964 for _ in 0..n {
965 new_blobs.push(BlobDigest(r.array()?));
966 }
967 WalRecord::RevisionAdmitted {
968 envelope,
969 chain,
970 admitted_at_ms,
971 new_blobs,
972 seal: get_seal(&mut r)?,
973 }
974 }
975 8 => WalRecord::ObsolescenceRecorded {
976 marker: r.embedded("obsolescence marker", ObsolescenceMarker::decode)?,
977 chain: r.embedded("chain path", ChainPath::decode)?,
978 recorded_at_ms: r.u64()?,
979 seal: get_seal(&mut r)?,
980 },
981 9 => {
982 let repo_id = r.repo()?;
983 let changeset_id = ChangesetId(r.array()?);
984 let at = r.pos;
985 let tag = r.u8()?;
986 let to = RevisionState::from_tag_byte(tag).ok_or(CodecRefusal::UnknownTag {
987 at,
988 field: "revision state",
989 tag,
990 })?;
991 let chain = r.embedded("chain path", ChainPath::decode)?;
992 let moved_at_ms = r.u64()?;
993 WalRecord::RevisionStateMoved {
994 state_move: SignedStateMove {
995 repo_id,
996 changeset_id,
997 to,
998 chain,
999 signed_at_ms: r.u64()?,
1000 leaf_link: r.embedded("leaf link", CapabilityLink::decode)?,
1001 mover_key: r.array()?,
1002 signature: r.array()?,
1003 },
1004 moved_at_ms,
1005 seal: get_seal(&mut r)?,
1006 }
1007 }
1008 11 => WalRecord::DerivedRevisionAdmitted {
1009 derived: r.embedded("derived revision", DerivedRevision::decode)?,
1010 chain: r.embedded("chain path", ChainPath::decode)?,
1011 admitted_at_ms: r.u64()?,
1012 seal: get_seal(&mut r)?,
1013 },
1014 10 => {
1015 let repo_id = r.repo()?;
1016 let entry = get_git_bridge_entry(&mut r)?;
1017 WalRecord::GitBridgeImported {
1018 repo_id,
1019 entry,
1020 seal: get_seal(&mut r)?,
1021 }
1022 }
1023 tag => {
1024 return Err(CodecRefusal::UnknownTag {
1025 at,
1026 field: "record kind",
1027 tag,
1028 })
1029 }
1030 };
1031 r.finish()?;
1032 Ok(record)
1033}
1034
1035/// Encode one changeset envelope alone: `CODEC_V2 | envelope body`, the same field layout a
1036/// `ChangesetIngest` record uses. The wire (`synapse-wire`, step G1) carries proposals in it.
1037pub fn encode_envelope(envelope: &ChangesetEnvelope) -> SynapseResult<Vec<u8>> {
1038 let mut w = Writer(Vec::with_capacity(256));
1039 w.u8(CODEC_V2);
1040 put_envelope(&mut w, envelope)?;
1041 Ok(w.0)
1042}
1043
1044/// Decode exactly one envelope written by [`encode_envelope`]. `cap` bounds every declared
1045/// length and reservation; trailing bytes and every non-canonical form are refused.
1046pub fn decode_envelope(bytes: &[u8], cap: u64) -> Result<ChangesetEnvelope, CodecRefusal> {
1047 let mut r = Reader::new(bytes, cap);
1048 get_version(&mut r)?;
1049 let envelope = get_envelope(&mut r)?;
1050 r.finish()?;
1051 Ok(envelope)
1052}
1053
1054/// Encode `record` with `codec`.
1055pub fn encode_record_with(record: &WalRecord, codec: RecordCodec) -> SynapseResult<Vec<u8>> {
1056 match codec {
1057 RecordCodec::JsonV1 => serde_json::to_vec(record).map_err(|e| {
1058 SynapseError::new(RefusalCode::IoFailure, format!("serialize WAL record: {e}"))
1059 }),
1060 RecordCodec::BinaryV2 => encode_record(record),
1061 }
1062}
1063
1064/// Decode a record payload written with `codec`. A malformed binary record is refused
1065/// with `WalRecordMalformed`; malformed JSON keeps its v1 code (`WalCrcMismatch`).
1066pub fn decode_record_with(bytes: &[u8], codec: RecordCodec, cap: u64) -> SynapseResult<WalRecord> {
1067 match codec {
1068 RecordCodec::JsonV1 => serde_json::from_slice(bytes).map_err(|e| {
1069 SynapseError::new(
1070 RefusalCode::WalCrcMismatch,
1071 format!("corrupt WAL record JSON: {e}"),
1072 )
1073 }),
1074 RecordCodec::BinaryV2 => decode_record(bytes, cap)
1075 .map_err(|r| r.into_error(RefusalCode::WalRecordMalformed, "binary WAL record")),
1076 }
1077}
1078
1079// ---------------------------------------------------------------------------------------
1080// Checkpoints
1081// ---------------------------------------------------------------------------------------
1082
1083/// Logical checkpoint state with typed keys (the content of `checkpoint.v1` and
1084/// `checkpoint.v2`).
1085#[derive(Debug, Clone, PartialEq, Eq, Default)]
1086pub struct CheckpointState {
1087 pub checkpoint_seq: WalSeq,
1088 pub anchor_frame_sha256: [u8; 32],
1089 pub changesets: BTreeMap<ChangesetId, StoredChangeset>,
1090 pub idempotency_index: BTreeMap<(RepoId, IdempotencyKey), (WalSeq, ChangesetId)>,
1091 pub blob_first_visible_seq: BTreeMap<BlobDigest, WalSeq>,
1092 pub github_projections: BTreeMap<u64, GitHubPullRequestProjection>,
1093 pub canonical_heads: BTreeMap<RepoId, RadicleCanonicalHead>,
1094 /// Revision records (kinds 7 to 11; 10 is the H1 Git bridge) in sequence order (ADR 0003 B1, B4, B5, H1). Written only when
1095 /// non-empty, so checkpoints of stores without revisions keep their exact bytes.
1096 pub revision_log: Vec<(WalSeq, WalRecord)>,
1097}
1098
1099/// `state_root_digest` of a store that holds nothing (sequence 0, no changesets): the
1100/// v1 root recorded by a store that never wrote a v1 record.
1101pub fn empty_state_root() -> [u8; 32] {
1102 state_root_of(&BTreeMap::new(), &[], WalSeq::ZERO)
1103}
1104
1105/// `SynapseStore::state_root_digest` over `changesets` at `snapshot_seq`.
1106pub fn state_root_of(
1107 changesets: &BTreeMap<ChangesetId, StoredChangeset>,
1108 revision_log: &[(WalSeq, WalRecord)],
1109 snapshot_seq: WalSeq,
1110) -> [u8; 32] {
1111 let mut hasher = Sha256::new();
1112 hasher.update(DOMAIN_STATE_ROOT_V1);
1113 hasher.update(snapshot_seq.0.to_le_bytes());
1114 for (id, cs) in changesets {
1115 if cs.committed_seq <= snapshot_seq {
1116 hasher.update(id.0);
1117 hasher.update(cs.committed_seq.0.to_le_bytes());
1118 hasher.update((cs.evaluations.len() as u32).to_le_bytes());
1119 hasher.update((cs.reviews.len() as u32).to_le_bytes());
1120 }
1121 }
1122 crate::revision::RevisionLedger::hash_into(revision_log, snapshot_seq, &mut hasher);
1123 hasher.finalize().into()
1124}
1125
1126fn corrupt(what: impl std::fmt::Display) -> SynapseError {
1127 SynapseError::new(
1128 RefusalCode::CheckpointCorrupt,
1129 format!("checkpoint: {what}"),
1130 )
1131}
1132
1133fn parse_hex32(s: &str) -> SynapseResult<[u8; 32]> {
1134 hex::decode(s)
1135 .ok()
1136 .and_then(|b| b.try_into().ok())
1137 .ok_or_else(|| corrupt(format!("invalid 32-byte hex key {s:?}")))
1138}
1139
1140impl CheckpointState {
1141 /// Typed state from a v1 JSON manifest. Every key must equal the key its value
1142 /// implies (the store derives them that way), so nothing in the manifest is lost.
1143 pub fn from_v1_manifest(m: CheckpointManifest) -> SynapseResult<Self> {
1144 if m.version != CHECKPOINT_VERSION {
1145 return Err(SynapseError::new(
1146 RefusalCode::WalVersionUnsupported,
1147 format!("unsupported checkpoint version {}", m.version),
1148 ));
1149 }
1150 let mut s = Self {
1151 checkpoint_seq: m.checkpoint_seq,
1152 anchor_frame_sha256: m.anchor_frame_sha256,
1153 ..Default::default()
1154 };
1155 for (k, v) in m.changesets {
1156 let id = ChangesetId(parse_hex32(&k)?);
1157 if v.changeset_id != id || k != id.to_hex() {
1158 return Err(corrupt(format!(
1159 "changeset key {k} does not match its value"
1160 )));
1161 }
1162 s.changesets.insert(id, v);
1163 }
1164 for (k, v) in m.idempotency_index {
1165 let (repo_s, idem_hex) = k
1166 .split_once("::")
1167 .ok_or_else(|| corrupt("invalid idempotency key"))?;
1168 let repo = RepoId::new(repo_s)?;
1169 let key = IdempotencyKey(parse_hex32(idem_hex)?);
1170 if format!("{}::{}", repo.as_str(), key.to_hex()) != k {
1171 return Err(corrupt(format!("idempotency key {k} is not canonical")));
1172 }
1173 s.idempotency_index.insert((repo, key), v);
1174 }
1175 for (k, v) in m.blob_first_visible_seq {
1176 let d = BlobDigest(parse_hex32(&k)?);
1177 if d.to_hex() != k {
1178 return Err(corrupt(format!("blob key {k} is not canonical")));
1179 }
1180 s.blob_first_visible_seq.insert(d, v);
1181 }
1182 for (k, v) in m.github_projections {
1183 if v.pr_number != k {
1184 return Err(corrupt(format!(
1185 "projection key {k} does not match its value"
1186 )));
1187 }
1188 s.github_projections.insert(k, v);
1189 }
1190 for (k, v) in m.canonical_heads {
1191 let repo = RepoId::new(k.clone())?;
1192 if v.repo_id != repo {
1193 return Err(corrupt(format!(
1194 "canonical head key {k} does not match its value"
1195 )));
1196 }
1197 s.canonical_heads.insert(repo, v);
1198 }
1199 Ok(s)
1200 }
1201
1202 /// The v1 JSON manifest of this state.
1203 pub fn to_v1_manifest(&self) -> CheckpointManifest {
1204 CheckpointManifest {
1205 version: CHECKPOINT_VERSION,
1206 checkpoint_seq: self.checkpoint_seq,
1207 anchor_frame_sha256: self.anchor_frame_sha256,
1208 changesets: self
1209 .changesets
1210 .iter()
1211 .map(|(k, v)| (k.to_hex(), v.clone()))
1212 .collect(),
1213 idempotency_index: self
1214 .idempotency_index
1215 .iter()
1216 .map(|((repo, key), v)| (format!("{}::{}", repo.as_str(), key.to_hex()), *v))
1217 .collect(),
1218 blob_first_visible_seq: self
1219 .blob_first_visible_seq
1220 .iter()
1221 .map(|(k, v)| (k.to_hex(), *v))
1222 .collect(),
1223 github_projections: self.github_projections.clone(),
1224 canonical_heads: self
1225 .canonical_heads
1226 .iter()
1227 .map(|(k, v)| (k.as_str().to_string(), v.clone()))
1228 .collect(),
1229 }
1230 }
1231
1232 /// State root of this state at its checkpoint sequence.
1233 pub fn state_root(&self) -> [u8; 32] {
1234 state_root_of(&self.changesets, &self.revision_log, self.checkpoint_seq)
1235 }
1236
1237 /// Keys that the encoding derives from values must match them.
1238 fn check_keys(&self) -> SynapseResult<()> {
1239 let ok = self.changesets.iter().all(|(k, v)| *k == v.changeset_id)
1240 && self
1241 .github_projections
1242 .iter()
1243 .all(|(k, v)| *k == v.pr_number)
1244 && self.canonical_heads.iter().all(|(k, v)| *k == v.repo_id);
1245 if ok {
1246 Ok(())
1247 } else {
1248 Err(corrupt("a map key does not match its value"))
1249 }
1250 }
1251
1252 pub(crate) fn encode_content(&self) -> SynapseResult<Vec<u8>> {
1253 self.check_keys()?;
1254 let mut w = Writer(Vec::with_capacity(4096));
1255 w.u8(CODEC_V2);
1256 w.len(self.changesets.len(), "changeset count")?;
1257 for s in self.changesets.values() {
1258 put_stored(&mut w, s)?;
1259 }
1260 w.len(self.idempotency_index.len(), "idempotency count")?;
1261 for ((repo, key), (seq, id)) in &self.idempotency_index {
1262 w.repo(repo)?;
1263 w.raw(&key.0);
1264 w.u64(seq.0);
1265 w.raw(&id.0);
1266 }
1267 w.len(self.blob_first_visible_seq.len(), "blob count")?;
1268 for (d, seq) in &self.blob_first_visible_seq {
1269 w.raw(&d.0);
1270 w.u64(seq.0);
1271 }
1272 w.len(self.github_projections.len(), "projection count")?;
1273 for p in self.github_projections.values() {
1274 put_projection(&mut w, p)?;
1275 }
1276 w.len(self.canonical_heads.len(), "canonical head count")?;
1277 for c in self.canonical_heads.values() {
1278 put_canonical(&mut w, c)?;
1279 }
1280 // Revision section (ADR 0003 B1): present only when there are revision records.
1281 if !self.revision_log.is_empty() {
1282 w.len(self.revision_log.len(), "revision record count")?;
1283 for (seq, record) in &self.revision_log {
1284 w.u64(seq.0);
1285 w.bytes(&encode_record(record)?, "revision record")?;
1286 }
1287 }
1288 Ok(w.0)
1289 }
1290
1291 pub(crate) fn decode_content(
1292 bytes: &[u8],
1293 checkpoint_seq: WalSeq,
1294 anchor_frame_sha256: [u8; 32],
1295 ) -> Decoded<Self> {
1296 let mut r = Reader::new(bytes, bytes.len() as u64);
1297 get_version(&mut r)?;
1298 let mut s = Self {
1299 checkpoint_seq,
1300 anchor_frame_sha256,
1301 ..Default::default()
1302 };
1303 // Maps are written in strictly increasing key order; anything else would be a
1304 // second encoding of the same state.
1305 fn ordered<K: Ord>(prev: &Option<K>, k: &K, at: usize, field: &'static str) -> Decoded<()> {
1306 match prev {
1307 Some(p) if p >= k => Err(CodecRefusal::NotCanonical { at, field }),
1308 _ => Ok(()),
1309 }
1310 }
1311 let (n, _) = r.vec::<u8>(32 + 8)?;
1312 let mut prev = None;
1313 for _ in 0..n {
1314 let at = r.pos;
1315 let v = get_stored(&mut r)?;
1316 ordered(&prev, &v.changeset_id, at, "changesets")?;
1317 prev = Some(v.changeset_id);
1318 s.changesets.insert(v.changeset_id, v);
1319 }
1320 let (n, _) = r.vec::<u8>(MIN_STR + 32 + 8 + 32)?;
1321 let mut prev = None;
1322 for _ in 0..n {
1323 let at = r.pos;
1324 let k = (r.repo()?, IdempotencyKey(r.array()?));
1325 let v = (WalSeq(r.u64()?), ChangesetId(r.array()?));
1326 ordered(&prev, &k, at, "idempotency index")?;
1327 prev = Some(k.clone());
1328 s.idempotency_index.insert(k, v);
1329 }
1330 let (n, _) = r.vec::<u8>(32 + 8)?;
1331 let mut prev = None;
1332 for _ in 0..n {
1333 let at = r.pos;
1334 let d = BlobDigest(r.array()?);
1335 ordered(&prev, &d, at, "blob visibility")?;
1336 prev = Some(d);
1337 s.blob_first_visible_seq.insert(d, WalSeq(r.u64()?));
1338 }
1339 let (n, _) = r.vec::<u8>(MIN_STR + 8)?;
1340 let mut prev = None;
1341 for _ in 0..n {
1342 let at = r.pos;
1343 let p = get_projection(&mut r)?;
1344 ordered(&prev, &p.pr_number, at, "projections")?;
1345 prev = Some(p.pr_number);
1346 s.github_projections.insert(p.pr_number, p);
1347 }
1348 let (n, _) = r.vec::<u8>(MIN_STR)?;
1349 let mut prev: Option<RepoId> = None;
1350 for _ in 0..n {
1351 let at = r.pos;
1352 let c = get_canonical(&mut r)?;
1353 ordered(&prev, &c.repo_id, at, "canonical heads")?;
1354 prev = Some(c.repo_id.clone());
1355 s.canonical_heads.insert(c.repo_id.clone(), c);
1356 }
1357 if r.remaining() > 0 {
1358 let at = r.pos;
1359 let (n, _) = r.vec::<u8>(8 + MIN_STR)?;
1360 if n == 0 {
1361 // An empty section is written as no section at all.
1362 return Err(CodecRefusal::NotCanonical {
1363 at,
1364 field: "revision records",
1365 });
1366 }
1367 let mut prev = None;
1368 for _ in 0..n {
1369 let at = r.pos;
1370 let seq = WalSeq(r.u64()?);
1371 if prev.is_some_and(|p| p >= seq) || seq > checkpoint_seq {
1372 return Err(CodecRefusal::NotCanonical {
1373 at,
1374 field: "revision records",
1375 });
1376 }
1377 prev = Some(seq);
1378 let tag_at = r.pos + 4 + 1;
1379 let bytes = r.bytes()?;
1380 let record = decode_record(&bytes, r.cap)?;
1381 if !matches!(record.kind_byte(), 7..=11) {
1382 return Err(CodecRefusal::UnknownTag {
1383 at: tag_at,
1384 field: "revision record kind",
1385 tag: record.kind_byte(),
1386 });
1387 }
1388 s.revision_log.push((seq, record));
1389 }
1390 }
1391 r.finish()?;
1392 Ok(s)
1393 }
1394}
1395
1396/// Chain fields of a binary checkpoint.
1397#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1398pub struct CheckpointChain {
1399 pub checkpoint_seq: WalSeq,
1400 pub anchor_frame_sha256: [u8; 32],
1401 /// The last v1 `state_root_digest` of this store (constant along the chain).
1402 pub v1_state_root: [u8; 32],
1403 /// Root of the previous checkpoint; the v1 state root for the first v2 checkpoint.
1404 pub prev_checkpoint_root: [u8; 32],
1405 /// `state_root_digest` of the state this checkpoint holds.
1406 pub state_root: [u8; 32],
1407 /// SHA-256 of the content (domain separated).
1408 pub content_sha256: [u8; 32],
1409 /// This checkpoint's root, see [`checkpoint_root`].
1410 pub checkpoint_root: [u8; 32],
1411}
1412
1413/// `SHA-256(DOMAIN_CHECKPOINT_ROOT_V2 || v1_state_root || prev_checkpoint_root ||
1414/// checkpoint_seq (u64 LE) || anchor_frame_sha256 || state_root || content_sha256)`.
1415pub fn checkpoint_root(
1416 v1_state_root: &[u8; 32],
1417 prev_checkpoint_root: &[u8; 32],
1418 checkpoint_seq: WalSeq,
1419 anchor_frame_sha256: &[u8; 32],
1420 state_root: &[u8; 32],
1421 content_sha256: &[u8; 32],
1422) -> [u8; 32] {
1423 let mut h = Sha256::new();
1424 h.update(DOMAIN_CHECKPOINT_ROOT_V2);
1425 h.update(v1_state_root);
1426 h.update(prev_checkpoint_root);
1427 h.update(checkpoint_seq.0.to_le_bytes());
1428 h.update(anchor_frame_sha256);
1429 h.update(state_root);
1430 h.update(content_sha256);
1431 h.finalize().into()
1432}
1433
1434fn content_digest(content: &[u8]) -> [u8; 32] {
1435 let mut h = Sha256::new();
1436 h.update(DOMAIN_CHECKPOINT_CONTENT_V2);
1437 h.update(content);
1438 h.finalize().into()
1439}
1440
1441/// Encode `state` as `checkpoint.v2` bytes chained to `prev_checkpoint_root`.
1442///
1443/// Layout: `SCK2 | version u16 = 2 | codec u8 = 2 | reserved u8 = 0 | checkpoint_seq u64
1444/// | anchor_frame_sha256 | v1_state_root | prev_checkpoint_root | state_root |
1445/// content_sha256 | checkpoint_root | content_len u64 | content`.
1446pub fn encode_checkpoint_v2(
1447 state: &CheckpointState,
1448 v1_state_root: [u8; 32],
1449 prev_checkpoint_root: [u8; 32],
1450) -> SynapseResult<(Vec<u8>, CheckpointChain)> {
1451 let content = state.encode_content()?;
1452 let state_root = state.state_root();
1453 let content_sha256 = content_digest(&content);
1454 let chain = CheckpointChain {
1455 checkpoint_seq: state.checkpoint_seq,
1456 anchor_frame_sha256: state.anchor_frame_sha256,
1457 v1_state_root,
1458 prev_checkpoint_root,
1459 state_root,
1460 content_sha256,
1461 checkpoint_root: checkpoint_root(
1462 &v1_state_root,
1463 &prev_checkpoint_root,
1464 state.checkpoint_seq,
1465 &state.anchor_frame_sha256,
1466 &state_root,
1467 &content_sha256,
1468 ),
1469 };
1470 let mut w = Writer(Vec::with_capacity(CHECKPOINT_V2_HEADER_LEN + content.len()));
1471 w.raw(&CHECKPOINT_V2_MAGIC);
1472 w.u16(CHECKPOINT_V2_VERSION);
1473 w.u8(CODEC_V2);
1474 w.u8(0);
1475 w.u64(chain.checkpoint_seq.0);
1476 w.raw(&chain.anchor_frame_sha256);
1477 w.raw(&chain.v1_state_root);
1478 w.raw(&chain.prev_checkpoint_root);
1479 w.raw(&chain.state_root);
1480 w.raw(&chain.content_sha256);
1481 w.raw(&chain.checkpoint_root);
1482 w.u64(content.len() as u64);
1483 debug_assert_eq!(w.0.len(), CHECKPOINT_V2_HEADER_LEN);
1484 w.raw(&content);
1485 Ok((w.0, chain))
1486}
1487
1488/// Decode and verify `checkpoint.v2` bytes: header, content length, content digest,
1489/// checkpoint root, canonical content, and the state root recomputed from the decoded
1490/// state. Every failure is `CheckpointCorrupt`.
1491pub fn decode_checkpoint_v2(bytes: &[u8]) -> SynapseResult<(CheckpointState, CheckpointChain)> {
1492 let mut r = Reader::new(bytes, bytes.len() as u64);
1493 let header =
1494 |e: CodecRefusal| e.into_error(RefusalCode::CheckpointCorrupt, "checkpoint.v2 header");
1495 if r.array::<4>().map_err(header)? != CHECKPOINT_V2_MAGIC {
1496 return Err(corrupt("bad checkpoint.v2 magic"));
1497 }
1498 let version = r.u16().map_err(header)?;
1499 // A later checkpoint format gets its own file name, so a `checkpoint.v2` with another
1500 // version is damaged.
1501 if version != CHECKPOINT_V2_VERSION {
1502 return Err(corrupt(format!("checkpoint.v2 states version {version}")));
1503 }
1504 let codec = r.u8().map_err(header)?;
1505 let reserved = r.u8().map_err(header)?;
1506 if codec != CODEC_V2 || reserved != 0 {
1507 return Err(corrupt(format!(
1508 "checkpoint.v2 codec {codec} reserved {reserved}"
1509 )));
1510 }
1511 let checkpoint_seq = WalSeq(r.u64().map_err(header)?);
1512 let anchor_frame_sha256 = r.array().map_err(header)?;
1513 let v1_state_root = r.array().map_err(header)?;
1514 let prev_checkpoint_root = r.array().map_err(header)?;
1515 let state_root = r.array().map_err(header)?;
1516 let content_sha256 = r.array().map_err(header)?;
1517 let stored_root = r.array().map_err(header)?;
1518 let content_len = r.u64().map_err(header)?;
1519 if content_len != r.remaining() as u64 {
1520 return Err(corrupt(format!(
1521 "checkpoint.v2 declares {content_len} content bytes, holds {}",
1522 r.remaining()
1523 )));
1524 }
1525 let content = &bytes[r.pos..];
1526 if content_digest(content) != content_sha256 {
1527 return Err(corrupt("checkpoint.v2 content digest mismatch"));
1528 }
1529 let root = checkpoint_root(
1530 &v1_state_root,
1531 &prev_checkpoint_root,
1532 checkpoint_seq,
1533 &anchor_frame_sha256,
1534 &state_root,
1535 &content_sha256,
1536 );
1537 if root != stored_root {
1538 return Err(corrupt("checkpoint.v2 root mismatch"));
1539 }
1540 let state = CheckpointState::decode_content(content, checkpoint_seq, anchor_frame_sha256)
1541 .map_err(|e| e.into_error(RefusalCode::CheckpointCorrupt, "checkpoint.v2 content"))?;
1542 if state.state_root() != state_root {
1543 return Err(corrupt(
1544 "checkpoint.v2 state root does not match its content",
1545 ));
1546 }
1547 Ok((
1548 state,
1549 CheckpointChain {
1550 checkpoint_seq,
1551 anchor_frame_sha256,
1552 v1_state_root,
1553 prev_checkpoint_root,
1554 state_root,
1555 content_sha256,
1556 checkpoint_root: root,
1557 },
1558 ))
1559}
1560
1561/// Bytes written to `checkpoint.v1` once `checkpoint.v2` exists: valid v1 JSON with
1562/// `version: 2` and nothing else, so a binary that only knows v1 refuses the store
1563/// (`WalVersionUnsupported`) instead of opening it as empty.
1564pub fn v1_tombstone_bytes() -> Vec<u8> {
1565 let tombstone = CheckpointManifest {
1566 version: CHECKPOINT_V2_VERSION,
1567 ..Default::default()
1568 };
1569 serde_json::to_vec(&tombstone).expect("a default manifest serializes")
1570}