referrerpolicy=no-referrer-when-downgrade

node_bench/
generator.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
5
6// This program is free software: you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
10
11// This program is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// You should have received a copy of the GNU General Public License
17// along with this program. If not, see <https://www.gnu.org/licenses/>.
18
19use std::{collections::HashMap, sync::Arc};
20
21use kvdb::KeyValueDB;
22use node_primitives::Hash;
23use sp_trie::{trie_types::TrieDBMutBuilderV1, TrieMut};
24
25use crate::simple_trie::SimpleTrie;
26
27/// Generate trie from given `key_values`.
28///
29/// Will fill your database `db` with trie data from `key_values` and
30/// return root.
31pub fn generate_trie(
32	db: Arc<dyn KeyValueDB>,
33	key_values: impl IntoIterator<Item = (Vec<u8>, Vec<u8>)>,
34) -> Hash {
35	let mut root = Hash::default();
36
37	let (db, overlay) = {
38		let mut overlay = HashMap::new();
39		overlay.insert(
40			array_bytes::hex2bytes(
41				"03170a2e7597b7b7e3d84c05391d139a62b157e78786d8c082f29dcf4c111314",
42			)
43			.expect("null key is valid"),
44			Some(vec![0]),
45		);
46		let mut trie = SimpleTrie { db, overlay: &mut overlay };
47		{
48			let mut trie_db =
49				TrieDBMutBuilderV1::<crate::simple_trie::Hasher>::new(&mut trie, &mut root).build();
50			for (key, value) in key_values {
51				trie_db.insert(&key, &value).expect("trie insertion failed");
52			}
53
54			trie_db.commit();
55		}
56		(trie.db, overlay)
57	};
58
59	let mut transaction = db.transaction();
60	for (key, value) in overlay.into_iter() {
61		match value {
62			Some(value) => transaction.put(0, &key[..], &value[..]),
63			None => transaction.delete(0, &key[..]),
64		}
65	}
66	db.write(transaction).expect("Failed to write transaction");
67
68	root
69}