1use std::collections::{BTreeMap, HashMap};
28
29use fjall::{Keyspace, OwnedWriteBatch};
30use witness_core::sha512_half;
31use witness_core::shamap::state_leaf_hash;
32
33type Hash = [u8; 32];
34const ZERO: Hash = [0; 32];
35
36pub const LEVEL_DEPTH: usize = 3;
38pub const LEVEL_SLOTS: usize = 1 << (4 * LEVEL_DEPTH);
40
41pub fn level_slot(key: &Hash) -> u16 {
43 (u16::from(key[0]) << 4) | u16::from(key[1] >> 4)
44}
45
46pub fn level_range(slot: u16) -> (Hash, Hash) {
48 let mut k = ZERO;
49 k[0] = (slot >> 4) as u8;
50 k[1] = ((slot & 0x0F) as u8) << 4;
51 range_of(&k, LEVEL_DEPTH)
52}
53
54const INNER_PREFIX: [u8; 4] = [b'M', b'I', b'N', 0];
56
57fn err(e: fjall::Error) -> String {
58 e.to_string()
59}
60
61pub(crate) fn nibble(key: &Hash, depth: usize) -> u8 {
62 let b = key[depth / 2];
63 if depth.is_multiple_of(2) {
64 b >> 4
65 } else {
66 b & 0x0F
67 }
68}
69
70fn with_nibble(prefix: &Hash, depth: usize, n: u8) -> Hash {
73 let mut k = *prefix;
74 let i = depth / 2;
75 if depth.is_multiple_of(2) {
76 k[i] = n << 4;
77 } else {
78 k[i] = (k[i] & 0xF0) | n;
79 }
80 k
81}
82
83pub(crate) fn range_of(prefix: &Hash, depth: usize) -> (Hash, Hash) {
85 let (mut lo, mut hi) = (*prefix, *prefix);
86 for d in depth..64 {
87 let i = d / 2;
88 if d.is_multiple_of(2) {
89 lo[i] &= 0x0F;
90 hi[i] |= 0xF0;
91 } else {
92 lo[i] &= 0xF0;
93 hi[i] |= 0x0F;
94 }
95 }
96 (lo, hi)
97}
98
99pub(crate) fn node_key(prefix: &Hash, depth: usize) -> Vec<u8> {
101 let (lo, _) = range_of(prefix, depth);
102 let mut k = Vec::with_capacity(1 + depth.div_ceil(2));
103 k.push(depth as u8);
104 k.extend_from_slice(&lo[..depth.div_ceil(2)]);
105 k
106}
107
108pub fn inner_hash(children: &[Hash; 16]) -> Hash {
109 if children.iter().all(|c| *c == ZERO) {
110 return ZERO;
111 }
112 let mut data = Vec::with_capacity(4 + 16 * 32);
113 data.extend_from_slice(&INNER_PREFIX);
114 for c in children {
115 data.extend_from_slice(c);
116 }
117 sha512_half(&data)
118}
119
120pub(crate) fn decode_node(v: &[u8]) -> Option<[Hash; 16]> {
121 let mut out = [ZERO; 16];
122 if v.len() == 16 * 32 {
123 for (i, c) in out.iter_mut().enumerate() {
124 c.copy_from_slice(&v[i * 32..(i + 1) * 32]);
125 }
126 return Some(out);
127 }
128 let mask = u16::from_be_bytes([*v.first()?, *v.get(1)?]);
129 if v.len() != 2 + 32 * mask.count_ones() as usize {
130 return None;
131 }
132 let mut at = 2;
133 for (i, c) in out.iter_mut().enumerate() {
134 if mask & (0x8000 >> i) != 0 {
135 c.copy_from_slice(&v[at..at + 32]);
136 at += 32;
137 }
138 }
139 Some(out)
140}
141
142fn encode_node(children: &[Hash; 16]) -> Vec<u8> {
143 let mut mask = 0u16;
144 let mut out = vec![0, 0];
145 for (i, c) in children.iter().enumerate() {
146 if *c != ZERO {
147 mask |= 0x8000 >> i;
148 out.extend_from_slice(c);
149 }
150 }
151 out[..2].copy_from_slice(&mask.to_be_bytes());
152 out
153}
154
155pub(crate) struct SubTree {
158 prefix: Hash,
159 depth: usize,
160 leaves: BTreeMap<Hash, Hash>,
161 inner: HashMap<(usize, Hash), Hash>,
162 deepest: usize,
164}
165
166impl SubTree {
167 pub(crate) fn new(prefix: Hash, depth: usize) -> Self {
168 Self {
169 prefix,
170 depth,
171 leaves: BTreeMap::new(),
172 inner: HashMap::new(),
173 deepest: depth,
174 }
175 }
176
177 pub(crate) fn set(&mut self, key: Hash, leaf: Option<Hash>) {
179 match leaf {
180 Some(h) => self.leaves.insert(key, h),
181 None => self.leaves.remove(&key),
182 };
183 if self.inner.is_empty() {
184 return;
185 }
186 let mut prefix = range_of(&key, self.depth).0;
189 for d in self.depth..=self.deepest {
190 self.inner.remove(&(d, prefix));
191 prefix = with_nibble(&prefix, d, nibble(&key, d));
192 }
193 }
194
195 pub(crate) fn len(&self) -> usize {
196 self.leaves.len()
197 }
198
199 pub(crate) fn leaves(&self) -> impl Iterator<Item = (&Hash, &Hash)> {
201 self.leaves.iter()
202 }
203
204 pub(crate) fn hash(&mut self) -> Hash {
207 self.node(self.prefix, self.depth)
208 }
209
210 fn node(&mut self, prefix: Hash, depth: usize) -> Hash {
211 let (lo, hi) = range_of(&prefix, depth);
212 let mut under = self.leaves.range(lo..=hi);
213 match (under.next(), under.next()) {
214 (None, _) => return ZERO,
215 (Some((_, h)), None) => return *h,
216 _ => {}
217 }
218 if let Some(h) = self.inner.get(&(depth, lo)) {
219 return *h;
220 }
221 let mut children = [ZERO; 16];
222 for (c, child) in children.iter_mut().enumerate() {
223 *child = self.node(with_nibble(&lo, depth, c as u8), depth + 1);
224 }
225 let h = inner_hash(&children);
226 self.inner.insert((depth, lo), h);
227 self.deepest = self.deepest.max(depth);
228 h
229 }
230}
231
232pub(crate) fn root_of_levels(hashes: &[Hash], counts: &[u32]) -> Hash {
235 fn go(hashes: &[Hash], counts: &[u32], depth: usize) -> Hash {
236 if depth == LEVEL_DEPTH {
237 return hashes[0];
238 }
239 if depth > 0 {
240 match counts.iter().map(|c| u64::from(*c)).sum::<u64>() {
241 0 => return ZERO,
242 1 => return hashes[counts.iter().position(|c| *c == 1).unwrap_or(0)],
243 _ => {}
244 }
245 }
246 let step = hashes.len() / 16;
247 let mut children = [ZERO; 16];
248 for (c, child) in children.iter_mut().enumerate() {
249 let r = c * step..(c + 1) * step;
250 *child = go(&hashes[r.clone()], &counts[r], depth + 1);
251 }
252 inner_hash(&children)
253 }
254 go(hashes, counts, 0)
255}
256
257pub type LeafChanges = BTreeMap<Hash, Option<Hash>>;
259
260pub fn state_leaf_hash_of(data: &[u8], key: &Hash) -> Option<Hash> {
262 (!data.is_empty()).then(|| state_leaf_hash(data, key))
263}
264
265pub fn leaf_changes(changes: &[crate::ledger::StateChange]) -> LeafChanges {
267 changes
268 .iter()
269 .map(|c| match c.change {
270 crate::ledger::Change::Deleted => (c.key, None),
271 _ => (c.key, Some(state_leaf_hash(&c.data, &c.key))),
272 })
273 .collect()
274}
275
276#[derive(Clone)]
277pub struct StateTree {
278 pub live: Keyspace,
279 pub tree: Keyspace,
280}
281
282impl std::fmt::Debug for StateTree {
283 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
284 f.debug_struct("StateTree").finish_non_exhaustive()
285 }
286}
287
288struct Round<'a> {
291 t: &'a StateTree,
292 changes: &'a LeafChanges,
293 written: HashMap<Vec<u8>, Option<[Hash; 16]>>,
294 level: BTreeMap<u16, Hash>,
296}
297
298impl Round<'_> {
299 fn count(&self, prefix: &Hash, depth: usize) -> Result<(usize, Option<Hash>), String> {
302 let (lo, hi) = range_of(prefix, depth);
303 let mut found: Vec<Hash> = Vec::with_capacity(2);
304 let mut single: Option<Hash> = None;
305 for (k, v) in self.changes.range(lo..=hi) {
307 if let Some(h) = v {
308 found.push(*k);
309 single = Some(*h);
310 if found.len() >= 2 {
311 return Ok((2, None));
312 }
313 }
314 }
315 for g in self.t.live.range(lo..=hi) {
317 let (k, v) = g.into_inner().map_err(err)?;
318 let key: Hash = k[..].try_into().map_err(|_| "live key")?;
319 if self.changes.contains_key(&key) {
320 continue;
321 }
322 found.push(key);
323 single = <Hash>::try_from(&v[..]).ok();
324 if found.len() >= 2 {
325 return Ok((2, None));
326 }
327 }
328 Ok((found.len(), if found.len() == 1 { single } else { None }))
329 }
330
331 fn node(&mut self, key: &[u8]) -> Result<Option<[Hash; 16]>, String> {
332 if let Some(n) = self.written.get(key) {
333 return Ok(*n);
334 }
335 Ok(self
336 .t
337 .tree
338 .get(key)
339 .map_err(err)?
340 .and_then(|v| decode_node(&v)))
341 }
342
343 fn purge(&mut self, prefix: &Hash, depth: usize) -> Result<(), String> {
346 let nk = node_key(prefix, depth);
347 if self.node(&nk)?.is_none() {
348 return Ok(());
349 }
350 self.written.insert(nk, None);
351 for c in 0..16u8 {
352 let sub = with_nibble(prefix, depth, c);
353 let (lo, hi) = range_of(&sub, depth + 1);
354 if self.changes.range(lo..=hi).next().is_some() {
355 self.purge(&sub, depth + 1)?;
356 }
357 }
358 Ok(())
359 }
360
361 fn subtree(&mut self, prefix: &Hash, depth: usize, touched: bool) -> Result<Hash, String> {
363 let h = self.subtree_at(prefix, depth, touched)?;
364 if depth == LEVEL_DEPTH && touched {
365 self.level.insert(level_slot(prefix), h);
366 }
367 Ok(h)
368 }
369
370 fn subtree_at(&mut self, prefix: &Hash, depth: usize, touched: bool) -> Result<Hash, String> {
371 let nk = node_key(prefix, depth);
372 if depth > 0 {
373 let (n, single) = self.count(prefix, depth)?;
374 if n < 2 {
375 if touched {
379 self.purge(prefix, depth)?;
380 }
381 return Ok(if n == 0 { ZERO } else { single.unwrap_or(ZERO) });
382 }
383 }
384 let old = self.node(&nk)?;
385 if !touched && let Some(o) = old {
386 return Ok(inner_hash(&o));
387 }
388 let (lo, hi) = range_of(prefix, depth);
389 let mut children = [ZERO; 16];
390 for (c, child) in children.iter_mut().enumerate() {
391 let sub = with_nibble(prefix, depth, c as u8);
392 let (slo, shi) = range_of(&sub, depth + 1);
393 let sub_touched = self
394 .changes
395 .range(slo.max(lo)..=shi.min(hi))
396 .next()
397 .is_some();
398 *child = match old {
399 Some(o) if !sub_touched => o[c],
400 _ => self.subtree(&sub, depth + 1, sub_touched)?,
401 };
402 }
403 self.written.insert(nk, Some(children));
404 Ok(inner_hash(&children))
405 }
406}
407
408impl StateTree {
409 pub fn update(
411 &self,
412 changes: &LeafChanges,
413 batch: &mut OwnedWriteBatch,
414 ) -> Result<Hash, String> {
415 Ok(self.update_levels(changes, batch, false)?.0)
416 }
417
418 pub fn update_levels(
423 &self,
424 changes: &LeafChanges,
425 batch: &mut OwnedWriteBatch,
426 full: bool,
427 ) -> Result<(Hash, BTreeMap<u16, Hash>), String> {
428 let mut r = Round {
429 t: self,
430 changes,
431 written: HashMap::new(),
432 level: BTreeMap::new(),
433 };
434 let root = r.subtree(&ZERO, 0, !changes.is_empty())?;
435 let mut level = std::mem::take(&mut r.level);
436 if full {
437 for top in 0..=u8::MAX {
438 let mut prefix = ZERO;
439 prefix[0] = top;
440 if let Some(children) = r.node(&node_key(&prefix, LEVEL_DEPTH - 1))? {
441 for (c, h) in children.iter().enumerate() {
442 level.insert((u16::from(top) << 4) | c as u16, *h);
443 }
444 }
445 }
446 }
447 for (k, v) in r.written {
448 match v {
449 Some(children) => batch.insert(&self.tree, k, encode_node(&children)),
450 None => batch.remove(&self.tree, k),
451 }
452 }
453 for (k, v) in changes {
454 match v {
455 Some(h) => batch.insert(&self.live, *k, *h),
456 None => batch.remove(&self.live, *k),
457 }
458 }
459 Ok((root, level))
460 }
461
462 pub fn levels(&self) -> Result<BTreeMap<u16, Hash>, String> {
465 let mut level = BTreeMap::new();
466 for top in 0..=u8::MAX {
467 let mut prefix = ZERO;
468 prefix[0] = top;
469 if let Some(children) = self
470 .tree
471 .get(node_key(&prefix, LEVEL_DEPTH - 1))
472 .map_err(err)?
473 .and_then(|v| decode_node(&v))
474 {
475 for (c, h) in children.iter().enumerate() {
476 level.insert((u16::from(top) << 4) | c as u16, *h);
477 }
478 }
479 }
480 Ok(level)
481 }
482
483 pub fn root(&self) -> Result<Hash, String> {
485 Ok(self
486 .tree
487 .get(node_key(&ZERO, 0))
488 .map_err(err)?
489 .and_then(|v| decode_node(&v))
490 .map_or(ZERO, |c| inner_hash(&c)))
491 }
492
493 pub fn build(
496 &self,
497 leaves: &[(Hash, Hash)],
498 mut emit: impl FnMut(Vec<u8>, Vec<u8>) -> Result<(), String>,
499 ) -> Result<Hash, String> {
500 fn go(
501 leaves: &[(Hash, Hash)],
502 prefix: &Hash,
503 depth: usize,
504 emit: &mut dyn FnMut(Vec<u8>, Vec<u8>) -> Result<(), String>,
505 ) -> Result<Hash, String> {
506 if depth > 0 {
507 match leaves {
508 [] => return Ok(ZERO),
509 [(_, h)] => return Ok(*h),
510 _ => {}
511 }
512 }
513 let mut children = [ZERO; 16];
514 let mut start = 0;
515 while start < leaves.len() {
516 let n = nibble(&leaves[start].0, depth);
517 let mut end = start + 1;
518 while end < leaves.len() && nibble(&leaves[end].0, depth) == n {
519 end += 1;
520 }
521 let sub = with_nibble(prefix, depth, n);
522 children[n as usize] = go(&leaves[start..end], &sub, depth + 1, emit)?;
523 start = end;
524 }
525 emit(node_key(prefix, depth), encode_node(&children))?;
526 Ok(inner_hash(&children))
527 }
528 go(leaves, &ZERO, 0, &mut emit)
529 }
530}
531
532#[cfg(test)]
533mod tests {
534 use super::*;
535 use fjall::{Database, KeyspaceCreateOptions};
536 use witness_core::shamap::root;
537
538 fn key(i: u32) -> Hash {
539 let mut k = sha512_half(&i.to_be_bytes());
541 if i.is_multiple_of(7) {
542 k[..3].copy_from_slice(&[0xAB, 0xCD, 0xEF]);
543 }
544 k
545 }
546
547 #[test]
548 fn subtrees_in_memory_give_the_root() {
549 let mut state: BTreeMap<Hash, Hash> = BTreeMap::new();
551 let mut slots: Vec<SubTree> = (0..LEVEL_SLOTS as u16)
552 .map(|s| SubTree::new(level_range(s).0, LEVEL_DEPTH))
553 .collect();
554 for round in 0..30u32 {
555 for j in 0..40u32 {
556 let i = (round * 53 + j * 17) % (if round < 10 { 60 } else { 3000 });
557 let k = key(i);
558 let v = (j % 5 != 0).then(|| sha512_half(&[i as u8, round as u8]));
559 match v {
560 Some(h) => state.insert(k, h),
561 None => state.remove(&k),
562 };
563 slots[level_slot(&k) as usize].set(k, v);
564 }
565 let hashes: Vec<Hash> = slots.iter_mut().map(SubTree::hash).collect();
566 let counts: Vec<u32> = slots.iter().map(|s| s.len() as u32).collect();
567 let want = root(&state.iter().map(|(k, v)| (*k, *v)).collect::<Vec<_>>());
568 assert_eq!(root_of_levels(&hashes, &counts), want, "round {round}");
569 }
570 }
571
572 #[test]
573 fn node_formats_roundtrip() {
574 let mut c = [ZERO; 16];
575 c[0] = [1; 32];
576 c[15] = [2; 32];
577 let sparse = encode_node(&c);
578 assert_eq!(sparse.len(), 2 + 64);
579 assert_eq!(decode_node(&sparse), Some(c));
580 let dense: Vec<u8> = c.iter().flat_map(|h| h.iter().copied()).collect();
581 assert_eq!(decode_node(&dense), Some(c));
582 assert_eq!(decode_node(&sparse[..10]), None);
583 }
584
585 #[test]
586 fn incremental_root_matches_full_rebuild() {
587 let dir = tempfile::tempdir().unwrap();
588 let db = Database::builder(dir.path()).open().unwrap();
589 let t = StateTree {
590 live: db.keyspace("live", KeyspaceCreateOptions::default).unwrap(),
591 tree: db.keyspace("tree", KeyspaceCreateOptions::default).unwrap(),
592 };
593 let mut state: BTreeMap<Hash, Hash> = (0..300)
595 .map(|i| (key(i), sha512_half(&[i as u8, 1])))
596 .collect();
597 let leaves: Vec<_> = state.iter().map(|(k, v)| (*k, *v)).collect();
598 let mut b = db.batch();
599 for (k, v) in &leaves {
600 b.insert(&t.live, *k, *v);
601 }
602 let built = t
603 .build(&leaves, |k, v| {
604 b.insert(&t.tree, k, v);
605 Ok(())
606 })
607 .unwrap();
608 b.commit().unwrap();
609 assert_eq!(built, root(&leaves));
610 assert_eq!(t.root().unwrap(), built);
611
612 for round in 0..40u32 {
614 let mut changes = LeafChanges::new();
615 for j in 0..15u32 {
616 let i = (round * 37 + j * 11) % 400;
617 let k = key(i);
618 let v = if (round + j) % 4 == 0 {
619 None
620 } else {
621 Some(sha512_half(&[i as u8, round as u8, 2]))
622 };
623 changes.insert(k, v);
624 }
625 for (k, v) in &changes {
626 match v {
627 Some(h) => {
628 state.insert(*k, *h);
629 }
630 None => {
631 state.remove(k);
632 }
633 }
634 }
635 let mut b = db.batch();
636 let got = t.update(&changes, &mut b).unwrap();
637 b.commit().unwrap();
638 let want = root(&state.iter().map(|(k, v)| (*k, *v)).collect::<Vec<_>>());
639 assert_eq!(got, want, "ledger {round}");
640 assert_eq!(t.root().unwrap(), want);
641 }
642
643 let keys: Vec<Hash> = state.keys().copied().collect();
645 let mut changes: LeafChanges = keys[1..].iter().map(|k| (*k, None)).collect();
646 let mut b = db.batch();
647 let got = t.update(&changes, &mut b).unwrap();
648 b.commit().unwrap();
649 assert_eq!(got, root(&[(keys[0], state[&keys[0]])]));
650 let refill: LeafChanges = keys[1..]
652 .iter()
653 .map(|k| (*k, Some(sha512_half(k))))
654 .collect();
655 let mut b = db.batch();
656 let got = t.update(&refill, &mut b).unwrap();
657 b.commit().unwrap();
658 let mut want: Vec<(Hash, Hash)> = keys[1..].iter().map(|k| (*k, sha512_half(k))).collect();
659 want.push((keys[0], state[&keys[0]]));
660 assert_eq!(got, root(&want));
661
662 changes = keys.iter().map(|k| (*k, None)).collect();
663 let mut b = db.batch();
664 assert_eq!(t.update(&changes, &mut b).unwrap(), ZERO);
665 }
666}