Skip to main content

phytrace_sdk/core/
merkle.rs

1//! Merkle batch signing (issue #392).
2//!
3//! A TPM 2.0 makes roughly 5-50 ECDSA signatures per second, far below
4//! robot topic rates.  In batch mode the agent hashes a batch of events
5//! into a Merkle tree and the signer signs only a *batch statement* naming
6//! the root, once per batch.  Each event carries the statement, its
7//! signature and its inclusion proof in `provenance.batch`, so it can still
8//! be verified on its own.
9//!
10//! The tree is the RFC 9162 (Certificate Transparency) Merkle tree over
11//! SHA-256: leaf `SHA-256(0x00 || leaf payload)`, node
12//! `SHA-256(0x01 || left || right)`, inclusion proofs as RFC 9162 audit
13//! paths (leaf first).  The leaf payload is the event's signing payload
14//! with `provenance.batch` also removed.  The construction is identical to
15//! the Python SDK's `phytrace.core.merkle` and PhyCloud's verifier, pinned
16//! by `PhyTrace/test-vectors/merkle-batch.json`.
17
18use serde_json::Value;
19use sha2::{Digest, Sha256};
20
21use crate::core::canonical::leaf_payload_from_value;
22
23/// `type` of a batch statement.
24pub const STATEMENT_TYPE: &str = "udm.merkle-batch.v1";
25
26/// A 32-byte SHA-256 hash.
27pub type Hash = [u8; 32];
28
29/// Hash of a leaf payload.
30pub fn leaf_hash(payload: &[u8]) -> Hash {
31    let mut h = Sha256::new();
32    h.update([0u8]);
33    h.update(payload);
34    h.finalize().into()
35}
36
37/// Hash of an interior node.
38pub fn node_hash(left: &Hash, right: &Hash) -> Hash {
39    let mut h = Sha256::new();
40    h.update([1u8]);
41    h.update(left);
42    h.update(right);
43    h.finalize().into()
44}
45
46/// The largest power of two smaller than `n` (`n > 1`).
47fn split(n: usize) -> usize {
48    let mut k = 1;
49    while k * 2 < n {
50        k *= 2;
51    }
52    k
53}
54
55/// RFC 9162 Merkle tree hash of leaf hashes.
56pub fn merkle_root(leaves: &[Hash]) -> Hash {
57    match leaves {
58        [] => Sha256::digest([]).into(),
59        [only] => *only,
60        _ => {
61            let (left, right) = leaves.split_at(split(leaves.len()));
62            node_hash(&merkle_root(left), &merkle_root(right))
63        }
64    }
65}
66
67/// RFC 9162 inclusion proof for `leaves[index]`, leaf first; `None` if
68/// `index` is out of range.
69pub fn audit_path(index: usize, leaves: &[Hash]) -> Option<Vec<Hash>> {
70    if index >= leaves.len() {
71        return None;
72    }
73    if leaves.len() == 1 {
74        return Some(Vec::new());
75    }
76    let (left, right) = leaves.split_at(split(leaves.len()));
77    let (mut path, sibling) = if index < left.len() {
78        (audit_path(index, left)?, merkle_root(right))
79    } else {
80        (audit_path(index - left.len(), right)?, merkle_root(left))
81    };
82    path.push(sibling);
83    Some(path)
84}
85
86/// The root an inclusion proof leads to (RFC 9162 ยง2.1.3.2), or `None` if
87/// the proof does not fit a tree of `size` leaves.
88pub fn root_from_proof(index: u64, size: u64, leaf: &Hash, proof: &[Hash]) -> Option<Hash> {
89    if index >= size {
90        return None;
91    }
92    let (mut f, mut s, mut r) = (index, size - 1, *leaf);
93    for p in proof {
94        if s == 0 {
95            return None;
96        }
97        if f & 1 == 1 || f == s {
98            r = node_hash(p, &r);
99            if f & 1 == 0 {
100                while f != 0 && f & 1 == 0 {
101                    f >>= 1;
102                    s >>= 1;
103                }
104            }
105        } else {
106            r = node_hash(&r, p);
107        }
108        f >>= 1;
109        s >>= 1;
110    }
111    (s == 0).then_some(r)
112}
113
114/// Lowercase hex.
115pub fn hex(bytes: &[u8]) -> String {
116    bytes.iter().map(|b| format!("{b:02x}")).collect()
117}
118
119fn hash_from_hex(s: &str) -> Option<Hash> {
120    if s.len() != 64 {
121        return None;
122    }
123    let bytes: Option<Vec<u8>> = (0..64)
124        .step_by(2)
125        .map(|i| u8::from_str_radix(s.get(i..i + 2)?, 16).ok())
126        .collect();
127    Hash::try_from(bytes?).ok()
128}
129
130/// Whether a batch-signed event (JSON) is in the batch its `statement`
131/// describes: its inclusion proof leads to the statement's root, and its
132/// provenance matches the statement (boot epoch, key, sequence range).
133/// The statement's signature is checked separately.
134pub fn verify_inclusion(event: &Value, statement: &Value, batch: &Value) -> bool {
135    let provenance = event.get("provenance").unwrap_or(&Value::Null);
136    let same = |field: &str| provenance.get(field) == statement.get(field);
137    if statement.get("type").and_then(Value::as_str) != Some(STATEMENT_TYPE)
138        || !same("boot_epoch")
139        || !same("key_id")
140    {
141        return false;
142    }
143    let sequence = provenance.get("sequence_num").and_then(Value::as_u64);
144    let first = statement.get("first_sequence").and_then(Value::as_u64);
145    let last = statement.get("last_sequence").and_then(Value::as_u64);
146    match (sequence, first, last) {
147        (Some(s), Some(a), Some(b)) if (a..=b).contains(&s) => {}
148        _ => return false,
149    }
150    let (Some(index), Some(size), Some(root)) = (
151        batch.get("leaf_index").and_then(Value::as_u64),
152        statement.get("leaf_count").and_then(Value::as_u64),
153        statement
154            .get("root")
155            .and_then(Value::as_str)
156            .and_then(hash_from_hex),
157    ) else {
158        return false;
159    };
160    let Some(proof) = batch.get("proof").and_then(Value::as_array).and_then(|p| {
161        p.iter()
162            .map(|h| h.as_str().and_then(hash_from_hex))
163            .collect::<Option<Vec<_>>>()
164    }) else {
165        return false;
166    };
167    let leaf = leaf_hash(leaf_payload_from_value(event).as_bytes());
168    root_from_proof(index, size, &leaf, &proof) == Some(root)
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174
175    #[test]
176    fn every_proof_verifies_for_sizes_1_to_20() {
177        for n in 1..=20usize {
178            let leaves: Vec<Hash> = (0..n).map(|i| leaf_hash(&[i as u8])).collect();
179            let root = merkle_root(&leaves);
180            for (i, leaf) in leaves.iter().enumerate() {
181                let proof = audit_path(i, &leaves).unwrap();
182                assert_eq!(
183                    root_from_proof(i as u64, n as u64, leaf, &proof),
184                    Some(root),
185                    "n={n} i={i}"
186                );
187                // A proof for one position does not verify another.
188                if n > 1 {
189                    let j = (i + 1) % n;
190                    assert_ne!(
191                        root_from_proof(j as u64, n as u64, leaf, &proof),
192                        Some(root)
193                    );
194                }
195            }
196            assert!(audit_path(n, &leaves).is_none());
197        }
198    }
199}