1use serde_json::{Map, Value};
12
13use crate::core::hive::events::sign;
14use crate::core::hive::replica::log::StoredEvent;
15use lean_ctx_protocol::hive::{canonical_json, signing_input_without_signature};
16
17pub const SNAPSHOT_DOMAIN: &str = "leanctx.hive.snapshot.v1\n";
19
20#[derive(Debug, Clone, PartialEq, Eq)]
22pub enum SegmentError {
23 Shape(String),
24 Count { expected: u64, got: u64 },
25 SeqRun,
26 Root,
27}
28
29impl std::fmt::Display for SegmentError {
30 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
31 match self {
32 Self::Shape(what) => write!(f, "segment record shape: {what}"),
33 Self::Count { expected, got } => {
34 write!(f, "segment holds {got} records, manifest says {expected}")
35 }
36 Self::SeqRun => f.write_str("segment seq run has a gap or does not match"),
37 Self::Root => f.write_str("segment envelope root does not match the manifest"),
38 }
39 }
40}
41
42pub fn leaf(envelope: &Value) -> Result<[u8; 32], SegmentError> {
44 let canonical = canonical_json(envelope).map_err(|e| SegmentError::Shape(e.to_string()))?;
45 let mut h = blake3::Hasher::new();
46 h.update(&[0]);
47 h.update(&canonical);
48 Ok(*h.finalize().as_bytes())
49}
50
51pub fn root(leaves: &[[u8; 32]]) -> Option<[u8; 32]> {
54 let mut level = leaves.to_vec();
55 if level.is_empty() {
56 return None;
57 }
58 while level.len() > 1 {
59 level = level
60 .chunks(2)
61 .map(|pair| match pair {
62 [l, r] => {
63 let mut h = blake3::Hasher::new();
64 h.update(&[1]);
65 h.update(l);
66 h.update(r);
67 *h.finalize().as_bytes()
68 }
69 [single] => *single,
70 _ => unreachable!("chunks of two"),
71 })
72 .collect();
73 }
74 level.first().copied()
75}
76
77pub fn manifest_verifies(manifest: &Value, public_key: &[u8; 32]) -> bool {
80 use ed25519_dalek::{Signature, Verifier as _, VerifyingKey};
81 if manifest.get("key_id").and_then(Value::as_str) != Some(sign::key_id(public_key).as_str()) {
82 return false;
83 }
84 let Some(sig) = manifest
85 .get("signature")
86 .and_then(Value::as_str)
87 .and_then(|s| hex::decode(s).ok())
88 .and_then(|b| <[u8; 64]>::try_from(b).ok())
89 else {
90 return false;
91 };
92 let (Ok(key), Ok(input)) = (
93 VerifyingKey::from_bytes(public_key),
94 signing_input_without_signature(SNAPSHOT_DOMAIN, manifest),
95 ) else {
96 return false;
97 };
98 key.verify(&input, &Signature::from_bytes(&sig)).is_ok()
99}
100
101#[derive(Debug, Clone, PartialEq, Eq)]
103pub struct SegmentMeta {
104 pub n: u64,
105 pub seq_from: u64,
106 pub seq_to: u64,
107 pub count: u64,
108 pub envelope_root: String,
109}
110
111pub fn segments(manifest: &Value) -> Result<Vec<SegmentMeta>, SegmentError> {
112 let list = manifest
113 .get("segments")
114 .and_then(Value::as_array)
115 .ok_or_else(|| SegmentError::Shape("manifest without segments".into()))?;
116 list.iter()
117 .map(|s| {
118 let n = |k: &str| {
119 s.get(k)
120 .and_then(Value::as_u64)
121 .ok_or_else(|| SegmentError::Shape(format!("segment {k}")))
122 };
123 Ok(SegmentMeta {
124 n: n("n")?,
125 seq_from: n("seq_from")?,
126 seq_to: n("seq_to")?,
127 count: n("count")?,
128 envelope_root: s
129 .get("envelope_root")
130 .and_then(Value::as_str)
131 .ok_or_else(|| SegmentError::Shape("segment envelope_root".into()))?
132 .to_string(),
133 })
134 })
135 .collect()
136}
137
138fn event_of(record: &Value) -> Result<Value, SegmentError> {
140 let mut event: Map<String, Value> = record
141 .get("envelope")
142 .and_then(Value::as_object)
143 .cloned()
144 .ok_or_else(|| SegmentError::Shape("record without envelope".into()))?;
145 if let Some(fields) = record.get("server_fields").and_then(Value::as_object) {
146 for (k, v) in fields {
147 event.insert(k.clone(), v.clone());
148 }
149 }
150 if let Some(body) = record.get("body") {
151 event.insert("body".into(), body.clone());
152 }
153 if record.get("purged").and_then(Value::as_bool) == Some(true) {
154 event.insert("purged".into(), Value::Bool(true));
155 }
156 Ok(Value::Object(event))
157}
158
159pub fn event_verifies(
165 event: &Value,
166 pk_id: &[u8; 32],
167 sealed: bool,
168 signature_ok: &dyn Fn(&Value) -> bool,
169) -> bool {
170 if !signature_ok(event) {
171 return false;
172 }
173 let Some(body) = event.get("body").filter(|b| !b.is_null()) else {
174 return true;
175 };
176 let unkeyed = sealed && event.get("op").and_then(Value::as_str) == Some("purge");
177 let commit = if unkeyed {
178 canonical_json(body)
179 .ok()
180 .map(|c| blake3::hash(&c).to_hex().to_string())
181 } else {
182 sign::body_commit(pk_id, body).ok()
183 };
184 commit.as_deref() == event.get("body_commit").and_then(Value::as_str)
185}
186
187pub fn import_segment(
191 meta: &SegmentMeta,
192 records: &[Value],
193 pk_id: &[u8; 32],
194 sealed: bool,
195 signature_ok: &dyn Fn(&Value) -> bool,
196) -> Result<Vec<StoredEvent>, SegmentError> {
197 if records.len() as u64 != meta.count {
198 return Err(SegmentError::Count {
199 expected: meta.count,
200 got: records.len() as u64,
201 });
202 }
203 let mut leaves = Vec::with_capacity(records.len());
204 let mut events = Vec::new();
205 for (i, record) in records.iter().enumerate() {
206 let seq = record
207 .get("seq")
208 .and_then(Value::as_u64)
209 .ok_or_else(|| SegmentError::Shape("record without seq".into()))?;
210 if seq != meta.seq_from + i as u64 {
211 return Err(SegmentError::SeqRun);
212 }
213 let stub = |k: &str| record.get(k).and_then(Value::as_bool) == Some(true);
214 if stub("withheld") || stub("converted") {
215 let l = record
216 .get("leaf")
217 .and_then(Value::as_str)
218 .and_then(|s| hex::decode(s).ok())
219 .and_then(|b| <[u8; 32]>::try_from(b).ok())
220 .ok_or_else(|| SegmentError::Shape("stub record without leaf".into()))?;
221 leaves.push(l);
222 continue;
223 }
224 let envelope = record
225 .get("envelope")
226 .ok_or_else(|| SegmentError::Shape("record without envelope".into()))?;
227 leaves.push(leaf(envelope)?);
228 let event = event_of(record)?;
229 let ok = event_verifies(&event, pk_id, sealed, signature_ok);
230 events.push(StoredEvent {
231 seq,
232 event,
233 sig_invalid: !ok,
234 });
235 }
236 if records
237 .last()
238 .and_then(|r| r.get("seq"))
239 .and_then(Value::as_u64)
240 != Some(meta.seq_to)
241 {
242 return Err(SegmentError::SeqRun);
243 }
244 if root(&leaves).map(hex::encode).as_deref() != Some(meta.envelope_root.as_str()) {
245 return Err(SegmentError::Root);
246 }
247 Ok(events)
248}
249
250#[derive(Debug, Clone, PartialEq)]
252pub struct TailPage {
253 pub events: Vec<StoredEvent>,
254 pub converted: Vec<u64>,
257 pub next_since: Option<u64>,
258 pub head_seq: u64,
259 pub epoch: Option<u64>,
260}
261
262pub fn tail_page(
263 page: &Value,
264 pk_id: &[u8; 32],
265 sealed: bool,
266 signature_ok: &dyn Fn(&Value) -> bool,
267) -> Result<TailPage, SegmentError> {
268 let list = page
269 .get("events")
270 .and_then(Value::as_array)
271 .ok_or_else(|| SegmentError::Shape("tail without events".into()))?;
272 let mut events = Vec::with_capacity(list.len());
273 let mut converted = Vec::new();
274 for event in list {
275 let seq = event
276 .get("seq")
277 .and_then(Value::as_u64)
278 .ok_or_else(|| SegmentError::Shape("tail event without seq".into()))?;
279 if event.get("converted").and_then(Value::as_bool) == Some(true) {
280 converted.push(seq);
281 continue;
282 }
283 events.push(StoredEvent {
284 seq,
285 event: event.clone(),
286 sig_invalid: !event_verifies(event, pk_id, sealed, signature_ok),
287 });
288 }
289 Ok(TailPage {
290 events,
291 converted,
292 next_since: page.get("next_since").and_then(Value::as_u64),
293 head_seq: page.get("head_seq").and_then(Value::as_u64).unwrap_or(0),
294 epoch: page.get("epoch").and_then(Value::as_u64),
295 })
296}
297
298#[cfg(test)]
299#[path = "records_tests.rs"]
300mod tests;