phytrace_sdk/core/
merkle.rs1use serde_json::Value;
19use sha2::{Digest, Sha256};
20
21use crate::core::canonical::leaf_payload_from_value;
22
23pub const STATEMENT_TYPE: &str = "udm.merkle-batch.v1";
25
26pub type Hash = [u8; 32];
28
29pub 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
37pub 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
46fn split(n: usize) -> usize {
48 let mut k = 1;
49 while k * 2 < n {
50 k *= 2;
51 }
52 k
53}
54
55pub 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
67pub 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
86pub 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
114pub 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
130pub 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 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}