Skip to main content

witness_core/
shamap.rs

1//! The ledger transaction tree (SHAMap) and inclusion proofs.
2//!
3//! A SHAMap is a tree with fan-out 16 over a 256-bit key: at depth d the
4//! branch is chosen by the d-th nibble of the key. A leaf sits at the depth
5//! where it becomes the only one in its subtree. The root is always an inner node.
6//!
7//! Hashes, as in xrpld:
8//! - transaction-with-metadata leaf: SHA-512Half(`SND\0`, VL(tx), VL(meta), key);
9//! - inner node: SHA-512Half(`MIN\0`, 16 child hashes; zeros for an empty one);
10//! - transaction key: its hash, SHA-512Half(`TXN\0`, tx);
11//! - state object leaf: SHA-512Half(`MLN\0`, object, key); the state tree
12//!   is built the same way, and its root is the header's `AccountHash`.
13//!
14//! The transaction tree root is stored in the ledger header (`TransactionHash`),
15//! and the header hash is the ledger hash that validators sign. So the path
16//! from a leaf to the root ties the transaction to the network's signatures.
17
18use crate::{HashPrefix, sha512_half};
19
20pub type Hash = [u8; 32];
21
22const ZERO: Hash = [0; 32];
23
24/// XRPL length prefix (VL) for `len` bytes.
25pub fn encode_vl(len: usize, out: &mut Vec<u8>) {
26    match len {
27        0..=192 => out.push(len as u8),
28        193..=12_480 => {
29            let l = len - 193;
30            out.push(193 + (l >> 8) as u8);
31            out.push((l & 0xFF) as u8);
32        }
33        _ => {
34            let l = len - 12_481;
35            out.push(241 + (l >> 16) as u8);
36            out.push(((l >> 8) & 0xFF) as u8);
37            out.push((l & 0xFF) as u8);
38        }
39    }
40}
41
42/// Transaction hash: its identifier and its key in the tree.
43pub fn tx_id(tx: &[u8]) -> Hash {
44    let mut data = HashPrefix::TransactionId.to_bytes().to_vec();
45    data.extend_from_slice(tx);
46    sha512_half(&data)
47}
48
49/// Hash of a "transaction with metadata" leaf.
50pub fn tx_leaf_hash(tx: &[u8], meta: &[u8], key: &Hash) -> Hash {
51    let mut data = HashPrefix::TxNode.to_bytes().to_vec();
52    encode_vl(tx.len(), &mut data);
53    data.extend_from_slice(tx);
54    encode_vl(meta.len(), &mut data);
55    data.extend_from_slice(meta);
56    data.extend_from_slice(key);
57    sha512_half(&data)
58}
59
60/// Hash of a state object leaf: SHA-512Half(`MLN\0`, object, key).
61/// The root of a tree of such leaves is the ledger header's `AccountHash`.
62pub fn state_leaf_hash(data: &[u8], key: &Hash) -> Hash {
63    let mut d = HashPrefix::LeafNode.to_bytes().to_vec();
64    d.extend_from_slice(data);
65    d.extend_from_slice(key);
66    sha512_half(&d)
67}
68
69fn inner_hash(children: &[Hash; 16]) -> Hash {
70    if children.iter().all(|c| *c == ZERO) {
71        return ZERO;
72    }
73    let mut data = HashPrefix::InnerNode.to_bytes().to_vec();
74    for c in children {
75        data.extend_from_slice(c);
76    }
77    sha512_half(&data)
78}
79
80fn nibble(key: &Hash, depth: usize) -> usize {
81    let b = key[depth / 2];
82    usize::from(if depth.is_multiple_of(2) {
83        b >> 4
84    } else {
85        b & 0x0F
86    })
87}
88
89/// Children of the inner node at depth `depth` for sorted leaves.
90fn children(items: &[(Hash, Hash)], depth: usize) -> [Hash; 16] {
91    let mut out = [ZERO; 16];
92    let mut start = 0;
93    while start < items.len() {
94        let branch = nibble(&items[start].0, depth);
95        let mut end = start + 1;
96        while end < items.len() && nibble(&items[end].0, depth) == branch {
97            end += 1;
98        }
99        out[branch] = subtree(&items[start..end], depth + 1);
100        start = end;
101    }
102    out
103}
104
105fn subtree(items: &[(Hash, Hash)], depth: usize) -> Hash {
106    match items {
107        [] => ZERO,
108        [(_, leaf)] => *leaf,
109        // The key ran out but there are several leaves: a duplicate key. Such
110        // a set has no real tree; the caller rejects duplicates up front
111        // (`has_duplicates`), and here we only make sure not to run past the
112        // key. Zeros will not match any real root.
113        _ if depth >= 64 => ZERO,
114        _ => inner_hash(&children(items, depth)),
115    }
116}
117
118/// Whether the leaves contain a duplicate key: such a set has no tree.
119pub fn has_duplicates(items: &[(Hash, Hash)]) -> bool {
120    let mut keys: Vec<&Hash> = items.iter().map(|(k, _)| k).collect();
121    keys.sort_unstable();
122    keys.windows(2).any(|w| w[0] == w[1])
123}
124
125fn sorted(items: &[(Hash, Hash)]) -> Vec<(Hash, Hash)> {
126    let mut v = items.to_vec();
127    v.sort_unstable_by_key(|a| a.0);
128    v
129}
130
131/// Hash of the subtree at `depth` for sorted leaves that share their first
132/// `depth` nibbles: zeros if empty, the leaf itself if alone, else an inner node.
133pub fn subtree_hash(items: &[(Hash, Hash)], depth: usize) -> Hash {
134    subtree(items, depth)
135}
136
137/// Inner nodes from `depth` down to the slot of `key`, for sorted leaves that
138/// share the key's first `depth` nibbles, and the leaf in that slot: the key's
139/// own, another key's (which proves the key absent), or none.
140pub fn walk_from(
141    items: &[(Hash, Hash)],
142    key: &Hash,
143    depth: usize,
144) -> (Vec<[Hash; 16]>, Option<(Hash, Hash)>) {
145    let mut slice = items;
146    let mut levels = Vec::new();
147    for depth in depth..64 {
148        levels.push(children(slice, depth));
149        let branch = nibble(key, depth);
150        let start = slice.partition_point(|(k, _)| nibble(k, depth) < branch);
151        let len = slice[start..]
152            .iter()
153            .take_while(|(k, _)| nibble(k, depth) == branch)
154            .count();
155        slice = &slice[start..start + len];
156        match slice {
157            [] => return (levels, None),
158            [leaf] => return (levels, Some(*leaf)),
159            _ => {}
160        }
161    }
162    (levels, None)
163}
164
165/// Tree root from leaves (key, leaf hash). An empty tree is zeros.
166pub fn root(items: &[(Hash, Hash)]) -> Hash {
167    let v = sorted(items);
168    if v.is_empty() {
169        return ZERO;
170    }
171    inner_hash(&children(&v, 0))
172}
173
174/// Path from the root to a leaf: the children of each inner node on the way,
175/// top down. The slot of the branch taken holds the hash of the node below, or of the leaf itself.
176#[derive(Debug, Clone, PartialEq, Eq)]
177pub struct Path {
178    pub levels: Vec<[Hash; 16]>,
179}
180
181/// Path to the leaf with key `key`, if there is such a leaf.
182pub fn prove(items: &[(Hash, Hash)], key: &Hash) -> Option<Path> {
183    let v = sorted(items);
184    let mut slice: &[(Hash, Hash)] = &v;
185    let mut levels = Vec::new();
186    for depth in 0..64 {
187        levels.push(children(slice, depth));
188        let branch = nibble(key, depth);
189        let start = slice.iter().position(|(k, _)| nibble(k, depth) == branch)?;
190        let len = slice[start..]
191            .iter()
192            .take_while(|(k, _)| nibble(k, depth) == branch)
193            .count();
194        slice = &slice[start..start + len];
195        if let [(k, _)] = slice {
196            return (k == key).then_some(Path { levels });
197        }
198    }
199    None
200}
201
202/// The path checks out: leaf `leaf` with key `key` is in the tree with root `root`.
203pub fn verify(path: &Path, key: &Hash, leaf: &Hash, root: &Hash) -> bool {
204    let mut below = *leaf;
205    for (depth, level) in path.levels.iter().enumerate().rev() {
206        if level[nibble(key, depth)] != below {
207            return false;
208        }
209        below = inner_hash(level);
210    }
211    !path.levels.is_empty() && below == *root
212}
213
214#[cfg(test)]
215mod tests {
216    use super::*;
217
218    fn key(first: u8, second: u8) -> Hash {
219        let mut k = [0u8; 32];
220        k[0] = first;
221        k[1] = second;
222        k[31] = first ^ second;
223        k
224    }
225
226    #[test]
227    fn vl_prefixes_match_the_decoder() {
228        for len in [0, 1, 192, 193, 300, 12_480, 12_481, 20_000] {
229            let mut out = Vec::new();
230            encode_vl(len, &mut out);
231            let mut buf = out.clone();
232            buf.extend(std::iter::repeat_n(0u8, len));
233            // A Blob field with this prefix parses into a value of the expected length.
234            let mut field = vec![0x77];
235            field.extend_from_slice(&buf);
236            let f = crate::stobject::fields(&field).unwrap();
237            assert_eq!(f[0].value.len(), len, "length {len}");
238        }
239    }
240
241    #[test]
242    fn every_leaf_has_a_path_and_forgeries_fail() {
243        // Keys with shared prefixes, so there are chains of inner nodes.
244        let items: Vec<(Hash, Hash)> = (0..40u8)
245            .map(|i| {
246                (
247                    key(i % 3 * 0x10, i),
248                    [i.wrapping_mul(7).wrapping_add(1); 32],
249                )
250            })
251            .collect();
252        let r = root(&items);
253        for (k, leaf) in &items {
254            let p = prove(&items, k).unwrap();
255            assert!(verify(&p, k, leaf, &r));
256            let mut wrong = *leaf;
257            wrong[0] ^= 1;
258            assert!(!verify(&p, k, &wrong, &r));
259        }
260        assert!(prove(&items, &key(0xFF, 0xFF)).is_none());
261    }
262
263    #[test]
264    fn single_item_tree_still_has_an_inner_root() {
265        let items = [(key(1, 2), [9; 32])];
266        let r = root(&items);
267        assert_ne!(r, [9; 32]);
268        let p = prove(&items, &items[0].0).unwrap();
269        assert_eq!(p.levels.len(), 1);
270        assert!(verify(&p, &items[0].0, &items[0].1, &r));
271        assert_eq!(root(&[]), ZERO);
272    }
273}