referrerpolicy=no-referrer-when-downgrade

cumulus_primitives_spec_messaging/
mmr.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//! MMR primitives for the Speculative Messaging protocol.
18//!
19//! Hashing is [`SpecHasher`] with the crate's domain tags: leaves by [`leaf_hash`], inner nodes by
20//! [`SpecMerge::merge`], peak bagging by [`SpecMerge::merge_peaks`] (`mmr_lib` calls it only when
21//! bagging), stream roots by [`MmrRoot::from_bag`].
22//!
23//! [`SpecMerge`] is the `mmr_lib::Merge` for inclusion proofs (`gen_proof` / `MerkleProof::verify`)
24//! and ancestry proofs (`gen_ancestry_proof` / `verify_incremental`). [`MmrFrontier`] is the
25//! peaks-only state: the sender's on-chain accumulator, and what proofs extend from.
26
27use alloc::{collections::BTreeMap, vec::Vec};
28use codec::{Decode, DecodeWithMemTracking, Encode, Error as CodecError, Input, MaxEncodedLen};
29use mmr_lib::{
30	ancestry_proof::bagging_peaks_hashes, helper::get_peaks, Error as MmrError, Merge,
31	NodeMerkleProof,
32};
33use polkadot_core_primitives::Hash;
34use scale_info::TypeInfo;
35use sp_core::ConstU32;
36use sp_runtime::{traits::Hash as HashT, BoundedVec};
37
38use crate::{SpecHasher, INNER_TAG, LEAF_TAG, LEAF_VERSION, PEAK_TAG, ROOT_TAG};
39
40/// Upper bound on any leaf count node positions are derived from; `mmr_lib`'s node count overflows
41/// `u64` above 2^63. Peer-supplied counts are checked against this first.
42pub const MAX_MMR_LEAF_COUNT: u64 = 1 << 48;
43
44/// Upper bound on a peak set or connecting-node list: one hash per bit of [`MAX_MMR_LEAF_COUNT`].
45pub const MAX_MMR_HASHES: u32 = 48;
46
47/// A leaf position within a stream's MMR.
48#[derive(
49	Clone,
50	Copy,
51	Encode,
52	Decode,
53	DecodeWithMemTracking,
54	MaxEncodedLen,
55	PartialEq,
56	Eq,
57	PartialOrd,
58	Ord,
59	Debug,
60	Default,
61	TypeInfo,
62)]
63pub struct MessagePosition(pub u64);
64
65/// Domain-tagged `mmr_lib::Merge` for the speculative-messaging MMR.
66pub struct SpecMerge;
67
68impl Merge for SpecMerge {
69	type Item = Hash;
70
71	fn merge(left: &Hash, right: &Hash) -> Result<Hash, MmrError> {
72		Ok(tagged_node(INNER_TAG, left, right))
73	}
74
75	fn merge_peaks(left: &Hash, right: &Hash) -> Result<Hash, MmrError> {
76		Ok(tagged_node(PEAK_TAG, left, right))
77	}
78}
79
80fn tagged_node(tag: u8, left: &Hash, right: &Hash) -> Hash {
81	let mut preimage = [0u8; 1 + 32 + 32];
82	preimage[0] = tag;
83	preimage[1..33].copy_from_slice(left.as_bytes());
84	preimage[33..65].copy_from_slice(right.as_bytes());
85	<SpecHasher as HashT>::hash(&preimage)
86}
87
88/// Hash a payload into a stream MMR leaf at [`LEAF_VERSION`]. Source, stream
89/// and position are structural and not in the preimage.
90pub fn leaf_hash(payload: &[u8]) -> Hash {
91	leaf_hash_with_version(LEAF_VERSION, payload)
92}
93
94/// Hash a payload into a stream MMR leaf at an explicit leaf version. Used to test format
95/// disjointness across format revisions.
96pub fn leaf_hash_with_version(leaf_version: u8, payload: &[u8]) -> Hash {
97	let mut preimage = Vec::with_capacity(2 + payload.len());
98	preimage.push(LEAF_TAG);
99	preimage.push(leaf_version);
100	preimage.extend_from_slice(payload);
101	<SpecHasher as HashT>::hash(&preimage)
102}
103
104/// The root of an empty MMR.
105pub fn empty_root() -> MmrRoot {
106	MmrRoot::from_bag(0, Hash::zero())
107}
108
109/// Bag the peaks (highest to lowest) with `mmr_lib`'s own bagging, so the result equals
110/// `MMR::get_root`. Not a stream root (see [`MmrRoot::from_bag`]). No peaks bag to zero.
111pub fn bag_peaks(peaks: &[Hash]) -> Hash {
112	// `SpecMerge` is infallible, so `Err` means no peaks.
113	bagging_peaks_hashes::<Hash, SpecMerge>(peaks.to_vec()).unwrap_or_default()
114}
115
116/// [`MmrFrontier::try_append`] refused a leaf: the frontier already holds [`MAX_MMR_LEAF_COUNT`].
117#[derive(Clone, Copy, PartialEq, Eq, Debug)]
118pub struct FrontierFull;
119
120/// A stream's committed root at some point in its history ([`Self::from_bag`]). A newtype so it
121/// cannot be confused with a `StreamsRoot`, the commitment-tree root.
122#[derive(
123	Clone,
124	Copy,
125	Encode,
126	Decode,
127	DecodeWithMemTracking,
128	MaxEncodedLen,
129	PartialEq,
130	Eq,
131	Debug,
132	TypeInfo,
133)]
134pub struct MmrRoot(pub Hash);
135
136impl MmrRoot {
137	/// Peak hashes do not commit their heights, so the same peaks bag identically at many leaf
138	/// counts; binding the count makes a forged count, and so a forged position, yield a root
139	/// nothing commits to.
140	pub fn from_bag(leaf_count: u64, bag: Hash) -> Self {
141		let mut preimage = [0u8; 1 + 8 + 32];
142		preimage[0] = ROOT_TAG;
143		preimage[1..9].copy_from_slice(&leaf_count.to_le_bytes());
144		preimage[9..41].copy_from_slice(bag.as_bytes());
145		Self(<SpecHasher as HashT>::hash(&preimage))
146	}
147}
148
149/// A peaks-only MMR frontier: the O(log n) state a stream continues from, and the accumulator that
150/// continues it. `leaf_count` fixes where an extension proof's connecting nodes go.
151///
152/// Peak hashes equal `mmr_lib`'s, so [`root`](Self::root) is `mmr_lib::MMR::get_root` bound to the
153/// leaf count, and proofs from a full `mmr_lib::MMR` over the same leaves verify against it.
154///
155/// Fields are private, so every frontier holds the [`from_parts`](Self::from_parts) rules.
156#[derive(Clone, Encode, MaxEncodedLen, PartialEq, Eq, Debug, TypeInfo, Default)]
157pub struct MmrFrontier {
158	/// Number of leaves these peaks summarize; also the position of the next message to append.
159	leaf_count: u64,
160	/// MMR peaks, highest to lowest. At most [`MAX_MMR_HASHES`].
161	peaks: BoundedVec<Hash, ConstU32<MAX_MMR_HASHES>>,
162}
163
164impl MmrFrontier {
165	pub fn new() -> Self {
166		Self::default()
167	}
168
169	/// A frontier from `(peaks, leaf_count)`. `None` unless there is one peak per set bit of
170	/// `leaf_count` and `leaf_count <= MAX_MMR_LEAF_COUNT`.
171	pub fn from_parts(peaks: Vec<Hash>, leaf_count: u64) -> Option<Self> {
172		if leaf_count > MAX_MMR_LEAF_COUNT || peaks.len() != leaf_count.count_ones() as usize {
173			return None;
174		}
175		// ≤ 48 is implied by the set-bit count up to `MAX_MMR_LEAF_COUNT`, so this cannot fail.
176		BoundedVec::try_from(peaks).ok().map(|peaks| Self { leaf_count, peaks })
177	}
178
179	/// The peaks, highest to lowest.
180	pub fn peaks(&self) -> &[Hash] {
181		&self.peaks
182	}
183
184	pub fn leaf_count(&self) -> u64 {
185		self.leaf_count
186	}
187
188	/// Append a leaf, merging equal-height peaks as `mmr_lib` does. At [`MAX_MMR_LEAF_COUNT`] the
189	/// leaf is refused and the frontier left unchanged, so every frontier still decodes.
190	pub fn try_append(&mut self, leaf: Hash) -> Result<(), FrontierFull> {
191		if self.leaf_count >= MAX_MMR_LEAF_COUNT {
192			return Err(FrontierFull);
193		}
194		let mut node = leaf;
195		// Going from `leaf_count` to `leaf_count + 1` merges exactly
196		// `trailing_zeros(leaf_count + 1)` pairs of peaks (binary-counter carry).
197		let merges = (self.leaf_count + 1).trailing_zeros();
198		for _ in 0..merges {
199			let left = self
200				.peaks
201				.pop()
202				.expect("the constructors enforce one peak per set bit of `leaf_count`; qed");
203			node = <SpecMerge as Merge>::merge(&left, &node).expect("SpecMerge is infallible; qed");
204		}
205		self.peaks
206			.try_push(node)
207			.expect("a leaf count up to `MAX_MMR_LEAF_COUNT` never has more than 48 set bits; qed");
208		self.leaf_count += 1;
209		Ok(())
210	}
211
212	/// [`try_append`](Self::try_append) for a frontier this chain built itself, from the empty
213	/// frontier one leaf at a time.
214	///
215	/// # Panics
216	///
217	/// At [`MAX_MMR_LEAF_COUNT`], which no stream reaches: `2^48` leaves are beyond any chain's
218	/// lifetime. Never call it on a frontier built from untrusted parts.
219	pub fn append(&mut self, leaf: Hash) {
220		self.try_append(leaf)
221			.expect("a frontier built leaf by leaf never reaches `MAX_MMR_LEAF_COUNT`; qed")
222	}
223
224	/// The stream root ([`MmrRoot::from_bag`]). The empty frontier bags to zero ([`empty_root`]),
225	/// so a frontier that has consumed nothing compares and extends like any other.
226	pub fn root(&self) -> MmrRoot {
227		MmrRoot::from_bag(self.leaf_count, bag_peaks(&self.peaks))
228	}
229
230	/// The `mmr_lib` node count (size) of this frontier's MMR. Total under the leaf-count
231	/// invariant.
232	pub(crate) fn mmr_size(&self) -> u64 {
233		mmr_size(self.leaf_count)
234	}
235}
236
237/// The `mmr_lib` node count (size) of an MMR with `leaf_count` leaves. Total up to
238/// [`MAX_MMR_LEAF_COUNT`].
239pub(crate) fn mmr_size(leaf_count: u64) -> u64 {
240	if leaf_count == 0 {
241		0
242	} else {
243		mmr_lib::leaf_index_to_mmr_size(leaf_count - 1)
244	}
245}
246
247/// Field order matches the derived `Encode`; the decoded pair goes through
248/// [`from_parts`](MmrFrontier::from_parts).
249impl Decode for MmrFrontier {
250	fn decode<I: Input>(input: &mut I) -> Result<Self, CodecError> {
251		let leaf_count = u64::decode(input)?;
252		let peaks = BoundedVec::<Hash, ConstU32<MAX_MMR_HASHES>>::decode(input)?;
253		Self::from_parts(peaks.into_inner(), leaf_count)
254			.ok_or_else(|| "MmrFrontier: inconsistent peaks / leaf count".into())
255	}
256}
257
258impl DecodeWithMemTracking for MmrFrontier {}
259
260/// Why an MMR proof verification rejected its input. Typed so callers can tell a malformed or
261/// forged proof from a non-forward or out-of-range one.
262#[derive(Clone, Copy, PartialEq, Eq, Debug)]
263pub enum ProofError {
264	/// The proof is structurally malformed: a wrong connecting-node count, or `mmr_lib` could not
265	/// reconstruct a root from it.
266	InvalidProof,
267	/// An extension does not go strictly forward (its target is not newer than the frontier).
268	NotForward,
269	/// A leaf count exceeds [`MAX_MMR_LEAF_COUNT`].
270	LeafCountTooLarge,
271}
272
273/// An append-only MMR extension proof: O(log n) connecting nodes that, with a frontier's own peaks,
274/// reconstruct a newer root. The `mmr_lib` `gen_ancestry_proof` form of the design's
275/// `connecting_nodes`. Verification computes the new root; it is never declared alongside the
276/// proof. It holds node hashes only, no message payloads.
277#[derive(
278	Clone, Encode, Decode, DecodeWithMemTracking, MaxEncodedLen, PartialEq, Eq, Debug, TypeInfo,
279)]
280pub struct MmrExtensionProof {
281	/// Leaf count of the extended MMR. The `mmr_lib` node count is derived from it, so no
282	/// independent size can be smuggled in. The frontier's own count with empty
283	/// `connecting_nodes` is the identity extension.
284	/// Compact-encoded, since this is PoV-carried.
285	#[codec(compact)]
286	pub leaf_count: u64,
287	/// The connecting-node hashes, in `mmr_lib`'s proof order. Positions are not stored: an MMR's
288	/// shape is fixed by its size, so they are derived at verify time from the two leaf counts
289	/// (`ancestry_proof_positions`). Empty for the identity.
290	pub connecting_nodes: BoundedVec<Hash, ConstU32<MAX_MMR_HASHES>>,
291}
292
293impl MmrExtensionProof {
294	/// The identity extension of `from`: its own leaf count and no connecting nodes.
295	pub fn identity(from: &MmrFrontier) -> Self {
296		Self { leaf_count: from.leaf_count(), connecting_nodes: BoundedVec::new() }
297	}
298
299	/// Exact encoded byte size of a skip/extension proof from `n1` leaves to `n2` leaves, computed
300	/// from the same `ancestry_proof_positions` count that [`Self::calculate_root`] enforces.
301	///
302	/// Returns `Some(0)` when `n1 == n2` (no gap, so no proof is added to `advances`), and `None`
303	/// outside `1 <= n1 <= n2 <= MAX_MMR_LEAF_COUNT`. Never panics.
304	pub fn encoded_len_for(n1: u64, n2: u64) -> Option<usize> {
305		if n1 == 0 || n1 > n2 || n2 > MAX_MMR_LEAF_COUNT {
306			return None;
307		}
308		if n1 == n2 {
309			return Some(0);
310		}
311		let nodes = mmr_lib::ancestry_proof::ancestry_proof_positions(mmr_size(n1), mmr_size(n2))
312			.ok()?
313			.len();
314		Some(
315			codec::Compact(n2).encoded_size() +
316				codec::Compact(nodes as u32).encoded_size() +
317				nodes * Hash::len_bytes(),
318		)
319	}
320
321	/// Extend `from` and return the new root, computed from `from`'s peaks and the connecting
322	/// nodes; `Err` if the proof does not fit that placement. The identity extension yields
323	/// `from`'s own root. Comparing the root is the caller's job. `from`'s contents are not
324	/// re-checked: a forged peak yields a root no committed `StreamsRoot` can bind.
325	pub fn calculate_root(&self, from: &MmrFrontier) -> Result<MmrRoot, ProofError> {
326		// `mmr_lib` accepts counts up to 2^63; bound the proof's to `MAX_MMR_LEAF_COUNT` first.
327		// `from` is already in range by construction.
328		if self.leaf_count > MAX_MMR_LEAF_COUNT {
329			return Err(ProofError::LeafCountTooLarge);
330		}
331		if self.leaf_count < from.leaf_count() {
332			return Err(ProofError::NotForward);
333		}
334		// The identity: the same count with no connecting nodes. This includes the empty frontier.
335		if self.leaf_count == from.leaf_count() {
336			return if self.connecting_nodes.is_empty() {
337				Ok(from.root())
338			} else {
339				Err(ProofError::InvalidProof)
340			};
341		}
342		let new_mmr_size = mmr_size(self.leaf_count);
343
344		// Extending from the empty stream: nothing binds, so the connecting nodes must be the new
345		// MMR's peaks in `get_peaks` order.
346		if from.leaf_count() == 0 {
347			// The nodes must form a frontier of exactly `self.leaf_count` leaves; `from_parts`
348			// checks that.
349			return MmrFrontier::from_parts(self.connecting_nodes.to_vec(), self.leaf_count)
350				.map(|f| f.root())
351				.ok_or(ProofError::InvalidProof);
352		}
353
354		// `from`'s peaks are complete subtrees of the new MMR at unchanged positions; with the
355		// connecting nodes they reconstruct the new root under `SpecMerge`.
356		let old_mmr_size = from.mmr_size();
357		let old_positions = get_peaks(old_mmr_size);
358		// Positions are not carried: derive them from the two sizes and pair them with the hashes
359		// in `mmr_lib`'s proof order. A length mismatch means the proof does not fit the claimed
360		// extension.
361		let positions =
362			mmr_lib::ancestry_proof::ancestry_proof_positions(old_mmr_size, new_mmr_size)
363				.map_err(|_| ProofError::InvalidProof)?;
364		if positions.len() != self.connecting_nodes.len() {
365			return Err(ProofError::InvalidProof);
366		}
367		let proof: Vec<(u64, Hash)> =
368			positions.into_iter().zip(self.connecting_nodes.iter().copied()).collect();
369		let nodes: Vec<(u64, Hash)> =
370			old_positions.into_iter().zip(from.peaks().iter().copied()).collect();
371		NodeMerkleProof::<Hash, SpecMerge>::new(new_mmr_size, proof)
372			.calculate_root(nodes)
373			.map(|bag| MmrRoot::from_bag(self.leaf_count, bag))
374			.map_err(|_| ProofError::InvalidProof)
375	}
376
377	/// This extension, which starts `leaves.len()` leaves past `from`, rebased to extend `from`
378	/// itself to the same root. `None` if `from` is empty (that extension carries the new peaks one
379	/// by one, and `self` may bag some) or if the material does not fit together.
380	///
381	/// The extension from `from` needs the subtrees right of it. Those over `leaves` are hashed,
382	/// those past them are `self`'s siblings, and one over both is merged from its halves. Its run
383	/// of new peaks ends with the run `self` bagged, which is folded into the rest. The result is
384	/// checked to reach the root `self` does before it is returned.
385	pub fn rebase(&self, from: &MmrFrontier, leaves: &[Hash]) -> Option<Self> {
386		let (old, count) = (from.leaf_count(), self.leaf_count);
387		let past = old.checked_add(leaves.len() as u64)?;
388		if old == 0 || past > count || count > MAX_MMR_LEAF_COUNT {
389			return None;
390		}
391		let given = Layout::new(past, count);
392		if given.len() != self.connecting_nodes.len() {
393			return None;
394		}
395		let (siblings, run) = self.connecting_nodes.split_at(given.siblings.len());
396		let subtrees = Subtrees {
397			first: old,
398			leaves,
399			known: given.siblings.iter().copied().zip(siblings.iter().copied()).collect(),
400		};
401
402		let wanted = Layout::new(old, count);
403		let mut nodes = wanted
404			.siblings
405			.iter()
406			.map(|span| subtrees.get(*span))
407			.collect::<Option<Vec<_>>>()?;
408		if let Some((lowest, higher)) = wanted.run.split_last() {
409			// Bags fold from the lowest peak up, so the run `self` bagged starts the fold.
410			let (mut bag, higher) = match run.first() {
411				Some(node) if wanted.run.ends_with(&given.run) => {
412					(*node, &wanted.run[..wanted.run.len() - given.run.len()])
413				},
414				_ => (subtrees.get(*lowest)?, higher),
415			};
416			for span in higher.iter().rev() {
417				bag = SpecMerge::merge_peaks(&bag, &subtrees.get(*span)?).ok()?;
418			}
419			nodes.push(bag);
420		}
421		let rebased = Self { leaf_count: count, connecting_nodes: nodes.try_into().ok()? };
422
423		let mut to = from.clone();
424		for leaf in leaves {
425			to.try_append(*leaf).ok()?;
426		}
427		(rebased.calculate_root(from).ok()? == self.calculate_root(&to).ok()?).then_some(rebased)
428	}
429}
430
431/// A perfect subtree of a stream's MMR: its first leaf and its height.
432#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
433struct Span {
434	start: u64,
435	height: u32,
436}
437
438impl Span {
439	/// The leaf after its last.
440	fn end(&self) -> u64 {
441		self.start + (1 << self.height)
442	}
443}
444
445/// The subtrees the connecting nodes of an extension stand for, in their wire order: one node per
446/// sibling, then one for the run if there is one.
447#[derive(Default)]
448struct Layout {
449	/// The right siblings on the path from the last old leaf up to the new peak over it, lowest
450	/// first.
451	siblings: Vec<Span>,
452	/// The new peaks to the right of the old leaves, highest first. The proof carries them as one
453	/// node: their bag, or the peak itself if there is only one.
454	run: Vec<Span>,
455}
456
457impl Layout {
458	/// The layout of an extension from `n1` to `n2` leaves, `1 <= n1 <= n2 <= MAX_MMR_LEAF_COUNT`.
459	/// Empty for the identity.
460	fn new(n1: u64, n2: u64) -> Self {
461		let mut layout = Self::default();
462		if n1 >= n2 {
463			return layout;
464		}
465		// The highest bit the counts differ in: `n2` has a peak of that height, starting at
466		// `split`, that `n1` lacks. The peaks before it are common to both.
467		let height = 63 - (n1 ^ n2).leading_zeros();
468		let split = (n2 >> (height + 1)) << (height + 1);
469		// The old leaves under that peak.
470		let held = n1 - split;
471		if held == 0 {
472			layout.run.push(Span { start: split, height });
473		} else {
474			for h in 0..height {
475				// The node over the last old leaf at height `h`. A right child merges with an old
476				// peak; a left child needs its sibling.
477				let index = (held - 1) >> h;
478				if index & 1 == 0 {
479					layout.siblings.push(Span { start: split + ((index + 1) << h), height: h });
480				}
481			}
482		}
483		let mut start = split + (1 << height);
484		for h in (0..height).rev() {
485			if (n2 >> h) & 1 == 1 {
486				layout.run.push(Span { start, height: h });
487				start += 1 << h;
488			}
489		}
490		layout
491	}
492
493	/// The number of connecting nodes.
494	fn len(&self) -> usize {
495		self.siblings.len() + usize::from(!self.run.is_empty())
496	}
497}
498
499/// The subtrees past `first`: over `leaves` from `first` on, the known ones past those, and
500/// whatever spans both, from its halves.
501struct Subtrees<'a> {
502	first: u64,
503	leaves: &'a [Hash],
504	known: BTreeMap<Span, Hash>,
505}
506
507impl Subtrees<'_> {
508	fn get(&self, span: Span) -> Option<Hash> {
509		let past = self.first + self.leaves.len() as u64;
510		if span.start >= self.first && span.end() <= past {
511			let (start, end) =
512				((span.start - self.first) as usize, (span.end() - self.first) as usize);
513			return merkle(&self.leaves[start..end]);
514		}
515		if let Some(node) = self.known.get(&span) {
516			return Some(*node);
517		}
518		if span.height == 0 || span.start >= past || span.end() <= past {
519			return None;
520		}
521		let half = span.height - 1;
522		let left = self.get(Span { start: span.start, height: half })?;
523		let right = self.get(Span { start: span.start + (1 << half), height: half })?;
524		SpecMerge::merge(&left, &right).ok()
525	}
526}
527
528/// The root of the perfect subtree over `leaves`, a power of two of them.
529fn merkle(leaves: &[Hash]) -> Option<Hash> {
530	match leaves {
531		[] => None,
532		[leaf] => Some(*leaf),
533		_ => {
534			let (left, right) = leaves.split_at(leaves.len() / 2);
535			SpecMerge::merge(&merkle(left)?, &merkle(right)?).ok()
536		},
537	}
538}
539
540#[cfg(test)]
541mod tests {
542	use super::*;
543	use crate::test_utils::{extension, frontier_at, leaves, mmr_size};
544	use mmr_lib::{
545		leaf_index_to_pos,
546		util::{MemMMR, MemStore},
547		MerkleProof,
548	};
549	use sp_core::H256;
550	fn h(byte: u8) -> Hash {
551		Hash::repeat_byte(byte)
552	}
553
554	/// Root over the first `k` leaves.
555	fn root_at(all: &[Hash], k: usize) -> MmrRoot {
556		frontier_at(all, k).root()
557	}
558
559	#[test]
560	fn merge_and_merge_peaks_are_domain_separated() {
561		let a = h(1);
562		let b = h(2);
563		// Inner-node merge and peak-bagging of the same inputs must differ (domain tags).
564		assert_ne!(
565			<SpecMerge as Merge>::merge(&a, &b).unwrap(),
566			<SpecMerge as Merge>::merge_peaks(&a, &b).unwrap()
567		);
568	}
569
570	#[test]
571	fn merge_is_order_sensitive() {
572		let a = h(1);
573		let b = h(2);
574		assert_ne!(
575			<SpecMerge as Merge>::merge(&a, &b).unwrap(),
576			<SpecMerge as Merge>::merge(&b, &a).unwrap()
577		);
578	}
579
580	#[test]
581	fn from_parts_enforces_append_invariants() {
582		// Consistent pairs round-trip, including the empty accumulator.
583		assert!(MmrFrontier::from_parts(Vec::new(), 0).is_some());
584		assert!(MmrFrontier::from_parts(vec![h(1)], 1).is_some());
585		assert!(MmrFrontier::from_parts(vec![h(1), h(2)], 3).is_some());
586		// One peak per set bit, or `append` would pop from an empty vec.
587		assert!(MmrFrontier::from_parts(Vec::new(), 1).is_none());
588		assert!(MmrFrontier::from_parts(vec![h(1)], 3).is_none());
589		assert!(MmrFrontier::from_parts(vec![h(1), h(2)], 1).is_none());
590		// And within the ceiling, or the node-position arithmetic downstream is not total.
591		assert!(MmrFrontier::from_parts(vec![h(1)], MAX_MMR_LEAF_COUNT).is_some());
592		assert!(MmrFrontier::from_parts(vec![h(1)], 1 << 63).is_none());
593		assert!(MmrFrontier::from_parts(vec![h(1); MAX_MMR_HASHES as usize], u64::MAX).is_none());
594	}
595
596	#[test]
597	fn accumulator_root_matches_mmr_lib() {
598		// Build via the peaks-only accumulator and via a full mmr_lib MMR; the
599		// roots and peak-count invariant must agree.
600		let mut acc = MmrFrontier::new();
601		let store = MemStore::<Hash>::default();
602		let mut reference = MemMMR::<Hash, SpecMerge>::new(0, &store);
603		for i in 1..=5u8 {
604			acc.append(h(i));
605			reference.push(h(i)).unwrap();
606			assert_eq!(acc.peaks().len() as u32, acc.leaf_count().count_ones());
607		}
608		assert_eq!(acc.root(), MmrRoot::from_bag(5, reference.get_root().unwrap()));
609	}
610
611	#[test]
612	fn empty_accumulator_root_is_empty_root() {
613		// A fresh accumulator is valid, and its root is the defined constant, not a panic in
614		// `bag_peaks`.
615		assert_eq!(bag_peaks(&[]), Hash::zero());
616		assert_eq!(MmrFrontier::new().root(), empty_root());
617		assert_eq!(MmrFrontier::from_parts(Vec::new(), 0).unwrap().root(), empty_root());
618	}
619
620	#[test]
621	fn decode_enforces_the_same_invariants_as_from_parts() {
622		// A frontier off the wire goes through `from_parts`, so it holds the invariants `append`
623		// and the position arithmetic rely on. Consistent bytes round-trip;
624		let good = MmrFrontier::from_parts(vec![h(1), h(2)], 3).unwrap();
625		assert_eq!(MmrFrontier::decode(&mut &good.encode()[..]).unwrap(), good);
626		// … inconsistent ones are rejected at decode, not later in a pop or a multiply.
627		let bad_shape = (3u64, vec![h(1)]).encode();
628		assert!(MmrFrontier::decode(&mut &bad_shape[..]).is_err());
629		let too_large = (1u64 << 63, vec![h(1)]).encode();
630		assert!(MmrFrontier::decode(&mut &too_large[..]).is_err());
631		// The bound is checked at the length prefix: 49 peaks are refused before being read.
632		let too_many = (u64::MAX, vec![h(1); MAX_MMR_HASHES as usize + 1]).encode();
633		assert!(MmrFrontier::decode(&mut &too_many[..]).is_err());
634		// And the wire order is the design's: `leaf_count` first.
635		assert_eq!(good.encode(), (3u64, vec![h(1), h(2)]).encode());
636	}
637
638	#[test]
639	fn empty_root_frozen_vector() {
640		// FROZEN consensus vector: blake2b-256 of `ROOT_TAG = 0x04`, a zero `u64` count and a zero
641		// bag, the defined root of an empty frontier.
642		assert_eq!(
643			empty_root().0,
644			Hash::from(hex_literal::hex!(
645				"3efd2c3528b8f163c2e2349211af73f86181b748be1b6a5eebfbadc9428643ce"
646			))
647		);
648	}
649
650	#[test]
651	fn mmr_root_frozen_vector() {
652		// Frozen consensus vector for tags `LEAF/INNER/PEAK/ROOT = 0x1/0x2/0x3/0x4`: a change to
653		// the tags or the bagging order is a consensus break and fails this.
654		let mut acc = MmrFrontier::new();
655		for i in 1..=5u8 {
656			acc.append(h(i));
657		}
658		assert_eq!(
659			acc.root().0,
660			Hash::from(hex_literal::hex!(
661				"1190cb02577a8bafec9f05c38e64ca9155b65e9d862604c4f3d920dff4e5a85f"
662			))
663		);
664	}
665
666	#[test]
667	fn mmr_root_frozen_vectors_at_64_and_65_leaves() {
668		// Frozen vectors, computed by an independent Python model: 64 leaves make one peak, 65 add
669		// a second to bag.
670		let mut acc = MmrFrontier::new();
671		for i in 1..=64u8 {
672			acc.append(h(i));
673		}
674		assert_eq!(acc.peaks().len(), 1);
675		assert_eq!(
676			acc.root().0,
677			Hash::from(hex_literal::hex!(
678				"41cec1de3c0e0af93a02932404fc195f0fbb56f542abbce0681b4632da0848c2"
679			))
680		);
681		acc.append(h(65));
682		assert_eq!(acc.peaks().len(), 2);
683		assert_eq!(
684			acc.root().0,
685			Hash::from(hex_literal::hex!(
686				"109ccf71e0b753f6ff76d7f48e59f6376c1347bea4556b20c4a453a2cb8ca28d"
687			))
688		);
689	}
690
691	#[test]
692	fn no_append_carries_a_frontier_past_the_ceiling() {
693		// A frontier built from untrusted parts can sit at the ceiling. Its next leaf is refused
694		// and the frontier left as it was, so it still decodes; one below, the last leaf fits.
695		let mut full = MmrFrontier::from_parts(vec![h(1)], MAX_MMR_LEAF_COUNT).unwrap();
696		assert_eq!(full.try_append(h(2)), Err(FrontierFull));
697		assert_eq!(full.leaf_count(), MAX_MMR_LEAF_COUNT);
698		assert_eq!(MmrFrontier::decode(&mut &full.encode()[..]).unwrap(), full);
699
700		let below = MAX_MMR_LEAF_COUNT - 1;
701		let mut last =
702			MmrFrontier::from_parts(vec![h(1); below.count_ones() as usize], below).unwrap();
703		assert_eq!(last.try_append(h(2)), Ok(()));
704		assert_eq!(last.leaf_count(), MAX_MMR_LEAF_COUNT);
705		assert_eq!(MmrFrontier::decode(&mut &last.encode()[..]).unwrap(), last);
706	}
707
708	#[test]
709	fn inclusion_proof_round_trips() {
710		let store = MemStore::<Hash>::default();
711		let mut mmr = MemMMR::<Hash, SpecMerge>::new(0, &store);
712		let positions: Vec<u64> = (0..6u8).map(|i| mmr.push(h(i)).unwrap()).collect();
713		let root = mmr.get_root().unwrap();
714
715		let proof: MerkleProof<Hash, SpecMerge> =
716			mmr.gen_proof(vec![leaf_index_to_pos(1), leaf_index_to_pos(4)]).unwrap();
717
718		assert!(proof.verify(root, vec![(positions[1], h(1)), (positions[4], h(4))]).unwrap());
719		assert!(!proof.verify(root, vec![(positions[1], h(99)), (positions[4], h(4))]).unwrap());
720	}
721
722	#[test]
723	fn extension_computes_root_and_rejects_tampering() {
724		let all = leaves(5);
725		let ext = extension(&all, 2, 5);
726		// Computes root@5 from frontier@2 + O(log n) connecting nodes (never a declared root).
727		assert_eq!(ext.calculate_root(&frontier_at(&all, 2)), Ok(root_at(&all, 5)));
728		// Wrong starting frontier → does not reconstruct the extended root.
729		assert_ne!(ext.calculate_root(&frontier_at(&all, 3)), Ok(root_at(&all, 5)));
730		// Tampered connecting node → a different computed root.
731		let mut bad = ext.clone();
732		bad.connecting_nodes[0] = H256::repeat_byte(0xff);
733		assert_ne!(bad.calculate_root(&frontier_at(&all, 2)), Ok(root_at(&all, 5)));
734		// Identity extension yields the frontier's own root.
735		let id = MmrExtensionProof::identity(&frontier_at(&all, 3));
736		assert_eq!(id.calculate_root(&frontier_at(&all, 3)), Ok(root_at(&all, 3)));
737	}
738
739	/// `connecting_nodes` stores bare hashes, so the positions we derive must match what
740	/// `gen_ancestry_proof` emits. Checked for every `(old, new)` pair up to 256 leaves, which
741	/// includes the seven- and eight-peak sizes 127 and 255. A change in `mmr_lib` trips this;
742	/// `Cargo.lock` pins it.
743	#[test]
744	fn ancestry_positions_matches_mmr_lib() {
745		for n in 2..=256usize {
746			let all = leaves(n as u64);
747			let store = MemStore::<Hash>::default();
748			let mut mmr = MemMMR::<Hash, SpecMerge>::new(0, &store);
749			for l in &all {
750				mmr.push(*l).unwrap();
751			}
752			for k in 1..n {
753				let ap = mmr.gen_ancestry_proof(mmr_size(k)).unwrap();
754				let expected: Vec<u64> =
755					ap.prev_peaks_proof.proof_items().iter().map(|(p, _)| *p).collect();
756				let got =
757					mmr_lib::ancestry_proof::ancestry_proof_positions(mmr_size(k), mmr_size(n))
758						.unwrap();
759				assert_eq!(got, expected, "position mismatch at k={k}, n={n}");
760			}
761		}
762	}
763
764	#[test]
765	fn extension_leaf_count_disambiguates_equal_node_counts() {
766		// 1→3 and 1→4 both take two nodes, placed differently, so only `leaf_count` tells them
767		// apart.
768		let all = leaves(4);
769		let to3 = extension(&all, 1, 3);
770		let to4 = extension(&all, 1, 4);
771		assert_eq!(to3.connecting_nodes.len(), 2);
772		assert_eq!(to4.connecting_nodes.len(), 2);
773		let from1 = frontier_at(&all, 1);
774		assert_eq!(to3.calculate_root(&from1), Ok(root_at(&all, 3)));
775		assert_eq!(to4.calculate_root(&from1), Ok(root_at(&all, 4)));
776		// The same two nodes under the other count place differently and reach neither root.
777		let relabelled =
778			MmrExtensionProof { leaf_count: 4, connecting_nodes: to3.connecting_nodes };
779		let got = relabelled.calculate_root(&from1);
780		assert_ne!(got, Ok(root_at(&all, 3)));
781		assert_ne!(got, Ok(root_at(&all, 4)));
782	}
783
784	#[test]
785	fn extension_verify_rejects_non_forward() {
786		let all = leaves(5);
787		// A real extension pointed *back* below the frontier's size is rejected up front, before
788		// any crypto work.
789		let mut ext = extension(&all, 2, 5);
790		ext.leaf_count = 1;
791		assert_eq!(ext.calculate_root(&frontier_at(&all, 2)), Err(ProofError::NotForward));
792	}
793
794	#[test]
795	fn extension_verify_bounds_untrusted_leaf_counts() {
796		let all = leaves(5);
797		// The proof's own count. A value whose derived node count would overflow `u64` is rejected
798		// before any position is computed from it.
799		let mut ext = extension(&all, 2, 5);
800		ext.leaf_count = u64::MAX;
801		assert_eq!(ext.calculate_root(&frontier_at(&all, 2)), Err(ProofError::LeafCountTooLarge));
802		ext.leaf_count = MAX_MMR_LEAF_COUNT + 1;
803		assert_eq!(ext.calculate_root(&frontier_at(&all, 2)), Err(ProofError::LeafCountTooLarge));
804		// The frontier's count is not this function's to check. An out-of-range `MmrFrontier`
805		// cannot be built, from `from_parts` or from `Decode`.
806		assert!(MmrFrontier::from_parts(vec![all[0]], 1 << 63).is_none());
807	}
808
809	#[test]
810	fn identity_verifies_to_the_frontier_root() {
811		let all = leaves(5);
812		for f in [MmrFrontier::new(), frontier_at(&all, 1), frontier_at(&all, 5)] {
813			let id = MmrExtensionProof::identity(&f);
814			assert_eq!(id.leaf_count, f.leaf_count());
815			assert!(id.connecting_nodes.is_empty());
816			assert_eq!(id.calculate_root(&f), Ok(f.root()));
817		}
818		assert_eq!(
819			MmrExtensionProof::identity(&MmrFrontier::new()).calculate_root(&MmrFrontier::new()),
820			Ok(empty_root()),
821		);
822	}
823
824	#[test]
825	fn empty_extension_is_only_the_identity() {
826		let all = leaves(5);
827		let f = frontier_at(&all, 3);
828		let empty =
829			|leaf_count| MmrExtensionProof { leaf_count, connecting_nodes: BoundedVec::new() };
830		// Below the frontier, including `0` on a non-empty one.
831		assert_eq!(empty(0).calculate_root(&f), Err(ProofError::NotForward));
832		assert_eq!(empty(2).calculate_root(&f), Err(ProofError::NotForward));
833		// Above it, no nodes cannot reach the new root.
834		assert_eq!(empty(4).calculate_root(&f), Err(ProofError::InvalidProof));
835		assert_eq!(empty(5).calculate_root(&f), Err(ProofError::InvalidProof));
836		assert_eq!(
837			empty(MAX_MMR_LEAF_COUNT + 1).calculate_root(&f),
838			Err(ProofError::LeafCountTooLarge)
839		);
840		// From the empty frontier any non-zero count without peaks is malformed.
841		assert_eq!(empty(1).calculate_root(&MmrFrontier::new()), Err(ProofError::InvalidProof));
842	}
843
844	#[test]
845	fn equal_count_with_connecting_nodes_is_invalid() {
846		let all = leaves(5);
847		for f in [MmrFrontier::new(), frontier_at(&all, 3)] {
848			let mut id = MmrExtensionProof::identity(&f);
849			id.connecting_nodes.try_push(h(1)).unwrap();
850			assert_eq!(id.calculate_root(&f), Err(ProofError::InvalidProof));
851		}
852	}
853
854	#[test]
855	fn the_longest_valid_extension_fits_the_node_ceiling() {
856		// Worst case, one node per set bit: 1 → the largest all-ones count. The lift's PoV
857		// reservation relies on it.
858		let nodes = mmr_lib::ancestry_proof::ancestry_proof_positions(
859			mmr_size(1),
860			mmr_size((MAX_MMR_LEAF_COUNT - 1) as usize),
861		)
862		.unwrap()
863		.len();
864		assert_eq!(nodes, 48);
865		assert!(nodes <= MAX_MMR_HASHES as usize);
866	}
867
868	#[test]
869	fn over_long_extension_proof_fails_to_decode() {
870		// The bound is in the type, so an over-long proof is rejected at the length prefix.
871		let max = MAX_MMR_HASHES as usize;
872		let at_bound = (codec::Compact(5u64), vec![H256::zero(); max]).encode();
873		assert!(MmrExtensionProof::decode(&mut &at_bound[..]).is_ok());
874		let over = (codec::Compact(5u64), vec![H256::zero(); max + 1]).encode();
875		assert!(MmrExtensionProof::decode(&mut &over[..]).is_err());
876	}
877
878	#[test]
879	fn leaf_hash_is_payload_only_and_version_disjoint() {
880		let payload = b"hello";
881		// Matches the explicit preimage `H(LEAF_TAG ++ version ++ payload)`.
882		let mut pre = Vec::new();
883		pre.push(LEAF_TAG);
884		pre.push(0u8);
885		pre.extend_from_slice(payload);
886		assert_eq!(leaf_hash(payload), <SpecHasher as HashT>::hash(&pre));
887		assert_eq!(leaf_hash(payload), leaf_hash_with_version(0, payload));
888		// Different version → different leaf (hash-disjoint domains).
889		assert_ne!(leaf_hash(payload), leaf_hash_with_version(1, payload));
890	}
891
892	#[test]
893	fn leaf_hash_frozen_vector() {
894		// FROZEN consensus vector: `H(0x01 ‖ 0x00 ‖ "hello")`. Any change to `LEAF_TAG`,
895		// `LEAF_VERSION`, the preimage layout or the hasher breaks this.
896		assert_eq!(
897			leaf_hash(b"hello"),
898			Hash::from(hex_literal::hex!(
899				"cd31917fb8992dae762dbaaf276d8eb65aa89cdfb87daf69e05f8c08b490e78b"
900			))
901		);
902	}
903
904	/// Every rebase from `from` past `later` leaves to `count` equals the extension built from
905	/// the leaves with `mmr_lib`, for every `1 <= from < later <= count <= 120`.
906	#[test]
907	fn a_rebased_extension_is_the_one_built_from_the_leaves() {
908		let all = leaves(120);
909		let mut checked = 0;
910		for count in 2..=all.len() {
911			for later in 2..=count {
912				let given = if later == count {
913					MmrExtensionProof::identity(&frontier_at(&all, count))
914				} else {
915					extension(&all, later, count)
916				};
917				for from in 1..later {
918					let rebased = given.rebase(&frontier_at(&all, from), &all[from..later]);
919					assert_eq!(
920						rebased.as_ref(),
921						Some(&extension(&all, from, count)),
922						"{from}, {later}, {count}"
923					);
924					checked += 1;
925				}
926			}
927		}
928		assert_eq!(checked, (2..=120u64).map(|n| n * (n - 1) / 2).sum::<u64>());
929	}
930
931	/// The extension from `from` over `leaves`, built from `from`'s peaks alone, so `from` can
932	/// stand for any count up to [`MAX_MMR_LEAF_COUNT`].
933	fn extension_from(from: &MmrFrontier, leaves: &[Hash]) -> MmrExtensionProof {
934		let store = MemStore::<Hash>::default();
935		let old_size = mmr_size(from.leaf_count() as usize);
936		for (pos, peak) in mmr_lib::helper::get_peaks(old_size).into_iter().zip(from.peaks()) {
937			mmr_lib::MMRStoreWriteOps::append(&mut &store, pos, vec![*peak]).unwrap();
938		}
939		let mut mmr = MemMMR::<Hash, SpecMerge>::new(old_size, &store);
940		for leaf in leaves {
941			mmr.push(*leaf).unwrap();
942		}
943		let new_count = from.leaf_count() + leaves.len() as u64;
944		let proof = mmr.gen_ancestry_proof(old_size).unwrap();
945		MmrExtensionProof {
946			leaf_count: new_count,
947			connecting_nodes: BoundedVec::truncate_from(
948				proof.prev_peaks_proof.proof_items().iter().map(|(_, h)| *h).collect::<Vec<_>>(),
949			),
950		}
951	}
952
953	/// The rebase check of [`a_rebased_extension_is_the_one_built_from_the_leaves`] at counts up to
954	/// [`MAX_MMR_LEAF_COUNT`]: made-up peaks stand for every subtree before the start, real
955	/// leaves follow it.
956	#[test]
957	fn a_rebase_at_large_counts_is_the_extension_built_from_the_leaves() {
958		let all = leaves(24);
959		let mut checked = 0;
960		for start in [(1 << 33) - 1, (1 << 40) + 12_345, (1 << 47) - 5, MAX_MMR_LEAF_COUNT - 24] {
961			let peaks = (0..u64::from(start.count_ones()))
962				.map(|i| H256::from_low_u64_be(0xF000_0000 + i))
963				.collect();
964			let base = MmrFrontier::from_parts(peaks, start).expect("one peak per set bit");
965			let at = |n: usize| {
966				let mut frontier = base.clone();
967				all[..n].iter().for_each(|leaf| frontier.append(*leaf));
968				frontier
969			};
970			for count in 1..=all.len() {
971				for later in 1..=count {
972					let given = if later == count {
973						MmrExtensionProof::identity(&at(count))
974					} else {
975						extension_from(&at(later), &all[later..count])
976					};
977					for from in 0..later {
978						let rebased = given.rebase(&at(from), &all[from..later]);
979						assert_eq!(
980							rebased.as_ref(),
981							Some(&extension_from(&at(from), &all[from..count])),
982							"{start} + {from}, {later}, {count}"
983						);
984						checked += 1;
985					}
986				}
987			}
988		}
989		assert_eq!(checked, 4 * (1..=24u64).map(|n| n * (n + 1) / 2).sum::<u64>());
990	}
991
992	#[test]
993	fn a_rebase_needs_a_start_and_a_proof_that_fits() {
994		let all = leaves(9);
995		let at = |n: usize| frontier_at(&all, n);
996		let given = extension(&all, 6, 9);
997
998		// No leaves: the extension itself.
999		assert_eq!(given.rebase(&at(6), &[]), Some(given.clone()));
1000		// From the empty stream, the proof is the new peaks themselves.
1001		assert_eq!(given.rebase(&MmrFrontier::new(), &all[..6]), None);
1002		// Leaves past the proof's count.
1003		let to_seven = extension(&all, 5, 7);
1004		assert_eq!(to_seven.rebase(&at(4), &all[4..9]), None);
1005		// A node too many or too few for the counts.
1006		let mut long = given.clone();
1007		long.connecting_nodes.try_push(all[0]).expect("room for one more");
1008		assert_eq!(long.rebase(&at(4), &all[4..6]), None);
1009		let mut short = given.clone();
1010		short.connecting_nodes.truncate(given.connecting_nodes.len() - 1);
1011		assert_eq!(short.rebase(&at(4), &all[4..6]), None);
1012		// The same proof with every node in place rebases.
1013		assert_eq!(given.rebase(&at(4), &all[4..6]), Some(extension(&all, 4, 9)));
1014	}
1015}