1use 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
48pub const COLLECTION_NSID: &str = "ai.hyprstream.ledger.checkpoint";
50
51#[derive(Clone, Debug, Eq, PartialEq)]
53pub struct StateRoot {
54 pub name: String,
56 pub root: String,
58}
59
60#[derive(Clone, Debug, Eq, PartialEq)]
62pub struct CheckpointRecord {
63 pub seq: u64,
65 pub head_hash: String,
67 pub state_roots: Vec<StateRoot>,
69 pub anchor: Option<String>,
71}
72
73impl CheckpointRecord {
74 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 pub fn to_dag_cbor(&self) -> Vec<u8> {
102 self.to_value().encode()
103 }
104
105 pub fn cid(&self) -> Cid {
107 Cid::from_dag_cbor(&self.to_dag_cbor())
108 }
109
110 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 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 assert!(CheckpointRecord::new(1, "x", roots(), None).is_err());
244 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 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 assert!(CheckpointRecord::new(
268 1,
269 "bafyreiledgerhead1234567890abcdefghij",
270 roots(),
271 Some("".into())
272 )
273 .is_err());
274 }
275}