evidencebook 0.0.23

Evidence book: records, epistemic types, typed links, retention, disclosure, index classes, request answers and reconcile/close over an embedded Checkpointed Local Log -- a Rust implementation of the Evidence Layer semantics.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
//! The commitment substrate a book embeds.
//!
//! I-D section: *The Commitment-Substrate Interface*.
//!
//! A conforming substrate supplies four properties: append order, inclusion,
//! consistency/continuity, and checkpoint identity. [`Substrate`] is that
//! interface; [`CllSubstrate`] is the reference implementation over the
//! Checkpointed Local Log, with a durable file-backed MMR node store and a
//! `checkpoints.jsonl` checkpoint file.
//!
//! Nothing here exposes a `cll` type. [`Checkpoint`], [`WitnessEntry`] and
//! [`InclusionEvidence`] carry the same fields and wire shape as the log's own
//! records (so a stranger's verifier reads them unchanged), and [`Signer`] is
//! this crate's signing interface.
//!
//! **One sequence commitment.** The MMR is the only structure that commits to
//! record order. A book keeps no second hash chain beside it; a record that
//! follows another says so with a typed link, which the substrate does not
//! validate as a chain.
//!
//! **Cutting a checkpoint is two steps.** [`CllSubstrate::prepare_checkpoint`]
//! checks monotonicity, computes the root, signs, and builds the COSE wire
//! form; the caller may then attach witness receipts to the prepared
//! checkpoint (registration needs the wire bytes) before
//! [`CllSubstrate::commit_checkpoint`] persists it. Checkpoint time is the
//! caller's: coarsening it is a privacy decision of the store, not of the log.

use crate::store::{CheckpointedLog, ConsistencyParts};
use cll::checkpoint::{
    checkpoint_to_cose, try_sign_checkpoint_digest, CheckpointRecord, CheckpointSigner,
    Signature as CllSignature, SignerError, WitnessRecord,
};
use cll::mmr::{
    add_leaf, consistency_proof, inclusion_proof, leaf_count as mmr_leaf_count, leaf_hash,
    leaf_index_to_pos, node_count, peaks, root_from_peaks, Hash, InclusionProof, NodeReader,
};
use cll::node_store::FileNodeStore;
use cll::store::{append_checkpoint, read_checkpoints, read_last_checkpoint, CheckpointLine};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};

/// Byte length of a record id (a SHA-256 digest).
pub const RECORD_ID_LEN: usize = 32;

/// A record id as the substrate commits it.
pub type RecordId = [u8; RECORD_ID_LEN];

/// The `kind` of every checkpoint this substrate cuts.
pub const CHECKPOINT_KIND: &str = "mmr_checkpoint";

/// Parse a record id from lowercase or uppercase hex; `None` unless it is
/// exactly [`RECORD_ID_LEN`] bytes.
pub fn record_id_from_hex(s: &str) -> Option<RecordId> {
    hex::decode(s).ok()?.try_into().ok()
}

/// The substrate interface (I-D *The Commitment-Substrate Interface*).
pub trait Substrate {
    type Error;

    /// Append order: commit `record_id` at the next position and return it.
    fn append(&mut self, record_id: &RecordId) -> Result<u64, Self::Error>;

    /// Records committed so far.
    fn record_count(&self) -> Result<u64, Self::Error>;

    /// Checkpoint identity: the latest committed checkpoint, if any.
    fn latest_checkpoint(&self) -> Option<&Checkpoint>;

    /// Inclusion: evidence that the record at `position` is committed under
    /// `checkpoint`.
    fn inclusion(
        &self,
        position: u64,
        checkpoint: &Checkpoint,
    ) -> Result<InclusionEvidence, Self::Error>;
}

/// Signs checkpoint digests. Implemented for a local Ed25519 key; a remote or
/// hardware signer implements it too.
pub trait Signer {
    /// Sign `digest` (the checkpoint's hex digest, as bytes).
    fn sign(&self, digest: &[u8]) -> Result<[u8; 64], SignError>;

    /// The signer's key id: the raw Ed25519 public key, hex.
    fn key_id(&self) -> String;
}

impl Signer for ed25519_dalek::SigningKey {
    fn sign(&self, digest: &[u8]) -> Result<[u8; 64], SignError> {
        Ok(ed25519_dalek::Signer::sign(self, digest).to_bytes())
    }

    fn key_id(&self) -> String {
        hex::encode(self.verifying_key().to_bytes())
    }
}

#[derive(Debug, thiserror::Error)]
#[error("signing failed: {0}")]
pub struct SignError(pub String);

/// Adapts a [`Signer`] to the log's own signer interface.
struct SignerAdapter<'a>(&'a dyn Signer);

impl CheckpointSigner for SignerAdapter<'_> {
    fn sign(&self, digest: &[u8]) -> Result<CllSignature, SignerError> {
        self.0
            .sign(digest)
            .map(CllSignature)
            .map_err(|e| SignerError::Failed(e.0))
    }

    fn key_id(&self) -> String {
        self.0.key_id()
    }
}

/// One witness receipt attached to a checkpoint. Same fields and wire shape
/// as the log's witness record.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WitnessEntry {
    pub ts_url: String,
    /// sha256(bytes.fromhex(checkpoint_digest)).hex() -- witness-derived.
    pub entry_hash: String,
    /// base64-encoded COSE Receipt.
    pub receipt_b64: String,
    pub leaf_index: i64,
    pub tree_size: i64,
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub is_stub: bool,
}

/// A signed checkpoint: one committed state, named independently of the
/// store that produced it (I-D checkpoint identity). Same fields and wire
/// shape as the log's checkpoint record.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Checkpoint {
    pub v: u32,
    pub kind: String,
    pub log_id: String,
    pub mmr_size: u64,
    /// Hex MMR root at `mmr_size`.
    pub root: String,
    /// 0 for the first checkpoint.
    pub prev_size: u64,
    /// Hex root at `prev_size`; empty for the first checkpoint.
    pub prev_root: String,
    pub key_id: String,
    pub timestamp: String,
    /// Hex Ed25519 signature over [`Checkpoint::digest`].
    pub signature: String,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub witnesses: Vec<WitnessEntry>,
}

impl Checkpoint {
    /// Records this checkpoint covers.
    pub fn leaf_count(&self) -> Result<u64, SubstrateError> {
        mmr_leaf_count(self.mmr_size).log_err()
    }

    /// The canonical JSON the signature covers.
    pub fn signing_body(&self) -> String {
        self.to_log().signing_body()
    }

    /// Hex SHA-256 of [`Checkpoint::signing_body`]: what is signed and what a
    /// witness registers.
    pub fn digest(&self) -> String {
        self.to_log().digest()
    }

    /// Verify `signature` from this record alone (key from `key_id`), with
    /// strict Ed25519: a small-order or non-canonical key never verifies
    /// (checkpointed-local-log#108).
    pub fn verify_signature_offline(&self) -> bool {
        let key: Option<[u8; 32]> = hex::decode(&self.key_id)
            .ok()
            .and_then(|k| k.try_into().ok());
        let signature: Option<[u8; 64]> = hex::decode(&self.signature)
            .ok()
            .and_then(|s| s.try_into().ok());
        match (key, signature) {
            (Some(key), Some(signature)) => {
                crate::ed25519::verify(&key, self.digest().as_bytes(), &signature)
            }
            _ => false,
        }
    }

    fn to_log(&self) -> CheckpointRecord {
        CheckpointRecord {
            v: self.v,
            kind: self.kind.clone(),
            log_id: self.log_id.clone(),
            mmr_size: self.mmr_size,
            root: self.root.clone(),
            prev_size: self.prev_size,
            prev_root: self.prev_root.clone(),
            key_id: self.key_id.clone(),
            timestamp: self.timestamp.clone(),
            signature: self.signature.clone(),
            witnesses: self
                .witnesses
                .iter()
                .map(|w| WitnessRecord {
                    ts_url: w.ts_url.clone(),
                    entry_hash: w.entry_hash.clone(),
                    receipt_b64: w.receipt_b64.clone(),
                    leaf_index: w.leaf_index,
                    tree_size: w.tree_size,
                    is_stub: w.is_stub,
                })
                .collect(),
        }
    }

    pub(crate) fn from_log(cp: CheckpointRecord) -> Self {
        Self {
            v: cp.v,
            kind: cp.kind,
            log_id: cp.log_id,
            mmr_size: cp.mmr_size,
            root: cp.root,
            prev_size: cp.prev_size,
            prev_root: cp.prev_root,
            key_id: cp.key_id,
            timestamp: cp.timestamp,
            signature: cp.signature,
            witnesses: cp
                .witnesses
                .into_iter()
                .map(|w| WitnessEntry {
                    ts_url: w.ts_url,
                    entry_hash: w.entry_hash,
                    receipt_b64: w.receipt_b64,
                    leaf_index: w.leaf_index,
                    tree_size: w.tree_size,
                    is_stub: w.is_stub,
                })
                .collect(),
        }
    }
}

/// Evidence that one record occupies one position under a checkpoint. Same
/// fields and wire shape as the log's inclusion proof.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct InclusionEvidence {
    pub v: u32,
    pub kind: String,
    pub size: u64,
    pub leaf_index: u64,
    pub witness: Vec<String>,
    pub peaks_left: Vec<String>,
    pub peaks_right: Vec<String>,
}

impl InclusionEvidence {
    fn from_log(p: InclusionProof) -> Self {
        Self {
            v: p.v,
            kind: p.kind,
            size: p.size,
            leaf_index: p.leaf_index,
            witness: p.witness,
            peaks_left: p.peaks_left,
            peaks_right: p.peaks_right,
        }
    }

    fn to_log(&self) -> InclusionProof {
        InclusionProof {
            v: self.v,
            kind: self.kind.clone(),
            size: self.size,
            leaf_index: self.leaf_index,
            witness: self.witness.clone(),
            peaks_left: self.peaks_left.clone(),
            peaks_right: self.peaks_right.clone(),
        }
    }

    /// The wire JSON of this evidence (the member set a `scitt_cose`
    /// inclusion-proof reader takes).
    pub fn to_wire_json(&self) -> serde_json::Value {
        serde_json::json!({
            "v": self.v,
            "kind": self.kind,
            "size": self.size,
            "leaf_index": self.leaf_index,
            "witness": self.witness,
            "peaks_left": self.peaks_left,
            "peaks_right": self.peaks_right,
        })
    }
}

/// Check `proof` places `record_id` at `leaf_index` under a checkpoint of
/// `size` with root `root`. Offline; needs nothing from the store.
pub fn verify_inclusion(
    root: &RecordId,
    size: u64,
    leaf_index: u64,
    record_id: &RecordId,
    proof: &InclusionEvidence,
) -> bool {
    cll::mmr::verify_inclusion(root, size, leaf_index, record_id, &proof.to_log())
}

/// What opening the durable node store found: its node count, and how many
/// bytes of a torn trailing write were truncated away.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct OpenReport {
    pub node_count: u64,
    pub truncated_bytes: u64,
}

#[derive(Debug, thiserror::Error)]
pub enum SubstrateError {
    #[error("node store error: {0}")]
    NodeStore(String),
    #[error("checkpoints.jsonl error: {0}")]
    Store(String),
    #[error("mmr error: {0}")]
    Mmr(String),
    #[error("checkpoint error: {0}")]
    Checkpoint(String),
    #[error("signer error: {0}")]
    Signer(String),
    #[error("cannot checkpoint an empty MMR (no leaves appended yet)")]
    EmptyMmr,
    #[error(
        "MMR size {current_size} is not greater than the previous checkpoint's size {prev_size} \
         -- monotonicity violated"
    )]
    RollbackSize { current_size: u64, prev_size: u64 },
    #[error(
        "MMR root at the previous checkpoint's size ({prev_size}) is {actual_root} but that \
         checkpoint recorded root {recorded_root} -- the log has been mutated since"
    )]
    RollbackRoot {
        prev_size: u64,
        actual_root: String,
        recorded_root: String,
    },
    #[error("leaf {leaf_index} is committed as {stored_leaf}, but the record id given leaf-hashes to {expected_leaf}")]
    LeafMismatch {
        leaf_index: u64,
        stored_leaf: String,
        expected_leaf: String,
    },
    #[error("cutting at {requested} leaves, but only {available} are committed")]
    CutBeyondLog { requested: u64, available: u64 },
    /// A store could not produce the record at a leaf, or its octets are not
    /// a record of the expected form.
    #[error("the record at leaf {leaf_index} cannot be read: {why}")]
    Record { leaf_index: u64, why: String },
    #[error(
        "prepared checkpoint chains to size {prev_size}, but the latest committed checkpoint \
         is at size {latest_size} -- prepare it again"
    )]
    StalePrepared { prev_size: u64, latest_size: u64 },
}

fn hashes(hex_list: &[String]) -> Result<Vec<[u8; 32]>, SubstrateError> {
    hex_list
        .iter()
        .map(|h| {
            hex::decode(h)
                .ok()
                .and_then(|b| b.try_into().ok())
                .ok_or_else(|| SubstrateError::Mmr(format!("not a 32-octet node hash: {h}")))
        })
        .collect()
}

/// Converts the embedded log's errors into [`SubstrateError`]. Private, so no
/// `cll` error type appears in this crate's public trait impls.
trait FromLog<T> {
    fn log_err(self) -> Result<T, SubstrateError>;
}

macro_rules! from_log {
    ($err:ty, $variant:ident) => {
        impl<T> FromLog<T> for Result<T, $err> {
            fn log_err(self) -> Result<T, SubstrateError> {
                self.map_err(|e| SubstrateError::$variant(e.to_string()))
            }
        }
    };
}

from_log!(cll::mmr::MmrError, Mmr);
from_log!(cll::node_store::NodeStoreError, NodeStore);
from_log!(cll::store::StoreError, Store);
from_log!(cll::checkpoint::CheckpointError, Checkpoint);
from_log!(SignerError, Signer);

/// A signed checkpoint not yet persisted. Witness receipts may be attached
/// to `checkpoint.witnesses` before [`CllSubstrate::commit_checkpoint`].
#[derive(Debug, Clone)]
pub struct PreparedCheckpoint {
    pub checkpoint: Checkpoint,
    cose: Option<Vec<u8>>,
    cose_error: Option<String>,
    leaf_count: u64,
}

impl PreparedCheckpoint {
    /// The COSE wire form, when it could be built. Building it is
    /// best-effort: a failure never blocks the JSON checkpoint, it only means
    /// the checkpoint stays self-attested (no witness can register it).
    pub fn cose(&self) -> Option<&[u8]> {
        self.cose.as_deref()
    }

    /// Why the COSE wire form could not be built, if it could not.
    pub fn cose_error(&self) -> Option<&str> {
        self.cose_error.as_deref()
    }

    /// The leaf count this checkpoint was cut at.
    pub fn leaf_count(&self) -> u64 {
        self.leaf_count
    }
}

/// A persisted checkpoint and its COSE wire statement: the form a stranger
/// verifies, and the coverage anchor of a request answer (identified by the
/// SHA-256 of `statement`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StatedCheckpoint {
    pub checkpoint: Checkpoint,
    pub statement: Vec<u8>,
}

/// The reference substrate: a Checkpointed Local Log with a durable MMR node
/// store and a JSON-lines checkpoint file.
pub struct CllSubstrate {
    node_store: FileNodeStore,
    checkpoints_path: PathBuf,
    last_checkpoint: Option<Checkpoint>,
    last_checkpoint_cose: Option<Vec<u8>>,
}

impl CllSubstrate {
    /// Open (or create) the node store at `node_store_path` and resume from
    /// the last line of `checkpoints_path` if it exists. A torn trailing
    /// node write is truncated away and reported.
    pub fn open(
        node_store_path: &Path,
        checkpoints_path: &Path,
    ) -> Result<(Self, OpenReport), SubstrateError> {
        let (node_store, report) = FileNodeStore::open(node_store_path).log_err()?;
        let last_line = read_last_checkpoint(checkpoints_path).log_err()?;
        let last_checkpoint = last_line
            .as_ref()
            .map(|l| Checkpoint::from_log(l.record.clone()));
        let last_checkpoint_cose = last_line
            .and_then(|l| l.checkpoint_cose_hex)
            .and_then(|hex_str| hex::decode(hex_str).ok());
        Ok((
            Self {
                node_store,
                checkpoints_path: checkpoints_path.to_path_buf(),
                last_checkpoint,
                last_checkpoint_cose,
            },
            OpenReport {
                node_count: report.node_count,
                truncated_bytes: report.truncated_bytes,
            },
        ))
    }

    /// Records committed so far.
    pub fn leaf_count(&self) -> Result<u64, SubstrateError> {
        mmr_leaf_count(self.node_store.size()).log_err()
    }

    /// Commit `record_id` as the next leaf; returns its leaf index.
    pub fn append_leaf(&mut self, record_id: &RecordId) -> Result<u64, SubstrateError> {
        let index = self.leaf_count()?;
        add_leaf(&mut self.node_store, leaf_hash(record_id)).log_err()?;
        Ok(index)
    }

    /// Check the leaf at `leaf_index` commits `record_id`. A store uses this
    /// to detect a record file rewritten under an existing node store: the
    /// substrate must never checkpoint over superseded leaves.
    pub fn check_leaf(&self, leaf_index: u64, record_id: &RecordId) -> Result<(), SubstrateError> {
        let expected_leaf = leaf_hash(record_id);
        let stored_leaf = self
            .node_store
            .node(leaf_index_to_pos(leaf_index).log_err()?);
        if stored_leaf != expected_leaf {
            return Err(SubstrateError::LeafMismatch {
                leaf_index,
                stored_leaf: hex::encode(stored_leaf),
                expected_leaf: hex::encode(expected_leaf),
            });
        }
        Ok(())
    }

    /// The latest persisted checkpoint.
    pub fn last_checkpoint(&self) -> Option<&Checkpoint> {
        self.last_checkpoint.as_ref()
    }

    /// The latest persisted checkpoint's COSE wire form, if it had one.
    pub fn last_checkpoint_cose(&self) -> Option<&[u8]> {
        self.last_checkpoint_cose.as_deref()
    }

    /// Mutable access to the latest checkpoint's witness list, for a late
    /// witness registration. The addition is in memory only, exactly as the
    /// registration retry has always behaved; the next persisted checkpoint
    /// supersedes it.
    pub fn last_checkpoint_witnesses_mut(&mut self) -> Option<&mut Vec<WitnessEntry>> {
        self.last_checkpoint.as_mut().map(|cp| &mut cp.witnesses)
    }

    /// Sign a checkpoint over the first `leaf_count` leaves, chained to the
    /// last persisted checkpoint. Refuses an empty cut, a cut that does not
    /// grow the log, and a log whose root at the previous checkpoint's size
    /// no longer matches the root that checkpoint recorded.
    pub fn prepare_checkpoint(
        &self,
        leaf_count: u64,
        log_id: &str,
        timestamp: &str,
        signer: &dyn Signer,
    ) -> Result<PreparedCheckpoint, SubstrateError> {
        let available = self.leaf_count()?;
        if leaf_count > available {
            return Err(SubstrateError::CutBeyondLog {
                requested: leaf_count,
                available,
            });
        }
        let current_size = node_count(leaf_count);
        if current_size == 0 {
            return Err(SubstrateError::EmptyMmr);
        }

        let (prev_size, prev_root) = match &self.last_checkpoint {
            None => (0u64, String::new()),
            Some(prev) => {
                if current_size <= prev.mmr_size {
                    return Err(SubstrateError::RollbackSize {
                        current_size,
                        prev_size: prev.mmr_size,
                    });
                }
                let actual_prev_root =
                    hex::encode(root_from_peaks(&self.peak_hashes(prev.mmr_size)?));
                if actual_prev_root != prev.root {
                    return Err(SubstrateError::RollbackRoot {
                        prev_size: prev.mmr_size,
                        actual_root: actual_prev_root,
                        recorded_root: prev.root.clone(),
                    });
                }
                (prev.mmr_size, prev.root.clone())
            }
        };

        let new_peak_hashes = self.peak_hashes(current_size)?;
        let root = hex::encode(root_from_peaks(&new_peak_hashes));
        let adapter = SignerAdapter(signer);
        let mut cp = CheckpointRecord {
            v: 1,
            kind: CHECKPOINT_KIND.to_string(),
            log_id: log_id.to_string(),
            mmr_size: current_size,
            root,
            prev_size,
            prev_root,
            key_id: adapter.key_id(),
            timestamp: timestamp.to_string(),
            signature: String::new(),
            witnesses: Vec::new(),
        };
        cp.signature = try_sign_checkpoint_digest(&cp, &adapter).log_err()?;

        // COSE wire form, best-effort: `cadence_seconds` is omitted, as the
        // Python reference omits it.
        let prev_peak_hashes = if prev_size > 0 {
            Some(self.peak_hashes(prev_size)?)
        } else {
            None
        };
        let consistency = if prev_size > 0 {
            Some(consistency_proof(&self.node_store, prev_size, current_size).log_err()?)
        } else {
            None
        };
        let (cose, cose_error) = match checkpoint_to_cose(
            &cp,
            &adapter,
            &new_peak_hashes,
            prev_peak_hashes.as_deref(),
            consistency.as_ref(),
            None,
        ) {
            Ok(bytes) => (Some(bytes), None),
            Err(err) => (None, Some(err.to_string())),
        };

        Ok(PreparedCheckpoint {
            checkpoint: Checkpoint::from_log(cp),
            cose,
            cose_error,
            leaf_count,
        })
    }

    /// Persist a prepared checkpoint (with whatever witness receipts were
    /// attached) as the new latest checkpoint.
    pub fn commit_checkpoint(
        &mut self,
        prepared: PreparedCheckpoint,
    ) -> Result<Checkpoint, SubstrateError> {
        let PreparedCheckpoint {
            checkpoint, cose, ..
        } = prepared;
        // A prepared checkpoint chains to the checkpoint that was latest when
        // it was prepared; if another was committed since, it would fork.
        let (latest_size, latest_root) = self
            .last_checkpoint
            .as_ref()
            .map_or((0, ""), |cp| (cp.mmr_size, cp.root.as_str()));
        if checkpoint.prev_size != latest_size || checkpoint.prev_root != latest_root {
            return Err(SubstrateError::StalePrepared {
                prev_size: checkpoint.prev_size,
                latest_size,
            });
        }
        append_checkpoint(
            &self.checkpoints_path,
            &CheckpointLine {
                record: checkpoint.to_log(),
                checkpoint_cose_hex: cose.as_ref().map(hex::encode),
            },
        )
        .log_err()?;
        self.last_checkpoint = Some(checkpoint.clone());
        self.last_checkpoint_cose = cose;
        Ok(checkpoint)
    }

    /// Inclusion evidence for the leaf at `leaf_index` under a checkpoint of
    /// `mmr_size`.
    pub fn inclusion_at(
        &self,
        leaf_index: u64,
        mmr_size: u64,
    ) -> Result<InclusionEvidence, SubstrateError> {
        Ok(InclusionEvidence::from_log(
            inclusion_proof(&self.node_store, leaf_index, mmr_size).log_err()?,
        ))
    }

    /// Every persisted checkpoint that has its COSE wire statement, oldest
    /// first. A checkpoint whose wire form could not be built stays
    /// self-attested and is left out: it cannot anchor an answer.
    pub fn stated_checkpoints(&self) -> Result<Vec<StatedCheckpoint>, SubstrateError> {
        if !self.checkpoints_path.exists() {
            return Ok(Vec::new());
        }
        Ok(read_checkpoints(&self.checkpoints_path)
            .log_err()?
            .into_iter()
            .filter_map(|line| {
                let statement = hex::decode(line.checkpoint_cose_hex?).ok()?;
                Some(StatedCheckpoint {
                    checkpoint: Checkpoint::from_log(line.record),
                    statement,
                })
            })
            .collect())
    }

    /// The inclusion path (sibling hashes, leaf upward) of the leaf at
    /// `leaf_index` in the MMR of `mmr_size` nodes.
    pub(crate) fn inclusion_path(
        &self,
        leaf_index: u64,
        mmr_size: u64,
    ) -> Result<Vec<[u8; 32]>, SubstrateError> {
        let proof = inclusion_proof(&self.node_store, leaf_index, mmr_size).log_err()?;
        hashes(&proof.witness)
    }

    /// What a consistency proof from the MMR of `from` nodes to the MMR of
    /// `to` nodes is made of: the old peaks, each one's path into the new
    /// MMR, and the new peaks.
    pub(crate) fn consistency_parts(
        &self,
        from: u64,
        to: u64,
    ) -> Result<ConsistencyParts, SubstrateError> {
        let proof = consistency_proof(&self.node_store, from, to).log_err()?;
        Ok((
            hashes(&proof.old_peaks)?,
            proof
                .witness
                .iter()
                .map(|p| hashes(p))
                .collect::<Result<_, _>>()?,
            hashes(&proof.new_peaks)?,
        ))
    }

    fn peak_hashes(&self, size: u64) -> Result<Vec<Hash>, SubstrateError> {
        Ok(peaks(size)
            .log_err()?
            .iter()
            .map(|&p| self.node_store.node(p))
            .collect())
    }
}

/// The reference store's commitment side: its checkpoint file and node store,
/// read in place.
impl CheckpointedLog for CllSubstrate {
    fn leaf_count(&self) -> Result<u64, SubstrateError> {
        CllSubstrate::leaf_count(self)
    }

    fn stated_checkpoints(&self) -> Result<Vec<StatedCheckpoint>, SubstrateError> {
        CllSubstrate::stated_checkpoints(self)
    }

    fn inclusion_path(
        &self,
        leaf_index: u64,
        mmr_size: u64,
    ) -> Result<Vec<[u8; 32]>, SubstrateError> {
        CllSubstrate::inclusion_path(self, leaf_index, mmr_size)
    }

    fn consistency_parts(&self, from: u64, to: u64) -> Result<ConsistencyParts, SubstrateError> {
        CllSubstrate::consistency_parts(self, from, to)
    }
}

impl Substrate for CllSubstrate {
    type Error = SubstrateError;

    fn append(&mut self, record_id: &RecordId) -> Result<u64, SubstrateError> {
        self.append_leaf(record_id)
    }

    fn record_count(&self) -> Result<u64, SubstrateError> {
        self.leaf_count()
    }

    fn latest_checkpoint(&self) -> Option<&Checkpoint> {
        self.last_checkpoint()
    }

    fn inclusion(
        &self,
        position: u64,
        checkpoint: &Checkpoint,
    ) -> Result<InclusionEvidence, SubstrateError> {
        self.inclusion_at(position, checkpoint.mmr_size)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use ed25519_dalek::SigningKey;

    fn id(n: u8) -> RecordId {
        [n; RECORD_ID_LEN]
    }

    fn open(dir: &Path) -> CllSubstrate {
        CllSubstrate::open(&dir.join("mmr_nodes.dat"), &dir.join("checkpoints.jsonl"))
            .unwrap()
            .0
    }

    fn cut(
        s: &mut CllSubstrate,
        leaves: u64,
        key: &SigningKey,
    ) -> Result<Checkpoint, SubstrateError> {
        let p = s.prepare_checkpoint(leaves, "log", "2026-09-27T00:00:00.000Z", key)?;
        s.commit_checkpoint(p)
    }

    #[test]
    fn checkpoints_chain_prove_inclusion_and_survive_reopen() {
        let dir = tempfile::tempdir().unwrap();
        let key = SigningKey::from_bytes(&[9u8; 32]);
        let mut s = open(dir.path());
        for n in 0..3 {
            assert_eq!(s.append(&id(n)).unwrap(), n as u64);
        }
        let first = cut(&mut s, 3, &key).unwrap();
        assert!(first.verify_signature_offline());
        // The identity key with R the identity and S = 0 signs every
        // message under a lenient check; this crate's strict check refuses
        // it, and so does the log's own since checkpointed-local-log 0.4.0
        // (its small-order key refusal).
        let identity = format!("01{}", "00".repeat(31));
        let forged = Checkpoint {
            key_id: identity.clone(),
            signature: format!("{identity}{}", "00".repeat(32)),
            ..first.clone()
        };
        assert!(!forged.to_log().verify_signature_offline());
        assert!(!forged.verify_signature_offline());
        assert_eq!((first.prev_size, first.prev_root.as_str()), (0, ""));
        for n in 3..5 {
            s.append(&id(n)).unwrap();
        }
        drop(s);

        let mut s = open(dir.path());
        assert_eq!(s.record_count().unwrap(), 5);
        assert_eq!(s.latest_checkpoint(), Some(&first));
        let second = cut(&mut s, 5, &key).unwrap();
        assert_eq!(
            (second.prev_size, &second.prev_root),
            (first.mmr_size, &first.root)
        );
        let root = record_id_from_hex(&second.root).unwrap();
        for n in 0..5u8 {
            let proof = s.inclusion(n as u64, &second).unwrap();
            assert!(verify_inclusion(
                &root,
                second.mmr_size,
                n as u64,
                &id(n),
                &proof
            ));
            assert!(!verify_inclusion(
                &root,
                second.mmr_size,
                n as u64,
                &id(99),
                &proof
            ));
        }
    }

    #[test]
    fn a_cut_must_grow_the_log_and_cannot_be_empty_or_beyond_it() {
        let dir = tempfile::tempdir().unwrap();
        let key = SigningKey::from_bytes(&[9u8; 32]);
        let mut s = open(dir.path());
        assert!(matches!(
            cut(&mut s, 0, &key),
            Err(SubstrateError::EmptyMmr)
        ));
        s.append(&id(1)).unwrap();
        assert!(matches!(
            cut(&mut s, 2, &key),
            Err(SubstrateError::CutBeyondLog {
                requested: 2,
                available: 1
            })
        ));
        cut(&mut s, 1, &key).unwrap();
        assert!(matches!(
            cut(&mut s, 1, &key),
            Err(SubstrateError::RollbackSize { .. })
        ));
    }

    #[test]
    fn a_rewritten_history_under_a_checkpoint_is_refused() {
        let dir = tempfile::tempdir().unwrap();
        let key = SigningKey::from_bytes(&[9u8; 32]);
        let mut s = open(dir.path());
        s.append(&id(1)).unwrap();
        cut(&mut s, 1, &key).unwrap();
        drop(s);
        // Rebuild the node store over a different first leaf, keep the
        // checkpoint file: the recorded root no longer matches.
        std::fs::remove_file(dir.path().join("mmr_nodes.dat")).unwrap();
        let mut s = open(dir.path());
        s.append(&id(2)).unwrap();
        s.append(&id(3)).unwrap();
        assert!(matches!(
            cut(&mut s, 2, &key),
            Err(SubstrateError::RollbackRoot { .. })
        ));
    }

    #[test]
    fn a_prepared_checkpoint_goes_stale_once_another_is_committed() {
        let dir = tempfile::tempdir().unwrap();
        let key = SigningKey::from_bytes(&[9u8; 32]);
        let mut s = open(dir.path());
        s.append(&id(1)).unwrap();
        s.append(&id(2)).unwrap();
        let first = s
            .prepare_checkpoint(1, "log", "2026-09-27T00:00:00.000Z", &key)
            .unwrap();
        let second = s
            .prepare_checkpoint(2, "log", "2026-09-27T00:00:00.000Z", &key)
            .unwrap();
        s.commit_checkpoint(second).unwrap();
        assert!(matches!(
            s.commit_checkpoint(first),
            Err(SubstrateError::StalePrepared {
                prev_size: 0,
                latest_size: 3
            })
        ));
        assert_eq!(s.last_checkpoint().unwrap().mmr_size, 3);
    }

    #[test]
    fn check_leaf_detects_a_different_record_at_a_position() {
        let dir = tempfile::tempdir().unwrap();
        let mut s = open(dir.path());
        s.append(&id(1)).unwrap();
        s.check_leaf(0, &id(1)).unwrap();
        assert!(matches!(
            s.check_leaf(0, &id(2)),
            Err(SubstrateError::LeafMismatch { leaf_index: 0, .. })
        ));
    }

    #[test]
    fn witnesses_attached_before_commit_are_persisted() {
        let dir = tempfile::tempdir().unwrap();
        let key = SigningKey::from_bytes(&[9u8; 32]);
        let mut s = open(dir.path());
        s.append(&id(1)).unwrap();
        let mut p = s
            .prepare_checkpoint(1, "log", "2026-09-27T00:00:00.000Z", &key)
            .unwrap();
        assert!(p.cose().is_some(), "{:?}", p.cose_error());
        p.checkpoint.witnesses.push(WitnessEntry {
            ts_url: "https://witness.example".into(),
            entry_hash: "e".repeat(64),
            receipt_b64: "cmVjZWlwdA==".into(),
            leaf_index: 0,
            tree_size: 1,
            is_stub: false,
        });
        let committed = s.commit_checkpoint(p).unwrap();
        drop(s);
        let s = open(dir.path());
        assert_eq!(s.last_checkpoint(), Some(&committed));
        assert_eq!(s.last_checkpoint().unwrap().witnesses.len(), 1);
        assert!(s.last_checkpoint_cose().is_some());
    }

    #[test]
    fn wire_shapes_match_the_logs_own_records() {
        let cp = Checkpoint {
            v: 1,
            kind: CHECKPOINT_KIND.into(),
            log_id: "log".into(),
            mmr_size: 1,
            root: "a".repeat(64),
            prev_size: 0,
            prev_root: String::new(),
            key_id: "b".repeat(64),
            timestamp: "2026-09-27T00:00:00.000Z".into(),
            signature: "c".repeat(128),
            witnesses: vec![WitnessEntry {
                ts_url: "https://witness.example".into(),
                entry_hash: "e".repeat(64),
                receipt_b64: "cmVjZWlwdA==".into(),
                leaf_index: 3,
                tree_size: 4,
                is_stub: true,
            }],
        };
        assert_eq!(
            serde_json::to_value(&cp).unwrap(),
            serde_json::to_value(cp.to_log()).unwrap()
        );
        assert_eq!(Checkpoint::from_log(cp.to_log()), cp);
        assert_eq!(cp.digest(), cp.to_log().digest());
    }
}