Skip to main content

link_cli/engine/
causal_merkle.rs

1//! Selected bounded content snapshots and proof-checked causal transfer.
2use super::{
3    causal::{CausalDot, CausalVersion},
4    causal_replica::CausalReplica,
5    cluster::AtomicJournalStore,
6};
7use crate::LinkError;
8use serde_json::{json, Value};
9use sha2::{Digest, Sha256};
10use std::collections::{BTreeMap, BTreeSet};
11use std::sync::OnceLock;
12
13const DOMAIN: &[u8] = b"causal-merkle1\0";
14type Hash = [u8; 32];
15fn invalid() -> LinkError {
16    LinkError::InvalidFormat("invalid causal Merkle state".into())
17}
18fn digest(parts: &[&[u8]]) -> Hash {
19    let mut value = Sha256::new();
20    for part in parts {
21        value.update(part);
22    }
23    value.finalize().into()
24}
25fn branch(depth: usize, children: &[Hash; 16]) -> Hash {
26    let mut value = Sha256::new();
27    value.update(DOMAIN);
28    value.update([b'N', depth as u8]);
29    for child in children {
30        value.update(child);
31    }
32    value.finalize().into()
33}
34fn empty() -> &'static [Hash; 17] {
35    static VALUES: OnceLock<[Hash; 17]> = OnceLock::new();
36    VALUES.get_or_init(|| {
37        let mut values = [[0u8; 32]; 17];
38        values[16] = digest(&[DOMAIN, b"E"]);
39        for depth in (0..16).rev() {
40            values[depth] = branch(depth, &[values[depth + 1]; 16]);
41        }
42        values
43    })
44}
45fn hex(value: &Hash) -> String {
46    value.iter().map(|byte| format!("{byte:02x}")).collect()
47}
48fn hash(value: &str) -> Result<Hash, LinkError> {
49    if value.len() != 64
50        || !value
51            .bytes()
52            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
53    {
54        return Err(invalid());
55    }
56    let mut result = [0u8; 32];
57    for (i, item) in result.iter_mut().enumerate() {
58        *item = u8::from_str_radix(&value[i * 2..i * 2 + 2], 16).map_err(|_| invalid())?;
59    }
60    Ok(result)
61}
62fn prefix(value: &str) -> Result<(), LinkError> {
63    if value.len() > 15
64        || !value
65            .bytes()
66            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
67    {
68        return Err(invalid());
69    }
70    Ok(())
71}
72fn admission(
73    values: &[CausalVersion],
74    max_versions: usize,
75    max_bytes: usize,
76) -> Result<BTreeMap<u64, Vec<CausalVersion>>, LinkError> {
77    if values.len() > max_versions {
78        return Err(invalid());
79    }
80    let mut bytes = 0usize;
81    let mut dots: BTreeMap<&CausalDot, String> = BTreeMap::new();
82    let mut groups: BTreeMap<u64, Vec<CausalVersion>> = BTreeMap::new();
83    for value in values {
84        let wire = value.encode()?;
85        bytes = bytes.checked_add(wire.len()).ok_or_else(invalid)?;
86        if bytes > max_bytes {
87            return Err(invalid());
88        }
89        if dots.get(&value.dot).is_some_and(|prior| prior != &wire) {
90            return Err(invalid());
91        }
92        dots.insert(&value.dot, wire);
93        let group = groups.entry(value.address).or_default();
94        group.push(value.clone());
95        if group.len() > 64 {
96            return Err(invalid());
97        }
98    }
99    Ok(groups)
100}
101fn leaf_hash(address: u64, versions: &[CausalVersion]) -> Result<Hash, LinkError> {
102    if versions.is_empty() {
103        return Ok(empty()[16]);
104    }
105    let mut hash = Sha256::new();
106    hash.update(DOMAIN);
107    hash.update(b"L");
108    hash.update(address.to_be_bytes());
109    hash.update((versions.len() as u16).to_be_bytes());
110    for value in versions {
111        let wire = value.encode()?;
112        hash.update((wire.len() as u32).to_be_bytes());
113        hash.update(wire.as_bytes());
114    }
115    Ok(hash.finalize().into())
116}
117fn proof(value: &[Vec<String>], depth: usize) -> Result<Vec<Vec<Hash>>, LinkError> {
118    if value.len() != depth {
119        return Err(invalid());
120    }
121    value
122        .iter()
123        .map(|level| {
124            if level.len() != 15 {
125                return Err(invalid());
126            }
127            level.iter().map(|value| hash(value)).collect()
128        })
129        .collect()
130}
131fn fold(mut current: Hash, path: &str, proof: &[Vec<Hash>]) -> Hash {
132    for depth in (0..path.len()).rev() {
133        let digit = (path.as_bytes()[depth] as char).to_digit(16).unwrap() as usize;
134        let mut children = [[0u8; 32]; 16];
135        let mut index = 0;
136        for (i, child) in children.iter_mut().enumerate() {
137            if i == digit {
138                *child = current;
139            } else {
140                *child = proof[depth][index];
141                index += 1;
142            }
143        }
144        current = branch(depth, &children);
145    }
146    current
147}
148fn frame(wire: &str, max_bytes: usize, tag: &str) -> Result<Value, LinkError> {
149    if wire.len() > max_bytes {
150        return Err(invalid());
151    }
152    let (mut depth, mut separators, mut quoted) = (0usize, 0usize, false);
153    for byte in wire.bytes() {
154        if !(b' '..=b'~').contains(&byte) || byte == b'\\' {
155            return Err(invalid());
156        }
157        if byte == b'"' {
158            quoted = !quoted;
159            continue;
160        }
161        if quoted {
162            continue;
163        }
164        match byte {
165            b'{' | b'}' => return Err(invalid()),
166            b'[' => {
167                depth += 1;
168                if depth > 5 {
169                    return Err(invalid());
170                }
171            }
172            b']' => {
173                depth = depth.checked_sub(1).ok_or_else(invalid)?;
174            }
175            b',' => {
176                separators += 1;
177                if separators > 32768 {
178                    return Err(invalid());
179                }
180            }
181            _ => (),
182        }
183    }
184    if quoted || depth != 0 {
185        return Err(invalid());
186    }
187    let value: Value = serde_json::from_str(wire).map_err(|_| invalid())?;
188    // Value's PartialEq<str> compares a JSON string value, not its wire encoding.
189    let canonical = value.to_string();
190    if !value
191        .as_array()
192        .is_some_and(|a| a.len() == 5 && a[0] == tag)
193        || canonical != wire
194    {
195        return Err(invalid());
196    }
197    Ok(value)
198}
199fn text(value: &Value) -> Result<&str, LinkError> {
200    value.as_str().ok_or_else(invalid)
201}
202fn strings(value: &Value, count: usize) -> Result<Vec<String>, LinkError> {
203    value
204        .as_array()
205        .filter(|a| a.len() == count)
206        .ok_or_else(invalid)?
207        .iter()
208        .map(|v| text(v).map(String::from))
209        .collect()
210}
211fn wire_proof(value: &Value, depth: usize) -> Result<Vec<Vec<String>>, LinkError> {
212    value
213        .as_array()
214        .filter(|a| a.len() == depth)
215        .ok_or_else(invalid)?
216        .iter()
217        .map(|v| strings(v, 15))
218        .collect()
219}
220
221#[derive(Clone, Copy, Debug)]
222pub struct CausalMerkleOptions {
223    pub max_versions: usize,
224    pub max_bytes: usize,
225}
226impl Default for CausalMerkleOptions {
227    fn default() -> Self {
228        Self {
229            max_versions: 4096,
230            max_bytes: 8_388_608,
231        }
232    }
233}
234#[derive(Clone, Debug, PartialEq, Eq)]
235pub struct CausalMerkleNode {
236    pub root: String,
237    pub prefix: String,
238    pub children: Vec<String>,
239    pub proof: Vec<Vec<String>>,
240}
241#[derive(Clone, Debug, PartialEq, Eq)]
242pub struct CausalMerkleLeaf {
243    pub root: String,
244    pub address: u64,
245    pub versions: Vec<CausalVersion>,
246    pub proof: Vec<Vec<String>>,
247}
248pub struct CausalMerkleSnapshot {
249    root: String,
250    rows: BTreeMap<u64, Vec<CausalVersion>>,
251    nodes: BTreeMap<String, Hash>,
252}
253impl CausalMerkleSnapshot {
254    pub fn new(values: &[CausalVersion], options: CausalMerkleOptions) -> Result<Self, LinkError> {
255        if !(1..=4096).contains(&options.max_versions)
256            || !(1..=8_388_608).contains(&options.max_bytes)
257        {
258            return Err(invalid());
259        }
260        let groups = admission(values, options.max_versions, options.max_bytes)?;
261        let mut result = Self {
262            root: String::new(),
263            rows: BTreeMap::new(),
264            nodes: BTreeMap::new(),
265        };
266        for (key, group) in groups {
267            let merged = CausalVersion::merge(&group, &[])?;
268            result
269                .nodes
270                .insert(format!("{key:016x}"), leaf_hash(key, &merged)?);
271            result.rows.insert(key, merged);
272        }
273        for depth in (0..16).rev() {
274            let parents: BTreeSet<String> = result
275                .nodes
276                .keys()
277                .filter(|p| p.len() == depth + 1)
278                .map(|p| p[..depth].into())
279                .collect();
280            for parent in parents {
281                result
282                    .nodes
283                    .insert(parent.clone(), branch(depth, &result.children(&parent)));
284            }
285        }
286        result.root = hex(result.nodes.get("").unwrap_or(&empty()[0]));
287        Ok(result)
288    }
289    pub fn root(&self) -> &str {
290        &self.root
291    }
292    fn children(&self, path: &str) -> [Hash; 16] {
293        std::array::from_fn(|i| {
294            *self
295                .nodes
296                .get(&format!("{path}{i:x}"))
297                .unwrap_or(&empty()[path.len() + 1])
298        })
299    }
300    fn proof(&self, path: &str) -> Vec<Vec<String>> {
301        path.bytes()
302            .enumerate()
303            .map(|(depth, digit)| {
304                let digit = (digit as char).to_digit(16).unwrap() as usize;
305                self.children(&path[..depth])
306                    .iter()
307                    .enumerate()
308                    .filter(|(i, _)| *i != digit)
309                    .map(|(_, value)| hex(value))
310                    .collect()
311            })
312            .collect()
313    }
314    pub fn node(&self, path: &str) -> Result<CausalMerkleNode, LinkError> {
315        prefix(path)?;
316        Ok(CausalMerkleNode {
317            root: self.root.clone(),
318            prefix: path.into(),
319            children: self.children(path).iter().map(hex).collect(),
320            proof: self.proof(path),
321        })
322    }
323    pub fn leaf(&self, address: u64) -> Result<CausalMerkleLeaf, LinkError> {
324        if address == 0 {
325            return Err(invalid());
326        }
327        let path = format!("{address:016x}");
328        Ok(CausalMerkleLeaf {
329            root: self.root.clone(),
330            address,
331            versions: self.rows.get(&address).cloned().unwrap_or_default(),
332            proof: self.proof(&path),
333        })
334    }
335    pub fn verify_node(root: &str, value: &CausalMerkleNode) -> Result<Vec<String>, LinkError> {
336        let expected = hash(root)?;
337        prefix(&value.prefix)?;
338        if value.root != root || value.children.len() != 16 {
339            return Err(invalid());
340        }
341        let children: Vec<_> = value
342            .children
343            .iter()
344            .map(|value| hash(value))
345            .collect::<Result<_, _>>()?;
346        let proof = proof(&value.proof, value.prefix.len())?;
347        let children: [Hash; 16] = children.try_into().map_err(|_| invalid())?;
348        if fold(branch(value.prefix.len(), &children), &value.prefix, &proof) != expected {
349            return Err(invalid());
350        }
351        Ok(value.children.clone())
352    }
353    pub fn verify_leaf(
354        root: &str,
355        value: &CausalMerkleLeaf,
356    ) -> Result<Vec<CausalVersion>, LinkError> {
357        let expected = hash(root)?;
358        if value.root != root || value.address == 0 {
359            return Err(invalid());
360        }
361        admission(&value.versions, 64, 1_048_576)?;
362        let proof = proof(&value.proof, 16)?;
363        if value.versions.iter().any(|v| v.address != value.address)
364            || CausalVersion::merge(&value.versions, &[])? != value.versions
365        {
366            return Err(invalid());
367        }
368        let current = leaf_hash(value.address, &value.versions)?;
369        if fold(current, &format!("{:016x}", value.address), &proof) != expected {
370            return Err(invalid());
371        }
372        Ok(value.versions.clone())
373    }
374    pub fn encode_node(value: &CausalMerkleNode) -> Result<String, LinkError> {
375        Self::verify_node(&value.root, value)?;
376        Ok(json!([
377            "causal-node1",
378            value.root,
379            value.prefix,
380            value.children,
381            value.proof
382        ])
383        .to_string())
384    }
385    pub fn decode_node(root: &str, wire: &str) -> Result<CausalMerkleNode, LinkError> {
386        let value = frame(wire, 32768, "causal-node1")?;
387        let path = text(&value[2])?;
388        prefix(path)?;
389        let result = CausalMerkleNode {
390            root: text(&value[1])?.into(),
391            prefix: path.into(),
392            children: strings(&value[3], 16)?,
393            proof: wire_proof(&value[4], path.len())?,
394        };
395        Self::verify_node(root, &result)?;
396        Ok(result)
397    }
398    pub fn encode_leaf(value: &CausalMerkleLeaf) -> Result<String, LinkError> {
399        let versions = Self::verify_leaf(&value.root, value)?
400            .iter()
401            .map(|v| serde_json::from_str::<Value>(&v.encode()?).map_err(|_| invalid()))
402            .collect::<Result<Vec<_>, _>>()?;
403        Ok(json!([
404            "causal-leaf1",
405            value.root,
406            value.address.to_string(),
407            versions,
408            value.proof
409        ])
410        .to_string())
411    }
412    pub fn decode_leaf(root: &str, wire: &str) -> Result<CausalMerkleLeaf, LinkError> {
413        let value = frame(wire, 1_081_344, "causal-leaf1")?;
414        let key = text(&value[2])?;
415        if key.is_empty() || key.len() > 20 {
416            return Err(invalid());
417        }
418        let address = key.parse::<u64>().map_err(|_| invalid())?;
419        if address == 0 || address.to_string() != key {
420            return Err(invalid());
421        }
422        let versions = value[3]
423            .as_array()
424            .filter(|a| a.len() <= 64)
425            .ok_or_else(invalid)?
426            .iter()
427            .map(|v| CausalVersion::decode(&v.to_string()))
428            .collect::<Result<_, _>>()?;
429        let result = CausalMerkleLeaf {
430            root: text(&value[1])?.into(),
431            address,
432            versions,
433            proof: wire_proof(&value[4], 16)?,
434        };
435        Self::verify_leaf(root, &result)?;
436        Ok(result)
437    }
438}
439pub trait CausalMerkleSource {
440    fn root(&self) -> &str;
441    fn node(&mut self, prefix: &str) -> Result<CausalMerkleNode, LinkError>;
442    fn leaf(&mut self, address: u64) -> Result<CausalMerkleLeaf, LinkError>;
443}
444impl CausalMerkleSource for CausalMerkleSnapshot {
445    fn root(&self) -> &str {
446        self.root()
447    }
448    fn node(&mut self, prefix: &str) -> Result<CausalMerkleNode, LinkError> {
449        CausalMerkleSnapshot::node(self, prefix)
450    }
451    fn leaf(&mut self, address: u64) -> Result<CausalMerkleLeaf, LinkError> {
452        CausalMerkleSnapshot::leaf(self, address)
453    }
454}
455/// Owned traversal frontier. Reuse only with the same monotone destination journal.
456#[derive(Clone, Debug, PartialEq, Eq)]
457pub struct CausalPullCursor {
458    root: String,
459    author: String,
460    pending: Vec<String>,
461}
462impl CausalPullCursor {
463    pub fn root(&self) -> &str {
464        &self.root
465    }
466}
467#[derive(Clone, Debug)]
468pub struct CausalPullOptions {
469    pub max_node_requests: usize,
470    pub max_leaf_requests: usize,
471    pub max_version_bytes: usize,
472    pub continuation: Option<CausalPullCursor>,
473}
474impl Default for CausalPullOptions {
475    fn default() -> Self {
476        Self {
477            max_node_requests: 4096,
478            max_leaf_requests: 64,
479            max_version_bytes: 8_388_608,
480            continuation: None,
481        }
482    }
483}
484#[derive(Clone, Debug, PartialEq, Eq)]
485pub struct CausalPullProgress {
486    pub root: String,
487    pub node_requests: usize,
488    pub leaf_requests: usize,
489    pub version_bytes: usize,
490    pub changed_leaves: usize,
491    pub complete: bool,
492    pub continuation: Option<CausalPullCursor>,
493}
494pub fn pull_causal<R: CausalMerkleSource, S: AtomicJournalStore>(
495    source: &mut R,
496    destination: &mut CausalReplica<S>,
497    options: CausalPullOptions,
498) -> Result<CausalPullProgress, LinkError> {
499    if !(1..=65536).contains(&options.max_node_requests)
500        || !(1..=4096).contains(&options.max_leaf_requests)
501        || !(1..=8_388_608).contains(&options.max_version_bytes)
502    {
503        return Err(invalid());
504    }
505    let root = source.root().to_owned();
506    hash(&root)?;
507    if options
508        .continuation
509        .as_ref()
510        .is_some_and(|cursor| cursor.root != root)
511    {
512        return Err(invalid());
513    }
514    let state = destination.snapshot()?;
515    let local = CausalMerkleSnapshot::new(&state.versions, CausalMerkleOptions::default())?;
516    let mut pending = match options.continuation {
517        Some(cursor) => {
518            if cursor.author != state.author {
519                return Err(invalid());
520            }
521            cursor.pending
522        }
523        None => vec![String::new()],
524    };
525    let mut progress = CausalPullProgress {
526        root: root.clone(),
527        node_requests: 0,
528        leaf_requests: 0,
529        version_bytes: 0,
530        changed_leaves: 0,
531        complete: false,
532        continuation: None,
533    };
534    if root == local.root || root == hex(&empty()[0]) {
535        pending.clear();
536    }
537    let paused = |mut progress: CausalPullProgress, mut pending: Vec<String>, path: String| {
538        pending.push(path);
539        progress.continuation = Some(CausalPullCursor {
540            root: root.clone(),
541            author: state.author.clone(),
542            pending,
543        });
544        Ok(progress)
545    };
546    while let Some(path) = pending.pop() {
547        if path.len() == 16 {
548            if progress.leaf_requests == options.max_leaf_requests {
549                return paused(progress, pending, path);
550            }
551            progress.leaf_requests += 1;
552            let address = u64::from_str_radix(&path, 16).map_err(|_| invalid())?;
553            let response = source.leaf(address)?;
554            if response.address != address {
555                return Err(invalid());
556            }
557            let versions = CausalMerkleSnapshot::verify_leaf(&root, &response)?;
558            let bytes: usize = versions
559                .iter()
560                .map(|v| v.encode().map(|s| s.len()))
561                .collect::<Result<Vec<_>, _>>()?
562                .iter()
563                .sum();
564            if progress.version_bytes + bytes > options.max_version_bytes {
565                return paused(progress, pending, path);
566            }
567            progress.version_bytes += bytes;
568            if destination.receive(&versions)? {
569                progress.changed_leaves += 1;
570            }
571        } else {
572            if progress.node_requests == options.max_node_requests {
573                return paused(progress, pending, path);
574            }
575            progress.node_requests += 1;
576            let response = source.node(&path)?;
577            if response.prefix != path {
578                return Err(invalid());
579            }
580            let remote = CausalMerkleSnapshot::verify_node(&root, &response)?;
581            let current = local.children(&path);
582            for digit in (0..16).rev() {
583                if remote[digit] != hex(&current[digit])
584                    && remote[digit] != hex(&empty()[path.len() + 1])
585                {
586                    pending.push(format!("{path}{digit:x}"));
587                }
588            }
589        }
590    }
591    progress.complete = true;
592    Ok(progress)
593}