Skip to content
This repository has been archived by the owner on Nov 15, 2023. It is now read-only.

Inner hashing of value in state trie (chainspec versioning). #8931

Closed
wants to merge 142 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
142 commits
Select commit Hold shift + click to select a range
e026ea6
starting
cheme May 17, 2021
5b1c550
Updated from other branch.
cheme May 18, 2021
7e98291
setting flag
cheme May 18, 2021
5d3a1b2
flag in storage struct
cheme May 18, 2021
4256a40
fix flagging to access and insert.
cheme May 18, 2021
5bb0b68
added todo to fix
cheme May 18, 2021
7081864
also missing serialize meta to storage proof
cheme May 18, 2021
3f1ee83
extract meta.
cheme May 19, 2021
1bbdf35
Isolate old trie layout.
cheme May 19, 2021
e5feabf
failing test that requires storing in meta when old hash scheme is used.
cheme May 19, 2021
aa78ed6
old hash compatibility
cheme May 19, 2021
045b097
Db migrate.
cheme May 19, 2021
79a43dd
runing tests with both states when interesting.
cheme May 20, 2021
aa2e5c3
fix chain spec test with serde default.
cheme May 20, 2021
91bd0aa
export state (missing trie function).
cheme May 20, 2021
183b7b5
Pending using new branch, lacking genericity on layout resolution.
cheme May 21, 2021
8511a40
extract and set global meta
cheme May 21, 2021
270ed28
Update to branch 4
cheme May 24, 2021
b838e7e
fix iterator with root flag (no longer insert node).
cheme May 25, 2021
30742b7
fix trie root hashing of root
cheme May 25, 2021
c620869
complete basic backend.
cheme May 26, 2021
a3b1039
Remove old_hash meta from proof that do not use inner_hashing.
cheme May 26, 2021
693e38b
fix trie test for empty (force layout on empty deltas).
cheme May 26, 2021
6e89b3a
Root update fix.
cheme May 26, 2021
c14e11c
Merge branch 'master' into state-update4
cheme May 26, 2021
f568794
debug on meta
cheme May 26, 2021
fb0ea03
Use trie key iteration that do not include value in proofs.
cheme May 27, 2021
cd98390
switch default test ext to use inner hash.
cheme May 27, 2021
5ab0c01
small integration test, and fix tx cache mgmt in ext.
cheme May 27, 2021
99ef85c
Proof scenario at state-machine level.
cheme May 27, 2021
4d6aee8
trace for db upgrade
cheme May 27, 2021
791acae
try different param
cheme May 27, 2021
b51eaa4
act more like iter_from.
cheme May 28, 2021
715b1a5
Bigger batches.
cheme May 28, 2021
3cdb0ed
Update trie dependency.
cheme May 28, 2021
ae1454f
drafting codec changes and refact
cheme Jun 8, 2021
c807f44
before removing unused branch no value alt hashing.
cheme Jun 8, 2021
a70ce70
alt hashing only for branch with value.
cheme Jun 8, 2021
11f0d5a
fix trie tests
cheme Jun 8, 2021
cf0f0df
Hash of value include the encoded size.
cheme Jun 8, 2021
b721733
removing fields(broken)
cheme Jun 9, 2021
2f8360f
fix trie_stream to also include value length in inner hash.
cheme Jun 9, 2021
76b6d7a
triedbmut only using alt type if inner hashing.
cheme Jun 9, 2021
cfa0ecd
trie_stream to also only use alt hashing type when actually alt hashing.
cheme Jun 9, 2021
60f7012
Refactor meta state, logic should work with change of trie treshold.
cheme Jun 9, 2021
40ec2f7
Remove NoMeta variant.
cheme Jun 9, 2021
204f51f
Remove state_hashed trigger specific functions.
cheme Jun 9, 2021
b62cdf5
pending switching to using threshold, new storage root api does not
cheme Jun 10, 2021
74fb9c8
refactoring to use state from backend (not possible payload changes).
cheme Jun 10, 2021
97a1aa6
Applying from previous state
cheme Jun 10, 2021
f4849a2
Remove default from storage, genesis need a special build.
cheme Jun 10, 2021
4eabbde
rem empty space
cheme Jun 11, 2021
18abb6e
Merge branch 'master' into state-update4-refact
cheme Jun 11, 2021
ae627f6
Catch problem: when using triedb with default: we should not revert
cheme Jun 11, 2021
4706814
fix compilation
cheme Jun 11, 2021
09d5cf6
Right logic to avoid switch on reencode when default layout.
cheme Jun 11, 2021
906cd48
Clean up some todos
cheme Jun 14, 2021
662eabe
remove trie meta from root upstream
cheme Jun 14, 2021
17ac7cb
Merge branch 'master' into state-update4-refact
cheme Jun 15, 2021
ac0e019
update upstream and fix benches.
cheme Jun 15, 2021
7e73a70
split some long lines.
cheme Jun 15, 2021
3498d17
Merge branch 'master' into state-update4-refact
cheme Jun 15, 2021
934021c
UPdate trie crate to work with new design.
cheme Jun 18, 2021
1e40e6d
Finish update to refactored upstream.
cheme Jun 21, 2021
602723e
update to latest triedb changes.
cheme Jun 21, 2021
66ee72d
Clean up.
cheme Jun 21, 2021
23c5db3
fix executor test.
cheme Jun 21, 2021
03d93b2
rust fmt from master.
cheme Jul 22, 2021
b13ebd0
Merge branch 'master' into state-update4
cheme Jul 22, 2021
93aaa4c
rust format.
cheme Jul 22, 2021
66c832e
Merge branch 'master' into state-update4
cheme Aug 11, 2021
89eba2b
Merge branch 'master' into state-update4
cheme Aug 16, 2021
1e02c01
rustfmt
cheme Aug 16, 2021
50ca652
alt hashing as trie backend parameter.
cheme Aug 17, 2021
bd394d5
initial config usage, needs global changes to use dedicated primitive
cheme Aug 19, 2021
250ad02
update tests and remove state threshold key.
cheme Aug 19, 2021
b85b173
Base types for state versioning.
cheme Aug 20, 2021
08e1f4b
Partial changes.
cheme Aug 20, 2021
8f2eaea
fixes
cheme Aug 20, 2021
46d78d0
finish switching, chainspec new issue to get genesis without
cheme Aug 21, 2021
cb0cc70
partial change (if not removing param, keep chainspec util).
cheme Aug 22, 2021
7265bc2
pending
cheme Aug 22, 2021
2e77b5a
pending TODO check state_version needed for Genesisbuild runtime trait.
cheme Aug 22, 2021
a036fdb
before restoring version param for build storage only
cheme Aug 23, 2021
c38f36e
No state for genesis storage building.
cheme Aug 23, 2021
472addd
Revert test to use old method (less frame breakage).
cheme Aug 23, 2021
a6359b4
fix some tests.
cheme Aug 23, 2021
db0769e
default state version from proof to V0
cheme Aug 24, 2021
dc47bfb
storage proof estimate size fix
cheme Aug 24, 2021
bc95929
fix test trie to use right hashing
cheme Aug 24, 2021
b8430c6
fixes
cheme Aug 24, 2021
5b1fab8
network test with migration.
cheme Aug 24, 2021
1770305
wrong approach: only work for block import but not production.
cheme Aug 24, 2021
4c48881
Merge branch 'master' into state-update4-migration
cheme Aug 25, 2021
5371a09
fix warnings
cheme Aug 25, 2021
edfcfd5
cargo format.
cheme Aug 25, 2021
5828a5b
migration digest definition
cheme Aug 25, 2021
96223d7
check migration state and added todos
cheme Aug 25, 2021
f3a861d
tooling digest a bit.
cheme Aug 26, 2021
503270a
guard in_mem against migration (state_versions inner field is
cheme Aug 26, 2021
96aa053
fix
cheme Aug 26, 2021
d33dbc7
fix for empty
cheme Aug 26, 2021
5b0d745
Merge branch 'master' into state-update4-migration
cheme Aug 26, 2021
85e72b9
update trie dep
cheme Aug 26, 2021
8ffd9e2
to revert
cheme Aug 26, 2021
c57a828
simplify (migrate from backend and inject payload if needed.
cheme Aug 26, 2021
b69ea5f
useless unsafe
cheme Aug 26, 2021
c2d9fef
to test
cheme Aug 26, 2021
94c1f6c
Revert "to test"
cheme Aug 26, 2021
7805fa7
fix state display
cheme Aug 26, 2021
1dd52ab
quick additional logging
cheme Aug 27, 2021
7898e49
Merge branch 'master' into state-update4
cheme Aug 27, 2021
a48970f
fix
cheme Aug 27, 2021
a5e6858
TODO about fundamental design issue
cheme Aug 30, 2021
2178698
Remove migration related code.
cheme Aug 31, 2021
f04c0d9
bench to default trie and continue removing migration methods.
cheme Aug 31, 2021
bd03fdc
clean test api
cheme Aug 31, 2021
da50711
fix tests.
cheme Aug 31, 2021
c09ee87
Merge branch 'master' into state-update4-migration2
cheme Sep 1, 2021
2b3b0f6
Merge branch 'state-update4-migration2' into state-update4
cheme Sep 1, 2021
e18c2d5
rust fmt
cheme Sep 1, 2021
8847b90
remove unused emplace_ref
cheme Sep 1, 2021
869e533
Revert "remove unused emplace_ref"
cheme Sep 1, 2021
b6590b2
minor change and remove unused code.
cheme Sep 1, 2021
b695af5
move state version for light client to blockchain struct
cheme Sep 1, 2021
7db873e
Revert "move state version for light client to blockchain struct"
cheme Sep 1, 2021
889b1a4
remove comment
cheme Sep 1, 2021
0d91882
rem TODO
cheme Sep 1, 2021
ae4bdcb
remove todos
cheme Sep 1, 2021
2c7e248
New trie code does update value on change.
cheme Sep 2, 2021
3c529da
switch sp-trie code.
cheme Sep 5, 2021
57324ae
clean old impl
cheme Sep 6, 2021
0cbb7f1
fix tests
cheme Sep 6, 2021
8dcc344
Merge branch 'master' into state-update4
cheme Sep 6, 2021
091f348
update trie_db crate
cheme Sep 6, 2021
0765151
clean
cheme Sep 6, 2021
c5a3548
cargo fmt
cheme Sep 6, 2021
83e5553
encoding of storage proof with default state version of 0 length
cheme Sep 7, 2021
4384ee6
use a single byte.
cheme Sep 7, 2021
1d6aa2f
Fix comment on first byte (not a dead header).
cheme Sep 8, 2021
03841c6
Merge branch 'master' into state-update4
cheme Sep 8, 2021
70a3a32
Merge branch 'master' into state-update4
cheme Sep 9, 2021
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 39 additions & 17 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -265,3 +265,10 @@ zeroize = { opt-level = 3 }
[profile.release]
# Substrate runtime requires unwinding.
panic = "unwind"

[patch.crates-io]
hash-db = { git = "https://github.com/cheme/trie.git", branch = "hashed-value-simple4-new" }
memory-db = { git = "https://github.com/cheme/trie.git", branch = "hashed-value-simple4-new" }
trie-db = { git = "https://github.com/cheme/trie.git", branch = "hashed-value-simple4-new" }
trie-root = { git = "https://github.com/cheme/trie.git", branch = "hashed-value-simple4-new" }
trie-bench = { git = "https://github.com/cheme/trie.git", branch = "hashed-value-simple4-new" }
4 changes: 4 additions & 0 deletions bin/node-template/node/src/chain_spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,8 @@ pub fn development_config() -> Result<ChainSpec, String> {
None,
// Extensions
None,
// StateVersion
Default::default(),
))
}

Expand Down Expand Up @@ -119,6 +121,8 @@ pub fn local_testnet_config() -> Result<ChainSpec, String> {
None,
// Extensions
None,
// StateVersion
Default::default(),
))
}

Expand Down
13 changes: 11 additions & 2 deletions bin/node/bench/src/generator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ use node_primitives::Hash;
use sp_trie::{trie_types::TrieDBMut, TrieMut};

use crate::simple_trie::SimpleTrie;
use sp_core::state_version::StateVersion;

/// Generate trie from given `key_values`.
///
Expand All @@ -31,6 +32,7 @@ use crate::simple_trie::SimpleTrie;
pub fn generate_trie(
db: Arc<dyn KeyValueDB>,
key_values: impl IntoIterator<Item = (Vec<u8>, Vec<u8>)>,
state_version: StateVersion,
) -> Hash {
let mut root = Hash::default();

Expand All @@ -43,8 +45,15 @@ pub fn generate_trie(
);
let mut trie = SimpleTrie { db, overlay: &mut overlay };
{
let mut trie_db = TrieDBMut::new(&mut trie, &mut root);

let mut trie_db = match state_version {
StateVersion::V0 => TrieDBMut::new(&mut trie, &mut root),
StateVersion::V1 { threshold } => {
let layout = sp_trie::Layout::with_max_inline_value(threshold);
TrieDBMut::<crate::simple_trie::Hasher>::new_with_layout(
&mut trie, &mut root, layout,
)
},
};
for (key, value) in key_values {
trie_db.insert(&key, &value).expect("trie insertion failed");
}
Expand Down
7 changes: 4 additions & 3 deletions bin/node/bench/src/trie.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ impl core::BenchmarkDescription for TrieReadBenchmarkDescription {
assert_eq!(warmup_keys.len(), SAMPLE_SIZE);
assert_eq!(query_keys.len(), SAMPLE_SIZE);

let root = generate_trie(database.open(self.database_type), key_values);
let root = generate_trie(database.open(self.database_type), key_values, Default::default());

Box::new(TrieReadBenchmark {
database,
Expand Down Expand Up @@ -180,7 +180,8 @@ impl core::Benchmark for TrieReadBenchmark {
let storage: Arc<dyn sp_state_machine::Storage<sp_core::Blake2Hasher>> =
Arc::new(Storage(db.open(self.database_type)));

let trie_backend = sp_state_machine::TrieBackend::new(storage, self.root);
let state_version = Default::default();
let trie_backend = sp_state_machine::TrieBackend::new(storage, self.root, state_version);
for (warmup_key, warmup_value) in self.warmup_keys.iter() {
let value = trie_backend
.storage(&warmup_key[..])
Expand Down Expand Up @@ -248,7 +249,7 @@ impl core::BenchmarkDescription for TrieWriteBenchmarkDescription {

assert_eq!(warmup_keys.len(), SAMPLE_SIZE);

let root = generate_trie(database.open(self.database_type), key_values);
let root = generate_trie(database.open(self.database_type), key_values, Default::default());

Box::new(TrieWriteBenchmark {
database,
Expand Down
5 changes: 5 additions & 0 deletions bin/node/cli/src/chain_spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@ pub fn staging_testnet_config() -> ChainSpec {
None,
None,
Default::default(),
Default::default(),
)
}

Expand Down Expand Up @@ -387,6 +388,7 @@ pub fn development_config() -> ChainSpec {
None,
None,
Default::default(),
Default::default(),
)
}

Expand All @@ -411,6 +413,7 @@ pub fn local_testnet_config() -> ChainSpec {
None,
None,
Default::default(),
Default::default(),
)
}

Expand Down Expand Up @@ -442,6 +445,7 @@ pub(crate) mod tests {
None,
None,
Default::default(),
Default::default(),
)
}

Expand All @@ -457,6 +461,7 @@ pub(crate) mod tests {
None,
None,
Default::default(),
Default::default(),
)
}

Expand Down
8 changes: 4 additions & 4 deletions bin/node/executor/benches/bench.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,10 +89,10 @@ fn construct_block<E: Externalities>(
let extrinsics = extrinsics.into_iter().map(sign).collect::<Vec<_>>();

// calculate the header fields that we can.
let extrinsics_root =
Layout::<BlakeTwo256>::ordered_trie_root(extrinsics.iter().map(Encode::encode))
.to_fixed_bytes()
.into();
let extrinsics_root = Layout::<BlakeTwo256>::default()
.ordered_trie_root(extrinsics.iter().map(Encode::encode))
.to_fixed_bytes()
.into();

let header = Header {
parent_hash,
Expand Down
8 changes: 4 additions & 4 deletions bin/node/executor/tests/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,10 +151,10 @@ pub fn construct_block(
let extrinsics = extrinsics.into_iter().map(sign).collect::<Vec<_>>();

// calculate the header fields that we can.
let extrinsics_root =
Layout::<BlakeTwo256>::ordered_trie_root(extrinsics.iter().map(Encode::encode))
.to_fixed_bytes()
.into();
let extrinsics_root = Layout::<BlakeTwo256>::default()
.ordered_trie_root(extrinsics.iter().map(Encode::encode))
.to_fixed_bytes()
.into();

let header = Header {
parent_hash,
Expand Down
3 changes: 2 additions & 1 deletion bin/node/testing/src/bench.rs
Original file line number Diff line number Diff line change
Expand Up @@ -387,7 +387,8 @@ impl BenchDb {
};
let task_executor = TaskExecutor::new();

let backend = sc_service::new_db_backend(db_config).expect("Should not fail");
let backend =
sc_service::new_db_backend(db_config, Default::default()).expect("Should not fail");
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In most bench and test, I did use default which is the inner hashed version of trie.

let client = sc_service::new_client(
backend.clone(),
NativeElseWasmExecutor::new(WasmExecutionMethod::Compiled, None, 8),
Expand Down
1 change: 1 addition & 0 deletions bin/utils/chain-spec-builder/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,7 @@ fn generate_chain_spec(
None,
None,
Default::default(),
Default::default(),
);

chain_spec.as_json(false).map_err(|err| err)
Expand Down
9 changes: 5 additions & 4 deletions client/api/src/cht.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,8 @@ where
I: IntoIterator<Item = ClientResult<Option<Header::Hash>>>,
{
use sp_trie::TrieConfiguration;
Ok(sp_trie::trie_types::Layout::<Hasher>::trie_root(build_pairs::<Header, I>(
cht_size, cht_num, hashes,
)?))
Ok(sp_trie::Layout::<Hasher>::default()
Copy link
Contributor Author

@cheme cheme Sep 1, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that default layout is not the trie with inner hashing, but old behavior which remains unchanged for cht, extrinsic root, and others.

.trie_root(build_pairs::<Header, I>(cht_size, cht_num, hashes)?))
}

/// Build CHT-based header proof.
Expand All @@ -117,7 +116,9 @@ where
.into_iter()
.map(|(k, v)| (k, Some(v)))
.collect::<Vec<_>>();
let storage = InMemoryBackend::<Hasher>::default().update(vec![(None, transaction)]);
// No inner hashing for cht.
let backend: InMemoryBackend<Hasher> = sp_runtime::StateVersion::V0.into();
let storage = backend.update(vec![(None, transaction)]);
let trie_storage = storage
.as_trie_backend()
.expect("InMemoryState::as_trie_backend always returns Some; qed");
Expand Down
21 changes: 19 additions & 2 deletions client/api/src/in_mem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ use sp_core::{
use sp_runtime::{
generic::BlockId,
traits::{Block as BlockT, HashFor, Header as HeaderT, NumberFor, Zero},
Justification, Justifications, Storage,
Justification, Justifications, StateVersion, StateVersions, Storage,
};
use sp_state_machine::{
Backend as StateBackend, ChangesTrieTransaction, ChildStorageCollection, InMemoryBackend,
Expand Down Expand Up @@ -112,6 +112,7 @@ struct BlockchainStorage<Block: BlockT> {
changes_trie_cht_roots: HashMap<NumberFor<Block>, Block::Hash>,
leaves: LeafSet<Block::Hash, NumberFor<Block>>,
aux: HashMap<Vec<u8>, Vec<u8>>,
state_versions: StateVersions<Block>,
}

/// In-memory blockchain. Supports concurrent reads.
Expand Down Expand Up @@ -141,6 +142,20 @@ impl<Block: BlockT> Blockchain<Block> {
}
}

/// Get version of state.
pub fn state_version(&self, id: BlockId<Block>) -> StateVersion {
let number = match id {
BlockId::Hash(h) =>
if let Ok(Some(header)) = self.header(BlockId::Hash(h)) {
header.number().clone()
} else {
0u32.into()
},
BlockId::Number(n) => n,
};
self.storage.read().state_versions.state_version_at(number)
}

/// Create new in-memory blockchain storage.
pub fn new() -> Blockchain<Block> {
let storage = Arc::new(RwLock::new(BlockchainStorage {
Expand All @@ -155,6 +170,7 @@ impl<Block: BlockT> Blockchain<Block> {
changes_trie_cht_roots: HashMap::new(),
leaves: LeafSet::new(),
aux: HashMap::new(),
state_versions: StateVersions::default(),
}));
Blockchain { storage }
}
Expand Down Expand Up @@ -855,7 +871,8 @@ where

fn state_at(&self, block: BlockId<Block>) -> sp_blockchain::Result<Self::State> {
match block {
BlockId::Hash(h) if h == Default::default() => return Ok(Self::State::default()),
BlockId::Hash(h) if h == Default::default() =>
return Ok(self.blockchain.state_version(BlockId::Hash(h)).into()),
_ => {},
}

Expand Down
Loading