referrerpolicy=no-referrer-when-downgrade

cumulus_primitives_spec_messaging/streams_root/
mod.rs

1// Copyright (C) Parity Technologies (UK) Ltd.
2// This file is part of Cumulus.
3// SPDX-License-Identifier: Apache-2.0
4
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// 	http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
17//! `StreamsRoot`: the sender's stream commitment.
18//!
19//! Each block that sends commits one hash, the root of a keyed binary Patricia trie over
20//! `(StreamId, current stream root)` for every active stream. The relay records it as the sender's
21//! `Provides`, and a receiver proves the streams it consumed against it, without a sender-state
22//! proof.
23//!
24//! The key drives the walk, so a proof cannot be moved to another stream
25//! ([`streams_root_from_proof`]).
26//!
27//! Roles: the sender builds the root ([`streams_root`]) and its node serves proofs
28//! ([`gen_stream_proof`]), checking its own header digest ([`read_streams_root`]); a receiver's
29//! lift walks a proof up to the committed root ([`streams_root_from_proof`]).
30
31use alloc::{collections::BTreeMap, vec::Vec};
32use codec::{Decode, DecodeAll, DecodeWithMemTracking, Encode, MaxEncodedLen};
33use polkadot_core_primitives::Hash;
34use sp_core::ConstU32;
35use sp_runtime::{traits::Hash as HashT, BoundedVec, Digest, DigestItem};
36
37use crate::{
38	stream::StreamId, SpecHasher, SPMS_ENGINE_ID, STREAM_ID_LEN, TREE_INNER_TAG, TREE_LEAF_TAG,
39};
40
41mod cache;
42
43pub use cache::{
44	gen_stream_proof_from_nodes, update_tree_leaf, InnerNode, NodeKey, NodeLookup, NodeStore,
45	StreamsTree, TreeChild, TreeError, TreeRootEntry,
46};
47
48/// Bit width of a `StreamId` key (the Patricia trie's maximum depth).
49const KEY_BITS: usize = STREAM_ID_LEN * 8;
50
51/// The sender's per-block stream commitment root. Defined relay-side and re-exported here.
52pub use polkadot_primitives::StreamsRoot;
53
54/// One step of a trie walk. The branch direction is not stored.
55#[derive(
56	Clone,
57	Copy,
58	Encode,
59	Decode,
60	DecodeWithMemTracking,
61	MaxEncodedLen,
62	PartialEq,
63	Eq,
64	Debug,
65	scale_info::TypeInfo,
66)]
67pub struct TreeStep {
68	/// Key-bit index this node branches on, `0..KEY_BITS` with `0` the MSB. Part of the inner-node
69	/// hash; the proven key's bit here gives the direction.
70	pub split_bit: u8,
71	pub sibling: Hash,
72}
73
74/// A membership proof that `(stream, stream_root)` is committed under a `StreamsRoot`. Served by
75/// the sender, verified by the receiver.
76#[derive(
77	Clone,
78	Encode,
79	Decode,
80	DecodeWithMemTracking,
81	MaxEncodedLen,
82	PartialEq,
83	Eq,
84	Debug,
85	scale_info::TypeInfo,
86)]
87pub struct StreamProof {
88	/// Branch steps leaf to root, split bits strictly decreasing. Empty for a single-stream tree.
89	/// Bounded at the trie depth, so an over-long proof is rejected at decode.
90	pub steps: BoundedVec<TreeStep, ConstU32<{ KEY_BITS as u32 }>>,
91}
92
93/// Bit `i` of an 8-byte key, `0` the MSB of byte 0.
94fn bit(key: &[u8; STREAM_ID_LEN], i: usize) -> bool {
95	(key[i >> 3] >> (7 - (i & 7))) & 1 == 1
96}
97
98/// First bit index (from the MSB, 0..64) at which two keys differ; returns 64 if identical.
99fn first_diverging_bit(a: &[u8; STREAM_ID_LEN], b: &[u8; STREAM_ID_LEN]) -> usize {
100	(u64::from_be_bytes(*a) ^ u64::from_be_bytes(*b)).leading_zeros() as usize
101}
102
103fn hash_leaf(key: &[u8; STREAM_ID_LEN], stream_root: &Hash) -> Hash {
104	let mut pre = [0u8; 1 + STREAM_ID_LEN + 32];
105	pre[0] = TREE_LEAF_TAG;
106	pre[1..1 + STREAM_ID_LEN].copy_from_slice(key);
107	pre[1 + STREAM_ID_LEN..].copy_from_slice(stream_root.as_bytes());
108	<SpecHasher as HashT>::hash(&pre)
109}
110
111fn hash_inner(split_bit: u8, left: &Hash, right: &Hash) -> Hash {
112	let mut pre = [0u8; 1 + 1 + 32 + 32];
113	pre[0] = TREE_INNER_TAG;
114	pre[1] = split_bit;
115	pre[2..34].copy_from_slice(left.as_bytes());
116	pre[34..].copy_from_slice(right.as_bytes());
117	<SpecHasher as HashT>::hash(&pre)
118}
119
120/// Split a key-sorted slice at its top-level branch: the bit where its first and last keys diverge,
121/// with all `bit == 0` keys before all `bit == 1` keys. Both sides are non-empty. Callers guarantee
122/// `entries.len() >= 2` and distinct keys.
123fn split<'a>(
124	entries: &'a [([u8; STREAM_ID_LEN], Hash)],
125) -> (usize, &'a [([u8; STREAM_ID_LEN], Hash)], &'a [([u8; STREAM_ID_LEN], Hash)]) {
126	let split_bit = first_diverging_bit(&entries[0].0, &entries[entries.len() - 1].0);
127	let p = entries.partition_point(|(k, _)| !bit(k, split_bit));
128	let (left, right) = entries.split_at(p);
129	(split_bit, left, right)
130}
131
132/// Trie root over a key-sorted, non-empty slice.
133fn node_hash(entries: &[([u8; STREAM_ID_LEN], Hash)]) -> Hash {
134	if let [(key, root)] = entries {
135		return hash_leaf(key, root);
136	}
137	let (split_bit, left, right) = split(entries);
138	hash_inner(split_bit as u8, &node_hash(left), &node_hash(right))
139}
140
141/// Encoded keys in trie order.
142///
143/// The trie splits on bytes, so sort by them rather than rely on `Ord`. Unsorted input would leave
144/// one side of `split` empty and make `prove` recurse on its own slice.
145fn keyed(entries: &BTreeMap<StreamId, Hash>) -> Vec<([u8; STREAM_ID_LEN], Hash)> {
146	let mut keyed: Vec<_> =
147		entries.iter().map(|(stream, root)| (stream.to_bytes(), *root)).collect();
148	keyed.sort_unstable_by_key(|(key, _)| *key);
149	keyed
150}
151
152/// The `StreamsRoot` over `(stream, stream_root)` entries; `None` with no active streams. Sender
153/// side. Takes a `BTreeMap` so keys are unique; duplicates would reach `first_diverging_bit` with
154/// identical keys.
155///
156/// For incremental updates in `O(log S)` without rebuilding from scratch in `O(S)`, see
157/// [`update_tree_leaf`] and [`StreamsTree`].
158pub fn streams_root(entries: &BTreeMap<StreamId, Hash>) -> Option<StreamsRoot> {
159	let entries = keyed(entries);
160	if entries.is_empty() {
161		return None;
162	}
163	Some(StreamsRoot(node_hash(&entries)))
164}
165
166/// Walk key-sorted `entries` toward `key`, pushing each branch step root-first, and return the
167/// subtree's root. `key` must be present.
168fn prove(
169	entries: &[([u8; STREAM_ID_LEN], Hash)],
170	key: &[u8; STREAM_ID_LEN],
171	steps: &mut Vec<TreeStep>,
172) -> Hash {
173	if let [(k, root)] = entries {
174		return hash_leaf(k, root);
175	}
176	let (split_bit, left, right) = split(entries);
177	let target_right = bit(key, split_bit);
178	let (sibling, descend) =
179		if target_right { (node_hash(left), right) } else { (node_hash(right), left) };
180	steps.push(TreeStep { split_bit: split_bit as u8, sibling });
181	let child = prove(descend, key, steps);
182	if target_right {
183		hash_inner(split_bit as u8, &sibling, &child)
184	} else {
185		hash_inner(split_bit as u8, &child, &sibling)
186	}
187}
188
189/// Build the trie over `entries` and return `(StreamsRoot, proof)` for `stream`, or `None` if
190/// absent. Sender side.
191pub fn gen_stream_proof(
192	entries: &BTreeMap<StreamId, Hash>,
193	stream: StreamId,
194) -> Option<(StreamsRoot, StreamProof)> {
195	if !entries.contains_key(&stream) {
196		return None;
197	}
198	let entries = keyed(entries);
199	let key = stream.to_bytes();
200	let mut steps = Vec::new();
201	let root = prove(&entries, &key, &mut steps);
202	// `prove` pushes root-first; the wire order is leaf-to-root.
203	steps.reverse();
204	let steps = BoundedVec::try_from(steps).expect("trie depth <= KEY_BITS; qed");
205	Some((StreamsRoot(root), StreamProof { steps }))
206}
207
208/// Read the sender's `StreamsRoot` from its header digest. `None` if absent or not exactly what the
209/// sender deposits: one `SPMS` item with a 32-byte payload. Foreign readers must agree on
210/// validity, so nothing else is accepted.
211pub fn read_streams_root(digest: &Digest) -> Option<StreamsRoot> {
212	let mut items = digest.logs().iter().filter_map(|item| match item {
213		DigestItem::Consensus(id, payload) if *id == SPMS_ENGINE_ID => Some(payload),
214		_ => None,
215	});
216	let payload = items.next()?;
217	if items.next().is_some() {
218		return None;
219	}
220	StreamsRoot::decode_all(&mut &payload[..]).ok()
221}
222
223/// Fold a membership proof for `(stream, stream_root)` up to the `StreamsRoot` it implies, or
224/// `None` on a malformed step. Callers compare the root themselves (the requires-lift records it,
225/// the fetch checks it against `under`). Each branch direction is `stream`'s bit at `split_bit`, so
226/// a proof built for another stream yields a different root.
227pub fn streams_root_from_proof(
228	stream: StreamId,
229	stream_root: Hash,
230	membership: &StreamProof,
231) -> Option<StreamsRoot> {
232	let key = stream.to_bytes();
233	let mut node = hash_leaf(&key, &stream_root);
234	// Steps are leaf-to-root with strictly decreasing split bits; anything else is rejected.
235	// Uniqueness rests on the key-in-leaf and bit-in-inner commitments, not on this rule. The
236	// length bound is in the type.
237	let mut prev: Option<u8> = None;
238	for step in membership.steps.iter() {
239		let split_bit = step.split_bit as usize;
240		// An out-of-range branch would index the key out of bounds.
241		if split_bit >= KEY_BITS {
242			return None;
243		}
244		if prev.is_some_and(|p| step.split_bit >= p) {
245			return None;
246		}
247		prev = Some(step.split_bit);
248		node = if bit(&key, split_bit) {
249			hash_inner(step.split_bit, &step.sibling, &node)
250		} else {
251			hash_inner(step.split_bit, &node, &step.sibling)
252		};
253	}
254	Some(StreamsRoot(node))
255}
256
257#[cfg(test)]
258mod tests {
259	use super::*;
260	use crate::{test_utils::ch, PrivateKind};
261	use sp_core::H256;
262
263	fn root(b: u8) -> Hash {
264		H256::repeat_byte(b)
265	}
266
267	/// Whether `stream_root` is committed for `stream` under `streams_root`.
268	fn verify_stream_membership(
269		streams_root: StreamsRoot,
270		stream: StreamId,
271		stream_root: Hash,
272		membership: &StreamProof,
273	) -> bool {
274		streams_root_from_proof(stream, stream_root, membership) == Some(streams_root)
275	}
276	fn entries() -> BTreeMap<StreamId, Hash> {
277		// inserted out of order; the map canonicalizes
278		BTreeMap::from([
279			(ch(4000), root(0xB)),
280			(ch(2000), root(0xA)),
281			(ch(3000), root(0xC)),
282			(StreamId::Ack { recipient: 2000.into(), domain: 0, num: 0 }, root(0xD)),
283			(StreamId::Broadcast { domain: 1, subdomain: 0, num: 7 }, root(0xE)),
284		])
285	}
286
287	#[test]
288	fn streams_root_frozen_vector() {
289		// Frozen vector. Any change to the trie encoding (tags, `split_bit`, ordering, key binding)
290		// is a consensus break.
291		assert_eq!(
292			streams_root(&entries()).unwrap(),
293			StreamsRoot(H256(hex_literal::hex!(
294				"12de235fb6d96933d6ba770efe16f891c87fb8a88a75e37a384b88ba11dee0dc"
295			))),
296		);
297	}
298
299	#[test]
300	fn round_trip_membership_verifies() {
301		for (stream, sr) in entries() {
302			let (r, proof) = gen_stream_proof(&entries(), stream).unwrap();
303			assert_eq!(Some(r), streams_root(&entries()));
304			assert!(verify_stream_membership(r, stream, sr, &proof), "{stream:?} must verify");
305		}
306	}
307
308	#[test]
309	fn wrong_root_or_stream_or_value_fails() {
310		let (r, proof) = gen_stream_proof(&entries(), ch(3000)).unwrap();
311		// wrong stream_root for the (correct) stream
312		assert!(!verify_stream_membership(r, ch(3000), root(0xFF), &proof));
313		// right value/proof but claimed for a different stream (key binding must reject)
314		assert!(!verify_stream_membership(r, ch(2000), root(0xC), &proof));
315		// wrong streams root
316		assert!(!verify_stream_membership(StreamsRoot(root(0x00)), ch(3000), root(0xC), &proof));
317	}
318
319	#[test]
320	fn proof_is_not_transferable_between_streams() {
321		// A proof for one stream must not verify for another, even with that stream's own value.
322		let (r, proof) = gen_stream_proof(&entries(), ch(4000)).unwrap();
323		for (other, other_root) in entries() {
324			if other == ch(4000) {
325				continue;
326			}
327			assert!(
328				!verify_stream_membership(r, other, other_root, &proof),
329				"proof for ch(4000) must not verify as {other:?}"
330			);
331		}
332	}
333
334	#[test]
335	fn order_independent_root() {
336		// Insertion order cannot affect the root.
337		let reversed: BTreeMap<_, _> = entries().into_iter().rev().collect();
338		assert_eq!(streams_root(&entries()), streams_root(&reversed));
339	}
340
341	#[test]
342	fn single_stream_tree_has_empty_proof() {
343		let one = BTreeMap::from([(ch(2000), root(0xA))]);
344		let (r, proof) = gen_stream_proof(&one, ch(2000)).unwrap();
345		assert!(proof.steps.is_empty());
346		assert_eq!(Some(r), streams_root(&one));
347		assert!(verify_stream_membership(r, ch(2000), root(0xA), &proof));
348	}
349
350	#[test]
351	fn proof_is_logarithmic() {
352		// 64 clustered channels: proof length is O(log S), not the 64-bit key width.
353		let many: BTreeMap<_, _> = (0..64u32).map(|i| (ch(2000 + i), root(i as u8))).collect();
354		let (_r, proof) = gen_stream_proof(&many, ch(2000 + 33)).unwrap();
355		assert!(proof.steps.len() <= 7, "log2(64) = 6-ish, got {}", proof.steps.len());
356	}
357
358	#[test]
359	fn a_full_depth_proof_round_trips_and_verifies() {
360		// A neighbour at every bit gives `stream` the deepest possible path.
361		let stream = StreamId::Private { kind: PrivateKind::new(0x80).unwrap(), body: [0; 7] };
362		let mut map = BTreeMap::from([(stream, root(1))]);
363		for bit in 0..KEY_BITS {
364			let mut key = stream.to_bytes();
365			key[bit / 8] ^= 0x80 >> (bit % 8);
366			map.insert(StreamId::from_bytes(key).unwrap(), root(2));
367		}
368
369		let tree = StreamsTree::from_entries(&map);
370		let (r, proof) = tree.gen_stream_proof(stream).unwrap();
371		assert_eq!(proof.steps.len(), KEY_BITS);
372		let decoded = StreamProof::decode_all(&mut &proof.encode()[..]).unwrap();
373		assert!(verify_stream_membership(r, stream, root(1), &decoded));
374		assert_eq!(Some(r), streams_root(&map));
375	}
376
377	#[test]
378	fn absent_stream_has_no_proof() {
379		assert!(gen_stream_proof(&entries(), ch(9999)).is_none());
380	}
381
382	#[test]
383	fn out_of_range_split_bit_is_rejected() {
384		let (r, mut proof) = gen_stream_proof(&entries(), ch(3000)).unwrap();
385		// Splice the bogus step in first (largest bit) so the range check, not the order check,
386		// rejects it.
387		let mut steps = vec![TreeStep { split_bit: 64, sibling: root(0) }];
388		steps.extend(proof.steps.iter().copied());
389		proof.steps = steps.try_into().unwrap();
390		assert!(!verify_stream_membership(r, ch(3000), root(0xC), &proof));
391	}
392
393	#[test]
394	fn over_long_proof_is_rejected_at_decode() {
395		// A valid proof never exceeds the trie depth, so longer input fails at decode.
396		let raw = vec![TreeStep { split_bit: 0, sibling: root(0) }; KEY_BITS + 1].encode();
397		assert!(StreamProof::decode(&mut &raw[..]).is_err());
398	}
399
400	#[test]
401	fn non_decreasing_step_order_is_rejected() {
402		// A reversed sequence is rejected even though every hash in it is genuine.
403		let (r, proof) = gen_stream_proof(&entries(), ch(3000)).unwrap();
404		assert!(proof.steps.len() >= 2, "need a multi-step proof");
405		let reversed: Vec<TreeStep> = proof.steps.iter().rev().copied().collect();
406		let bad = StreamProof { steps: reversed.try_into().unwrap() };
407		assert!(!verify_stream_membership(r, ch(3000), root(0xC), &bad));
408	}
409
410	#[test]
411	fn read_streams_root_extracts_digest() {
412		let r = streams_root(&entries()).unwrap();
413		let digest = Digest {
414			logs: vec![
415				DigestItem::Other(vec![1, 2, 3]),
416				DigestItem::Consensus(SPMS_ENGINE_ID, r.encode()),
417			],
418		};
419		assert_eq!(read_streams_root(&digest), Some(r));
420		assert_eq!(read_streams_root(&Digest { logs: vec![] }), None);
421	}
422
423	#[test]
424	fn read_streams_root_accepts_only_the_canonical_digest() {
425		let r = streams_root(&entries()).unwrap();
426		let spms = |payload: Vec<u8>| DigestItem::Consensus(SPMS_ENGINE_ID, payload);
427		let digest = |logs: Vec<DigestItem>| Digest { logs };
428
429		// Exactly 32 bytes.
430		let mut trailing = r.encode();
431		trailing.push(0);
432		assert_eq!(read_streams_root(&digest(vec![spms(trailing)])), None);
433		assert_eq!(read_streams_root(&digest(vec![spms(r.encode()[..31].to_vec())])), None);
434
435		// Exactly one item. A malformed first item is not skipped for a later one.
436		let other = StreamsRoot(Hash::repeat_byte(0xAB));
437		assert_eq!(read_streams_root(&digest(vec![spms(r.encode()), spms(other.encode())])), None);
438		assert_eq!(read_streams_root(&digest(vec![spms(vec![0; 3]), spms(r.encode())])), None);
439
440		// Other engines' items are not counted against it.
441		let foreign = DigestItem::Consensus(*b"AURA", vec![0; 32]);
442		assert_eq!(read_streams_root(&digest(vec![foreign, spms(r.encode())])), Some(r));
443	}
444
445	#[test]
446	fn streams_tree_matches_from_scratch_streams_root() {
447		let map = entries();
448		let tree = StreamsTree::from_entries(&map);
449		assert_eq!(tree.root(), streams_root(&map));
450
451		// Check proof generation from tree
452		for (stream, sr) in &map {
453			let (r_tree, proof_tree) = tree.gen_stream_proof(*stream).unwrap();
454			let (r_scratch, proof_scratch) = gen_stream_proof(&map, *stream).unwrap();
455			assert_eq!(r_tree, r_scratch);
456			assert_eq!(proof_tree, proof_scratch);
457			assert!(verify_stream_membership(r_tree, *stream, *sr, &proof_tree));
458		}
459	}
460
461	#[test]
462	fn streams_tree_incremental_updates() {
463		let mut map = BTreeMap::new();
464		let mut tree = StreamsTree::new();
465		assert!(tree.is_empty());
466		assert_eq!(tree.root(), None);
467
468		// Insert 100 streams incrementally
469		for i in 0..100u32 {
470			let stream = ch(1000 + i);
471			let r = root(i as u8);
472			map.insert(stream, r);
473			let tree_root = tree.insert(stream, r).unwrap();
474			assert_eq!(Some(tree_root), streams_root(&map));
475			assert_eq!(tree.root(), Some(tree_root));
476		}
477
478		// Update 50 existing streams with new roots
479		for i in (0..100u32).step_by(2) {
480			let stream = ch(1000 + i);
481			let new_r = root((i + 17) as u8);
482			map.insert(stream, new_r);
483			let tree_root = tree.insert(stream, new_r).unwrap();
484			assert_eq!(Some(tree_root), streams_root(&map));
485			assert_eq!(tree.root(), Some(tree_root));
486		}
487
488		// Verify proofs for all 100 streams
489		for (stream, sr) in &map {
490			let (r_tree, proof_tree) = tree.gen_stream_proof(*stream).unwrap();
491			let (r_scratch, proof_scratch) = gen_stream_proof(&map, *stream).unwrap();
492			assert_eq!(r_tree, r_scratch);
493			assert_eq!(proof_tree, proof_scratch);
494			assert!(verify_stream_membership(r_tree, *stream, *sr, &proof_tree));
495		}
496	}
497
498	#[test]
499	fn a_cyclic_or_out_of_range_node_is_corrupt_not_an_endless_walk() {
500		let (mut entry, mut store) = (None, BTreeMap::new());
501		for stream in [ch(1000), ch(1001)] {
502			update_tree_leaf(&mut entry, stream, root(0x1), &mut store).unwrap();
503		}
504		let Some(TreeRootEntry::Node { key, .. }) = entry else { panic!("two streams") };
505
506		// The root's children point back at the root.
507		let mut node = store[&key];
508		(node.left_child, node.right_child) = (TreeChild::Node { key }, TreeChild::Node { key });
509		let mut cyclic = BTreeMap::from([(key, node)]);
510		let mut e = entry;
511		assert_eq!(
512			update_tree_leaf(&mut e, ch(1000), root(0x2), &mut cyclic),
513			Err(TreeError::CorruptNode(key))
514		);
515		assert_eq!(gen_stream_proof_from_nodes(&entry, ch(1000), &cyclic), None);
516
517		// A split bit past the key width would index the key out of bounds.
518		let wide = NodeKey { prefix: key.prefix, prefix_len: KEY_BITS as u8 };
519		let mut node = store[&key];
520		node.split_bit = KEY_BITS as u8;
521		let mut out_of_range = BTreeMap::from([(wide, node)]);
522		let mut e = Some(TreeRootEntry::Node { key: wide, root_hash: root(0x1) });
523		assert_eq!(
524			update_tree_leaf(&mut e, ch(1002), root(0x2), &mut out_of_range),
525			Err(TreeError::CorruptNode(wide))
526		);
527	}
528
529	#[test]
530	fn a_child_off_the_walked_side_is_corrupt() {
531		// The root holds a node on one side and a leaf on the other.
532		let streams = [ch(1000), ch(1001), ch(3000)];
533		let (mut entry, mut store) = (None, BTreeMap::new());
534		for stream in streams {
535			update_tree_leaf(&mut entry, stream, root(0x1), &mut store).unwrap();
536		}
537		let Some(TreeRootEntry::Node { key, .. }) = entry else { panic!("three streams") };
538		let node = store[&key];
539		assert!(
540			matches!(
541				(node.left_child, node.right_child),
542				(TreeChild::Node { .. }, TreeChild::Leaf { .. }) |
543					(TreeChild::Leaf { .. }, TreeChild::Node { .. })
544			),
545			"a node and a leaf under the root"
546		);
547
548		// Swap the root's children: each is now on the side the other's keys walk.
549		let mut swapped = store.clone();
550		swapped.insert(
551			key,
552			InnerNode {
553				left_child: node.right_child,
554				left_hash: node.right_hash,
555				right_child: node.left_child,
556				right_hash: node.left_hash,
557				..node
558			},
559		);
560		for stream in streams {
561			let mut e = entry;
562			assert!(
563				matches!(
564					update_tree_leaf(&mut e, stream, root(0x2), &mut swapped.clone()),
565					Err(TreeError::CorruptNode(_))
566				),
567				"{stream:?}"
568			);
569			assert_eq!(gen_stream_proof_from_nodes(&entry, stream, &swapped), None, "{stream:?}");
570		}
571	}
572
573	#[test]
574	fn missing_node_returns_error() {
575		// Tree with an entry pointing to a missing inner node
576		let node_key = NodeKey::new(&ch(1000).to_bytes(), 10);
577		let mut root_entry = Some(TreeRootEntry::Node { key: node_key, root_hash: root(0x1) });
578		let mut empty_store = BTreeMap::new();
579		let before = root_entry;
580		let res = update_tree_leaf(&mut root_entry, ch(1001), root(0x2), &mut empty_store);
581		assert_eq!(res, Err(TreeError::MissingNode(node_key)));
582		assert_eq!(root_entry, before);
583		assert!(empty_store.is_empty());
584	}
585
586	#[test]
587	fn differential_fuzz_random_tree_insertions_and_updates() {
588		let mut seed = 0x85EB_CA6B_472C_1A55u64;
589		let mut rng = || {
590			seed ^= seed << 13;
591			seed ^= seed >> 7;
592			seed ^= seed << 17;
593			seed
594		};
595
596		let mut map = BTreeMap::new();
597		let mut tree = StreamsTree::new();
598
599		// Narrow field ranges give keys that split inside the kind, recipient and domain bytes.
600		let random_stream = |x: u64| match x % 3 {
601			0 => StreamId::Channel {
602				recipient: (((x >> 8) % 64) as u32).into(),
603				domain: (x >> 16) as u8 % 2,
604				num: (x >> 24) as u16 % 4,
605			},
606			1 => StreamId::Ack {
607				recipient: (((x >> 8) % 64) as u32).into(),
608				domain: (x >> 16) as u8 % 2,
609				num: (x >> 24) as u16 % 4,
610			},
611			_ => StreamId::Broadcast {
612				domain: (x >> 8) as u16 % 4,
613				subdomain: (x >> 16) as u8 % 2,
614				num: (x >> 24) as u32 % 64,
615			},
616		};
617
618		// Insert 200 streams with pseudo-random keys and values
619		for _ in 0..200 {
620			let stream = random_stream(rng());
621			let r = Hash::from_low_u64_be(rng());
622			map.insert(stream, r);
623			let tree_root = tree.insert(stream, r).unwrap();
624			assert_eq!(Some(tree_root), streams_root(&map));
625		}
626
627		// Mutate 100 random streams
628		let keys: Vec<_> = map.keys().copied().collect();
629		for _ in 0..100 {
630			let idx = (rng() as usize) % keys.len();
631			let stream = keys[idx];
632			let new_r = Hash::from_low_u64_be(rng());
633			map.insert(stream, new_r);
634			let tree_root = tree.insert(stream, new_r).unwrap();
635			assert_eq!(Some(tree_root), streams_root(&map));
636		}
637
638		// Verify every proof
639		for (stream, sr) in &map {
640			let (r_tree, proof_tree) = tree.gen_stream_proof(*stream).unwrap();
641			let (r_scratch, proof_scratch) = gen_stream_proof(&map, *stream).unwrap();
642			assert_eq!(r_tree, r_scratch);
643			assert_eq!(proof_tree, proof_scratch);
644			assert!(verify_stream_membership(r_tree, *stream, *sr, &proof_tree));
645		}
646
647		// The cached layout does not depend on insertion order.
648		let mut reversed = StreamsTree::new();
649		for (stream, sr) in map.iter().rev() {
650			reversed.insert(*stream, *sr).unwrap();
651		}
652		assert_eq!(reversed, tree);
653	}
654}