Skip to main content

hyprstream_pds/ledger/
checkpoint.rs

1//! `ai.hyprstream.ledger.checkpoint` — a signed ledger head (the anchorable
2//! object).
3//!
4//! ```json
5//! {
6//!   "lexicon": 1,
7//!   "id": "ai.hyprstream.ledger.checkpoint",
8//!   "defs": { "main": { "type": "record", "key": "tid", "record": {
9//!     "type": "object",
10//!     "required": ["seq", "headHash", "stateRoots"],
11//!     "properties": {
12//!       "seq":        { "type": "integer", "minimum": 0 },
13//!       "headHash":   { "type": "string", "format": "cid" },
14//!       "stateRoots": { "type": "array", "items": { "type": "object",
15//!                         "required": ["name", "root"], "properties": {
16//!                           "name": { "type": "string" },
17//!                           "root": { "type": "string", "format": "cid" } } } },
18//!       "anchor":     { "type": "string" }
19//!     }
20//! }}}
21//! ```
22//!
23//! A checkpoint commits the ledger's head at a point in time. It is the object an
24//! external timestamp/anchor (e.g. OpenTimestamps) attests to — so it **carries a
25//! reference to** the anchor, it never *embeds* the anchor proof:
26//!
27//! - `seq` — the monotonically-advancing checkpoint sequence number (`u64`).
28//! - `headHash` — the CID of the ledger head this checkpoint commits (`format:
29//!   "cid"` string).
30//! - `stateRoots` — the named state-tree roots at this head ([`StateRoot`]): each
31//!   a `{name, root-cid}` pair (e.g. `{"accounts", <cid>}`, `{"receipts", <cid>}`).
32//! - `anchor` — *optional* reference to the external anchor for this checkpoint
33//!   (an opaque locator: an OTS receipt id, a txid, a CID …). Omitted until the
34//!   checkpoint is anchored; the anchor proof itself lives outside this record.
35//!   Per #928 rule 8, anchors carry digests only and are submitted on a fixed
36//!   cadence — this record holds only the reference, never activity-correlated
37//!   payload.
38
39use anyhow::{bail, Result};
40
41use super::{
42    map_get_opt_str, map_get_str, map_get_uint, reject_unknown_fields, validate_cid_string,
43    validate_token,
44};
45use crate::cid::Cid;
46use crate::dag_cbor::DagCbor;
47
48/// The NSID of this record type.
49pub const COLLECTION_NSID: &str = "ai.hyprstream.ledger.checkpoint";
50
51/// A named state-tree root at the checkpoint's head.
52#[derive(Clone, Debug, Eq, PartialEq)]
53pub struct StateRoot {
54    /// The root's name (e.g. `"accounts"`, `"receipts"`). Non-empty.
55    pub name: String,
56    /// The root CID. `format: "cid"`.
57    pub root: String,
58}
59
60/// An `ai.hyprstream.ledger.checkpoint` record.
61#[derive(Clone, Debug, Eq, PartialEq)]
62pub struct CheckpointRecord {
63    /// Monotonic checkpoint sequence number.
64    pub seq: u64,
65    /// CID of the ledger head this checkpoint commits. `format: "cid"`.
66    pub head_hash: String,
67    /// Named state-tree roots at this head.
68    pub state_roots: Vec<StateRoot>,
69    /// Optional reference to the external anchor (never the proof itself).
70    pub anchor: Option<String>,
71}
72
73impl CheckpointRecord {
74    /// Validate and construct a record.
75    pub fn new(
76        seq: u64,
77        head_hash: impl Into<String>,
78        state_roots: Vec<StateRoot>,
79        anchor: Option<String>,
80    ) -> Result<Self> {
81        let head_hash = head_hash.into();
82        validate_cid_string(&head_hash, "headHash")?;
83        for sr in &state_roots {
84            if sr.name.is_empty() {
85                bail!("{COLLECTION_NSID}: stateRoots[].name must not be empty");
86            }
87            validate_cid_string(&sr.root, "stateRoots[].root")?;
88        }
89        if let Some(a) = &anchor {
90            validate_token(a, "anchor")?;
91        }
92        Ok(CheckpointRecord {
93            seq,
94            head_hash,
95            state_roots,
96            anchor,
97        })
98    }
99
100    /// Encode to canonical DAG-CBOR bytes (deterministic).
101    pub fn to_dag_cbor(&self) -> Vec<u8> {
102        self.to_value().encode()
103    }
104
105    /// The CID of this record (CIDv1 dag-cbor over its canonical bytes).
106    pub fn cid(&self) -> Cid {
107        Cid::from_dag_cbor(&self.to_dag_cbor())
108    }
109
110    /// Build the typed [`DagCbor`] value form. The optional `anchor` field is
111    /// omitted from the map when absent.
112    pub fn to_value(&self) -> DagCbor {
113        let state_roots = DagCbor::list(self.state_roots.iter().map(|sr| {
114            DagCbor::str_map([
115                ("name", DagCbor::Text(sr.name.clone())),
116                ("root", DagCbor::Text(sr.root.clone())),
117            ])
118        }));
119        let mut pairs: Vec<(&str, DagCbor)> = vec![
120            ("seq", DagCbor::Unsigned(self.seq)),
121            ("headHash", DagCbor::Text(self.head_hash.clone())),
122            ("stateRoots", state_roots),
123        ];
124        if let Some(anchor) = &self.anchor {
125            pairs.push(("anchor", DagCbor::Text(anchor.clone())));
126        }
127        DagCbor::str_map(pairs)
128    }
129
130    /// Decode canonical DAG-CBOR bytes into a record, validating all fields.
131    pub fn from_dag_cbor(bytes: &[u8]) -> Result<Self> {
132        let value = DagCbor::decode(bytes)?;
133        Self::from_value(&value)
134    }
135
136    pub fn from_value(value: &DagCbor) -> Result<Self> {
137        reject_unknown_fields(
138            value,
139            &["seq", "headHash", "stateRoots", "anchor"],
140            COLLECTION_NSID,
141        )?;
142        let seq = map_get_uint(value, "seq", COLLECTION_NSID)?;
143        let head_hash = map_get_str(value, "headHash", COLLECTION_NSID)?.to_owned();
144        let state_roots = value
145            .get("stateRoots")
146            .ok_or_else(|| {
147                anyhow::anyhow!("{COLLECTION_NSID}: missing required field \"stateRoots\"")
148            })?
149            .as_list()?
150            .iter()
151            .map(parse_state_root)
152            .collect::<Result<Vec<_>>>()?;
153        let anchor = map_get_opt_str(value, "anchor")?.map(str::to_owned);
154        Self::new(seq, head_hash, state_roots, anchor)
155    }
156}
157
158fn parse_state_root(value: &DagCbor) -> Result<StateRoot> {
159    reject_unknown_fields(value, &["name", "root"], COLLECTION_NSID)?;
160    let name = map_get_str(value, "name", COLLECTION_NSID)?.to_owned();
161    let root = map_get_str(value, "root", COLLECTION_NSID)?.to_owned();
162    Ok(StateRoot { name, root })
163}
164
165#[cfg(test)]
166mod tests {
167    #![allow(
168        clippy::unwrap_used,
169        clippy::expect_used,
170        clippy::indexing_slicing,
171        clippy::panic
172    )]
173    use super::*;
174
175    fn roots() -> Vec<StateRoot> {
176        vec![
177            StateRoot {
178                name: "accounts".into(),
179                root: "bafyreiaccountsroot1234567890abcdef".into(),
180            },
181            StateRoot {
182                name: "receipts".into(),
183                root: "bafyreireceiptsroot1234567890abcdef".into(),
184            },
185        ]
186    }
187
188    fn sample() -> CheckpointRecord {
189        CheckpointRecord::new(
190            42,
191            "bafyreiledgerhead1234567890abcdefghij",
192            roots(),
193            Some("ots:abcdef0123456789".into()),
194        )
195        .expect("valid sample")
196    }
197
198    #[test]
199    fn record_round_trip_same_cid() {
200        let r = sample();
201        let bytes = r.to_dag_cbor();
202        let back = CheckpointRecord::from_dag_cbor(&bytes).expect("round-trip");
203        assert_eq!(r, back);
204        assert_eq!(r.cid(), back.cid());
205        assert_eq!(back.to_dag_cbor(), bytes);
206    }
207
208    #[test]
209    fn record_fields_canonical_order() {
210        let r = sample();
211        let v = DagCbor::decode(&r.to_dag_cbor()).expect("decode");
212        let map = v.as_map().expect("map");
213        let keys: Vec<&str> = map.iter().map(|(k, _)| k.as_str().expect("str")).collect();
214        assert_eq!(keys, vec!["anchor", "headHash", "seq", "stateRoots"]);
215    }
216
217    #[test]
218    fn optional_anchor_omitted_when_absent() {
219        let mut r = sample();
220        r.anchor = None;
221        let v = r.to_value();
222        assert!(v.get("anchor").is_none(), "absent anchor must be omitted");
223        let back = CheckpointRecord::from_dag_cbor(&r.to_dag_cbor()).expect("round-trip");
224        assert_eq!(r, back);
225    }
226
227    #[test]
228    fn no_legal_identity_field_is_representable() {
229        let mut v = sample().to_value();
230        if let DagCbor::Map(ref mut pairs) = v {
231            pairs.push((
232                DagCbor::Text("operatorName".into()),
233                DagCbor::Text("Acme LLC".into()),
234            ));
235            pairs.sort_by(|a, b| a.0.as_str().unwrap_or("").cmp(b.0.as_str().unwrap_or("")));
236        }
237        assert!(CheckpointRecord::from_value(&v).is_err());
238    }
239
240    #[test]
241    fn record_validates_formats() {
242        // Bad head hash cid.
243        assert!(CheckpointRecord::new(1, "x", roots(), None).is_err());
244        // Bad state-root cid.
245        assert!(CheckpointRecord::new(
246            1,
247            "bafyreiledgerhead1234567890abcdefghij",
248            vec![StateRoot {
249                name: "accounts".into(),
250                root: "bad".into()
251            }],
252            None
253        )
254        .is_err());
255        // Empty state-root name.
256        assert!(CheckpointRecord::new(
257            1,
258            "bafyreiledgerhead1234567890abcdefghij",
259            vec![StateRoot {
260                name: "".into(),
261                root: "bafyreiaccountsroot1234567890abcdef".into()
262            }],
263            None
264        )
265        .is_err());
266        // Empty anchor when present.
267        assert!(CheckpointRecord::new(
268            1,
269            "bafyreiledgerhead1234567890abcdefghij",
270            roots(),
271            Some("".into())
272        )
273        .is_err());
274    }
275}