feat: generalize some functions in sp-trie (#12376)

* feat: add to_memory_db to StorageProof

* feat: add iter method and generalize iter_nodes

* fmt

* feat: generalize `encode_compact` like `decode_compact`, add to_compact_proof to StorageProof

* fix to_compact_proof

* improve by suggestions

* improve by suggestions

Co-authored-by: Bastian Köcher <git@kchr.de>
This commit is contained in:
yjh
2022-10-25 15:04:32 +08:00
committed by GitHub
parent 54204d7628
commit 9375665218
7 changed files with 56 additions and 45 deletions
+8 -8
View File
@@ -20,7 +20,7 @@
//! This uses compact proof from trie crate and extends
//! it to substrate specific layout and child trie system.
use crate::{CompactProof, HashDBT, StorageProof, TrieConfiguration, TrieHash, EMPTY_PREFIX};
use crate::{CompactProof, HashDBT, TrieConfiguration, TrieHash, EMPTY_PREFIX};
use sp_std::{boxed::Box, vec::Vec};
use trie_db::{CError, Trie};
@@ -149,17 +149,17 @@ where
/// Then parse all child trie root and compress main trie content first
/// then all child trie contents.
/// Child trie are ordered by the order of their roots in the top trie.
pub fn encode_compact<L>(
proof: StorageProof,
root: TrieHash<L>,
pub fn encode_compact<L, DB>(
partial_db: &DB,
root: &TrieHash<L>,
) -> Result<CompactProof, Error<TrieHash<L>, CError<L>>>
where
L: TrieConfiguration,
DB: HashDBT<L::Hash, trie_db::DBValue> + hash_db::HashDBRef<L::Hash, trie_db::DBValue>,
{
let mut child_tries = Vec::new();
let partial_db = proof.into_memory_db();
let mut compact_proof = {
let trie = crate::TrieDBBuilder::<L>::new(&partial_db, &root).build();
let trie = crate::TrieDBBuilder::<L>::new(partial_db, root).build();
let mut iter = trie.iter()?;
@@ -191,13 +191,13 @@ where
};
for child_root in child_tries {
if !HashDBT::<L::Hash, _>::contains(&partial_db, &child_root, EMPTY_PREFIX) {
if !HashDBT::<L::Hash, _>::contains(partial_db, &child_root, EMPTY_PREFIX) {
// child proof are allowed to be missing (unused root can be included
// due to trie structure modification).
continue
}
let trie = crate::TrieDBBuilder::<L>::new(&partial_db, &child_root).build();
let trie = crate::TrieDBBuilder::<L>::new(partial_db, &child_root).build();
let child_proof = trie_db::encode_compact::<L>(&trie)?;
compact_proof.extend(child_proof);