referrerpolicy=no-referrer-when-downgrade

cumulus_primitives_spec_messaging/streams_root/
cache.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//! The sender's node cache for the commitment trie: `O(log S)` updates and proofs without a
18//! rebuild. Not normative; verifiers depend only on the parent module's roots and proofs.
19
20use alloc::{collections::BTreeMap, vec::Vec};
21use codec::{Decode, DecodeWithMemTracking, Encode, MaxEncodedLen};
22use polkadot_core_primitives::Hash;
23use sp_runtime::BoundedVec;
24
25use super::{
26	bit, first_diverging_bit, hash_inner, hash_leaf, StreamProof, StreamsRoot, TreeStep, KEY_BITS,
27};
28use crate::{stream::StreamId, STREAM_ID_LEN};
29
30/// Key identifying an inner node in the commitment trie storage.
31#[derive(
32	Clone,
33	Copy,
34	Encode,
35	Decode,
36	DecodeWithMemTracking,
37	MaxEncodedLen,
38	PartialEq,
39	Eq,
40	PartialOrd,
41	Ord,
42	Debug,
43	scale_info::TypeInfo,
44)]
45pub struct NodeKey {
46	/// Prefix bytes with bits at index >= prefix_len cleared to zero.
47	pub prefix: [u8; STREAM_ID_LEN],
48	/// Number of prefix bits shared by all keys under this node (0..64).
49	pub prefix_len: u8,
50}
51
52impl NodeKey {
53	/// Create a new `NodeKey` with prefix bits `0..prefix_len` from `key`.
54	pub fn new(key: &[u8; STREAM_ID_LEN], prefix_len: u8) -> Self {
55		let mut prefix = *key;
56		for i in (prefix_len as usize)..KEY_BITS {
57			prefix[i >> 3] &= !(1 << (7 - (i & 7)));
58		}
59		Self { prefix, prefix_len }
60	}
61}
62
63/// A child pointer in an inner node or root entry.
64#[derive(
65	Clone,
66	Copy,
67	Encode,
68	Decode,
69	DecodeWithMemTracking,
70	MaxEncodedLen,
71	PartialEq,
72	Eq,
73	Debug,
74	scale_info::TypeInfo,
75)]
76pub enum TreeChild {
77	/// Child is a leaf storing `(stream_id_key, stream_root)`.
78	Leaf { key: [u8; STREAM_ID_LEN], value: Hash },
79	/// Child is an inner node stored under `key`.
80	Node { key: NodeKey },
81}
82
83/// An inner node in the commitment trie.
84#[derive(
85	Clone,
86	Copy,
87	Encode,
88	Decode,
89	DecodeWithMemTracking,
90	MaxEncodedLen,
91	PartialEq,
92	Eq,
93	Debug,
94	scale_info::TypeInfo,
95)]
96pub struct InnerNode {
97	/// The bit index this node branches on (0..64).
98	pub split_bit: u8,
99	pub left_child: TreeChild,
100	pub left_hash: Hash,
101	pub right_child: TreeChild,
102	pub right_hash: Hash,
103}
104
105impl InnerNode {
106	pub fn hash(&self) -> Hash {
107		hash_inner(self.split_bit, &self.left_hash, &self.right_hash)
108	}
109}
110
111/// The root entry of the commitment trie.
112#[derive(
113	Clone,
114	Copy,
115	Encode,
116	Decode,
117	DecodeWithMemTracking,
118	MaxEncodedLen,
119	PartialEq,
120	Eq,
121	Debug,
122	scale_info::TypeInfo,
123)]
124pub enum TreeRootEntry {
125	/// Tree has a single stream.
126	Leaf { key: [u8; STREAM_ID_LEN], value: Hash },
127	/// Tree has >= 2 streams, rooted at the inner node with `key`.
128	Node { key: NodeKey, root_hash: Hash },
129}
130
131impl TreeRootEntry {
132	/// The `StreamsRoot` committed by this root entry.
133	pub fn streams_root(&self) -> StreamsRoot {
134		match self {
135			Self::Leaf { key, value } => StreamsRoot(hash_leaf(key, value)),
136			Self::Node { root_hash, .. } => StreamsRoot(*root_hash),
137		}
138	}
139}
140
141/// Read-only accessor for inner nodes in the commitment trie.
142pub trait NodeLookup {
143	fn get_node(&self, key: &NodeKey) -> Option<InnerNode>;
144}
145
146/// Storage accessor for inner nodes in the commitment trie.
147pub trait NodeStore: NodeLookup {
148	fn set_node(&mut self, key: NodeKey, node: InnerNode);
149}
150
151impl NodeLookup for BTreeMap<NodeKey, InnerNode> {
152	fn get_node(&self, key: &NodeKey) -> Option<InnerNode> {
153		self.get(key).copied()
154	}
155}
156
157impl NodeStore for BTreeMap<NodeKey, InnerNode> {
158	fn set_node(&mut self, key: NodeKey, node: InnerNode) {
159		self.insert(key, node);
160	}
161}
162
163/// Error encountered during commitment trie updates.
164#[derive(Clone, Copy, Encode, Decode, PartialEq, Eq, Debug, scale_info::TypeInfo)]
165pub enum TreeError {
166	/// An expected inner node was missing from the node store.
167	MissingNode(NodeKey),
168	/// A stored inner node does not branch at its key's prefix length, below its parent, or a
169	/// child lies off the side of its parent the walk took.
170	CorruptNode(NodeKey),
171}
172
173/// Load the inner node at `key`, reached from a parent that splits at `parent.0` while walking to
174/// the stream key `parent.1`. Requiring each node to branch at its key's prefix length, strictly
175/// below its parent's split bit and within the key, bounds every walk at [`KEY_BITS`] steps, even
176/// over a corrupt store. Requiring its prefix to match the walked key through the parent's split
177/// bit keeps the walk on its side of every parent.
178fn load_node(
179	store: &impl NodeLookup,
180	key: NodeKey,
181	parent: Option<(u8, &[u8; STREAM_ID_LEN])>,
182) -> Result<InnerNode, TreeError> {
183	let node = store.get_node(&key).ok_or(TreeError::MissingNode(key))?;
184	let under_parent = parent.map_or(true, |(p, walked)| {
185		node.split_bit > p && first_diverging_bit(&key.prefix, walked) > p as usize
186	});
187	if node.split_bit != key.prefix_len || (node.split_bit as usize) >= KEY_BITS || !under_parent {
188		return Err(TreeError::CorruptNode(key));
189	}
190	Ok(node)
191}
192
193/// An inner node at `split_bit` with `ours` on the side `ours_right` names and `other` opposite.
194fn branch(
195	split_bit: u8,
196	ours_right: bool,
197	ours: (TreeChild, Hash),
198	other: (TreeChild, Hash),
199) -> InnerNode {
200	let ((left_child, left_hash), (right_child, right_hash)) =
201		if ours_right { (other, ours) } else { (ours, other) };
202	InnerNode { split_bit, left_child, left_hash, right_child, right_hash }
203}
204
205fn leaf(key: &[u8; STREAM_ID_LEN], value: Hash) -> (TreeChild, Hash) {
206	(TreeChild::Leaf { key: *key, value }, hash_leaf(key, &value))
207}
208
209/// Split an existing leaf `(old_key, old_val)` with a new leaf `(new_key, new_val)`. Callers
210/// guarantee `old_key != new_key`.
211fn split_leaf(
212	old_key: &[u8; STREAM_ID_LEN],
213	old_val: Hash,
214	new_key: &[u8; STREAM_ID_LEN],
215	new_val: Hash,
216) -> (NodeKey, InnerNode) {
217	let split = first_diverging_bit(new_key, old_key);
218	let node =
219		branch(split as u8, bit(new_key, split), leaf(new_key, new_val), leaf(old_key, old_val));
220	(NodeKey::new(new_key, split as u8), node)
221}
222
223/// Recursively insert or update `(key, stream_root)` into an inner node subtree.
224fn insert_inner_node(
225	curr_key: NodeKey,
226	parent: Option<u8>,
227	key: &[u8; STREAM_ID_LEN],
228	stream_root: Hash,
229	store: &mut impl NodeStore,
230) -> Result<(NodeKey, Hash), TreeError> {
231	let mut inner = load_node(store, curr_key, parent.map(|p| (p, key)))?;
232	let d = first_diverging_bit(key, &curr_key.prefix);
233
234	// `key` leaves this node's prefix above its split bit: a new inner node goes above it.
235	if d < inner.split_bit as usize {
236		let above = (TreeChild::Node { key: curr_key }, inner.hash());
237		let new_node = branch(d as u8, bit(key, d), leaf(key, stream_root), above);
238		let (new_key, hash) = (NodeKey::new(key, d as u8), new_node.hash());
239		store.set_node(new_key, new_node);
240		return Ok((new_key, hash));
241	}
242
243	let (child, child_hash) = if bit(key, inner.split_bit as usize) {
244		(&mut inner.right_child, &mut inner.right_hash)
245	} else {
246		(&mut inner.left_child, &mut inner.left_hash)
247	};
248	// A leaf on this side shares `key`'s bits through the split bit.
249	if let TreeChild::Leaf { key: leaf_key, .. } = *child {
250		if first_diverging_bit(key, &leaf_key) <= inner.split_bit as usize {
251			return Err(TreeError::CorruptNode(curr_key));
252		}
253	}
254	(*child, *child_hash) = match *child {
255		TreeChild::Leaf { key: leaf_key, .. } if &leaf_key == key => leaf(key, stream_root),
256		TreeChild::Leaf { key: leaf_key, value } => {
257			let (node_key, node) = split_leaf(&leaf_key, value, key, stream_root);
258			let hash = node.hash();
259			store.set_node(node_key, node);
260			(TreeChild::Node { key: node_key }, hash)
261		},
262		TreeChild::Node { key: child_key } => {
263			let (child_key, hash) =
264				insert_inner_node(child_key, Some(inner.split_bit), key, stream_root, store)?;
265			(TreeChild::Node { key: child_key }, hash)
266		},
267	};
268
269	let hash = inner.hash();
270	store.set_node(curr_key, inner);
271	Ok((curr_key, hash))
272}
273
274/// Incrementally update or insert a stream into the commitment trie storage.
275///
276/// Updates the path in `O(log S)` time, reading only nodes along the path from root to leaf and
277/// updating inner node sibling caches. Untouched subtrees are neither read nor recomputed.
278///
279/// Returns the new `StreamsRoot`, or `TreeError` if an expected inner node is missing from `store`.
280pub fn update_tree_leaf(
281	root_entry: &mut Option<TreeRootEntry>,
282	stream: StreamId,
283	stream_root: Hash,
284	store: &mut impl NodeStore,
285) -> Result<StreamsRoot, TreeError> {
286	let key = stream.to_bytes();
287	match root_entry {
288		None => {
289			*root_entry = Some(TreeRootEntry::Leaf { key, value: stream_root });
290			Ok(StreamsRoot(hash_leaf(&key, &stream_root)))
291		},
292		Some(TreeRootEntry::Leaf { key: leaf_key, value: leaf_val }) => {
293			if leaf_key == &key {
294				*root_entry = Some(TreeRootEntry::Leaf { key, value: stream_root });
295				Ok(StreamsRoot(hash_leaf(&key, &stream_root)))
296			} else {
297				let (node_key, node) = split_leaf(leaf_key, *leaf_val, &key, stream_root);
298				let root_hash = node.hash();
299				store.set_node(node_key, node);
300				*root_entry = Some(TreeRootEntry::Node { key: node_key, root_hash });
301				Ok(StreamsRoot(root_hash))
302			}
303		},
304		Some(TreeRootEntry::Node { key: root_key, .. }) => {
305			let root_key = *root_key;
306			let (new_root_key, new_root_hash) =
307				insert_inner_node(root_key, None, &key, stream_root, store)?;
308			*root_entry = Some(TreeRootEntry::Node { key: new_root_key, root_hash: new_root_hash });
309			Ok(StreamsRoot(new_root_hash))
310		},
311	}
312}
313
314/// Generate a `StreamProof` for `stream` using the node storage cache.
315///
316/// Walks down the tree in `O(log S)` time, retrieving sibling hashes cached in `InnerNode`
317/// without reading untouched subtrees from storage.
318pub fn gen_stream_proof_from_nodes(
319	root_entry: &Option<TreeRootEntry>,
320	stream: StreamId,
321	lookup: &impl NodeLookup,
322) -> Option<(StreamsRoot, StreamProof)> {
323	let key = stream.to_bytes();
324	match root_entry.as_ref()? {
325		TreeRootEntry::Leaf { key: leaf_key, value: leaf_val } => {
326			if leaf_key == &key {
327				Some((
328					StreamsRoot(hash_leaf(&key, leaf_val)),
329					StreamProof { steps: BoundedVec::new() },
330				))
331			} else {
332				None
333			}
334		},
335		TreeRootEntry::Node { key: root_key, root_hash } => {
336			let mut curr_key = *root_key;
337			let mut parent = None;
338			let mut steps = Vec::new();
339			loop {
340				let inner = load_node(lookup, curr_key, parent.map(|p| (p, &key))).ok()?;
341				parent = Some(inner.split_bit);
342				let d = first_diverging_bit(&key, &curr_key.prefix);
343				if d < inner.split_bit as usize {
344					return None;
345				}
346				let (sibling, child) = if bit(&key, inner.split_bit as usize) {
347					(inner.left_hash, inner.right_child)
348				} else {
349					(inner.right_hash, inner.left_child)
350				};
351				steps.push(TreeStep { split_bit: inner.split_bit, sibling });
352				match child {
353					TreeChild::Leaf { key: leaf_key, .. } if leaf_key == key => break,
354					TreeChild::Leaf { .. } => return None,
355					TreeChild::Node { key: next_key } => curr_key = next_key,
356				}
357			}
358			steps.reverse();
359			let steps = BoundedVec::try_from(steps).ok()?;
360			Some((StreamsRoot(*root_hash), StreamProof { steps }))
361		},
362	}
363}
364
365/// An in-memory commitment tree caching inner nodes for `O(log S)` updates and proofs.
366#[derive(Clone, Default, PartialEq, Eq, Debug)]
367pub struct StreamsTree {
368	root: Option<TreeRootEntry>,
369	nodes: BTreeMap<NodeKey, InnerNode>,
370}
371
372impl StreamsTree {
373	pub fn new() -> Self {
374		Self::default()
375	}
376
377	pub fn is_empty(&self) -> bool {
378		self.root.is_none()
379	}
380
381	/// The current `StreamsRoot`, or `None` if empty.
382	pub fn root(&self) -> Option<StreamsRoot> {
383		self.root.as_ref().map(|r| r.streams_root())
384	}
385
386	/// Update or insert a stream root in `O(log S)` time.
387	pub fn insert(
388		&mut self,
389		stream: StreamId,
390		stream_root: Hash,
391	) -> Result<StreamsRoot, TreeError> {
392		update_tree_leaf(&mut self.root, stream, stream_root, &mut self.nodes)
393	}
394
395	/// Build a proof for `stream` in `O(log S)` time.
396	pub fn gen_stream_proof(&self, stream: StreamId) -> Option<(StreamsRoot, StreamProof)> {
397		gen_stream_proof_from_nodes(&self.root, stream, &self.nodes)
398	}
399
400	/// Construct a tree from an existing map of entries.
401	pub fn from_entries(entries: &BTreeMap<StreamId, Hash>) -> Self {
402		let mut tree = Self::new();
403		for (stream, root) in entries {
404			tree.insert(*stream, *root).expect("in-memory node store never fails; qed");
405		}
406		tree
407	}
408}