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