sp_trie/
accessed_nodes_tracker.rs

1// This file is part of Substrate.
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
18//! Helpers for checking for duplicate nodes.
19
20use alloc::collections::BTreeSet;
21use core::hash::Hash;
22use scale_info::TypeInfo;
23use sp_core::{Decode, Encode};
24use trie_db::{RecordedForKey, TrieAccess, TrieRecorder};
25
26/// Error associated with the `AccessedNodesTracker` module.
27#[derive(Encode, Decode, Clone, Eq, PartialEq, Debug, TypeInfo)]
28pub enum Error {
29	/// The proof contains unused nodes.
30	UnusedNodes,
31}
32
33/// Helper struct used to ensure that a storage proof doesn't contain duplicate or unused nodes.
34///
35/// The struct needs to be used as a `TrieRecorder` and `ensure_no_unused_nodes()` has to be called
36/// to actually perform the check.
37pub struct AccessedNodesTracker<H: Hash> {
38	proof_nodes_count: usize,
39	recorder: BTreeSet<H>,
40}
41
42impl<H: Hash> AccessedNodesTracker<H> {
43	/// Create a new instance of `RedundantNodesChecker`, starting from a `RawStorageProof`.
44	pub fn new(proof_nodes_count: usize) -> Self {
45		Self { proof_nodes_count, recorder: BTreeSet::new() }
46	}
47
48	/// Ensure that all the nodes in the proof have been accessed.
49	pub fn ensure_no_unused_nodes(self) -> Result<(), Error> {
50		if self.proof_nodes_count != self.recorder.len() {
51			return Err(Error::UnusedNodes)
52		}
53
54		Ok(())
55	}
56}
57
58impl<H: Hash + Ord> TrieRecorder<H> for AccessedNodesTracker<H> {
59	fn record(&mut self, access: TrieAccess<H>) {
60		match access {
61			TrieAccess::NodeOwned { hash, .. } |
62			TrieAccess::EncodedNode { hash, .. } |
63			TrieAccess::Value { hash, .. } => {
64				self.recorder.insert(hash);
65			},
66			_ => {},
67		}
68	}
69
70	fn trie_nodes_recorded_for_key(&self, _key: &[u8]) -> RecordedForKey {
71		RecordedForKey::None
72	}
73}
74
75#[cfg(test)]
76pub mod tests {
77	use super::*;
78	use crate::{tests::create_storage_proof, StorageProof};
79	use hash_db::Hasher;
80	use trie_db::{Trie, TrieDBBuilder};
81
82	type Hash = <sp_core::Blake2Hasher as Hasher>::Out;
83	type Layout = crate::LayoutV1<sp_core::Blake2Hasher>;
84
85	const TEST_DATA: &[(&[u8], &[u8])] =
86		&[(b"key1", &[1; 64]), (b"key2", &[2; 64]), (b"key3", &[3; 64])];
87
88	#[test]
89	fn proof_with_unused_nodes_is_rejected() {
90		let (raw_proof, root) = create_storage_proof::<Layout>(TEST_DATA);
91		let proof = StorageProof::new(raw_proof.clone());
92		let proof_nodes_count = proof.len();
93
94		let mut accessed_nodes_tracker = AccessedNodesTracker::<Hash>::new(proof_nodes_count);
95		{
96			let db = proof.clone().into_memory_db();
97			let trie = TrieDBBuilder::<Layout>::new(&db, &root)
98				.with_recorder(&mut accessed_nodes_tracker)
99				.build();
100
101			trie.get(b"key1").unwrap().unwrap();
102			trie.get(b"key2").unwrap().unwrap();
103			trie.get(b"key3").unwrap().unwrap();
104		}
105		assert_eq!(accessed_nodes_tracker.ensure_no_unused_nodes(), Ok(()));
106
107		let mut accessed_nodes_tracker = AccessedNodesTracker::<Hash>::new(proof_nodes_count);
108		{
109			let db = proof.into_memory_db();
110			let trie = TrieDBBuilder::<Layout>::new(&db, &root)
111				.with_recorder(&mut accessed_nodes_tracker)
112				.build();
113
114			trie.get(b"key1").unwrap().unwrap();
115			trie.get(b"key2").unwrap().unwrap();
116		}
117		assert_eq!(accessed_nodes_tracker.ensure_no_unused_nodes(), Err(Error::UnusedNodes));
118	}
119}