referrerpolicy=no-referrer-when-downgrade

bp_runtime/
storage_proof.rs

1// Copyright (C) Parity Technologies (UK) Ltd.
2// This file is part of Parity Bridges Common.
3
4// Parity Bridges Common is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// Parity Bridges Common is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12// GNU General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with Parity Bridges Common.  If not, see <http://www.gnu.org/licenses/>.
16
17//! Logic for working with storage proofs.
18
19use frame_support::PalletError;
20use sp_core::RuntimeDebug;
21use sp_std::vec::Vec;
22use sp_trie::{
23	accessed_nodes_tracker::AccessedNodesTracker, read_trie_value, LayoutV1, MemoryDB, StorageProof,
24};
25
26use codec::{Decode, DecodeWithMemTracking, Encode};
27use hash_db::{HashDB, Hasher, EMPTY_PREFIX};
28use scale_info::TypeInfo;
29#[cfg(feature = "test-helpers")]
30use sp_trie::{recorder_ext::RecorderExt, Recorder, TrieDBBuilder, TrieError, TrieHash};
31#[cfg(feature = "test-helpers")]
32use trie_db::{Trie, TrieConfiguration, TrieDBMut};
33
34/// Errors that can occur when interacting with `UnverifiedStorageProof` and `VerifiedStorageProof`.
35#[derive(
36	Clone, Encode, Decode, DecodeWithMemTracking, RuntimeDebug, PartialEq, Eq, PalletError, TypeInfo,
37)]
38pub enum StorageProofError {
39	/// Call to `generate_trie_proof()` failed.
40	UnableToGenerateTrieProof,
41	/// Call to `verify_trie_proof()` failed.
42	InvalidProof,
43	/// The `Vec` entries weren't sorted as expected.
44	UnsortedEntries,
45	/// The provided key wasn't found.
46	UnavailableKey,
47	/// The value associated to the provided key is `None`.
48	EmptyVal,
49	/// Error decoding value associated to a provided key.
50	DecodeError,
51	/// At least one key or node wasn't read.
52	UnusedKey,
53
54	/// Expected storage root is missing from the proof. (for non-compact proofs)
55	StorageRootMismatch,
56	/// Unable to reach expected storage value using provided trie nodes. (for non-compact proofs)
57	StorageValueUnavailable,
58	/// The proof contains duplicate nodes. (for non-compact proofs)
59	DuplicateNodes,
60}
61
62impl From<sp_trie::StorageProofError> for StorageProofError {
63	fn from(e: sp_trie::StorageProofError) -> Self {
64		match e {
65			sp_trie::StorageProofError::DuplicateNodes => StorageProofError::DuplicateNodes,
66		}
67	}
68}
69
70impl From<sp_trie::accessed_nodes_tracker::Error> for StorageProofError {
71	fn from(e: sp_trie::accessed_nodes_tracker::Error) -> Self {
72		match e {
73			sp_trie::accessed_nodes_tracker::Error::UnusedNodes => StorageProofError::UnusedKey,
74		}
75	}
76}
77
78/// Raw storage proof type (just raw trie nodes).
79pub type RawStorageProof = sp_trie::RawStorageProof;
80
81/// Calculates size for `RawStorageProof`.
82pub fn raw_storage_proof_size(raw_storage_proof: &RawStorageProof) -> usize {
83	raw_storage_proof
84		.iter()
85		.fold(0usize, |sum, node| sum.saturating_add(node.len()))
86}
87
88/// Storage values size requirements.
89///
90/// This is currently used by benchmarks when generating storage proofs.
91#[cfg(feature = "test-helpers")]
92#[derive(Clone, Copy, Debug, Default)]
93pub struct UnverifiedStorageProofParams {
94	/// Expected storage proof size in bytes.
95	pub db_size: Option<u32>,
96}
97
98#[cfg(feature = "test-helpers")]
99impl UnverifiedStorageProofParams {
100	/// Make storage proof parameters that require proof of at least `db_size` bytes.
101	pub fn from_db_size(db_size: u32) -> Self {
102		Self { db_size: Some(db_size) }
103	}
104}
105
106/// This struct is used to read storage values from a subset of a Merklized database. The "proof"
107/// is a subset of the nodes in the Merkle structure of the database, so that it provides
108/// authentication against a known Merkle root as well as the values in the
109/// database themselves.
110pub struct StorageProofChecker<H>
111where
112	H: Hasher,
113{
114	root: H::Out,
115	db: MemoryDB<H>,
116	accessed_nodes_tracker: AccessedNodesTracker<H::Out>,
117}
118
119impl<H> StorageProofChecker<H>
120where
121	H: Hasher,
122{
123	/// Constructs a new storage proof checker.
124	///
125	/// This returns an error if the given proof is invalid with respect to the given root.
126	pub fn new(root: H::Out, proof: RawStorageProof) -> Result<Self, StorageProofError> {
127		let proof = StorageProof::new_with_duplicate_nodes_check(proof)?;
128
129		let recorder = AccessedNodesTracker::new(proof.len());
130
131		let db = proof.into_memory_db();
132		if !db.contains(&root, EMPTY_PREFIX) {
133			return Err(StorageProofError::StorageRootMismatch)
134		}
135
136		Ok(StorageProofChecker { root, db, accessed_nodes_tracker: recorder })
137	}
138
139	/// Returns error if the proof has some nodes that are left intact by previous `read_value`
140	/// calls.
141	pub fn ensure_no_unused_nodes(self) -> Result<(), StorageProofError> {
142		self.accessed_nodes_tracker.ensure_no_unused_nodes().map_err(Into::into)
143	}
144
145	/// Reads a value from the available subset of storage. If the value cannot be read due to an
146	/// incomplete or otherwise invalid proof, this function returns an error.
147	pub fn read_value(&mut self, key: &[u8]) -> Result<Option<Vec<u8>>, StorageProofError> {
148		// LayoutV1 or LayoutV0 is identical for proof that only read values.
149		read_trie_value::<LayoutV1<H>, _>(
150			&self.db,
151			&self.root,
152			key,
153			Some(&mut self.accessed_nodes_tracker),
154			None,
155		)
156		.map_err(|_| StorageProofError::StorageValueUnavailable)
157	}
158
159	/// Reads and decodes a value from the available subset of storage. If the value cannot be read
160	/// due to an incomplete or otherwise invalid proof, this function returns an error. If value is
161	/// read, but decoding fails, this function returns an error.
162	pub fn read_and_decode_value<T: Decode>(
163		&mut self,
164		key: &[u8],
165	) -> Result<Option<T>, StorageProofError> {
166		self.read_value(key).and_then(|v| {
167			v.map(|v| {
168				T::decode(&mut &v[..]).map_err(|e| {
169					tracing::warn!(target: "bridge-storage-proofs", error=?e, "read_and_decode_value");
170					StorageProofError::DecodeError
171				})
172			})
173			.transpose()
174		})
175	}
176
177	/// Reads and decodes a value from the available subset of storage. If the value cannot be read
178	/// due to an incomplete or otherwise invalid proof, or if the value is `None`, this function
179	/// returns an error. If value is read, but decoding fails, this function returns an error.
180	pub fn read_and_decode_mandatory_value<T: Decode>(
181		&mut self,
182		key: &[u8],
183	) -> Result<T, StorageProofError> {
184		self.read_and_decode_value(key)?.ok_or(StorageProofError::EmptyVal)
185	}
186
187	/// Reads and decodes a value from the available subset of storage. If the value cannot be read
188	/// due to an incomplete or otherwise invalid proof, this function returns `Ok(None)`.
189	/// If value is read, but decoding fails, this function returns an error.
190	pub fn read_and_decode_opt_value<T: Decode>(
191		&mut self,
192		key: &[u8],
193	) -> Result<Option<T>, StorageProofError> {
194		match self.read_and_decode_value(key) {
195			Ok(outbound_lane_data) => Ok(outbound_lane_data),
196			Err(StorageProofError::StorageValueUnavailable) => Ok(None),
197			Err(e) => Err(e),
198		}
199	}
200}
201
202/// Add extra data to the storage value so that it'll be of given size.
203#[cfg(feature = "test-helpers")]
204pub fn grow_storage_value(mut value: Vec<u8>, params: &UnverifiedStorageProofParams) -> Vec<u8> {
205	if let Some(db_size) = params.db_size {
206		if db_size as usize > value.len() {
207			value.extend(sp_std::iter::repeat(42u8).take(db_size as usize - value.len()));
208		}
209	}
210	value
211}
212
213/// Insert values in the provided trie at common-prefix keys in order to inflate the resulting
214/// storage proof.
215///
216/// This function can add at most 15 common-prefix keys per prefix nibble (4 bits).
217/// Each such key adds about 33 bytes (a node) to the proof.
218#[cfg(feature = "test-helpers")]
219pub fn grow_storage_proof<L: TrieConfiguration>(
220	trie: &mut TrieDBMut<L>,
221	prefix: Vec<u8>,
222	num_extra_nodes: usize,
223) {
224	use sp_trie::TrieMut;
225
226	let mut added_nodes = 0;
227	for i in 0..prefix.len() {
228		let mut prefix = prefix[0..=i].to_vec();
229		// 1 byte has 2 nibbles (4 bits each)
230		let first_nibble = (prefix[i] & 0xf0) >> 4;
231		let second_nibble = prefix[i] & 0x0f;
232
233		// create branches at the 1st nibble
234		for branch in 1..=15 {
235			if added_nodes >= num_extra_nodes {
236				return
237			}
238
239			// create branches at the 1st nibble
240			prefix[i] = (first_nibble.wrapping_add(branch) % 16) << 4;
241			trie.insert(&prefix, &[0; 32])
242				.map_err(|_| "TrieMut::insert has failed")
243				.expect("TrieMut::insert should not fail in benchmarks");
244			added_nodes += 1;
245		}
246
247		// create branches at the 2nd nibble
248		for branch in 1..=15 {
249			if added_nodes >= num_extra_nodes {
250				return
251			}
252
253			prefix[i] = (first_nibble << 4) | (second_nibble.wrapping_add(branch) % 16);
254			trie.insert(&prefix, &[0; 32])
255				.map_err(|_| "TrieMut::insert has failed")
256				.expect("TrieMut::insert should not fail in benchmarks");
257			added_nodes += 1;
258		}
259	}
260
261	assert_eq!(added_nodes, num_extra_nodes)
262}
263
264/// Record all keys for a given root.
265#[cfg(feature = "test-helpers")]
266pub fn record_all_keys<L: TrieConfiguration, DB>(
267	db: &DB,
268	root: &TrieHash<L>,
269) -> Result<RawStorageProof, sp_std::boxed::Box<TrieError<L>>>
270where
271	DB: hash_db::HashDBRef<L::Hash, trie_db::DBValue>,
272{
273	let mut recorder = Recorder::<L>::new();
274	let trie = TrieDBBuilder::<L>::new(db, root).with_recorder(&mut recorder).build();
275	for x in trie.iter()? {
276		let (key, _) = x?;
277		trie.get(&key)?;
278	}
279
280	Ok(recorder.into_raw_storage_proof())
281}
282
283/// Return valid storage proof and state root.
284///
285/// Note: This should only be used for **testing**.
286#[cfg(feature = "std")]
287pub fn craft_valid_storage_proof() -> (sp_core::H256, RawStorageProof) {
288	use sp_state_machine::{backend::Backend, prove_read, InMemoryBackend};
289
290	let state_version = sp_runtime::StateVersion::default();
291
292	// construct storage proof
293	let backend = <InMemoryBackend<sp_core::Blake2Hasher>>::from((
294		sp_std::vec![
295			(None, vec![(b"key1".to_vec(), Some(b"value1".to_vec()))]),
296			(None, vec![(b"key2".to_vec(), Some(b"value2".to_vec()))]),
297			(None, vec![(b"key3".to_vec(), Some(b"value3".to_vec()))]),
298			(None, vec![(b"key4".to_vec(), Some((42u64, 42u32, 42u16, 42u8).encode()))]),
299			// Value is too big to fit in a branch node
300			(None, vec![(b"key11".to_vec(), Some(vec![0u8; 32]))]),
301		],
302		state_version,
303	));
304	let root = backend.storage_root(sp_std::iter::empty(), state_version).0;
305	let proof =
306		prove_read(backend, &[&b"key1"[..], &b"key2"[..], &b"key4"[..], &b"key22"[..]]).unwrap();
307
308	(root, proof.into_nodes().into_iter().collect())
309}
310
311#[cfg(test)]
312pub mod tests_for_storage_proof_checker {
313	use super::*;
314	use codec::Encode;
315
316	#[test]
317	fn storage_proof_check() {
318		let (root, proof) = craft_valid_storage_proof();
319
320		// check proof in runtime
321		let mut checker =
322			<StorageProofChecker<sp_core::Blake2Hasher>>::new(root, proof.clone()).unwrap();
323		assert_eq!(checker.read_value(b"key1"), Ok(Some(b"value1".to_vec())));
324		assert_eq!(checker.read_value(b"key2"), Ok(Some(b"value2".to_vec())));
325		assert_eq!(checker.read_value(b"key4"), Ok(Some((42u64, 42u32, 42u16, 42u8).encode())));
326		assert_eq!(
327			checker.read_value(b"key11111"),
328			Err(StorageProofError::StorageValueUnavailable)
329		);
330		assert_eq!(checker.read_value(b"key22"), Ok(None));
331		assert_eq!(checker.read_and_decode_value(b"key4"), Ok(Some((42u64, 42u32, 42u16, 42u8))),);
332		assert!(matches!(
333			checker.read_and_decode_value::<[u8; 64]>(b"key4"),
334			Err(StorageProofError::DecodeError),
335		));
336
337		// checking proof against invalid commitment fails
338		assert_eq!(
339			<StorageProofChecker<sp_core::Blake2Hasher>>::new(sp_core::H256::random(), proof).err(),
340			Some(StorageProofError::StorageRootMismatch)
341		);
342	}
343
344	#[test]
345	fn proof_with_unused_items_is_rejected() {
346		let (root, proof) = craft_valid_storage_proof();
347
348		let mut checker =
349			StorageProofChecker::<sp_core::Blake2Hasher>::new(root, proof.clone()).unwrap();
350		checker.read_value(b"key1").unwrap().unwrap();
351		checker.read_value(b"key2").unwrap();
352		checker.read_value(b"key4").unwrap();
353		checker.read_value(b"key22").unwrap();
354		assert_eq!(checker.ensure_no_unused_nodes(), Ok(()));
355
356		let checker = StorageProofChecker::<sp_core::Blake2Hasher>::new(root, proof).unwrap();
357		assert_eq!(checker.ensure_no_unused_nodes(), Err(StorageProofError::UnusedKey));
358	}
359}