referrerpolicy=no-referrer-when-downgrade

cumulus_aura_authorizer_utils/
merkle.rs

1// This file is part of Cumulus.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18use alloc::vec::Vec;
19use primitive_types::H256;
20use sp_crypto_hashing::blake2_256;
21
22use crate::token::CollatorKey;
23
24/// Blake2b-256 adapter for the SDK's binary Merkle tree.
25pub(crate) struct CollatorHasher;
26
27impl hash_db::Hasher for CollatorHasher {
28	type Out = H256;
29	type StdHasher = hash256_std_hasher::Hash256StdHasher;
30	const LENGTH: usize = 32;
31
32	fn hash(input: &[u8]) -> H256 {
33		H256::from(blake2_256(input))
34	}
35}
36
37/// Invalid collator set or index supplied to the proof builder.
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub enum CollatorProofError {
40	EmptySet,
41	InvalidCollatorIndex,
42}
43
44/// Build an unpadded Merkle tree and return its root and proof for `collator_index`.
45///
46/// Keys are hashed as leaves; unpaired nodes are promoted to the next level.
47/// Construction takes O(n) hashing work for n keys.
48///
49/// Returns an error for an empty set or an invalid index.
50pub fn build_collator_proof(
51	keys: &[CollatorKey],
52	collator_index: u32,
53) -> Result<(H256, Vec<H256>), CollatorProofError> {
54	if keys.is_empty() {
55		return Err(CollatorProofError::EmptySet);
56	}
57	if collator_index as usize >= keys.len() {
58		return Err(CollatorProofError::InvalidCollatorIndex);
59	}
60
61	let proof = binary_merkle_tree::merkle_proof::<CollatorHasher, _, _>(keys, collator_index);
62	Ok((proof.root, proof.proof))
63}
64
65/// Verify collator membership, including the leaf index and proof length.
66pub(crate) fn verify_collator_proof(
67	root: &H256,
68	proof: &[H256],
69	size: u32,
70	collator_index: u32,
71	key: &CollatorKey,
72) -> bool {
73	if collator_index >= size || proof.len() != expected_siblings(size, collator_index) {
74		return false;
75	}
76
77	binary_merkle_tree::verify_proof::<CollatorHasher, _, _>(
78		root,
79		proof.iter().copied(),
80		size,
81		collator_index,
82		binary_merkle_tree::Leaf::Value(key),
83	)
84}
85
86/// Count sibling hashes needed to prove membership of the value at the position.
87///
88/// This is used to ensure that the right number of hashes was provided by the proof.
89///
90/// Unpaired nodes are promoted without a sibling, at any level. In the trees below, `(n)` is
91/// the proven leaf, `[s]` a sibling in the proof and `|` a promotion.
92///
93/// No promotion (width 4, position 1, siblings=2):
94///
95/// ```text
96///        root
97///       /    \
98///      .     [s]
99///     / \    / \
100///   [0] (1) 2   3
101/// ```
102///
103/// ```
104/// assert_eq!(cumulus_aura_authorizer_utils::expected_siblings(4, 1), 2);
105/// ```
106///
107/// Promoted at level 0 (width 7, position 6, siblings 2):
108///
109/// ```text
110///             root
111///         /          \
112///       [s]            .
113///      /   \         /   \
114///     .     .      [s]    |
115///    / \   / \     / \    |
116///   0   1 2   3   4   5  (6)
117/// ```
118///
119/// ```
120/// assert_eq!(cumulus_aura_authorizer_utils::expected_siblings(7, 6), 2);
121/// ```
122///
123/// Promoted twice at levels 0 and 1 (width 5, position 4, siblings 1):
124///
125/// ```text
126///           root
127///         /      \
128///       [s]       |
129///      /   \      |
130///     .     .     |
131///    / \   / \    |
132///   0   1 2   3  (4)
133/// ```
134///
135/// ```
136/// assert_eq!(cumulus_aura_authorizer_utils::expected_siblings(5, 4), 1);
137/// ```
138pub fn expected_siblings(mut width: u32, mut position: u32) -> usize {
139	let mut siblings = 0;
140
141	while width > 1 {
142		// Odd positions have a left sibling; even positions need a node to their right.
143		if position % 2 == 1 || position < width - 1 {
144			siblings += 1;
145		}
146		position /= 2;
147		width = width.div_ceil(2);
148	}
149
150	siblings
151}
152
153#[cfg(test)]
154mod tests {
155	use alloc::vec::Vec;
156
157	#[test]
158	fn build_collator_proof_empty_set_errors() {
159		for index in [0, 1, u32::MAX] {
160			assert_eq!(
161				super::build_collator_proof(&[], index),
162				Err(super::CollatorProofError::EmptySet)
163			);
164		}
165	}
166
167	#[test]
168	fn build_collator_proof_invalid_index_errors() {
169		for index in [3, 4, u32::MAX] {
170			assert_eq!(
171				super::build_collator_proof(&[[1; 32], [2; 32], [3; 32]], index),
172				Err(super::CollatorProofError::InvalidCollatorIndex)
173			);
174		}
175	}
176
177	/// Every proof the SDK tree builds has exactly the expected number of siblings.
178	#[test]
179	fn expected_siblings_matches_built_proofs_works() {
180		for width in 1u32..=130 {
181			let members: Vec<_> = (0..width).map(|i| [i as u8; 32]).collect();
182
183			for position in 0..width {
184				let (_, proof) = super::build_collator_proof(&members, position).unwrap();
185
186				assert_eq!(
187					super::expected_siblings(width, position),
188					proof.len(),
189					"width {width}, position {position}"
190				);
191			}
192		}
193	}
194
195	#[test]
196	fn expected_siblings_works() {
197		for (width, position, siblings) in [
198			(1, 0, 0), // Single leaf is the root.
199			(2, 0, 1),
200			(2, 1, 1),
201			(6, 4, 2), // Even width, promoted at level 1.
202			(1 << 31, 0, 31),
203			((1 << 31) + 1, 1 << 31, 1), // Promoted at every level but the top.
204			(u32::MAX, 0, 32),           // `width - 1` and `div_ceil` must not overflow.
205			(u32::MAX, u32::MAX - 1, 31),
206		] {
207			assert_eq!(
208				super::expected_siblings(width, position),
209				siblings,
210				"width {width}, position {position}"
211			);
212		}
213	}
214}