referrerpolicy=no-referrer-when-downgrade

cumulus_primitives_spec_messaging/
lift.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//! Requires-lift and consumption-record primitives.
18//!
19//! Blocks never emit `Requires` and never see a `StreamsRoot`. Processing the messaging inherent
20//! writes a [`ConsumptionRecord`]: which streams the block touched and the [`Interval`] consumed on
21//! each. The `validate_block` wrapper then synthesizes the candidate's `Requires` set from the
22//! records plus PoV-carried lifts ([`RequiresLift`]), one per recorded stream, binding that
23//! stream's consumption to a current committed `StreamsRoot`. The relay chain sees only entries it
24//! can match.
25//!
26//! The invariant [`build_requires`] enforces, per stream and candidate: the recorded intervals form
27//! a proven forward chain (each block continues where the previous ended, or a PoV proof shows the
28//! gap is a forward extension, see [`stitch`]), and one lift binds the chain's endpoint to a
29//! committed root, which binds everything consumed.
30//!
31//! The record is STF output and trusted; the lifts are PoV data and verified here.
32
33use alloc::{collections::BTreeMap, vec::Vec};
34use codec::{Decode, DecodeWithMemTracking, Encode, MaxEncodedLen};
35use polkadot_parachain_primitives::primitives::Id as ParaId;
36use polkadot_primitives::{v9::MAX_COMMITMENT_ENTRIES, RequiresSet};
37use scale_info::TypeInfo;
38use sp_core::ConstU32;
39use sp_runtime::BoundedVec;
40
41use crate::{
42	mmr::{MmrExtensionProof, MmrFrontier, MmrRoot},
43	stream::StreamId,
44	streams_root::{streams_root_from_proof, StreamProof, StreamsRoot},
45};
46
47/// Per stream and block: consumption entered the block at `start` and left it at `end`.
48///
49/// The candidate's lift binds only the last state to a committed root; the intervals extend that
50/// guarantee back over the bundle. Each block must start where the previous ended, or prove the
51/// jump moved forward ([`stitch`]).
52///
53/// - Channels: `start` is the frontier root before the block's incoming messages, `end` the
54/// frontier after. `start == previous end` holds by construction, so the chain check is free.
55/// - Register and event reads: `start` is the root of the frontier before the read's payloads, and
56/// `end` is the frontier after appending them. Contexts can skip leaves between blocks, so a skip
57/// is a gap and must be proven forward.
58///
59/// `end` is a full frontier because the next gap check, or the lift, extends from it.
60#[derive(
61	Clone, Encode, Decode, DecodeWithMemTracking, MaxEncodedLen, PartialEq, Eq, Debug, TypeInfo,
62)]
63pub struct Interval {
64	/// Root the block's consumption on this stream started from.
65	pub start: MmrRoot,
66	/// Frontier the block's consumption on this stream ended at.
67	pub end: MmrFrontier,
68}
69
70/// Written per block: the streams this block touched and the interval consumed on each, grouped by
71/// source. The API view of a flat, host-append-only outbox vec.
72#[derive(Clone, Encode, Decode, PartialEq, Eq, Debug, TypeInfo, Default)]
73pub struct ConsumptionRecord {
74	/// Per source, one interval per stream in `StreamId` order, the order the lifts match against.
75	/// A list rather than a map, so a duplicate stays visible and [`build_requires`] rejects it.
76	pub entries: BTreeMap<ParaId, Vec<(StreamId, Interval)>>,
77}
78
79/// One source's streams with their intervals across a bundle, in block order. [`build_requires`]
80/// merges the per-block records into this and [`build_requires_entry`] lifts it.
81pub type SourceStreams = BTreeMap<StreamId, Vec<Interval>>;
82
83/// One lift, carried in the PoV. Matched by position to a source's `StreamId`-sorted record
84/// streams.
85#[derive(Clone, Encode, Decode, DecodeWithMemTracking, PartialEq, Eq, Debug, TypeInfo)]
86pub struct RequiresLift {
87	/// One extension per gap in the stream's interval chain, in gap order. Empty when there are no
88	/// gaps.
89	pub advances: Vec<MmrExtensionProof>,
90	/// Extends the chain's endpoint to the stream's current root. The identity of the endpoint's
91	/// frontier when it already is that root.
92	pub extension: MmrExtensionProof,
93	/// Keyed walk from the current stream root to the `StreamsRoot` the requires entry becomes.
94	pub tree_proof: StreamProof,
95}
96
97/// The candidate's lifts, grouped per source: the PoV transport form. `Decode` enforces strictly
98/// increasing `ParaId`s and bounds the source count at [`MAX_COMMITMENT_ENTRIES`], so more sources
99/// than a `RequiresSet` can hold are rejected before any lift is verified.
100/// [`TryFrom<BTreeMap>`](Self::try_from) is canonical by construction. [`build_requires`] zips
101/// these against the record's sources by position.
102#[derive(Clone, Encode, PartialEq, Eq, Debug, TypeInfo, Default)]
103pub struct LiftsBySource(BoundedVec<(ParaId, Vec<RequiresLift>), ConstU32<MAX_COMMITMENT_ENTRIES>>);
104
105impl LiftsBySource {
106	/// The sources, in strictly increasing order.
107	pub fn sources(&self) -> impl Iterator<Item = &ParaId> {
108		self.0.iter().map(|(source, _)| source)
109	}
110
111	/// `(source, lifts)` pairs, in source order.
112	pub fn iter(&self) -> impl Iterator<Item = &(ParaId, Vec<RequiresLift>)> {
113		self.0.iter()
114	}
115
116	pub fn len(&self) -> usize {
117		self.0.len()
118	}
119
120	pub fn is_empty(&self) -> bool {
121		self.0.is_empty()
122	}
123}
124
125impl TryFrom<BTreeMap<ParaId, Vec<RequiresLift>>> for LiftsBySource {
126	type Error = LiftError;
127
128	/// A map iterates in `ParaId` order with unique keys, so only the bound can fail.
129	fn try_from(map: BTreeMap<ParaId, Vec<RequiresLift>>) -> Result<Self, LiftError> {
130		BoundedVec::try_from(map.into_iter().collect::<Vec<_>>())
131			.map(Self)
132			.map_err(|_| LiftError::TooManySources)
133	}
134}
135
136/// Matches the derived `Encode`. The sequence must be strictly increasing by `ParaId`.
137impl Decode for LiftsBySource {
138	fn decode<I: codec::Input>(input: &mut I) -> Result<Self, codec::Error> {
139		let inner =
140			BoundedVec::<(ParaId, Vec<RequiresLift>), ConstU32<MAX_COMMITMENT_ENTRIES>>::decode(
141				input,
142			)?;
143		if inner.windows(2).any(|w| w[0].0 >= w[1].0) {
144			return Err("LiftsBySource: sources must be strictly increasing".into());
145		}
146		Ok(Self(inner))
147	}
148}
149
150impl DecodeWithMemTracking for LiftsBySource {}
151
152/// Why requires synthesis failed. All are deterministic in the records and PoV, so every validator
153/// reaches the same verdict.
154#[derive(Clone, Copy, PartialEq, Eq, Debug)]
155pub enum LiftError {
156	/// A stream's interval list was empty.
157	EmptyRecord,
158	/// A block's record listed a source's streams out of order or more than once.
159	UnsortedRecord,
160	/// A gap needed a forward-extension proof but `advances` was exhausted.
161	MissingAdvance,
162	/// `advances` carried more proofs than there were gaps.
163	StrayAdvance,
164	/// A gap's proof did not forward-extend the previous endpoint to the next start.
165	BrokenChain,
166	/// The endpoint extension did not verify against the stitched endpoint.
167	BadExtension,
168	/// The tree proof did not fold to a `StreamsRoot` (malformed / wrong key).
169	BadTreeProof,
170	/// A source's stream count and lift count disagreed.
171	LiftCountMismatch,
172	/// A source's streams lifted to more than one `StreamsRoot`.
173	DivergentRoots,
174	/// The recorded sources and the provided lifts' sources did not match exactly.
175	LiftSourceMismatch,
176	/// More sources than the `RequiresSet` bound allows.
177	TooManySources,
178}
179
180/// Stitch one stream's intervals, in bundle order, into its endpoint frontier. `advances` must hold
181/// exactly one extension per gap (a `start` that is not the previous `end`'s root), in gap order.
182/// Gaps are proven forward, so within a candidate verified states cannot regress; across candidates
183/// that is the STF's to hold.
184pub fn stitch(
185	intervals: &[Interval],
186	advances: &[MmrExtensionProof],
187) -> Result<MmrFrontier, LiftError> {
188	let (first, rest) = intervals.split_first().ok_or(LiftError::EmptyRecord)?;
189	let mut gaps = advances.iter();
190	// `first.start` is the boundary with the previous candidate; nothing here can check it, and
191	// nothing needs to: everything consumed is bound through the chain from `first.end`.
192	// Cross-candidate continuity is the STF's (the stored frontier for channels; for register
193	// reads, the last applied position and the register's monotonic fields).
194	let mut current = &first.end;
195	for next in rest {
196		let current_root = current.root();
197		if next.start != current_root {
198			// A gap must be a proven forward extension of where we ended.
199			let proof = gaps.next().ok_or(LiftError::MissingAdvance)?;
200			let extended = proof.calculate_root(current).map_err(|_| LiftError::BrokenChain)?;
201			if extended != next.start {
202				return Err(LiftError::BrokenChain);
203			}
204		}
205		current = &next.end;
206	}
207	if gaps.next().is_some() {
208		return Err(LiftError::StrayAdvance);
209	}
210	Ok(current.clone())
211}
212
213/// Lift one source's streams to a single committed `StreamsRoot`: stitch each stream's intervals
214/// into an endpoint, extend it to the stream's current root, walk the tree to the `StreamsRoot`,
215/// and require all of the source's streams to reach the same root. `streams` iterates in `StreamId`
216/// order; `lifts` matches it by position.
217pub fn build_requires_entry(
218	streams: &SourceStreams,
219	lifts: &[RequiresLift],
220) -> Result<StreamsRoot, LiftError> {
221	if streams.len() != lifts.len() {
222		return Err(LiftError::LiftCountMismatch);
223	}
224	let mut entry: Option<StreamsRoot> = None;
225	for ((stream, intervals), lift) in streams.iter().zip(lifts) {
226		let endpoint = stitch(intervals, &lift.advances)?;
227		// The endpoint is contained in the stream's current root, computed rather than declared,
228		let current =
229			lift.extension.calculate_root(&endpoint).map_err(|_| LiftError::BadExtension)?;
230		// and the walk from it, keyed by the record's `stream`, yields the `StreamsRoot`.
231		let root = streams_root_from_proof(*stream, current.0, &lift.tree_proof)
232			.ok_or(LiftError::BadTreeProof)?;
233		match entry {
234			None => entry = Some(root),
235			Some(prev) if prev != root => return Err(LiftError::DivergentRoots),
236			Some(_) => {},
237		}
238	}
239	entry.ok_or(LiftError::EmptyRecord)
240}
241
242/// Synthesize the candidate's [`RequiresSet`] from the per-block records, in bundle order, and the
243/// PoV lifts. Sources must match exactly; a recorded source without lifts, or lifts for an
244/// unrecorded source, invalidates the candidate.
245///
246/// `None` when the candidate consumed nothing: there is no entry the relay could match, and the
247/// candidate emits no `Requires` signal. `RequiresSet` cannot be empty.
248pub fn build_requires(
249	records: &[ConsumptionRecord],
250	lifts: &LiftsBySource,
251) -> Result<Option<RequiresSet>, LiftError> {
252	// Merge per (source, stream) intervals across the bundle, preserving block order.
253	let mut merged: BTreeMap<ParaId, SourceStreams> = BTreeMap::new();
254	for record in records {
255		for (source, streams) in &record.entries {
256			if streams.windows(2).any(|w| w[0].0 >= w[1].0) {
257				return Err(LiftError::UnsortedRecord);
258			}
259			let by_stream = merged.entry(*source).or_default();
260			for (stream, interval) in streams {
261				by_stream.entry(*stream).or_default().push(interval.clone());
262			}
263		}
264	}
265	// Recorded sources and lift sources must be equal; both are ParaId-sorted.
266	if !merged.keys().eq(lifts.sources()) {
267		return Err(LiftError::LiftSourceMismatch);
268	}
269	if merged.is_empty() {
270		return Ok(None);
271	}
272	let entries = merged
273		.iter()
274		.zip(lifts.iter())
275		.map(|((source, by_stream), (_, source_lifts))| {
276			build_requires_entry(by_stream, source_lifts).map(|root| (*source, root))
277		})
278		.collect::<Result<Vec<_>, _>>()?;
279	RequiresSet::try_from_iter(entries)
280		.map(Some)
281		.map_err(|_| LiftError::TooManySources)
282}
283
284#[cfg(test)]
285mod tests {
286	use super::*;
287	use crate::{
288		mmr::{ProofError, MAX_MMR_LEAF_COUNT},
289		streams_root::{gen_stream_proof, streams_root, TreeStep},
290		test_utils::{ch, extension, frontier_at, leaves},
291	};
292	use polkadot_core_primitives::Hash;
293	use polkadot_primitives::v9::MAX_COMMITMENT_ENTRIES;
294	use sp_core::H256;
295
296	/// Root over the first `k` leaves.
297	fn root_at(all: &[Hash], k: usize) -> MmrRoot {
298		frontier_at(all, k).root()
299	}
300
301	#[test]
302	fn stitch_caught_up_needs_no_advance() {
303		let all = leaves(5);
304		let i1 = Interval { start: MmrRoot(H256::zero()), end: frontier_at(&all, 2) };
305		let i2 = Interval { start: root_at(&all, 2), end: frontier_at(&all, 5) };
306		assert_eq!(stitch(&[i1, i2], &[]).unwrap(), frontier_at(&all, 5));
307	}
308
309	#[test]
310	fn stitch_bridges_a_gap_and_flags_bad_advance_counts() {
311		let all = leaves(5);
312		let i1 = Interval { start: MmrRoot(H256::zero()), end: frontier_at(&all, 2) };
313		// Block 2 jumped forward to context @4 before continuing to @5.
314		let i2 = Interval { start: root_at(&all, 4), end: frontier_at(&all, 5) };
315		let advance = extension(&all, 2, 4);
316
317		assert_eq!(
318			stitch(&[i1.clone(), i2.clone()], &[advance.clone()]).unwrap(),
319			frontier_at(&all, 5)
320		);
321		// Missing the gap proof.
322		assert_eq!(stitch(&[i1.clone(), i2.clone()], &[]), Err(LiftError::MissingAdvance));
323		// A stray advance where the chain was already continuous.
324		let cont = Interval { start: root_at(&all, 2), end: frontier_at(&all, 5) };
325		assert_eq!(stitch(&[i1, cont], &[advance]), Err(LiftError::StrayAdvance));
326	}
327
328	#[test]
329	fn stitch_rejects_a_gap_bridged_to_the_wrong_context() {
330		// The advance is all that binds the earlier read to the stream: a context the chain does
331		// not reach must fail, or a fabricated read could hide behind a later genuine one.
332		let all = leaves(5);
333		let i1 = Interval { start: MmrRoot(H256::zero()), end: frontier_at(&all, 2) };
334		let i2 = Interval { start: root_at(&all, 4), end: frontier_at(&all, 5) };
335		// A genuine extension of @2, but to @3, not to the context @4 block 2 started from.
336		assert_eq!(
337			stitch(&[i1.clone(), i2.clone()], &[extension(&all, 2, 3)]),
338			Err(LiftError::BrokenChain)
339		);
340		// An extension that does not fit @2 at all (built from @1).
341		assert_eq!(stitch(&[i1, i2], &[extension(&all, 1, 4)]), Err(LiftError::BrokenChain));
342	}
343
344	#[test]
345	fn stitch_rejects_a_backward_step() {
346		// A later block read an older context. Extensions only go forward, so nothing can bridge
347		// it; the pallet does not record an ignored stale read for this reason.
348		let all = leaves(5);
349		let i1 = Interval { start: MmrRoot(H256::zero()), end: frontier_at(&all, 4) };
350		let i2 = Interval { start: root_at(&all, 2), end: frontier_at(&all, 2) };
351		assert_eq!(stitch(&[i1.clone(), i2.clone()], &[]), Err(LiftError::MissingAdvance));
352		assert_eq!(stitch(&[i1, i2], &[extension(&all, 4, 5)]), Err(LiftError::BrokenChain));
353	}
354
355	#[test]
356	fn nothing_recorded_lifts_nothing() {
357		assert_eq!(stitch(&[], &[]), Err(LiftError::EmptyRecord));
358		assert_eq!(build_requires_entry(&SourceStreams::new(), &[]), Err(LiftError::EmptyRecord));
359	}
360
361	#[test]
362	fn an_empty_source_entry_fails_closed() {
363		// The pallet records a source only with a stream. An entry with none has nothing to lift,
364		// so the candidate is invalid rather than silently requiring nothing from that source.
365		let source = ParaId::from(1000);
366		let record = ConsumptionRecord { entries: BTreeMap::from([(source, Vec::new())]) };
367		let lifts = LiftsBySource::try_from(BTreeMap::from([(source, Vec::new())])).unwrap();
368		assert_eq!(build_requires(&[record], &lifts), Err(LiftError::EmptyRecord));
369	}
370
371	#[test]
372	fn a_duplicate_or_unsorted_record_fails_closed() {
373		let all = leaves(3);
374		let source = ParaId::from(7);
375		let (a, b) = (ch(1), ch(2));
376		let (ia, ib) = (
377			Interval { start: MmrRoot(H256::zero()), end: frontier_at(&all, 1) },
378			Interval { start: root_at(&all, 1), end: frontier_at(&all, 3) },
379		);
380		let lifts = LiftsBySource::try_from(BTreeMap::from([(source, Vec::new())])).unwrap();
381		for streams in [vec![(a, ia.clone()), (a, ib.clone())], vec![(b, ib), (a, ia)]] {
382			let record = ConsumptionRecord { entries: BTreeMap::from([(source, streams)]) };
383			// The decode keeps the bad entries for the check to see.
384			let decoded = ConsumptionRecord::decode(&mut &record.encode()[..]).unwrap();
385			assert_eq!(build_requires(&[decoded], &lifts), Err(LiftError::UnsortedRecord));
386		}
387	}
388
389	#[test]
390	fn hot_path_single_block_single_stream() {
391		let all = leaves(3);
392		let root3 = root_at(&all, 3);
393		let stream = ch(2000);
394		// StreamsRoot over the single active stream at root@3.
395		let entries = BTreeMap::from([(stream, root3.0)]);
396		let expected = streams_root(&entries).unwrap();
397		let (_r, tree_proof) = gen_stream_proof(&entries, stream).unwrap();
398
399		// One interval, endpoint = frontier@3; identity extension (caught up).
400		let interval = Interval { start: MmrRoot(H256::zero()), end: frontier_at(&all, 3) };
401		let lift = RequiresLift {
402			advances: Vec::new(),
403			extension: MmrExtensionProof::identity(&frontier_at(&all, 3)),
404			tree_proof,
405		};
406		let streams = SourceStreams::from([(stream, vec![interval])]);
407		let root = build_requires_entry(&streams, &[lift]).unwrap();
408		assert_eq!(root, expected);
409	}
410
411	#[test]
412	fn build_requires_end_to_end_and_source_match() {
413		let all = leaves(3);
414		let root3 = root_at(&all, 3);
415		let source = ParaId::from(1000);
416		let stream = ch(2000);
417		let entries = BTreeMap::from([(stream, root3.0)]);
418		let expected = streams_root(&entries).unwrap();
419		let (_r, tree_proof) = gen_stream_proof(&entries, stream).unwrap();
420
421		let record = ConsumptionRecord {
422			entries: BTreeMap::from([(
423				source,
424				vec![(
425					stream,
426					Interval { start: MmrRoot(H256::zero()), end: frontier_at(&all, 3) },
427				)],
428			)]),
429		};
430		let mut lifts = BTreeMap::new();
431		lifts.insert(
432			source,
433			vec![RequiresLift {
434				advances: Vec::new(),
435				extension: MmrExtensionProof::identity(&frontier_at(&all, 3)),
436				tree_proof,
437			}],
438		);
439
440		let lifts_by_source = LiftsBySource::try_from(lifts.clone()).unwrap();
441		let requires = build_requires(&[record.clone()], &lifts_by_source).unwrap().unwrap();
442		assert_eq!(requires.get(source), Some(&expected));
443
444		// A lift for an unrecorded source (or a missing one) is rejected.
445		let mut extra = lifts.clone();
446		extra.insert(ParaId::from(9999), Vec::new());
447		let extra = LiftsBySource::try_from(extra).unwrap();
448		assert_eq!(build_requires(&[record], &extra), Err(LiftError::LiftSourceMismatch));
449
450		// Nothing consumed, nothing lifted: no set, not an empty one.
451		assert_eq!(build_requires(&[], &LiftsBySource::default()), Ok(None));
452	}
453
454	#[test]
455	fn lifts_by_source_decode_enforces_canonical_form() {
456		let lift = || RequiresLift {
457			advances: Vec::new(),
458			extension: MmrExtensionProof::identity(&MmrFrontier::new()),
459			tree_proof: StreamProof { steps: Default::default() },
460		};
461		let pair = |id: u32| (ParaId::from(id), vec![lift()]);
462		// Canonical round-trips …
463		let good = vec![pair(1), pair(2)].encode();
464		assert!(LiftsBySource::decode(&mut &good[..]).is_ok());
465		// … out of order and duplicate sources do not …
466		let unsorted = vec![pair(2), pair(1)].encode();
467		assert!(LiftsBySource::decode(&mut &unsorted[..]).is_err());
468		let duplicate = vec![pair(1), pair(1)].encode();
469		assert!(LiftsBySource::decode(&mut &duplicate[..]).is_err());
470		// … and more sources than a RequiresSet could hold are rejected before any verification.
471		let too_many: Vec<_> = (0..=MAX_COMMITMENT_ENTRIES).map(pair).collect();
472		assert!(LiftsBySource::decode(&mut &too_many.encode()[..]).is_err());
473		// A map is canonical by construction; only the bound can fail it.
474		let map: BTreeMap<_, _> = (0..=MAX_COMMITMENT_ENTRIES).map(pair).collect();
475		assert_eq!(LiftsBySource::try_from(map).err(), Some(LiftError::TooManySources));
476	}
477
478	#[test]
479	fn late_block_non_identity_extension_end_to_end() {
480		// The block ended at @2 and the committed root is at @5: a real extension bridges them.
481		let all = leaves(5);
482		let stream = ch(2000);
483		let committed = root_at(&all, 5);
484		let entries = BTreeMap::from([(stream, committed.0)]);
485		let expected = streams_root(&entries).unwrap();
486		let (_r, tree_proof) = gen_stream_proof(&entries, stream).unwrap();
487
488		let interval = Interval { start: MmrRoot(H256::zero()), end: frontier_at(&all, 2) };
489		let lift =
490			RequiresLift { advances: Vec::new(), extension: extension(&all, 2, 5), tree_proof };
491		let streams = SourceStreams::from([(stream, vec![interval])]);
492		assert_eq!(build_requires_entry(&streams, &[lift]).unwrap(), expected);
493	}
494
495	#[test]
496	fn multi_stream_source_converges_on_one_root() {
497		// Two streams at different frontiers both lift to the source's one `StreamsRoot`.
498		let all = leaves(5);
499		let (a, b) = (ch(2000), ch(3000));
500		let (ra, rb) = (root_at(&all, 3), root_at(&all, 5));
501		let entries = BTreeMap::from([(a, ra.0), (b, rb.0)]);
502		let expected = streams_root(&entries).unwrap();
503		let (_pa, proof_a) = gen_stream_proof(&entries, a).unwrap();
504		let (_pb, proof_b) = gen_stream_proof(&entries, b).unwrap();
505
506		let lift = |tree_proof, n| RequiresLift {
507			advances: Vec::new(),
508			extension: MmrExtensionProof::identity(&frontier_at(&all, n)),
509			tree_proof,
510		};
511		// SourceStreams is keyed, so it iterates a, b — the order the lifts must match.
512		let streams = SourceStreams::from([
513			(a, vec![Interval { start: MmrRoot(H256::zero()), end: frontier_at(&all, 3) }]),
514			(b, vec![Interval { start: MmrRoot(H256::zero()), end: frontier_at(&all, 5) }]),
515		]);
516		assert_eq!(
517			build_requires_entry(&streams, &[lift(proof_a, 3), lift(proof_b, 5)]).unwrap(),
518			expected
519		);
520	}
521
522	#[test]
523	fn build_requires_covers_multiple_sources() {
524		// Two sources, each one stream → a two-entry RequiresSet, each entry the source's own root.
525		let all = leaves(3);
526		let committed = root_at(&all, 3);
527		let (src_a, src_b) = (ParaId::from(1000), ParaId::from(2000));
528		let stream = ch(4000);
529		let entries = BTreeMap::from([(stream, committed.0)]);
530		let expected = streams_root(&entries).unwrap();
531
532		let record_for = |source| {
533			let (_r, tree_proof) = gen_stream_proof(&entries, stream).unwrap();
534			let record = ConsumptionRecord {
535				entries: BTreeMap::from([(
536					source,
537					vec![(
538						stream,
539						Interval { start: MmrRoot(H256::zero()), end: frontier_at(&all, 3) },
540					)],
541				)]),
542			};
543			let lift = RequiresLift {
544				advances: Vec::new(),
545				extension: MmrExtensionProof::identity(&frontier_at(&all, 3)),
546				tree_proof,
547			};
548			(record, lift)
549		};
550		let (ra, la) = record_for(src_a);
551		let (rb, lb) = record_for(src_b);
552		let lifts = LiftsBySource::try_from(BTreeMap::from([(src_a, vec![la]), (src_b, vec![lb])]))
553			.unwrap();
554
555		let requires = build_requires(&[ra, rb], &lifts).unwrap().unwrap();
556		assert_eq!(requires.len(), 2);
557		assert_eq!(requires.get(src_a), Some(&expected));
558		assert_eq!(requires.get(src_b), Some(&expected));
559	}
560
561	#[test]
562	fn build_requires_entry_stitches_a_bundle_gap() {
563		// A bundle whose second block jumped @2 → @4: an advance bridges the gap, then the
564		// extension reaches the committed @5.
565		let all = leaves(5);
566		let stream = ch(2000);
567		let committed = root_at(&all, 5);
568		let entries = BTreeMap::from([(stream, committed.0)]);
569		let expected = streams_root(&entries).unwrap();
570		let (_r, tree_proof) = gen_stream_proof(&entries, stream).unwrap();
571
572		let intervals = vec![
573			Interval { start: MmrRoot(H256::zero()), end: frontier_at(&all, 2) },
574			Interval { start: root_at(&all, 4), end: frontier_at(&all, 5) }, // gap @2 → @4
575		];
576		let lift = RequiresLift {
577			advances: vec![extension(&all, 2, 4)], // bridges the gap
578			extension: MmrExtensionProof::identity(&frontier_at(&all, 5)), /* endpoint @5 already
579			                                        * the committed root */
580			tree_proof,
581		};
582		let streams = SourceStreams::from([(stream, intervals)]);
583		assert_eq!(build_requires_entry(&streams, &[lift]).unwrap(), expected);
584	}
585
586	#[test]
587	fn lift_count_must_match_stream_count() {
588		let all = leaves(3);
589		let stream = ch(2000);
590		let streams = SourceStreams::from([(
591			stream,
592			vec![Interval { start: MmrRoot(H256::zero()), end: frontier_at(&all, 3) }],
593		)]);
594		let lift = || RequiresLift {
595			advances: Vec::new(),
596			extension: MmrExtensionProof::identity(&frontier_at(&all, 3)),
597			tree_proof: StreamProof { steps: Default::default() },
598		};
599		// One stream, no lifts, and one stream, two lifts — both mismatch.
600		assert_eq!(build_requires_entry(&streams, &[]), Err(LiftError::LiftCountMismatch));
601		assert_eq!(
602			build_requires_entry(&streams, &[lift(), lift()]),
603			Err(LiftError::LiftCountMismatch)
604		);
605	}
606
607	#[test]
608	fn build_requires_entry_rejects_a_backward_extension() {
609		// A forged extension that does not go strictly forward fails verification → BadExtension,
610		// before any root is synthesized.
611		let all = leaves(5);
612		let stream = ch(2000);
613		let (_r, tree_proof) =
614			gen_stream_proof(&BTreeMap::from([(stream, root_at(&all, 5).0)]), stream).unwrap();
615		let streams = SourceStreams::from([(
616			stream,
617			vec![Interval { start: MmrRoot(H256::zero()), end: frontier_at(&all, 3) }],
618		)]);
619		// leaf_count 1 <= the endpoint's 3 leaves → NotForward inside `calculate_root` →
620		// BadExtension.
621		let lift = RequiresLift {
622			advances: Vec::new(),
623			extension: MmrExtensionProof { leaf_count: 1, connecting_nodes: BoundedVec::new() },
624			tree_proof,
625		};
626		assert_eq!(build_requires_entry(&streams, &[lift]), Err(LiftError::BadExtension));
627	}
628
629	#[test]
630	fn stitch_ignores_the_first_interval_start() {
631		// `first.start` is the boundary with the previous candidate and is deliberately unchecked;
632		// garbage there does not affect the stitched endpoint.
633		let all = leaves(5);
634		let garbage =
635			Interval { start: MmrRoot(H256::repeat_byte(0xEE)), end: frontier_at(&all, 2) };
636		let cont = Interval { start: root_at(&all, 2), end: frontier_at(&all, 5) };
637		assert_eq!(stitch(&[garbage, cont], &[]).unwrap(), frontier_at(&all, 5));
638	}
639
640	#[test]
641	fn build_requires_entry_rejects_a_malformed_tree_proof() {
642		// A hand-built step with an out-of-range split bit (a one-stream tree has no real steps).
643		let all = leaves(3);
644		let stream = ch(2000);
645		let streams = SourceStreams::from([(
646			stream,
647			vec![Interval { start: MmrRoot(H256::zero()), end: frontier_at(&all, 3) }],
648		)]);
649		// `split_bit == KEY_BITS` (64) is past the key; the fold rejects it.
650		let bad = StreamProof {
651			steps: BoundedVec::try_from(vec![TreeStep { split_bit: 64, sibling: H256::zero() }])
652				.unwrap(),
653		};
654		let lift = RequiresLift {
655			advances: Vec::new(),
656			extension: MmrExtensionProof::identity(&frontier_at(&all, 3)),
657			tree_proof: bad,
658		};
659		assert_eq!(build_requires_entry(&streams, &[lift]), Err(LiftError::BadTreeProof));
660	}
661
662	#[test]
663	fn build_requires_entry_flags_missing_and_stray_advances() {
664		// stitch's advance-count errors, reached through the entry path rather than in isolation.
665		let all = leaves(5);
666		let stream = ch(2000);
667		let (_r, tree_proof) =
668			gen_stream_proof(&BTreeMap::from([(stream, root_at(&all, 5).0)]), stream).unwrap();
669		let mk = |intervals, advances| {
670			let lift = RequiresLift {
671				advances,
672				extension: MmrExtensionProof::identity(&frontier_at(&all, 5)),
673				tree_proof: tree_proof.clone(),
674			};
675			build_requires_entry(&SourceStreams::from([(stream, intervals)]), &[lift])
676		};
677
678		// Gap @2 → @4 with no advance to bridge it.
679		let gapped = vec![
680			Interval { start: MmrRoot(H256::zero()), end: frontier_at(&all, 2) },
681			Interval { start: root_at(&all, 4), end: frontier_at(&all, 5) },
682		];
683		assert_eq!(mk(gapped, Vec::new()), Err(LiftError::MissingAdvance));
684
685		// Continuous @2 → @2 but an advance supplied anyway.
686		let continuous = vec![
687			Interval { start: MmrRoot(H256::zero()), end: frontier_at(&all, 2) },
688			Interval { start: root_at(&all, 2), end: frontier_at(&all, 5) },
689		];
690		assert_eq!(mk(continuous, vec![extension(&all, 2, 4)]), Err(LiftError::StrayAdvance));
691	}
692
693	#[test]
694	fn divergent_roots_rejected() {
695		let all = leaves(3);
696		let root3 = root_at(&all, 3);
697		let (sa, sb) = (ch(2000), ch(3000));
698
699		// Two single-stream trees → each stream's tree_proof folds to a DIFFERENT StreamsRoot.
700		let (_ra, proof_a) = gen_stream_proof(&BTreeMap::from([(sa, root3.0)]), sa).unwrap();
701		let (_rb, proof_b) = gen_stream_proof(&BTreeMap::from([(sb, root3.0)]), sb).unwrap();
702
703		let mk = |tree_proof| RequiresLift {
704			advances: Vec::new(),
705			extension: MmrExtensionProof::identity(&frontier_at(&all, 3)),
706			tree_proof,
707		};
708		let streams = SourceStreams::from([
709			(sa, vec![Interval { start: MmrRoot(H256::zero()), end: frontier_at(&all, 3) }]),
710			(sb, vec![Interval { start: MmrRoot(H256::zero()), end: frontier_at(&all, 3) }]),
711		]);
712		assert_eq!(
713			build_requires_entry(&streams, &[mk(proof_a), mk(proof_b)]),
714			Err(LiftError::DivergentRoots),
715		);
716	}
717
718	#[test]
719	fn encoded_len_for_matches_generated_proofs_and_rejects_other_node_counts() {
720		// Out-of-range inputs return None without panicking.
721		assert_eq!(MmrExtensionProof::encoded_len_for(0, 1), None);
722		assert_eq!(MmrExtensionProof::encoded_len_for(5, 4), None);
723		assert_eq!(MmrExtensionProof::encoded_len_for(1, MAX_MMR_LEAF_COUNT + 1), None);
724		assert_eq!(
725			MmrExtensionProof::encoded_len_for(MAX_MMR_LEAF_COUNT + 1, MAX_MMR_LEAF_COUNT + 1),
726			None,
727		);
728
729		// Equal counts need no skip proof (0 bytes).
730		for n in [1, 2, 64, 1 << 20, MAX_MMR_LEAF_COUNT] {
731			assert_eq!(MmrExtensionProof::encoded_len_for(n, n), Some(0));
732		}
733
734		// Exhaustively check every pair up to 64 leaves against real generated proofs, and verify
735		// that padded or truncated connecting_nodes are rejected by `verify`.
736		let all = leaves(64);
737		for n2 in 2..=64usize {
738			for n1 in 1..n2 {
739				let from = frontier_at(&all, n1);
740				let proof = extension(&all, n1, n2);
741				assert_eq!(
742					MmrExtensionProof::encoded_len_for(n1 as u64, n2 as u64),
743					Some(proof.encoded_size()),
744					"encoded_len_for mismatch at {n1} -> {n2}"
745				);
746				assert!(proof.encoded_size() <= MmrExtensionProof::max_encoded_len());
747
748				// Truncated proof must fail verify.
749				let mut truncated = proof.clone();
750				truncated.connecting_nodes.pop();
751				assert_eq!(truncated.calculate_root(&from), Err(ProofError::InvalidProof));
752
753				// Padded proof must fail verify.
754				let mut padded = proof;
755				padded.connecting_nodes.try_push(H256::zero()).expect("<= 64 leaves < 48; qed");
756				assert_eq!(padded.calculate_root(&from), Err(ProofError::InvalidProof));
757			}
758		}
759
760		// Power-of-two and worst-case edge pairs up to MAX_MMR_LEAF_COUNT.
761		let edge_counts = [
762			1,
763			2,
764			3,
765			(1 << 16) - 1,
766			1 << 16,
767			(1 << 32) - 1,
768			1 << 32,
769			(1 << 47) - 1,
770			1 << 47,
771			MAX_MMR_LEAF_COUNT - 1,
772			MAX_MMR_LEAF_COUNT,
773		];
774		for (i, &n1) in edge_counts.iter().enumerate() {
775			for &n2 in &edge_counts[i + 1..] {
776				let len = MmrExtensionProof::encoded_len_for(n1, n2).unwrap();
777				assert!(
778					len <= MmrExtensionProof::max_encoded_len(),
779					"{n1} -> {n2}: {len} > {}",
780					MmrExtensionProof::max_encoded_len()
781				);
782			}
783		}
784		// Worst-case extension (1 -> 2^48 - 1) takes 48 hashes: 7 + 1 + 48*32 = 1,544 bytes
785		// (`Compact(2^48 - 1)` is 7 bytes; `MaxEncodedLen` reserves 8 bytes for `#[codec(compact)]
786		// u64` = 1,545 bytes).
787		assert_eq!(MmrExtensionProof::encoded_len_for(1, MAX_MMR_LEAF_COUNT - 1), Some(1_544));
788		assert_eq!(MmrExtensionProof::max_encoded_len(), 1_545);
789		assert_eq!(StreamProof::max_encoded_len(), 2_114);
790	}
791
792	/// The PoV reservation for a lossy read is `encoded_len_for(previous end, read start)`. Over
793	/// random read sequences (adjacent reads, skips, cut reads), the reserved bytes must equal the
794	/// encoded advances that `stitch` accepts.
795	#[test]
796	fn reserved_skip_bytes_equal_the_advances_stitch_accepts() {
797		const N: usize = 256;
798		let all = leaves(N as u64);
799		let mut seed = 0x9E37_79B9_7F4A_7C15u64;
800		let mut next = |bound: usize| {
801			seed ^= seed << 13;
802			seed ^= seed >> 7;
803			seed ^= seed << 17;
804			seed as usize % bound
805		};
806
807		for _ in 0..300 {
808			let first = next(N / 2);
809			let mut prev_end = first + 1 + next(8);
810			let mut intervals =
811				vec![Interval { start: root_at(&all, first), end: frontier_at(&all, prev_end) }];
812			let (mut reserved, mut advances) = (0, Vec::new());
813			loop {
814				// A third of reads continue where the last one ended; the rest skip ahead.
815				let skip_bound = 1 << next(7);
816				let start = prev_end + if next(3) == 0 { 0 } else { 1 + next(skip_bound) };
817				let end = start + 1 + next(8);
818				if end > N {
819					break;
820				}
821				reserved += MmrExtensionProof::encoded_len_for(prev_end as u64, start as u64)
822					.expect("1 <= prev_end <= start <= N; qed");
823				if start > prev_end {
824					advances.push(extension(&all, prev_end, start));
825				}
826				intervals
827					.push(Interval { start: root_at(&all, start), end: frontier_at(&all, end) });
828				prev_end = end;
829			}
830
831			assert_eq!(stitch(&intervals, &advances), Ok(frontier_at(&all, prev_end)));
832			assert_eq!(reserved, advances.iter().map(Encode::encoded_size).sum::<usize>());
833		}
834	}
835
836	#[test]
837	fn extension_proof_frozen_layout() {
838		assert_eq!(MmrExtensionProof::identity(&MmrFrontier::new()).encode(), vec![0x00, 0x00]);
839
840		let proof = MmrExtensionProof {
841			leaf_count: 1 << 47,
842			connecting_nodes: BoundedVec::truncate_from(vec![
843				H256::repeat_byte(0x01),
844				H256::repeat_byte(0x02),
845			]),
846		};
847		// Compact `2^47` takes the big-integer mode: a 0x0B length byte (6 bytes), then LE.
848		let mut expected = vec![0x0B, 0, 0, 0, 0, 0, 0x80, 0x08];
849		expected.extend([0x01; 32]);
850		expected.extend([0x02; 32]);
851		assert_eq!(proof.encode(), expected);
852		assert_eq!(MmrExtensionProof::decode(&mut &expected[..]).unwrap(), proof);
853	}
854}