diff --git a/substrate/Cargo.lock b/substrate/Cargo.lock index ee69ca599e..6b3fca15e4 100644 --- a/substrate/Cargo.lock +++ b/substrate/Cargo.lock @@ -6045,6 +6045,7 @@ dependencies = [ "sp-externalities", "sp-io", "sp-panic-handler", + "sp-runtime", "sp-runtime-interface", "sp-serializer", "sp-state-machine", @@ -7273,6 +7274,7 @@ dependencies = [ name = "sp-runtime" version = "2.0.0-alpha.3" dependencies = [ + "hash256-std-hasher", "impl-trait-for-tuples", "log 0.4.8", "parity-scale-codec", @@ -7324,8 +7326,8 @@ name = "sp-runtime-interface-test" version = "2.0.0-dev" dependencies = [ "sc-executor", - "sp-core", "sp-io", + "sp-runtime", "sp-runtime-interface", "sp-runtime-interface-test-wasm", "sp-state-machine", @@ -7397,6 +7399,7 @@ dependencies = [ "sp-core", "sp-externalities", "sp-panic-handler", + "sp-runtime", "sp-trie", "trie-db", "trie-root", @@ -7464,6 +7467,7 @@ dependencies = [ "memory-db", "parity-scale-codec", "sp-core", + "sp-runtime", "sp-std", "trie-bench", "trie-db", diff --git a/substrate/bin/node/executor/benches/bench.rs b/substrate/bin/node/executor/benches/bench.rs index c411bec851..faebdd302a 100644 --- a/substrate/bin/node/executor/benches/bench.rs +++ b/substrate/bin/node/executor/benches/bench.rs @@ -23,12 +23,13 @@ use node_runtime::{ }; use node_runtime::constants::currency::*; use node_testing::keyring::*; -use sp_core::{Blake2Hasher, NativeOrEncoded, NeverNativeValue}; +use sp_core::{NativeOrEncoded, NeverNativeValue}; use sp_core::storage::well_known_keys; use sp_core::traits::{CodeExecutor, RuntimeCode}; use frame_support::Hashable; use sp_state_machine::TestExternalities as CoreTestExternalities; use sc_executor::{NativeExecutor, RuntimeInfo, WasmExecutionMethod, Externalities}; +use sp_runtime::traits::BlakeTwo256; criterion_group!(benches, bench_execute_block); criterion_main!(benches); @@ -54,7 +55,7 @@ fn sign(xt: CheckedExtrinsic) -> UncheckedExtrinsic { node_testing::keyring::sign(xt, VERSION, GENESIS_HASH) } -fn new_test_ext(genesis_config: &GenesisConfig) -> TestExternalities { +fn new_test_ext(genesis_config: &GenesisConfig) -> TestExternalities { let mut test_ext = TestExternalities::new_with_code( COMPACT_CODE, genesis_config.build_storage().unwrap(), @@ -76,7 +77,7 @@ fn construct_block( let extrinsics = extrinsics.into_iter().map(sign).collect::>(); // calculate the header fields that we can. - let extrinsics_root = Layout::::ordered_trie_root( + let extrinsics_root = Layout::::ordered_trie_root( extrinsics.iter().map(Encode::encode) ).to_fixed_bytes() .into(); diff --git a/substrate/bin/node/executor/tests/basic.rs b/substrate/bin/node/executor/tests/basic.rs index eb629029c6..1ee0a17c81 100644 --- a/substrate/bin/node/executor/tests/basic.rs +++ b/substrate/bin/node/executor/tests/basic.rs @@ -21,13 +21,11 @@ use frame_support::{ weights::{GetDispatchInfo, DispatchInfo, DispatchClass}, }; use sp_core::{ - Blake2Hasher, NeverNativeValue, map, - traits::Externalities, - storage::{well_known_keys, Storage}, + NeverNativeValue, map, traits::Externalities, storage::{well_known_keys, Storage}, }; use sp_runtime::{ ApplyExtrinsicResult, Fixed64, - traits::{Hash as HashT, Convert}, + traits::{Hash as HashT, Convert, BlakeTwo256}, transaction_validity::InvalidTransaction, }; use pallet_contracts::ContractAddressFor; @@ -93,7 +91,6 @@ fn changes_trie_block() -> (Vec, Hash) { ) } - /// block 1 and 2 must be created together to ensure transactions are only signed once (since they /// are not guaranteed to be deterministic) and to ensure that the correct state is propagated /// from block1's execution to block2 to derive the correct storage_root. @@ -161,7 +158,7 @@ fn block_with_size(time: u64, nonce: u32, size: usize) -> (Vec, Hash) { #[test] fn panic_execution_with_foreign_code_gives_error() { - let mut t = TestExternalities::::new_with_code(BLOATY_CODE, Storage { + let mut t = TestExternalities::::new_with_code(BLOATY_CODE, Storage { top: map![ >::hashed_key_for(alice()) => { (69u128, 0u8, 0u128, 0u128, 0u128).encode() @@ -197,7 +194,7 @@ fn panic_execution_with_foreign_code_gives_error() { #[test] fn bad_extrinsic_with_native_equivalent_code_gives_error() { - let mut t = TestExternalities::::new_with_code(COMPACT_CODE, Storage { + let mut t = TestExternalities::::new_with_code(COMPACT_CODE, Storage { top: map![ >::hashed_key_for(alice()) => { (0u32, 0u8, 69u128, 0u128, 0u128, 0u128).encode() @@ -233,7 +230,7 @@ fn bad_extrinsic_with_native_equivalent_code_gives_error() { #[test] fn successful_execution_with_native_equivalent_code_gives_ok() { - let mut t = TestExternalities::::new_with_code(COMPACT_CODE, Storage { + let mut t = TestExternalities::::new_with_code(COMPACT_CODE, Storage { top: map![ >::hashed_key_for(alice()) => { (0u32, 0u8, 111 * DOLLARS, 0u128, 0u128, 0u128).encode() @@ -275,7 +272,7 @@ fn successful_execution_with_native_equivalent_code_gives_ok() { #[test] fn successful_execution_with_foreign_code_gives_ok() { - let mut t = TestExternalities::::new_with_code(BLOATY_CODE, Storage { + let mut t = TestExternalities::::new_with_code(BLOATY_CODE, Storage { top: map![ >::hashed_key_for(alice()) => { (0u32, 0u8, 111 * DOLLARS, 0u128, 0u128, 0u128).encode() @@ -700,7 +697,7 @@ fn native_big_block_import_fails_on_fallback() { #[test] fn panic_execution_gives_error() { - let mut t = TestExternalities::::new_with_code(BLOATY_CODE, Storage { + let mut t = TestExternalities::::new_with_code(BLOATY_CODE, Storage { top: map![ >::hashed_key().to_vec() => { 0_u128.encode() @@ -731,7 +728,7 @@ fn panic_execution_gives_error() { #[test] fn successful_execution_gives_ok() { - let mut t = TestExternalities::::new_with_code(COMPACT_CODE, Storage { + let mut t = TestExternalities::::new_with_code(COMPACT_CODE, Storage { top: map![ >::hashed_key_for(alice()) => { (0u32, 0u8, 111 * DOLLARS, 0u128, 0u128, 0u128).encode() diff --git a/substrate/bin/node/executor/tests/common.rs b/substrate/bin/node/executor/tests/common.rs index 4b83825722..25ada87a97 100644 --- a/substrate/bin/node/executor/tests/common.rs +++ b/substrate/bin/node/executor/tests/common.rs @@ -17,10 +17,8 @@ use codec::{Encode, Decode}; use frame_support::Hashable; use sp_state_machine::TestExternalities as CoreTestExternalities; -use sp_core::{ - Blake2Hasher, NeverNativeValue, NativeOrEncoded, traits::{CodeExecutor, RuntimeCode}, -}; -use sp_runtime::{ApplyExtrinsicResult, traits::Header as HeaderT}; +use sp_core::{NeverNativeValue, NativeOrEncoded, traits::{CodeExecutor, RuntimeCode}}; +use sp_runtime::{ApplyExtrinsicResult, traits::{Header as HeaderT, BlakeTwo256}}; use sc_executor::{NativeExecutor, WasmExecutionMethod}; use sc_executor::error::Result; @@ -66,7 +64,7 @@ pub fn executor_call< R:Decode + Encode + PartialEq, NC: FnOnce() -> std::result::Result + std::panic::UnwindSafe >( - t: &mut TestExternalities, + t: &mut TestExternalities, method: &str, data: &[u8], use_native: bool, @@ -85,7 +83,7 @@ pub fn executor_call< ) } -pub fn new_test_ext(code: &[u8], support_changes_trie: bool) -> TestExternalities { +pub fn new_test_ext(code: &[u8], support_changes_trie: bool) -> TestExternalities { let mut ext = TestExternalities::new_with_code( code, node_testing::genesis::config(support_changes_trie, Some(code)).build_storage().unwrap(), @@ -99,7 +97,7 @@ pub fn new_test_ext(code: &[u8], support_changes_trie: bool) -> TestExternalitie /// `extrinsics` must be a list of valid extrinsics, i.e. none of the extrinsics for example /// can report `ExhaustResources`. Otherwise, this function panics. pub fn construct_block( - env: &mut TestExternalities, + env: &mut TestExternalities, number: BlockNumber, parent_hash: Hash, extrinsics: Vec, @@ -111,7 +109,7 @@ pub fn construct_block( // calculate the header fields that we can. let extrinsics_root = - Layout::::ordered_trie_root(extrinsics.iter().map(Encode::encode)) + Layout::::ordered_trie_root(extrinsics.iter().map(Encode::encode)) .to_fixed_bytes() .into(); diff --git a/substrate/bin/node/executor/tests/fees.rs b/substrate/bin/node/executor/tests/fees.rs index 024c02bd6a..ea9d740a05 100644 --- a/substrate/bin/node/executor/tests/fees.rs +++ b/substrate/bin/node/executor/tests/fees.rs @@ -20,14 +20,8 @@ use frame_support::{ traits::Currency, weights::GetDispatchInfo, }; -use sp_core::{ - Blake2Hasher, NeverNativeValue, map, - storage::Storage, -}; -use sp_runtime::{ - Fixed64, Perbill, - traits::Convert, -}; +use sp_core::{NeverNativeValue, map, storage::Storage}; +use sp_runtime::{Fixed64, Perbill, traits::{Convert, BlakeTwo256}}; use node_runtime::{ CheckedExtrinsic, Call, Runtime, Balances, TransactionPayment, TransactionBaseFee, TransactionByteFee, WeightFeeCoefficient, @@ -136,7 +130,7 @@ fn transaction_fee_is_correct_ultimate() { // - 1 MILLICENTS in substrate node. // - 1 milli-dot based on current polkadot runtime. // (this baed on assigning 0.1 CENT to the cheapest tx with `weight = 100`) - let mut t = TestExternalities::::new_with_code(COMPACT_CODE, Storage { + let mut t = TestExternalities::::new_with_code(COMPACT_CODE, Storage { top: map![ >::hashed_key_for(alice()) => { (0u32, 0u8, 100 * DOLLARS, 0 * DOLLARS, 0 * DOLLARS, 0 * DOLLARS).encode() diff --git a/substrate/client/api/src/backend.rs b/substrate/client/api/src/backend.rs index c3e56e7f8b..1f76aa8c1a 100644 --- a/substrate/client/api/src/backend.rs +++ b/substrate/client/api/src/backend.rs @@ -21,7 +21,7 @@ use std::collections::HashMap; use sp_core::ChangesTrieConfigurationRange; use sp_core::offchain::OffchainStorage; use sp_runtime::{generic::BlockId, Justification, Storage}; -use sp_runtime::traits::{Block as BlockT, NumberFor, HasherFor}; +use sp_runtime::traits::{Block as BlockT, NumberFor, HashFor}; use sp_state_machine::{ ChangesTrieState, ChangesTrieStorage as StateChangesTrieStorage, ChangesTrieTransaction, StorageCollection, ChildStorageCollection, @@ -43,7 +43,7 @@ pub use sp_state_machine::Backend as StateBackend; pub type StateBackendFor = >::State; /// Extracts the transaction for the given state backend. -pub type TransactionForSB = >>::Transaction; +pub type TransactionForSB = >>::Transaction; /// Extracts the transaction for the given backend. pub type TransactionFor = TransactionForSB, Block>; @@ -111,7 +111,7 @@ impl NewBlockState { /// Keeps hold if the inserted block state and data. pub trait BlockImportOperation { /// Associated state backend type. - type State: StateBackend>; + type State: StateBackend>; /// Returns pending state. /// @@ -149,7 +149,7 @@ pub trait BlockImportOperation { /// Inject changes trie data into the database. fn update_changes_trie( &mut self, - update: ChangesTrieTransaction, NumberFor>, + update: ChangesTrieTransaction, NumberFor>, ) -> sp_blockchain::Result<()>; /// Insert auxiliary keys. @@ -253,7 +253,7 @@ pub trait Backend: AuxStore + Send + Sync { /// Associated blockchain backend type. type Blockchain: BlockchainBackend; /// Associated state backend type. - type State: StateBackend> + Send; + type State: StateBackend> + Send; /// Offchain workers local storage. type OffchainStorage: OffchainStorage; @@ -344,10 +344,10 @@ pub trait Backend: AuxStore + Send + Sync { /// Changes trie storage that supports pruning. pub trait PrunableStateChangesTrieStorage: - StateChangesTrieStorage, NumberFor> + StateChangesTrieStorage, NumberFor> { /// Get reference to StateChangesTrieStorage. - fn storage(&self) -> &dyn StateChangesTrieStorage, NumberFor>; + fn storage(&self) -> &dyn StateChangesTrieStorage, NumberFor>; /// Get configuration at given block. fn configuration_at(&self, at: &BlockId) -> sp_blockchain::Result< ChangesTrieConfigurationRange, Block::Hash> @@ -377,7 +377,7 @@ pub trait RemoteBackend: Backend { pub fn changes_tries_state_at_block<'a, Block: BlockT>( block: &BlockId, maybe_storage: Option<&'a dyn PrunableStateChangesTrieStorage>, -) -> sp_blockchain::Result, NumberFor>>> { +) -> sp_blockchain::Result, NumberFor>>> { let storage = match maybe_storage { Some(storage) => storage, None => return Ok(None), diff --git a/substrate/client/api/src/call_executor.rs b/substrate/client/api/src/call_executor.rs index aff38a26aa..1a7b53d541 100644 --- a/substrate/client/api/src/call_executor.rs +++ b/substrate/client/api/src/call_executor.rs @@ -19,7 +19,7 @@ use std::{panic::UnwindSafe, result, cell::RefCell}; use codec::{Encode, Decode}; use sp_runtime::{ - generic::BlockId, traits::{Block as BlockT, HasherFor}, + generic::BlockId, traits::{Block as BlockT, HashFor}, }; use sp_state_machine::{ OverlayedChanges, ExecutionManager, ExecutionStrategy, StorageProof, @@ -89,7 +89,7 @@ pub trait CallExecutor { /// Execute a call to a contract on top of given state, gathering execution proof. /// /// No changes are made. - fn prove_at_state>>( + fn prove_at_state>>( &self, mut state: S, overlay: &mut OverlayedChanges, @@ -107,9 +107,9 @@ pub trait CallExecutor { /// Execute a call to a contract on top of given trie state, gathering execution proof. /// /// No changes are made. - fn prove_at_trie_state>>( + fn prove_at_trie_state>>( &self, - trie_state: &sp_state_machine::TrieBackend>, + trie_state: &sp_state_machine::TrieBackend>, overlay: &mut OverlayedChanges, method: &str, call_data: &[u8] diff --git a/substrate/client/authority-discovery/src/tests.rs b/substrate/client/authority-discovery/src/tests.rs index 77ed6a1d94..55ee6c7aac 100644 --- a/substrate/client/authority-discovery/src/tests.rs +++ b/substrate/client/authority-discovery/src/tests.rs @@ -215,7 +215,7 @@ impl ApiExt for RuntimeApi { fn into_storage_changes( &self, _: &Self::StateBackend, - _: Option<&sp_api::ChangesTrieState, sp_api::NumberFor>>, + _: Option<&sp_api::ChangesTrieState, sp_api::NumberFor>>, _: ::Hash, ) -> std::result::Result, String> where Self: Sized diff --git a/substrate/client/block-builder/src/lib.rs b/substrate/client/block-builder/src/lib.rs index c9b2efbea9..82c7c91159 100644 --- a/substrate/client/block-builder/src/lib.rs +++ b/substrate/client/block-builder/src/lib.rs @@ -28,9 +28,7 @@ use codec::Encode; use sp_runtime::{ generic::BlockId, - traits::{ - Header as HeaderT, Hash, Block as BlockT, HashFor, DigestFor, NumberFor, One, HasherFor, - }, + traits::{Header as HeaderT, Hash, Block as BlockT, HashFor, DigestFor, NumberFor, One}, }; use sp_blockchain::{ApplyExtrinsicFailed, Error}; use sp_core::ExecutionContext; @@ -47,7 +45,7 @@ use sc_client_api::backend; /// backend to get the state of the block. Furthermore an optional `proof` is included which /// can be used to proof that the build block contains the expected data. The `proof` will /// only be set when proof recording was activated. -pub struct BuiltBlock>> { +pub struct BuiltBlock>> { /// The actual block that was build. pub block: Block, /// The changes that need to be applied to the backend to get the state of the build block. @@ -56,7 +54,7 @@ pub struct BuiltBlock, } -impl>> BuiltBlock { +impl>> BuiltBlock { /// Convert into the inner values. pub fn into_inner(self) -> (Block, StorageChanges, Option) { (self.block, self.storage_changes, self.proof) diff --git a/substrate/client/consensus/slots/src/lib.rs b/substrate/client/consensus/slots/src/lib.rs index 892c8b1364..e23b2fb321 100644 --- a/substrate/client/consensus/slots/src/lib.rs +++ b/substrate/client/consensus/slots/src/lib.rs @@ -37,7 +37,7 @@ use futures_timer::Delay; use sp_inherents::{InherentData, InherentDataProviders}; use log::{debug, error, info, warn}; use sp_runtime::generic::BlockId; -use sp_runtime::traits::{Block as BlockT, Header, HasherFor, NumberFor}; +use sp_runtime::traits::{Block as BlockT, Header, HashFor, NumberFor}; use sp_api::{ProvideRuntimeApi, ApiRef}; use std::{fmt::Debug, ops::Deref, pin::Pin, sync::Arc, time::{Instant, Duration}}; use sc_telemetry::{telemetry, CONSENSUS_DEBUG, CONSENSUS_WARN, CONSENSUS_INFO}; @@ -47,7 +47,7 @@ use parking_lot::Mutex; /// /// See [`sp_state_machine::StorageChanges`] for more information. pub type StorageChanges = - sp_state_machine::StorageChanges, NumberFor>; + sp_state_machine::StorageChanges, NumberFor>; /// A worker that should be invoked at every new slot. pub trait SlotWorker { diff --git a/substrate/client/db/src/bench.rs b/substrate/client/db/src/bench.rs index 9858a5c148..b6a6b3f8d4 100644 --- a/substrate/client/db/src/bench.rs +++ b/substrate/client/db/src/bench.rs @@ -24,14 +24,14 @@ use rand::Rng; use hash_db::{Prefix, Hasher}; use sp_trie::{MemoryDB, prefixed_key}; use sp_core::storage::ChildInfo; -use sp_runtime::traits::{Block as BlockT, HasherFor}; +use sp_runtime::traits::{Block as BlockT, HashFor}; use sp_runtime::Storage; use sp_state_machine::{DBValue, backend::Backend as StateBackend}; use kvdb::{KeyValueDB, DBTransaction}; use kvdb_rocksdb::{Database, DatabaseConfig}; type DbState = sp_state_machine::TrieBackend< - Arc>>, HasherFor + Arc>>, HashFor >; struct StorageDb { @@ -39,9 +39,9 @@ struct StorageDb { _block: std::marker::PhantomData, } -impl sp_state_machine::Storage> for StorageDb { +impl sp_state_machine::Storage> for StorageDb { fn get(&self, key: &Block::Hash, prefix: Prefix) -> Result, String> { - let key = prefixed_key::>(key, prefix); + let key = prefixed_key::>(key, prefix); self.db.get(0, &key) .map_err(|e| format!("Database backend error: {:?}", e)) } @@ -53,7 +53,7 @@ pub struct BenchmarkingState { root: Cell, state: RefCell>>, db: Cell>>, - genesis: as StateBackend>>::Transaction, + genesis: as StateBackend>>::Transaction, } impl BenchmarkingState { @@ -64,8 +64,8 @@ impl BenchmarkingState { let path = temp_dir.join(&name); let mut root = B::Hash::default(); - let mut mdb = MemoryDB::>::default(); - sp_state_machine::TrieDBMut::>::new(&mut mdb, &mut root); + let mut mdb = MemoryDB::>::default(); + sp_state_machine::TrieDBMut::>::new(&mut mdb, &mut root); std::fs::create_dir(&path).map_err(|_| String::from("Error creating temp dir"))?; let mut state = BenchmarkingState { @@ -108,8 +108,8 @@ impl BenchmarkingState { self.db.set(None); *self.state.borrow_mut() = None; let mut root = B::Hash::default(); - let mut mdb = MemoryDB::>::default(); - sp_state_machine::TrieDBMut::>::new(&mut mdb, &mut root); + let mut mdb = MemoryDB::>::default(); + sp_state_machine::TrieDBMut::>::new(&mut mdb, &mut root); self.root.set(root); std::fs::remove_dir_all(&self.path).map_err(|_| "Error removing database dir".into()) @@ -126,10 +126,10 @@ fn state_err() -> String { "State is not open".into() } -impl StateBackend> for BenchmarkingState { - type Error = as StateBackend>>::Error; - type Transaction = as StateBackend>>::Transaction; - type TrieBackendStorage = as StateBackend>>::TrieBackendStorage; +impl StateBackend> for BenchmarkingState { + type Error = as StateBackend>>::Error; + type Transaction = as StateBackend>>::Transaction; + type TrieBackendStorage = as StateBackend>>::TrieBackendStorage; fn storage(&self, key: &[u8]) -> Result>, Self::Error> { self.state.borrow().as_ref().ok_or_else(state_err)?.storage(key) @@ -244,12 +244,12 @@ impl StateBackend> for BenchmarkingState { } fn as_trie_backend(&mut self) - -> Option<&sp_state_machine::TrieBackend>> + -> Option<&sp_state_machine::TrieBackend>> { None } - fn commit(&self, storage_root: as Hasher>::Out, mut transaction: Self::Transaction) + fn commit(&self, storage_root: as Hasher>::Out, mut transaction: Self::Transaction) -> Result<(), Self::Error> { if let Some(db) = self.db.take() { diff --git a/substrate/client/db/src/changes_tries_storage.rs b/substrate/client/db/src/changes_tries_storage.rs index 99488bbaed..a28cd604fe 100644 --- a/substrate/client/db/src/changes_tries_storage.rs +++ b/substrate/client/db/src/changes_tries_storage.rs @@ -28,7 +28,7 @@ use sc_client_api::backend::PrunableStateChangesTrieStorage; use sp_blockchain::{well_known_cache_keys, Cache as BlockchainCache}; use sp_core::{ChangesTrieConfiguration, ChangesTrieConfigurationRange, convert_hash}; use sp_runtime::traits::{ - Block as BlockT, Header as HeaderT, HasherFor, NumberFor, One, Zero, CheckedSub, + Block as BlockT, Header as HeaderT, HashFor, NumberFor, One, Zero, CheckedSub, }; use sp_runtime::generic::{BlockId, DigestItem, ChangesTrieSignal}; use sp_state_machine::{DBValue, ChangesTrieBuildCache, ChangesTrieCacheAction}; @@ -150,7 +150,7 @@ impl DbChangesTrieStorage { pub fn commit( &self, tx: &mut DBTransaction, - mut changes_trie: MemoryDB>, + mut changes_trie: MemoryDB>, parent_block: ComplexBlockId, block: ComplexBlockId, new_header: &Block::Header, @@ -377,7 +377,7 @@ impl DbChangesTrieStorage { } impl PrunableStateChangesTrieStorage for DbChangesTrieStorage { - fn storage(&self) -> &dyn sp_state_machine::ChangesTrieStorage, NumberFor> { + fn storage(&self) -> &dyn sp_state_machine::ChangesTrieStorage, NumberFor> { self } @@ -396,7 +396,7 @@ impl PrunableStateChangesTrieStorage for DbChangesTrieStor } } -impl sp_state_machine::ChangesTrieRootsStorage, NumberFor> +impl sp_state_machine::ChangesTrieRootsStorage, NumberFor> for DbChangesTrieStorage { fn build_anchor( @@ -469,12 +469,12 @@ impl sp_state_machine::ChangesTrieRootsStorage, } } -impl sp_state_machine::ChangesTrieStorage, NumberFor> +impl sp_state_machine::ChangesTrieStorage, NumberFor> for DbChangesTrieStorage where Block: BlockT, { - fn as_roots_storage(&self) -> &dyn sp_state_machine::ChangesTrieRootsStorage, NumberFor> { + fn as_roots_storage(&self) -> &dyn sp_state_machine::ChangesTrieRootsStorage, NumberFor> { self } diff --git a/substrate/client/db/src/lib.rs b/substrate/client/db/src/lib.rs index b4dd98457d..d4c157986f 100644 --- a/substrate/client/db/src/lib.rs +++ b/substrate/client/db/src/lib.rs @@ -67,7 +67,7 @@ use sp_runtime::{ BuildStorage, }; use sp_runtime::traits::{ - Block as BlockT, Header as HeaderT, NumberFor, Zero, One, SaturatedConversion, HasherFor, + Block as BlockT, Header as HeaderT, NumberFor, Zero, One, SaturatedConversion, HashFor, }; use sc_executor::RuntimeInfo; use sp_state_machine::{ @@ -99,7 +99,7 @@ const DEFAULT_CHILD_RATIO: (usize, usize) = (1, 10); /// DB-backed patricia trie state, transaction type is an overlay of changes to commit. pub type DbState = sp_state_machine::TrieBackend< - Arc>>, HasherFor + Arc>>, HashFor >; /// Re-export the KVDB trait so that one can pass an implementation of it. @@ -139,10 +139,10 @@ impl std::fmt::Debug for RefTrackingState { } } -impl StateBackend> for RefTrackingState { - type Error = as StateBackend>>::Error; - type Transaction = as StateBackend>>::Transaction; - type TrieBackendStorage = as StateBackend>>::TrieBackendStorage; +impl StateBackend> for RefTrackingState { + type Error = as StateBackend>>::Error; + type Transaction = as StateBackend>>::Transaction; + type TrieBackendStorage = as StateBackend>>::TrieBackendStorage; fn storage(&self, key: &[u8]) -> Result>, Self::Error> { self.state.storage(key) @@ -251,7 +251,7 @@ impl StateBackend> for RefTrackingState { } fn as_trie_backend(&mut self) - -> Option<&sp_state_machine::TrieBackend>> + -> Option<&sp_state_machine::TrieBackend>> { self.state.as_trie_backend() } @@ -521,10 +521,10 @@ impl HeaderMetadata for BlockchainDb { /// Database transaction pub struct BlockImportOperation { old_state: CachingState, Block>, - db_updates: PrefixedMemoryDB>, + db_updates: PrefixedMemoryDB>, storage_updates: StorageCollection, child_storage_updates: ChildStorageCollection, - changes_trie_updates: MemoryDB>, + changes_trie_updates: MemoryDB>, changes_trie_build_cache_update: Option>>, changes_trie_config_update: Option>, pending_block: Option>, @@ -576,7 +576,7 @@ impl sc_client_api::backend::BlockImportOperation for Bloc // Currently cache isn't implemented on full nodes. } - fn update_db_storage(&mut self, update: PrefixedMemoryDB>) -> ClientResult<()> { + fn update_db_storage(&mut self, update: PrefixedMemoryDB>) -> ClientResult<()> { self.db_updates = update; Ok(()) } @@ -623,7 +623,7 @@ impl sc_client_api::backend::BlockImportOperation for Bloc fn update_changes_trie( &mut self, - update: ChangesTrieTransaction, NumberFor>, + update: ChangesTrieTransaction, NumberFor>, ) -> ClientResult<()> { self.changes_trie_updates = update.0; self.changes_trie_build_cache_update = Some(update.1); @@ -668,9 +668,9 @@ struct StorageDb { pub state_db: StateDb>, } -impl sp_state_machine::Storage> for StorageDb { +impl sp_state_machine::Storage> for StorageDb { fn get(&self, key: &Block::Hash, prefix: Prefix) -> Result, String> { - let key = prefixed_key::>(key, prefix); + let key = prefixed_key::>(key, prefix); self.state_db.get(&key, self) .map_err(|e| format!("Database backend error: {:?}", e)) } @@ -690,13 +690,13 @@ struct DbGenesisStorage(pub Block::Hash); impl DbGenesisStorage { pub fn new() -> Self { let mut root = Block::Hash::default(); - let mut mdb = MemoryDB::>::default(); - sp_state_machine::TrieDBMut::>::new(&mut mdb, &mut root); + let mut mdb = MemoryDB::>::default(); + sp_state_machine::TrieDBMut::>::new(&mut mdb, &mut root); DbGenesisStorage(root) } } -impl sp_state_machine::Storage> for DbGenesisStorage { +impl sp_state_machine::Storage> for DbGenesisStorage { fn get(&self, _key: &Block::Hash, _prefix: Prefix) -> Result, String> { Ok(None) } @@ -1653,7 +1653,7 @@ pub(crate) mod tests { use hash_db::{HashDB, EMPTY_PREFIX}; use super::*; use crate::columns; - use sp_core::{Blake2Hasher, H256}; + use sp_core::H256; use sc_client_api::backend::{Backend as BTrait, BlockImportOperation as Op}; use sc_client::blockchain::Backend as BLBTrait; use sp_runtime::testing::{Header, Block as RawBlock, ExtrinsicWrapper}; @@ -1664,11 +1664,11 @@ pub(crate) mod tests { pub(crate) type Block = RawBlock>; - pub fn prepare_changes(changes: Vec<(Vec, Vec)>) -> (H256, MemoryDB) { + pub fn prepare_changes(changes: Vec<(Vec, Vec)>) -> (H256, MemoryDB) { let mut changes_root = H256::default(); - let mut changes_trie_update = MemoryDB::::default(); + let mut changes_trie_update = MemoryDB::::default(); { - let mut trie = TrieDBMut::::new( + let mut trie = TrieDBMut::::new( &mut changes_trie_update, &mut changes_root ); @@ -1900,7 +1900,7 @@ pub(crate) mod tests { backend.commit_operation(op).unwrap(); assert_eq!(backend.storage.db.get( columns::STATE, - &sp_trie::prefixed_key::(&key, EMPTY_PREFIX) + &sp_trie::prefixed_key::(&key, EMPTY_PREFIX) ).unwrap().unwrap(), &b"hello"[..]); hash }; @@ -1937,7 +1937,7 @@ pub(crate) mod tests { backend.commit_operation(op).unwrap(); assert_eq!(backend.storage.db.get( columns::STATE, - &sp_trie::prefixed_key::(&key, EMPTY_PREFIX) + &sp_trie::prefixed_key::(&key, EMPTY_PREFIX) ).unwrap().unwrap(), &b"hello"[..]); hash }; @@ -1975,7 +1975,7 @@ pub(crate) mod tests { assert!(backend.storage.db.get( columns::STATE, - &sp_trie::prefixed_key::(&key, EMPTY_PREFIX) + &sp_trie::prefixed_key::(&key, EMPTY_PREFIX) ).unwrap().is_some()); hash }; @@ -2009,7 +2009,7 @@ pub(crate) mod tests { backend.commit_operation(op).unwrap(); assert!(backend.storage.db.get( columns::STATE, - &sp_trie::prefixed_key::(&key, EMPTY_PREFIX) + &sp_trie::prefixed_key::(&key, EMPTY_PREFIX) ).unwrap().is_none()); } @@ -2018,7 +2018,7 @@ pub(crate) mod tests { backend.finalize_block(BlockId::Number(3), None).unwrap(); assert!(backend.storage.db.get( columns::STATE, - &sp_trie::prefixed_key::(&key, EMPTY_PREFIX) + &sp_trie::prefixed_key::(&key, EMPTY_PREFIX) ).unwrap().is_none()); } diff --git a/substrate/client/db/src/light.rs b/substrate/client/db/src/light.rs index 3d30598b19..cda1a11952 100644 --- a/substrate/client/db/src/light.rs +++ b/substrate/client/db/src/light.rs @@ -36,7 +36,7 @@ use sp_blockchain::{ use sc_client::light::blockchain::Storage as LightBlockchainStorage; use codec::{Decode, Encode}; use sp_runtime::generic::{DigestItem, BlockId}; -use sp_runtime::traits::{Block as BlockT, Header as HeaderT, Zero, One, NumberFor, HasherFor}; +use sp_runtime::traits::{Block as BlockT, Header as HeaderT, Zero, One, NumberFor, HashFor}; use crate::cache::{DbCacheSync, DbCache, ComplexBlockId, EntryType as CacheEntryType}; use crate::utils::{self, meta_keys, DatabaseType, Meta, db_err, read_db, block_id_to_lookup_key, read_meta}; use crate::{DatabaseSettings, FrozenForDuration}; @@ -305,7 +305,7 @@ impl LightStorage { Some(old_current_num) }); - let new_header_cht_root = cht::compute_root::, _>( + let new_header_cht_root = cht::compute_root::, _>( cht::size(), new_cht_number, cht_range.map(|num| self.hash(num)) )?; transaction.put( @@ -322,7 +322,7 @@ impl LightStorage { current_num = current_num + One::one(); Some(old_current_num) }); - let new_changes_trie_cht_root = cht::compute_root::, _>( + let new_changes_trie_cht_root = cht::compute_root::, _>( cht::size(), new_cht_number, cht_range .map(|num| self.changes_trie_root(BlockId::Number(num))) )?; diff --git a/substrate/client/db/src/storage_cache.rs b/substrate/client/db/src/storage_cache.rs index 6ef29f47b8..6f289369e2 100644 --- a/substrate/client/db/src/storage_cache.rs +++ b/substrate/client/db/src/storage_cache.rs @@ -21,7 +21,7 @@ use std::sync::Arc; use parking_lot::{Mutex, RwLock, RwLockUpgradableReadGuard}; use linked_hash_map::{LinkedHashMap, Entry}; use hash_db::Hasher; -use sp_runtime::traits::{Block as BlockT, Header, HasherFor, NumberFor}; +use sp_runtime::traits::{Block as BlockT, Header, HashFor, NumberFor}; use sp_core::hexdisplay::HexDisplay; use sp_core::storage::ChildInfo; use sp_state_machine::{ @@ -281,7 +281,7 @@ pub struct CacheChanges { /// Shared canonical state cache. shared_cache: SharedCache, /// Local cache of values for this state. - local_cache: RwLock>>, + local_cache: RwLock>>, /// Hash of the block on top of which this instance was created or /// `None` if cache is disabled pub parent_hash: Option, @@ -296,7 +296,7 @@ pub struct CacheChanges { /// For canonical instances local cache is accumulated and applied /// in `sync_cache` along with the change overlay. /// For non-canonical clones local cache and changes are dropped. -pub struct CachingState>, B: BlockT> { +pub struct CachingState>, B: BlockT> { /// Usage statistics usage: StateUsageStats, /// Backing state. @@ -305,7 +305,7 @@ pub struct CachingState>, B: BlockT> { pub cache: CacheChanges, } -impl>, B: BlockT> std::fmt::Debug for CachingState { +impl>, B: BlockT> std::fmt::Debug for CachingState { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "Block {:?}", self.cache.parent_hash) } @@ -420,7 +420,7 @@ impl CacheChanges { } -impl>, B: BlockT> CachingState { +impl>, B: BlockT> CachingState { /// Create a new instance wrapping generic State and shared cache. pub fn new(state: S, shared_cache: SharedCache, parent_hash: Option) -> Self { CachingState { @@ -489,7 +489,7 @@ impl>, B: BlockT> CachingState { } } -impl>, B: BlockT> StateBackend> for CachingState { +impl>, B: BlockT> StateBackend> for CachingState { type Error = S::Error; type Transaction = S::Transaction; type TrieBackendStorage = S::TrieBackendStorage; @@ -659,7 +659,7 @@ impl>, B: BlockT> StateBackend> for Ca self.state.child_keys(storage_key, child_info, prefix) } - fn as_trie_backend(&mut self) -> Option<&TrieBackend>> { + fn as_trie_backend(&mut self) -> Option<&TrieBackend>> { self.state.as_trie_backend() } @@ -671,9 +671,11 @@ impl>, B: BlockT> StateBackend> for Ca #[cfg(test)] mod tests { use super::*; - use sp_runtime::testing::{H256, Block as RawBlock, ExtrinsicWrapper}; + use sp_runtime::{ + traits::BlakeTwo256, + testing::{H256, Block as RawBlock, ExtrinsicWrapper}, + }; use sp_state_machine::InMemoryBackend; - use sp_core::Blake2Hasher; type Block = RawBlock>; @@ -695,7 +697,7 @@ mod tests { // blocks [ 3a(c) 2a(c) 2b 1b 1a(c) 0 ] // state [ 5 5 4 3 2 2 ] let mut s = CachingState::new( - InMemoryBackend::::default(), + InMemoryBackend::::default(), shared.clone(), Some(root_parent), ); @@ -710,14 +712,14 @@ mod tests { ); let mut s = CachingState::new( - InMemoryBackend::::default(), + InMemoryBackend::::default(), shared.clone(), Some(h0), ); s.cache.sync_cache(&[], &[], vec![], vec![], Some(h1a), Some(1), true); let mut s = CachingState::new( - InMemoryBackend::::default(), + InMemoryBackend::::default(), shared.clone(), Some(h0), ); @@ -732,7 +734,7 @@ mod tests { ); let mut s = CachingState::new( - InMemoryBackend::::default(), + InMemoryBackend::::default(), shared.clone(), Some(h1b), ); @@ -747,7 +749,7 @@ mod tests { ); let mut s = CachingState::new( - InMemoryBackend::::default(), + InMemoryBackend::::default(), shared.clone(), Some(h1a), ); @@ -762,35 +764,35 @@ mod tests { ); let mut s = CachingState::new( - InMemoryBackend::::default(), + InMemoryBackend::::default(), shared.clone(), Some(h2a), ); s.cache.sync_cache(&[], &[], vec![], vec![], Some(h3a), Some(3), true); let s = CachingState::new( - InMemoryBackend::::default(), + InMemoryBackend::::default(), shared.clone(), Some(h3a), ); assert_eq!(s.storage(&key).unwrap().unwrap(), vec![5]); let s = CachingState::new( - InMemoryBackend::::default(), + InMemoryBackend::::default(), shared.clone(), Some(h1a), ); assert!(s.storage(&key).unwrap().is_none()); let s = CachingState::new( - InMemoryBackend::::default(), + InMemoryBackend::::default(), shared.clone(), Some(h2b), ); assert!(s.storage(&key).unwrap().is_none()); let s = CachingState::new( - InMemoryBackend::::default(), + InMemoryBackend::::default(), shared.clone(), Some(h1b), ); @@ -799,7 +801,7 @@ mod tests { // reorg to 3b // blocks [ 3b(c) 3a 2a 2b(c) 1b 1a 0 ] let mut s = CachingState::new( - InMemoryBackend::::default(), + InMemoryBackend::::default(), shared.clone(), Some(h2b), ); @@ -813,7 +815,7 @@ mod tests { true, ); let s = CachingState::new( - InMemoryBackend::::default(), + InMemoryBackend::::default(), shared.clone(), Some(h3a), ); @@ -834,7 +836,7 @@ mod tests { let shared = new_shared_cache::(256*1024, (0,1)); let mut s = CachingState::new( - InMemoryBackend::::default(), + InMemoryBackend::::default(), shared.clone(), Some(root_parent), ); @@ -849,14 +851,14 @@ mod tests { ); let mut s = CachingState::new( - InMemoryBackend::::default(), + InMemoryBackend::::default(), shared.clone(), Some(h1), ); s.cache.sync_cache(&[], &[], vec![], vec![], Some(h2a), Some(2), true); let mut s = CachingState::new( - InMemoryBackend::::default(), + InMemoryBackend::::default(), shared.clone(), Some(h1), ); @@ -871,7 +873,7 @@ mod tests { ); let mut s = CachingState::new( - InMemoryBackend::::default(), + InMemoryBackend::::default(), shared.clone(), Some(h2b), ); @@ -886,7 +888,7 @@ mod tests { ); let s = CachingState::new( - InMemoryBackend::::default(), + InMemoryBackend::::default(), shared.clone(), Some(h2a), ); @@ -906,21 +908,21 @@ mod tests { let shared = new_shared_cache::(256*1024, (0,1)); let mut s = CachingState::new( - InMemoryBackend::::default(), + InMemoryBackend::::default(), shared.clone(), Some(root_parent), ); s.cache.sync_cache(&[], &[], vec![], vec![], Some(h1), Some(1), true); let mut s = CachingState::new( - InMemoryBackend::::default(), + InMemoryBackend::::default(), shared.clone(), Some(h1), ); s.cache.sync_cache(&[], &[], vec![], vec![], Some(h2a), Some(2), true); let mut s = CachingState::new( - InMemoryBackend::::default(), + InMemoryBackend::::default(), shared.clone(), Some(h2a), ); @@ -935,14 +937,14 @@ mod tests { ); let mut s = CachingState::new( - InMemoryBackend::::default(), + InMemoryBackend::::default(), shared.clone(), Some(h1), ); s.cache.sync_cache(&[], &[], vec![], vec![], Some(h2b), Some(2), false); let mut s = CachingState::new( - InMemoryBackend::::default(), + InMemoryBackend::::default(), shared.clone(), Some(h2b), ); @@ -957,7 +959,7 @@ mod tests { ); let s = CachingState::new( - InMemoryBackend::::default(), + InMemoryBackend::::default(), shared.clone(), Some(h3a), ); @@ -971,7 +973,7 @@ mod tests { let h0 = H256::random(); let mut s = CachingState::new( - InMemoryBackend::::default(), shared.clone(), Some(root_parent.clone()), + InMemoryBackend::::default(), shared.clone(), Some(root_parent.clone()), ); let key = H256::random()[..].to_vec(); @@ -1009,7 +1011,7 @@ mod tests { let h0 = H256::random(); let mut s = CachingState::new( - InMemoryBackend::::default(), + InMemoryBackend::::default(), shared.clone(), Some(root_parent), ); @@ -1053,7 +1055,7 @@ mod tests { let shared = new_shared_cache::(256 * 1024, (0, 1)); let mut s = CachingState::new( - InMemoryBackend::::default(), + InMemoryBackend::::default(), shared.clone(), Some(root_parent.clone()), ); @@ -1068,7 +1070,7 @@ mod tests { ); let mut s = CachingState::new( - InMemoryBackend::::default(), + InMemoryBackend::::default(), shared.clone(), Some(h0), ); @@ -1083,7 +1085,7 @@ mod tests { ); let mut s = CachingState::new( - InMemoryBackend::::default(), + InMemoryBackend::::default(), shared.clone(), Some(h1), ); @@ -1106,7 +1108,7 @@ mod tests { s.cache.sync_cache(&[], &[], vec![], vec![], None, None, true); let s = CachingState::new( - InMemoryBackend::::default(), + InMemoryBackend::::default(), shared.clone(), Some(h1), ); @@ -1121,9 +1123,11 @@ mod qc { use quickcheck::{quickcheck, TestResult, Arbitrary}; use super::*; - use sp_runtime::testing::{H256, Block as RawBlock, ExtrinsicWrapper}; + use sp_runtime::{ + traits::BlakeTwo256, + testing::{H256, Block as RawBlock, ExtrinsicWrapper}, + }; use sp_state_machine::InMemoryBackend; - use sp_core::Blake2Hasher; type Block = RawBlock>; @@ -1250,22 +1254,22 @@ mod qc { } } - fn head_state(&self, hash: H256) -> CachingState, Block> { + fn head_state(&self, hash: H256) -> CachingState, Block> { CachingState::new( - InMemoryBackend::::default(), + InMemoryBackend::::default(), self.shared.clone(), Some(hash) ) } - fn canon_head_state(&self) -> CachingState, Block> { + fn canon_head_state(&self) -> CachingState, Block> { self.head_state(self.canon.last().expect("Expected to be one commit").hash) } fn mutate_static( &mut self, action: Action, - ) -> CachingState, Block> { + ) -> CachingState, Block> { self.mutate(action).expect("Expected to provide only valid actions to the mutate_static") } @@ -1284,7 +1288,7 @@ mod qc { fn mutate( &mut self, action: Action, - ) -> Result, Block>, ()> { + ) -> Result, Block>, ()> { let state = match action { Action::Fork { depth, hash, changes } => { let pos = self.canon.len() as isize - depth as isize; @@ -1321,7 +1325,7 @@ mod qc { }; let mut state = CachingState::new( - InMemoryBackend::::default(), + InMemoryBackend::::default(), self.shared.clone(), Some(parent) ); @@ -1360,7 +1364,7 @@ mod qc { } let mut state = CachingState::new( - InMemoryBackend::::default(), + InMemoryBackend::::default(), self.shared.clone(), Some(parent_hash) ); @@ -1407,7 +1411,7 @@ mod qc { self.canon.push(node); let mut state = CachingState::new( - InMemoryBackend::::default(), + InMemoryBackend::::default(), self.shared.clone(), Some(fork_at) ); diff --git a/substrate/client/executor/Cargo.toml b/substrate/client/executor/Cargo.toml index 46e4bb04bb..1353bc5730 100644 --- a/substrate/client/executor/Cargo.toml +++ b/substrate/client/executor/Cargo.toml @@ -39,6 +39,7 @@ sc-runtime-test = { version = "2.0.0-dev", path = "runtime-test" } substrate-test-runtime = { version = "2.0.0-dev", path = "../../test-utils/runtime" } sp-state-machine = { version = "0.8.0-alpha.2", path = "../../primitives/state-machine" } test-case = "0.3.3" +sp-runtime = { version = "2.0.0-alpha.2", path = "../../primitives/runtime" } [features] default = [ "std" ] diff --git a/substrate/client/executor/src/integration_tests/mod.rs b/substrate/client/executor/src/integration_tests/mod.rs index c0516d3ac7..87ca33c4da 100644 --- a/substrate/client/executor/src/integration_tests/mod.rs +++ b/substrate/client/executor/src/integration_tests/mod.rs @@ -19,7 +19,7 @@ mod sandbox; use codec::{Encode, Decode}; use hex_literal::hex; use sp_core::{ - Blake2Hasher, blake2_128, blake2_256, ed25519, sr25519, map, Pair, + blake2_128, blake2_256, ed25519, sr25519, map, Pair, offchain::{OffchainExt, testing}, traits::Externalities, }; @@ -28,10 +28,11 @@ use sp_state_machine::TestExternalities as CoreTestExternalities; use test_case::test_case; use sp_trie::{TrieConfiguration, trie_types::Layout}; use sp_wasm_interface::HostFunctions as _; +use sp_runtime::traits::BlakeTwo256; use crate::WasmExecutionMethod; -pub type TestExternalities = CoreTestExternalities; +pub type TestExternalities = CoreTestExternalities; type HostFunctions = sp_io::SubstrateHostFunctions; fn call_in_wasm( @@ -440,7 +441,7 @@ fn ordered_trie_root_should_work(wasm_method: WasmExecutionMethod) { wasm_method, &mut ext.ext(), ).unwrap(), - Layout::::ordered_trie_root(trie_input.iter()).as_bytes().encode(), + Layout::::ordered_trie_root(trie_input.iter()).as_bytes().encode(), ); } diff --git a/substrate/client/finality-grandpa/src/tests.rs b/substrate/client/finality-grandpa/src/tests.rs index 7b5880f7ee..2734101500 100644 --- a/substrate/client/finality-grandpa/src/tests.rs +++ b/substrate/client/finality-grandpa/src/tests.rs @@ -42,7 +42,7 @@ use std::{ pin::Pin, task, }; use parity_scale_codec::Decode; -use sp_runtime::traits::{Block as BlockT, Header as HeaderT, HasherFor}; +use sp_runtime::traits::{Block as BlockT, Header as HeaderT, HashFor}; use sp_runtime::generic::{BlockId, DigestItem}; use sp_core::{H256, NativeOrEncoded, ExecutionContext, crypto::Public}; use sp_finality_grandpa::{GRANDPA_ENGINE_ID, AuthorityList, GrandpaApi}; @@ -289,7 +289,7 @@ impl ApiExt for RuntimeApi { fn into_storage_changes( &self, _: &Self::StateBackend, - _: Option<&sp_api::ChangesTrieState, sp_api::NumberFor>>, + _: Option<&sp_api::ChangesTrieState, sp_api::NumberFor>>, _: ::Hash, ) -> std::result::Result, String> where Self: Sized @@ -323,7 +323,7 @@ impl AuthoritySetForFinalityProver for TestApi { fn prove_authorities(&self, block: &BlockId) -> Result { let authorities = self.authorities(block)?; - let backend = >>::from(vec![ + let backend = >>::from(vec![ (None, vec![(b"authorities".to_vec(), Some(authorities.encode()))]) ]); let proof = prove_read(backend, vec![b"authorities"]) @@ -339,7 +339,7 @@ impl AuthoritySetForFinalityChecker for TestApi { header: ::Header, proof: StorageProof, ) -> Result { - let results = read_proof_check::, _>( + let results = read_proof_check::, _>( *header.state_root(), proof, vec![b"authorities"] ) .expect("failure checking read proof for authorities"); diff --git a/substrate/client/rpc/src/state/state_light.rs b/substrate/client/rpc/src/state/state_light.rs index 7b2455a8fc..4d2e8fbb05 100644 --- a/substrate/client/rpc/src/state/state_light.rs +++ b/substrate/client/rpc/src/state/state_light.rs @@ -52,7 +52,7 @@ use sp_core::{ Bytes, OpaqueMetadata, storage::{StorageKey, StorageData, StorageChangeSet}, }; use sp_version::RuntimeVersion; -use sp_runtime::{generic::BlockId, traits::{Block as BlockT, HasherFor}}; +use sp_runtime::{generic::BlockId, traits::{Block as BlockT, HashFor}}; use super::{StateBackend, error::{FutureResult, Error}, client_err}; @@ -241,7 +241,7 @@ impl StateBackend for LightState::hash(&storage.0)))) + result(Ok(maybe_storage.map(|storage| HashFor::::hash(&storage.0)))) ) ) } @@ -302,7 +302,7 @@ impl StateBackend for LightState::hash(&storage.0)))) + result(Ok(maybe_storage.map(|storage| HashFor::::hash(&storage.0)))) ) ) } diff --git a/substrate/client/service/src/builder.rs b/substrate/client/service/src/builder.rs index 01bba286c6..bc731dd2de 100644 --- a/substrate/client/service/src/builder.rs +++ b/substrate/client/service/src/builder.rs @@ -39,7 +39,7 @@ use sc_network::{NetworkService, NetworkStateInfo}; use parking_lot::{Mutex, RwLock}; use sp_runtime::generic::BlockId; use sp_runtime::traits::{ - Block as BlockT, NumberFor, SaturatedConversion, HasherFor, UniqueSaturatedInto, + Block as BlockT, NumberFor, SaturatedConversion, HashFor, UniqueSaturatedInto, }; use sp_api::ProvideRuntimeApi; use sc_executor::{NativeExecutor, NativeExecutionDispatch}; @@ -159,19 +159,19 @@ pub type TLightClient = Client< /// Light client backend type. pub type TLightBackend = sc_client::light::backend::Backend< sc_client_db::light::LightStorage, - HasherFor, + HashFor, >; /// Light call executor type. pub type TLightCallExecutor = sc_client::light::call_executor::GenesisCallExecutor< sc_client::light::backend::Backend< sc_client_db::light::LightStorage, - HasherFor + HashFor >, sc_client::LocalCallExecutor< sc_client::light::backend::Backend< sc_client_db::light::LightStorage, - HasherFor + HashFor >, NativeExecutor >, diff --git a/substrate/client/src/call_executor.rs b/substrate/client/src/call_executor.rs index 659e015239..db95309458 100644 --- a/substrate/client/src/call_executor.rs +++ b/substrate/client/src/call_executor.rs @@ -17,7 +17,7 @@ use std::{sync::Arc, panic::UnwindSafe, result, cell::RefCell}; use codec::{Encode, Decode}; use sp_runtime::{ - generic::BlockId, traits::{Block as BlockT, HasherFor, NumberFor}, + generic::BlockId, traits::{Block as BlockT, HashFor, NumberFor}, }; use sp_state_machine::{ self, OverlayedChanges, Ext, ExecutionManager, StateMachine, ExecutionStrategy, @@ -211,9 +211,9 @@ where version.map_err(|e| sp_blockchain::Error::VersionInvalid(format!("{:?}", e)).into()) } - fn prove_at_trie_state>>( + fn prove_at_trie_state>>( &self, - trie_state: &sp_state_machine::TrieBackend>, + trie_state: &sp_state_machine::TrieBackend>, overlay: &mut OverlayedChanges, method: &str, call_data: &[u8] diff --git a/substrate/client/src/cht.rs b/substrate/client/src/cht.rs index 1435b77ec5..de67280632 100644 --- a/substrate/client/src/cht.rs +++ b/substrate/client/src/cht.rs @@ -331,8 +331,8 @@ pub fn decode_cht_value(value: &[u8]) -> Option { #[cfg(test)] mod tests { - use sp_core::Blake2Hasher; use substrate_test_runtime_client::runtime::Header; + use sp_runtime::traits::BlakeTwo256; use super::*; #[test] @@ -398,7 +398,7 @@ mod tests { #[test] fn compute_root_works() { - assert!(compute_root::( + assert!(compute_root::( SIZE as _, 42, ::std::iter::repeat_with(|| Ok(Some(H256::from_low_u64_be(1)))) @@ -409,7 +409,7 @@ mod tests { #[test] #[should_panic] fn build_proof_panics_when_querying_wrong_block() { - assert!(build_proof::( + assert!(build_proof::( SIZE as _, 0, vec![(SIZE * 1000) as u64], @@ -420,7 +420,7 @@ mod tests { #[test] fn build_proof_works() { - assert!(build_proof::( + assert!(build_proof::( SIZE as _, 0, vec![(SIZE / 2) as u64], diff --git a/substrate/client/src/client.rs b/substrate/client/src/client.rs index 68970cbb2a..5a0093308e 100644 --- a/substrate/client/src/client.rs +++ b/substrate/client/src/client.rs @@ -34,7 +34,7 @@ use sp_runtime::{ Justification, BuildStorage, generic::{BlockId, SignedBlock, DigestItem}, traits::{ - Block as BlockT, Header as HeaderT, Zero, NumberFor, HasherFor, SaturatedConversion, One, + Block as BlockT, Header as HeaderT, Zero, NumberFor, HashFor, SaturatedConversion, One, DigestFor, }, }; @@ -120,7 +120,7 @@ impl <'a, State, Block> KeyIterator<'a, State, Block> { impl<'a, State, Block> Iterator for KeyIterator<'a, State, Block> where Block: BlockT, - State: StateBackend>, + State: StateBackend>, { type Item = StorageKey; @@ -527,7 +527,7 @@ impl Client where Some(old_current_num) }); let headers = cht_range.map(|num| self.block_hash(num)); - let proof = cht::build_proof::, _, _>( + let proof = cht::build_proof::, _, _>( cht_size, cht_num, std::iter::once(block_num), @@ -600,7 +600,7 @@ impl Client where zero: config_zero.clone(), end: config_end.map(|(config_end_number, _)| config_end_number), }; - let result_range: Vec<(NumberFor, u32)> = key_changes::, _>( + let result_range: Vec<(NumberFor, u32)> = key_changes::, _>( config_range, storage.storage(), range_first, @@ -654,12 +654,12 @@ impl Client where cht_size: NumberFor, ) -> sp_blockchain::Result> { struct AccessedRootsRecorder<'a, Block: BlockT> { - storage: &'a dyn ChangesTrieStorage, NumberFor>, + storage: &'a dyn ChangesTrieStorage, NumberFor>, min: NumberFor, required_roots_proofs: Mutex, Block::Hash>>, }; - impl<'a, Block: BlockT> ChangesTrieRootsStorage, NumberFor> for + impl<'a, Block: BlockT> ChangesTrieRootsStorage, NumberFor> for AccessedRootsRecorder<'a, Block> { fn build_anchor(&self, hash: Block::Hash) @@ -686,11 +686,11 @@ impl Client where } } - impl<'a, Block: BlockT> ChangesTrieStorage, NumberFor> for + impl<'a, Block: BlockT> ChangesTrieStorage, NumberFor> for AccessedRootsRecorder<'a, Block> { fn as_roots_storage(&self) - -> &dyn sp_state_machine::ChangesTrieRootsStorage, NumberFor> + -> &dyn sp_state_machine::ChangesTrieRootsStorage, NumberFor> { self } @@ -734,7 +734,7 @@ impl Client where zero: config_zero, end: config_end.map(|(config_end_number, _)| config_end_number), }; - let proof_range = key_changes_proof::, _>( + let proof_range = key_changes_proof::, _>( config_range, &recording_storage, first_number, @@ -801,7 +801,7 @@ impl Client where .map(|block| block.and_then(|block| block.digest().log(DigestItem::as_changes_trie_root).cloned())) ); - let proof = cht::build_proof::, _, _>( + let proof = cht::build_proof::, _, _>( cht_size, cht_num, blocks, diff --git a/substrate/client/src/genesis.rs b/substrate/client/src/genesis.rs index 006ed00c43..c3ca82292d 100644 --- a/substrate/client/src/genesis.rs +++ b/substrate/client/src/genesis.rs @@ -53,7 +53,7 @@ mod tests { runtime::{Hash, Transfer, Block, BlockNumber, Header, Digest}, AccountKeyring, Sr25519Keyring, }; - use sp_core::Blake2Hasher; + use sp_runtime::traits::BlakeTwo256; use hex_literal::*; native_executor_instance!( @@ -67,7 +67,7 @@ mod tests { } fn construct_block( - backend: &InMemoryBackend, + backend: &InMemoryBackend, number: BlockNumber, parent_hash: Hash, state_root: Hash, @@ -78,7 +78,7 @@ mod tests { let transactions = txs.into_iter().map(|tx| tx.into_signed_tx()).collect::>(); let iter = transactions.iter().map(Encode::encode); - let extrinsics_root = Layout::::ordered_trie_root(iter).into(); + let extrinsics_root = Layout::::ordered_trie_root(iter).into(); let mut header = Header { parent_hash, @@ -137,7 +137,7 @@ mod tests { (vec![].and(&Block { header, extrinsics: transactions }), hash) } - fn block1(genesis_hash: Hash, backend: &InMemoryBackend) -> (Vec, Hash) { + fn block1(genesis_hash: Hash, backend: &InMemoryBackend) -> (Vec, Hash) { construct_block( backend, 1, diff --git a/substrate/client/src/in_mem.rs b/substrate/client/src/in_mem.rs index dcff8102ae..bdbfdbc7ec 100644 --- a/substrate/client/src/in_mem.rs +++ b/substrate/client/src/in_mem.rs @@ -24,7 +24,7 @@ use sp_core::offchain::storage::{ InMemOffchainStorage as OffchainStorage }; use sp_runtime::generic::BlockId; -use sp_runtime::traits::{Block as BlockT, Header as HeaderT, Zero, NumberFor, HasherFor}; +use sp_runtime::traits::{Block as BlockT, Header as HeaderT, Zero, NumberFor, HashFor}; use sp_runtime::{Justification, Storage}; use sp_state_machine::{ ChangesTrieTransaction, InMemoryBackend, Backend as StateBackend, StorageCollection, @@ -462,8 +462,8 @@ impl sc_client_api::light::Storage for Blockchain pub struct BlockImportOperation { pending_block: Option>, pending_cache: HashMap>, - old_state: InMemoryBackend>, - new_state: Option>>, + old_state: InMemoryBackend>, + new_state: Option>>, aux: Vec<(Vec, Option>)>, finalized_blocks: Vec<(BlockId, Option)>, set_head: Option>, @@ -472,7 +472,7 @@ pub struct BlockImportOperation { impl backend::BlockImportOperation for BlockImportOperation where Block::Hash: Ord, { - type State = InMemoryBackend>; + type State = InMemoryBackend>; fn state(&self) -> sp_blockchain::Result> { Ok(Some(&self.old_state)) @@ -499,7 +499,7 @@ impl backend::BlockImportOperation for BlockImportOperatio fn update_db_storage( &mut self, - update: > as StateBackend>>::Transaction, + update: > as StateBackend>>::Transaction, ) -> sp_blockchain::Result<()> { self.new_state = Some(self.old_state.update(update)); Ok(()) @@ -507,7 +507,7 @@ impl backend::BlockImportOperation for BlockImportOperatio fn update_changes_trie( &mut self, - _update: ChangesTrieTransaction, NumberFor>, + _update: ChangesTrieTransaction, NumberFor>, ) -> sp_blockchain::Result<()> { Ok(()) } @@ -564,7 +564,7 @@ impl backend::BlockImportOperation for BlockImportOperatio /// > **Warning**: Doesn't support all the features necessary for a proper database. Only use this /// > struct for testing purposes. Do **NOT** use in production. pub struct Backend where Block::Hash: Ord { - states: RwLock>>>, + states: RwLock>>>, blockchain: Blockchain, import_lock: RwLock<()>, } @@ -599,7 +599,7 @@ impl backend::AuxStore for Backend where Block::Hash: Ord impl backend::Backend for Backend where Block::Hash: Ord { type BlockImportOperation = BlockImportOperation; type Blockchain = Blockchain; - type State = InMemoryBackend>; + type State = InMemoryBackend>; type OffchainStorage = OffchainStorage; fn begin_operation(&self) -> sp_blockchain::Result { diff --git a/substrate/client/src/lib.rs b/substrate/client/src/lib.rs index 1d279cabad..f282449c27 100644 --- a/substrate/client/src/lib.rs +++ b/substrate/client/src/lib.rs @@ -47,7 +47,6 @@ //! ``` //! use std::sync::Arc; //! use sc_client::{Client, in_mem::Backend, LocalCallExecutor}; -//! use sp_core::Blake2Hasher; //! use sp_runtime::Storage; //! use sc_executor::{NativeExecutor, WasmExecutionMethod}; //! diff --git a/substrate/client/src/light/backend.rs b/substrate/client/src/light/backend.rs index 48434bb41d..749e24af04 100644 --- a/substrate/client/src/light/backend.rs +++ b/substrate/client/src/light/backend.rs @@ -31,7 +31,7 @@ use sp_state_machine::{ StorageCollection, ChildStorageCollection, }; use sp_runtime::{generic::BlockId, Justification, Storage}; -use sp_runtime::traits::{Block as BlockT, NumberFor, Zero, Header, HasherFor}; +use sp_runtime::traits::{Block as BlockT, NumberFor, Zero, Header, HashFor}; use crate::in_mem::check_genesis_storage; use sp_blockchain::{Error as ClientError, Result as ClientResult}; use sc_client_api::{ @@ -65,7 +65,7 @@ pub struct ImportOperation { aux_ops: Vec<(Vec, Option>)>, finalized_blocks: Vec>, set_head: Option>, - storage_update: Option>>, + storage_update: Option>>, changes_trie_config_update: Option>, _phantom: std::marker::PhantomData, } @@ -111,7 +111,7 @@ impl AuxStore for Backend { } } -impl ClientBackend for Backend> +impl ClientBackend for Backend> where Block: BlockT, S: BlockchainStorage, @@ -119,7 +119,7 @@ impl ClientBackend for Backend> { type BlockImportOperation = ImportOperation; type Blockchain = Blockchain; - type State = GenesisOrUnavailableState>; + type State = GenesisOrUnavailableState>; type OffchainStorage = InMemOffchainStorage; fn begin_operation(&self) -> ClientResult { @@ -238,7 +238,7 @@ impl ClientBackend for Backend> } } -impl RemoteBackend for Backend> +impl RemoteBackend for Backend> where Block: BlockT, S: BlockchainStorage + 'static, @@ -262,7 +262,7 @@ impl BlockImportOperation for ImportOperation S: BlockchainStorage, Block::Hash: Ord, { - type State = GenesisOrUnavailableState>; + type State = GenesisOrUnavailableState>; fn state(&self) -> ClientResult> { // None means 'locally-stateless' backend @@ -287,7 +287,7 @@ impl BlockImportOperation for ImportOperation fn update_db_storage( &mut self, - _update: >>::Transaction, + _update: >>::Transaction, ) -> ClientResult<()> { // we're not storing anything locally => ignore changes Ok(()) @@ -295,7 +295,7 @@ impl BlockImportOperation for ImportOperation fn update_changes_trie( &mut self, - _update: ChangesTrieTransaction, NumberFor>, + _update: ChangesTrieTransaction, NumberFor>, ) -> ClientResult<()> { // we're not storing anything locally => ignore changes Ok(()) @@ -515,10 +515,10 @@ impl StateBackend for GenesisOrUnavailableState #[cfg(test)] mod tests { - use sp_core::Blake2Hasher; use substrate_test_runtime_client::{self, runtime::Block}; use sc_client_api::backend::NewBlockState; use crate::light::blockchain::tests::{DummyBlockchain, DummyStorage}; + use sp_runtime::traits::BlakeTwo256; use super::*; #[test] @@ -526,7 +526,9 @@ mod tests { let def = Default::default(); let header0 = substrate_test_runtime_client::runtime::Header::new(0, def, def, def, Default::default()); - let backend: Backend<_, Blake2Hasher> = Backend::new(Arc::new(DummyBlockchain::new(DummyStorage::new()))); + let backend: Backend<_, BlakeTwo256> = Backend::new( + Arc::new(DummyBlockchain::new(DummyStorage::new())), + ); let mut op = backend.begin_operation().unwrap(); op.set_block_data(header0, None, None, NewBlockState::Final).unwrap(); op.reset_storage(Default::default()).unwrap(); @@ -540,7 +542,9 @@ mod tests { #[test] fn unavailable_state_is_created_when_genesis_state_is_unavailable() { - let backend: Backend<_, Blake2Hasher> = Backend::new(Arc::new(DummyBlockchain::new(DummyStorage::new()))); + let backend: Backend<_, BlakeTwo256> = Backend::new( + Arc::new(DummyBlockchain::new(DummyStorage::new())), + ); match backend.state_at(BlockId::Number(0)).unwrap() { GenesisOrUnavailableState::Unavailable => (), diff --git a/substrate/client/src/light/call_executor.rs b/substrate/client/src/light/call_executor.rs index a440f5ad67..613d88045d 100644 --- a/substrate/client/src/light/call_executor.rs +++ b/substrate/client/src/light/call_executor.rs @@ -23,7 +23,7 @@ use std::{ use codec::{Encode, Decode}; use sp_core::{convert_hash, NativeOrEncoded, traits::CodeExecutor}; use sp_runtime::{ - generic::BlockId, traits::{One, Block as BlockT, Header as HeaderT, HasherFor}, + generic::BlockId, traits::{One, Block as BlockT, Header as HeaderT, HashFor}, }; use sp_externalities::Extensions; use sp_state_machine::{ @@ -152,9 +152,9 @@ impl CallExecutor for } } - fn prove_at_trie_state>>( + fn prove_at_trie_state>>( &self, - _state: &sp_state_machine::TrieBackend>, + _state: &sp_state_machine::TrieBackend>, _changes: &mut OverlayedChanges, _method: &str, _call_data: &[u8], @@ -180,7 +180,7 @@ pub fn prove_execution( ) -> ClientResult<(Vec, StorageProof)> where Block: BlockT, - S: StateBackend>, + S: StateBackend>, E: CallExecutor, { let trie_state = state.as_trie_backend() @@ -291,9 +291,10 @@ mod tests { runtime::{Header, Digest, Block}, TestClient, ClientBlockImportExt, }; use sc_executor::{NativeExecutor, WasmExecutionMethod}; - use sp_core::{Blake2Hasher, H256}; + use sp_core::H256; use sc_client_api::backend::{Backend, NewBlockState}; use crate::in_mem::Backend as InMemBackend; + use sp_runtime::traits::BlakeTwo256; struct DummyCallExecutor; @@ -348,9 +349,9 @@ mod tests { unreachable!() } - fn prove_at_trie_state>>( + fn prove_at_trie_state>>( &self, - _trie_state: &sp_state_machine::TrieBackend>, + _trie_state: &sp_state_machine::TrieBackend>, _overlay: &mut OverlayedChanges, _method: &str, _call_data: &[u8] @@ -381,7 +382,7 @@ mod tests { ).unwrap(); // check remote execution proof locally - let local_result = check_execution_proof::<_, _, Blake2Hasher>( + let local_result = check_execution_proof::<_, _, BlakeTwo256>( &local_executor(), &RemoteCallRequest { block: substrate_test_runtime_client::runtime::Hash::default(), @@ -408,7 +409,7 @@ mod tests { ).unwrap(); // check remote execution proof locally - let execution_result = check_execution_proof_with_make_header::<_, _, Blake2Hasher, _>( + let execution_result = check_execution_proof_with_make_header::<_, _, BlakeTwo256, _>( &local_executor(), &RemoteCallRequest { block: substrate_test_runtime_client::runtime::Hash::default(), diff --git a/substrate/client/src/light/fetcher.rs b/substrate/client/src/light/fetcher.rs index b5fccb455a..00e3eef2b6 100644 --- a/substrate/client/src/light/fetcher.rs +++ b/substrate/client/src/light/fetcher.rs @@ -342,12 +342,12 @@ pub mod tests { }; use sp_consensus::BlockOrigin; - use crate::in_mem::{Blockchain as InMemoryBlockchain}; + use crate::in_mem::Blockchain as InMemoryBlockchain; use crate::light::fetcher::{FetchChecker, LightDataChecker, RemoteHeaderRequest}; use crate::light::blockchain::tests::{DummyStorage, DummyBlockchain}; - use sp_core::{blake2_256, Blake2Hasher, ChangesTrieConfiguration, H256}; + use sp_core::{blake2_256, ChangesTrieConfiguration, H256}; use sp_core::storage::{well_known_keys, StorageKey, ChildInfo}; - use sp_runtime::generic::BlockId; + use sp_runtime::{generic::BlockId, traits::BlakeTwo256}; use sp_state_machine::Backend; use super::*; @@ -355,7 +355,7 @@ pub mod tests { type TestChecker = LightDataChecker< NativeExecutor, - Blake2Hasher, + BlakeTwo256, Block, DummyStorage, >; @@ -465,7 +465,7 @@ pub mod tests { // check remote read proof locally let local_storage = InMemoryBlockchain::::new(); - let local_cht_root = cht::compute_root::(4, 0, local_headers_hashes).unwrap(); + let local_cht_root = cht::compute_root::(4, 0, local_headers_hashes).unwrap(); if insert_cht { local_storage.insert_cht_root(1, local_cht_root); } @@ -479,7 +479,7 @@ pub mod tests { fn header_with_computed_extrinsics_root(extrinsics: Vec) -> Header { use sp_trie::{TrieConfiguration, trie_types::Layout}; let iter = extrinsics.iter().map(Encode::encode); - let extrinsics_root = Layout::::ordered_trie_root(iter); + let extrinsics_root = Layout::::ordered_trie_root(iter); // only care about `extrinsics_root` Header::new(0, extrinsics_root, H256::zero(), H256::zero(), Default::default()) @@ -625,7 +625,7 @@ pub mod tests { ).unwrap(); // prepare local checker, having a root of changes trie CHT#0 - let local_cht_root = cht::compute_root::(4, 0, remote_roots.iter().cloned().map(|ct| Ok(Some(ct)))).unwrap(); + let local_cht_root = cht::compute_root::(4, 0, remote_roots.iter().cloned().map(|ct| Ok(Some(ct)))).unwrap(); let mut local_storage = DummyStorage::new(); local_storage.changes_tries_cht_roots.insert(0, local_cht_root); let local_checker = TestChecker::new( @@ -732,7 +732,7 @@ pub mod tests { // we're testing this test case here: // (1, 4, dave.clone(), vec![(4, 0), (1, 1), (1, 0)]), let (remote_client, remote_roots, _) = prepare_client_with_key_changes(); - let local_cht_root = cht::compute_root::( + let local_cht_root = cht::compute_root::( 4, 0, remote_roots.iter().cloned().map(|ct| Ok(Some(ct)))).unwrap(); let dave = blake2_256(&runtime::system::balance_of_key(AccountKeyring::Dave.into())).to_vec(); let dave = StorageKey(dave); diff --git a/substrate/client/src/light/mod.rs b/substrate/client/src/light/mod.rs index d65fdef711..ca1a3a50c6 100644 --- a/substrate/client/src/light/mod.rs +++ b/substrate/client/src/light/mod.rs @@ -26,7 +26,7 @@ use std::sync::Arc; use sc_executor::RuntimeInfo; use sp_core::traits::CodeExecutor; use sp_runtime::BuildStorage; -use sp_runtime::traits::{Block as BlockT, HasherFor}; +use sp_runtime::traits::{Block as BlockT, HashFor}; use sp_blockchain::Result as ClientResult; use crate::call_executor::LocalCallExecutor; @@ -45,7 +45,7 @@ pub fn new_light_blockchain>(storage: S) -> A } /// Create an instance of light client backend. -pub fn new_light_backend(blockchain: Arc>) -> Arc>> +pub fn new_light_backend(blockchain: Arc>) -> Arc>> where B: BlockT, S: BlockchainStorage, @@ -55,15 +55,15 @@ pub fn new_light_backend(blockchain: Arc>) -> Arc( - backend: Arc>>, + backend: Arc>>, genesis_storage: &GS, code_executor: E, ) -> ClientResult< Client< - Backend>, + Backend>, GenesisCallExecutor< - Backend>, - LocalCallExecutor>, E> + Backend>, + LocalCallExecutor>, E> >, B, RA @@ -91,7 +91,7 @@ pub fn new_light( pub fn new_fetch_checker>( blockchain: Arc>, executor: E, -) -> LightDataChecker, B, S> +) -> LightDataChecker, B, S> where E: CodeExecutor, { diff --git a/substrate/client/transaction-pool/src/api.rs b/substrate/client/transaction-pool/src/api.rs index 84e06cc33e..d14f532435 100644 --- a/substrate/client/transaction-pool/src/api.rs +++ b/substrate/client/transaction-pool/src/api.rs @@ -27,7 +27,6 @@ use sc_client_api::{ light::{Fetcher, RemoteCallRequest, RemoteBodyRequest}, BlockBody, }; -use sp_core::Hasher; use sp_runtime::{ generic::BlockId, traits::{self, Block as BlockT, BlockIdTo, Header as HeaderT, Hash as HashT}, transaction_validity::TransactionValidity, @@ -120,7 +119,7 @@ impl sc_transaction_graph::ChainApi for FullChainApi) -> (Self::Hash, usize) { ex.using_encoded(|x| { - (traits::HasherFor::::hash(x), x.len()) + ( as traits::Hash>::hash(x), x.len()) }) } } diff --git a/substrate/frame/benchmarking/src/tests.rs b/substrate/frame/benchmarking/src/tests.rs index d47488604e..4327476c4a 100644 --- a/substrate/frame/benchmarking/src/tests.rs +++ b/substrate/frame/benchmarking/src/tests.rs @@ -21,10 +21,7 @@ use super::*; use codec::Decode; use sp_std::prelude::*; -use sp_runtime::{ - traits::{Dispatchable, BlakeTwo256, IdentityLookup}, - testing::{H256, Header}, -}; +use sp_runtime::{traits::{BlakeTwo256, IdentityLookup}, testing::{H256, Header}}; use frame_support::{dispatch::DispatchResult, decl_module, impl_outer_origin}; use frame_system::{RawOrigin, ensure_signed, ensure_none}; @@ -166,4 +163,4 @@ fn benchmarks_macro_works_for_non_dispatchable() { ).expect("failed to create closure"); assert_eq!(closure(), Ok(())); -} \ No newline at end of file +} diff --git a/substrate/frame/contracts/src/lib.rs b/substrate/frame/contracts/src/lib.rs index 571ae9700c..93e470a51b 100644 --- a/substrate/frame/contracts/src/lib.rs +++ b/substrate/frame/contracts/src/lib.rs @@ -254,7 +254,7 @@ where let mut buf = Vec::new(); storage_root.using_encoded(|encoded| buf.extend_from_slice(encoded)); buf.extend_from_slice(code_hash.as_ref()); - RawTombstoneContractInfo(Hasher::hash(&buf[..]), PhantomData) + RawTombstoneContractInfo(::hash(&buf[..]), PhantomData) } } diff --git a/substrate/frame/session/src/historical.rs b/substrate/frame/session/src/historical.rs index 6c305a1a1d..5b492d8d21 100644 --- a/substrate/frame/session/src/historical.rs +++ b/substrate/frame/session/src/historical.rs @@ -28,7 +28,7 @@ use sp_std::prelude::*; use codec::{Encode, Decode}; use sp_runtime::KeyTypeId; -use sp_runtime::traits::{Convert, OpaqueKeys, Hash as HashT}; +use sp_runtime::traits::{Convert, OpaqueKeys}; use frame_support::{decl_module, decl_storage}; use frame_support::{Parameter, print}; use sp_trie::{MemoryDB, Trie, TrieMut, Recorder, EMPTY_PREFIX}; @@ -155,14 +155,12 @@ impl crate::SessionManager for NoteHistoricalRoot = <::Hashing as HashT>::Hasher; - /// A tuple of the validator's ID and their full identification. pub type IdentificationTuple = (::ValidatorId, ::FullIdentification); /// a trie instance for checking and generating proofs. pub struct ProvingTrie { - db: MemoryDB>, + db: MemoryDB, root: T::Hash, } diff --git a/substrate/primitives/api/proc-macro/src/impl_runtime_apis.rs b/substrate/primitives/api/proc-macro/src/impl_runtime_apis.rs index 770a843bfa..07d7ae4040 100644 --- a/substrate/primitives/api/proc-macro/src/impl_runtime_apis.rs +++ b/substrate/primitives/api/proc-macro/src/impl_runtime_apis.rs @@ -237,7 +237,7 @@ fn generate_runtime_api_base_structures() -> Result { pub struct RuntimeApiImpl + 'static> where // Rust bug: https://github.com/rust-lang/rust/issues/24159 - C::StateBackend: #crate_::StateBackend<#crate_::HasherFor>, + C::StateBackend: #crate_::StateBackend<#crate_::HashFor>, { call: &'static C, commit_on_success: std::cell::RefCell, @@ -257,7 +257,7 @@ fn generate_runtime_api_base_structures() -> Result { for RuntimeApiImpl where // Rust bug: https://github.com/rust-lang/rust/issues/24159 - C::StateBackend: #crate_::StateBackend<#crate_::HasherFor>, + C::StateBackend: #crate_::StateBackend<#crate_::HashFor>, {} #[cfg(any(feature = "std", test))] @@ -265,7 +265,7 @@ fn generate_runtime_api_base_structures() -> Result { for RuntimeApiImpl where // Rust bug: https://github.com/rust-lang/rust/issues/24159 - C::StateBackend: #crate_::StateBackend<#crate_::HasherFor>, + C::StateBackend: #crate_::StateBackend<#crate_::HashFor>, {} #[cfg(any(feature = "std", test))] @@ -273,7 +273,7 @@ fn generate_runtime_api_base_structures() -> Result { for RuntimeApiImpl where // Rust bug: https://github.com/rust-lang/rust/issues/24159 - C::StateBackend: #crate_::StateBackend<#crate_::HasherFor>, + C::StateBackend: #crate_::StateBackend<#crate_::HashFor>, { type Error = C::Error; } @@ -283,7 +283,7 @@ fn generate_runtime_api_base_structures() -> Result { RuntimeApiImpl where // Rust bug: https://github.com/rust-lang/rust/issues/24159 - C::StateBackend: #crate_::StateBackend<#crate_::HasherFor>, + C::StateBackend: #crate_::StateBackend<#crate_::HashFor>, { type StateBackend = C::StateBackend; @@ -327,7 +327,7 @@ fn generate_runtime_api_base_structures() -> Result { &self, backend: &Self::StateBackend, changes_trie_state: Option<&#crate_::ChangesTrieState< - #crate_::HasherFor, + #crate_::HashFor, #crate_::NumberFor, >>, parent_hash: Block::Hash, @@ -351,7 +351,7 @@ fn generate_runtime_api_base_structures() -> Result { where C: #crate_::CallApiAt + 'static, // Rust bug: https://github.com/rust-lang/rust/issues/24159 - C::StateBackend: #crate_::StateBackend<#crate_::HasherFor>, + C::StateBackend: #crate_::StateBackend<#crate_::HashFor>, { type RuntimeApi = RuntimeApiImpl; @@ -373,7 +373,7 @@ fn generate_runtime_api_base_structures() -> Result { impl> RuntimeApiImpl where // Rust bug: https://github.com/rust-lang/rust/issues/24159 - C::StateBackend: #crate_::StateBackend<#crate_::HasherFor>, + C::StateBackend: #crate_::StateBackend<#crate_::HashFor>, { fn call_api_at< R: #crate_::Encode + #crate_::Decode + PartialEq, @@ -603,7 +603,7 @@ impl<'a> Fold for ApiRuntimeImplToApiRuntimeApiImpl<'a> { where_clause.predicates.push( parse_quote! { RuntimeApiImplCall::StateBackend: - #crate_::StateBackend<#crate_::HasherFor<__SR_API_BLOCK__>> + #crate_::StateBackend<#crate_::HashFor<__SR_API_BLOCK__>> } ); diff --git a/substrate/primitives/api/src/lib.rs b/substrate/primitives/api/src/lib.rs index bde00d4817..0901be5831 100644 --- a/substrate/primitives/api/src/lib.rs +++ b/substrate/primitives/api/src/lib.rs @@ -50,7 +50,7 @@ pub use sp_core::to_substrate_wasm_fn_return_value; #[doc(hidden)] pub use sp_runtime::{ traits::{ - Block as BlockT, GetNodeBlockType, GetRuntimeBlockType, HasherFor, NumberFor, + Block as BlockT, GetNodeBlockType, GetRuntimeBlockType, HashFor, NumberFor, Header as HeaderT, Hash as HashT, }, generic::BlockId, transaction_validity::TransactionValidity, @@ -228,22 +228,20 @@ pub use sp_api_proc_macro::impl_runtime_apis; /// A type that records all accessed trie nodes and generates a proof out of it. #[cfg(feature = "std")] -pub type ProofRecorder = sp_state_machine::ProofRecorder< - <<::Header as HeaderT>::Hashing as HashT>::Hasher ->; +pub type ProofRecorder = sp_state_machine::ProofRecorder>; /// A type that is used as cache for the storage transactions. #[cfg(feature = "std")] pub type StorageTransactionCache = sp_state_machine::StorageTransactionCache< - >>::Transaction, HasherFor, NumberFor + >>::Transaction, HashFor, NumberFor >; #[cfg(feature = "std")] pub type StorageChanges = sp_state_machine::StorageChanges< - >>::Transaction, - HasherFor, + >>::Transaction, + HashFor, NumberFor >; @@ -255,7 +253,7 @@ pub type StateBackendFor = /// Extract the state backend transaction type for a type that implements `ProvideRuntimeApi`. #[cfg(feature = "std")] pub type TransactionFor = - as StateBackend>>::Transaction; + as StateBackend>>::Transaction; /// Something that can be constructed to a runtime api. #[cfg(feature = "std")] @@ -279,7 +277,7 @@ pub trait ApiErrorExt { #[cfg(feature = "std")] pub trait ApiExt: ApiErrorExt { /// The state backend that is used to store the block states. - type StateBackend: StateBackend>; + type StateBackend: StateBackend>; /// The given closure will be called with api instance. Inside the closure any api call is /// allowed. After doing the api call, the closure is allowed to map the `Result` to a @@ -328,7 +326,7 @@ pub trait ApiExt: ApiErrorExt { fn into_storage_changes( &self, backend: &Self::StateBackend, - changes_trie_state: Option<&ChangesTrieState, NumberFor>>, + changes_trie_state: Option<&ChangesTrieState, NumberFor>>, parent_hash: Block::Hash, ) -> Result, String> where Self: Sized; } @@ -355,7 +353,7 @@ pub enum InitializeBlock<'a, Block: BlockT> { /// Parameters for [`CallApiAt::call_api_at`]. #[cfg(feature = "std")] -pub struct CallApiAtParams<'a, Block: BlockT, C, NC, Backend: StateBackend>> { +pub struct CallApiAtParams<'a, Block: BlockT, C, NC, Backend: StateBackend>> { /// A reference to something that implements the [`Core`] api. pub core_api: &'a C, /// The block id that determines the state that should be setup when calling the function. @@ -389,7 +387,7 @@ pub trait CallApiAt { type Error: std::fmt::Debug + From; /// The state backend that is used to store the block states. - type StateBackend: StateBackend>; + type StateBackend: StateBackend>; /// Calls the given api function with the given encoded arguments at the given block and returns /// the encoded result. diff --git a/substrate/primitives/api/test/tests/runtime_calls.rs b/substrate/primitives/api/test/tests/runtime_calls.rs index 64c20473d1..9088f18265 100644 --- a/substrate/primitives/api/test/tests/runtime_calls.rs +++ b/substrate/primitives/api/test/tests/runtime_calls.rs @@ -18,9 +18,9 @@ use sp_api::ProvideRuntimeApi; use substrate_test_runtime_client::{ prelude::*, DefaultTestClientBuilderExt, TestClientBuilder, - runtime::{TestAPI, DecodeFails, Transfer, Header}, + runtime::{TestAPI, DecodeFails, Transfer, Block}, }; -use sp_runtime::{generic::BlockId, traits::{Header as HeaderT, Hash as HashT}}; +use sp_runtime::{generic::BlockId, traits::{Header as HeaderT, HashFor}}; use sp_state_machine::{ ExecutionStrategy, create_proof_check_backend, execution_proof_check_on_trie_backend, @@ -184,7 +184,7 @@ fn record_proof_works() { builder.push(transaction.clone()).unwrap(); let (block, _, proof) = builder.build().expect("Bake block").into_inner(); - let backend = create_proof_check_backend::<<
::Hashing as HashT>::Hasher>( + let backend = create_proof_check_backend::>( storage_root, proof.expect("Proof was generated"), ).expect("Creates proof backend."); diff --git a/substrate/primitives/consensus/common/src/block_import.rs b/substrate/primitives/consensus/common/src/block_import.rs index 3000477ded..eb90ac9f1d 100644 --- a/substrate/primitives/consensus/common/src/block_import.rs +++ b/substrate/primitives/consensus/common/src/block_import.rs @@ -16,7 +16,7 @@ //! Block import helpers. -use sp_runtime::traits::{Block as BlockT, DigestItemFor, Header as HeaderT, NumberFor, HasherFor}; +use sp_runtime::traits::{Block as BlockT, DigestItemFor, Header as HeaderT, NumberFor, HashFor}; use sp_runtime::Justification; use serde::{Serialize, Deserialize}; use std::borrow::Cow; @@ -139,7 +139,7 @@ pub struct BlockImportParams { /// The changes to the storage to create the state for the block. If this is `Some(_)`, /// the block import will not need to re-execute the block for importing it. pub storage_changes: Option< - sp_state_machine::StorageChanges, NumberFor> + sp_state_machine::StorageChanges, NumberFor> >, /// Is this block finalized already? /// `true` implies instant finality. diff --git a/substrate/primitives/consensus/common/src/lib.rs b/substrate/primitives/consensus/common/src/lib.rs index 4927faede0..09dc031dc9 100644 --- a/substrate/primitives/consensus/common/src/lib.rs +++ b/substrate/primitives/consensus/common/src/lib.rs @@ -32,7 +32,7 @@ use std::sync::Arc; use std::time::Duration; use sp_runtime::{ - generic::BlockId, traits::{Block as BlockT, DigestFor, NumberFor, HasherFor}, + generic::BlockId, traits::{Block as BlockT, DigestFor, NumberFor, HashFor}, }; use futures::prelude::*; pub use sp_inherents::InherentData; @@ -93,7 +93,7 @@ pub struct Proposal { /// Optional proof that was recorded while building the block. pub proof: Option, /// The storage changes while building this block. - pub storage_changes: sp_state_machine::StorageChanges, NumberFor>, + pub storage_changes: sp_state_machine::StorageChanges, NumberFor>, } /// Used as parameter to [`Proposer`] to tell the requirement on recording a proof. diff --git a/substrate/primitives/core/src/hasher.rs b/substrate/primitives/core/src/hasher.rs index 68fce90644..28da432da7 100644 --- a/substrate/primitives/core/src/hasher.rs +++ b/substrate/primitives/core/src/hasher.rs @@ -16,27 +16,10 @@ //! Substrate Blake2b Hasher implementation -use hash_db::Hasher; -use hash256_std_hasher::Hash256StdHasher; -use crate::hash::H256; - pub mod blake2 { - use super::{Hasher, Hash256StdHasher, H256}; - #[cfg(feature = "std")] - use crate::hashing::blake2_256; - - #[cfg(not(feature = "std"))] - extern "C" { - fn ext_blake2_256(data: *const u8, len: u32, out: *mut u8); - } - #[cfg(not(feature = "std"))] - fn blake2_256(data: &[u8]) -> [u8; 32] { - let mut result: [u8; 32] = Default::default(); - unsafe { - ext_blake2_256(data.as_ptr(), data.len() as u32, result.as_mut_ptr()); - } - result - } + use hash_db::Hasher; + use hash256_std_hasher::Hash256StdHasher; + use crate::hash::H256; /// Concrete implementation of Hasher using Blake2b 256-bit hashes #[derive(Debug)] @@ -46,8 +29,9 @@ pub mod blake2 { type Out = H256; type StdHasher = Hash256StdHasher; const LENGTH: usize = 32; + fn hash(x: &[u8]) -> Self::Out { - blake2_256(x).into() + crate::hashing::blake2_256(x).into() } } } diff --git a/substrate/primitives/core/src/lib.rs b/substrate/primitives/core/src/lib.rs index 01a96d8853..79721b9b76 100644 --- a/substrate/primitives/core/src/lib.rs +++ b/substrate/primitives/core/src/lib.rs @@ -61,6 +61,7 @@ pub mod ed25519; pub mod sr25519; pub mod ecdsa; pub mod hash; +#[cfg(feature = "std")] mod hasher; pub mod offchain; pub mod sandbox; @@ -77,8 +78,7 @@ pub use changes_trie::{ChangesTrieConfiguration, ChangesTrieConfigurationRange}; pub use crypto::{DeriveJunction, Pair, Public}; pub use hash_db::Hasher; -// Switch back to Blake after PoC-3 is out -// pub use self::hasher::blake::BlakeHasher; +#[cfg(feature = "std")] pub use self::hasher::blake2::Blake2Hasher; pub use sp_storage as storage; diff --git a/substrate/primitives/io/src/lib.rs b/substrate/primitives/io/src/lib.rs index aef3eed5aa..4b520a240a 100644 --- a/substrate/primitives/io/src/lib.rs +++ b/substrate/primitives/io/src/lib.rs @@ -915,56 +915,6 @@ pub fn oom(_: core::alloc::Layout) -> ! { #[cfg(feature = "std")] pub type TestExternalities = sp_state_machine::TestExternalities; -#[cfg(feature = "std")] -mod ext_blake2_256 { - use sp_wasm_interface::{Signature, Function, HostFunctions, ValueType, Value, FunctionContext}; - - /// There is a custom `extern function` in `sp_core::hasher` for `ext_blake2_256` hasher. This - /// custom extern was missed to remove and requires us to support this now. This type is a custom - /// implementation for the wasm function in native. - pub struct ExtBlake2_256; - - impl HostFunctions for ExtBlake2_256 { - fn host_functions() -> Vec<&'static dyn Function> { - vec![&ExtBlake2_256] - } - } - - impl Function for ExtBlake2_256 { - fn name(&self) -> &str { - "ext_blake2_256" - } - - fn signature(&self) -> Signature { - Signature::new_with_args(&[ValueType::I32, ValueType::I32, ValueType::I32][..]) - } - - fn execute( - &self, - context: &mut dyn FunctionContext, - args: &mut dyn Iterator, - ) -> sp_wasm_interface::Result> { - let data = args.next().and_then(|v| v.as_i32()) - .ok_or_else(|| "`data` not present or not an `i32`")? as u32; - let len = args.next().and_then(|v| v.as_i32()) - .ok_or_else(|| "`len` not present or not an `i32`")? as u32; - let out = args.next().and_then(|v| v.as_i32()) - .ok_or_else(|| "`out` not present or not an `i32`")? as u32; - - let result: [u8; 32] = if len == 0 { - sp_core::hashing::blake2_256(&[0u8; 0]) - } else { - let mem = context.read_memory(data.into(), len) - .map_err(|_| "Invalid attempt to get data in ext_blake2_256")?; - sp_core::hashing::blake2_256(&mem) - }; - context.write_memory(out.into(), &result) - .map_err(|_| "Invalid attempt to set result in ext_blake2_256")?; - Ok(None) - } - } -} - /// The host functions Substrate provides for the Wasm runtime environment. /// /// All these host functions will be callable from inside the Wasm environment. @@ -979,7 +929,6 @@ pub type SubstrateHostFunctions = ( logging::HostFunctions, sandbox::HostFunctions, crate::trie::HostFunctions, - ext_blake2_256::ExtBlake2_256, ); #[cfg(test)] diff --git a/substrate/primitives/runtime-interface/test-wasm/src/lib.rs b/substrate/primitives/runtime-interface/test-wasm/src/lib.rs index 2e1ab52d67..ee7120b1b8 100644 --- a/substrate/primitives/runtime-interface/test-wasm/src/lib.rs +++ b/substrate/primitives/runtime-interface/test-wasm/src/lib.rs @@ -231,14 +231,4 @@ wasm_export_functions! { } assert_eq!(0, len); } - - fn test_ext_blake2_256() { - use sp_core::Hasher; - - let data = "hey, hash me please!"; - let hash = sp_core::Blake2Hasher::hash(data.as_bytes()); - - let expected = sp_io::hashing::blake2_256(data.as_bytes()); - assert_eq!(&expected, hash.as_ref()); - } } diff --git a/substrate/primitives/runtime-interface/test/Cargo.toml b/substrate/primitives/runtime-interface/test/Cargo.toml index 6694272529..53c05b68b3 100644 --- a/substrate/primitives/runtime-interface/test/Cargo.toml +++ b/substrate/primitives/runtime-interface/test/Cargo.toml @@ -13,5 +13,5 @@ sp-runtime-interface = { version = "2.0.0-alpha.2", path = "../" } sc-executor = { version = "0.8.0-alpha.2", path = "../../../client/executor" } sp-runtime-interface-test-wasm = { version = "2.0.0-dev", path = "../test-wasm" } sp-state-machine = { version = "0.8.0-alpha.2", path = "../../../primitives/state-machine" } -sp-core = { version = "2.0.0-alpha.2", path = "../../core" } +sp-runtime = { version = "2.0.0-alpha.2", path = "../../runtime" } sp-io = { version = "2.0.0-alpha.2", path = "../../io" } diff --git a/substrate/primitives/runtime-interface/test/src/lib.rs b/substrate/primitives/runtime-interface/test/src/lib.rs index 5c5d1db970..01fc0a46b7 100644 --- a/substrate/primitives/runtime-interface/test/src/lib.rs +++ b/substrate/primitives/runtime-interface/test/src/lib.rs @@ -23,7 +23,7 @@ use sp_runtime_interface::*; use sp_runtime_interface_test_wasm::{WASM_BINARY, test_api::HostFunctions}; use sp_wasm_interface::HostFunctions as HostFunctionsT; -type TestExternalities = sp_state_machine::TestExternalities; +type TestExternalities = sp_state_machine::TestExternalities; fn call_wasm_method(method: &str) -> TestExternalities { let mut ext = TestExternalities::default(); @@ -127,8 +127,3 @@ fn test_encoded_return_value_memory_is_freed() { fn test_array_return_value_memory_is_freed() { call_wasm_method::("test_array_return_value_memory_is_freed"); } - -#[test] -fn test_ext_blake2_256() { - call_wasm_method::("test_ext_blake2_256"); -} diff --git a/substrate/primitives/runtime/Cargo.toml b/substrate/primitives/runtime/Cargo.toml index 430d29d8e2..84e452a5b4 100644 --- a/substrate/primitives/runtime/Cargo.toml +++ b/substrate/primitives/runtime/Cargo.toml @@ -24,6 +24,7 @@ rand = { version = "0.7.2", optional = true } impl-trait-for-tuples = "0.1.3" sp-inherents = { version = "2.0.0-alpha.2", default-features = false, path = "../inherents" } parity-util-mem = { version = "0.5.1", default-features = false, features = ["primitive-types"] } +hash256-std-hasher = { version = "0.15.2", default-features = false } [dev-dependencies] serde_json = "1.0.41" @@ -44,4 +45,5 @@ std = [ "serde", "sp-inherents/std", "parity-util-mem/std", + "hash256-std-hasher/std", ] diff --git a/substrate/primitives/runtime/src/random_number_generator.rs b/substrate/primitives/runtime/src/random_number_generator.rs index e741aac097..c3cd3dfb90 100644 --- a/substrate/primitives/runtime/src/random_number_generator.rs +++ b/substrate/primitives/runtime/src/random_number_generator.rs @@ -66,7 +66,7 @@ impl RandomNumberGenerator { loop { if self.offset() + needed > self.current.as_ref().len() { // rehash - self.current = Hashing::hash(self.current.as_ref()); + self.current = ::hash(self.current.as_ref()); self.offset = 0; } let data = &self.current.as_ref()[self.offset()..self.offset() + needed]; diff --git a/substrate/primitives/runtime/src/traits.rs b/substrate/primitives/runtime/src/traits.rs index fef20c826a..d9c32d221c 100644 --- a/substrate/primitives/runtime/src/traits.rs +++ b/substrate/primitives/runtime/src/traits.rs @@ -25,7 +25,7 @@ use std::fmt::Display; use std::str::FromStr; #[cfg(feature = "std")] use serde::{Serialize, Deserialize, de::DeserializeOwned}; -use sp_core::{self, Hasher, Blake2Hasher, TypeId, RuntimeDebug}; +use sp_core::{self, Hasher, TypeId, RuntimeDebug}; use crate::codec::{Codec, Encode, Decode}; use crate::transaction_validity::{ ValidTransaction, TransactionValidity, TransactionValidityError, UnknownTransaction, @@ -369,20 +369,19 @@ pub trait OffchainWorker { /// Abstraction around hashing // Stupid bug in the Rust compiler believes derived // traits must be fulfilled by all type parameters. -pub trait Hash: 'static + MaybeSerializeDeserialize + Debug + Clone + Eq + PartialEq { +pub trait Hash: 'static + MaybeSerializeDeserialize + Debug + Clone + Eq + PartialEq + Hasher::Output> { /// The hash type produced. type Output: Member + MaybeSerializeDeserialize + Debug + sp_std::hash::Hash + AsRef<[u8]> + AsMut<[u8]> + Copy + Default + Encode + Decode; - /// The associated hash_db Hasher type. - type Hasher: Hasher; - /// Produce the hash of some byte-slice. - fn hash(s: &[u8]) -> Self::Output; + fn hash(s: &[u8]) -> Self::Output { + ::hash(s) + } /// Produce the hash of some codec-encodable value. fn hash_of(s: &S) -> Self::Output { - Encode::using_encoded(s, Self::hash) + Encode::using_encoded(s, ::hash) } /// The ordered Patricia tree root of the given `input`. @@ -397,12 +396,18 @@ pub trait Hash: 'static + MaybeSerializeDeserialize + Debug + Clone + Eq + Parti #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] pub struct BlakeTwo256; -impl Hash for BlakeTwo256 { - type Output = sp_core::H256; - type Hasher = Blake2Hasher; - fn hash(s: &[u8]) -> Self::Output { +impl Hasher for BlakeTwo256 { + type Out = sp_core::H256; + type StdHasher = hash256_std_hasher::Hash256StdHasher; + const LENGTH: usize = 32; + + fn hash(s: &[u8]) -> Self::Out { sp_io::hashing::blake2_256(s).into() } +} + +impl Hash for BlakeTwo256 { + type Output = sp_core::H256; fn trie_root(input: Vec<(Vec, Vec)>) -> Self::Output { sp_io::trie::blake2_256_root(input) @@ -616,8 +621,6 @@ pub trait ExtrinsicMetadata { type SignedExtensions: SignedExtension; } -/// Extract the hasher type for a block. -pub type HasherFor = as Hash>::Hasher; /// Extract the hashing type for a block. pub type HashFor = <::Header as Header>::Hashing; /// Extract the number type for a block. diff --git a/substrate/primitives/state-machine/Cargo.toml b/substrate/primitives/state-machine/Cargo.toml index 51f311e44a..16f921c3ac 100644 --- a/substrate/primitives/state-machine/Cargo.toml +++ b/substrate/primitives/state-machine/Cargo.toml @@ -25,6 +25,7 @@ sp-externalities = { version = "0.8.0-alpha.2", path = "../externalities" } [dev-dependencies] hex-literal = "0.2.1" +sp-runtime = { version = "2.0.0-alpha.2", path = "../runtime" } [features] default = [] diff --git a/substrate/primitives/state-machine/src/basic.rs b/substrate/primitives/state-machine/src/basic.rs index 966648bc82..7252ae10e9 100644 --- a/substrate/primitives/state-machine/src/basic.rs +++ b/substrate/primitives/state-machine/src/basic.rs @@ -350,7 +350,7 @@ mod tests { top: Default::default(), children: map![ child_storage.clone() => StorageChild { - data: map![ b"doe".to_vec() => b"reindeer".to_vec() ], + data: map![ b"doe".to_vec() => b"reindeer".to_vec() ], child_info: CHILD_INFO_1.to_owned(), } ] diff --git a/substrate/primitives/state-machine/src/changes_trie/changes_iterator.rs b/substrate/primitives/state-machine/src/changes_trie/changes_iterator.rs index 9f2d44967d..685786218c 100644 --- a/substrate/primitives/state-machine/src/changes_trie/changes_iterator.rs +++ b/substrate/primitives/state-machine/src/changes_trie/changes_iterator.rs @@ -376,13 +376,13 @@ impl<'a, H, Number> Iterator for ProvingDrilldownIterator<'a, H, Number> #[cfg(test)] mod tests { use std::iter::FromIterator; - use sp_core::Blake2Hasher; use crate::changes_trie::Configuration; use crate::changes_trie::input::InputPair; use crate::changes_trie::storage::InMemoryStorage; + use sp_runtime::traits::BlakeTwo256; use super::*; - fn prepare_for_drilldown() -> (Configuration, InMemoryStorage) { + fn prepare_for_drilldown() -> (Configuration, InMemoryStorage) { let config = Configuration { digest_interval: 4, digest_levels: 2 }; let backend = InMemoryStorage::with_inputs(vec![ // digest: 1..4 => [(3, 0)] @@ -447,7 +447,7 @@ mod tests { #[test] fn drilldown_iterator_works() { let (config, storage) = prepare_for_drilldown(); - let drilldown_result = key_changes::( + let drilldown_result = key_changes::( configuration_range(&config, 0), &storage, 1, @@ -458,7 +458,7 @@ mod tests { ).and_then(Result::from_iter); assert_eq!(drilldown_result, Ok(vec![(8, 2), (8, 1), (6, 3), (3, 0)])); - let drilldown_result = key_changes::( + let drilldown_result = key_changes::( configuration_range(&config, 0), &storage, 1, @@ -469,7 +469,7 @@ mod tests { ).and_then(Result::from_iter); assert_eq!(drilldown_result, Ok(vec![])); - let drilldown_result = key_changes::( + let drilldown_result = key_changes::( configuration_range(&config, 0), &storage, 1, @@ -480,7 +480,7 @@ mod tests { ).and_then(Result::from_iter); assert_eq!(drilldown_result, Ok(vec![(3, 0)])); - let drilldown_result = key_changes::( + let drilldown_result = key_changes::( configuration_range(&config, 0), &storage, 1, @@ -491,7 +491,7 @@ mod tests { ).and_then(Result::from_iter); assert_eq!(drilldown_result, Ok(vec![(6, 3), (3, 0)])); - let drilldown_result = key_changes::( + let drilldown_result = key_changes::( configuration_range(&config, 0), &storage, 7, @@ -502,7 +502,7 @@ mod tests { ).and_then(Result::from_iter); assert_eq!(drilldown_result, Ok(vec![(8, 2), (8, 1)])); - let drilldown_result = key_changes::( + let drilldown_result = key_changes::( configuration_range(&config, 0), &storage, 5, @@ -519,7 +519,7 @@ mod tests { let (config, storage) = prepare_for_drilldown(); storage.clear_storage(); - assert!(key_changes::( + assert!(key_changes::( configuration_range(&config, 0), &storage, 1, @@ -529,7 +529,7 @@ mod tests { &[42], ).and_then(|i| i.collect::, _>>()).is_err()); - assert!(key_changes::( + assert!(key_changes::( configuration_range(&config, 0), &storage, 1, @@ -543,7 +543,7 @@ mod tests { #[test] fn drilldown_iterator_fails_when_range_is_invalid() { let (config, storage) = prepare_for_drilldown(); - assert!(key_changes::( + assert!(key_changes::( configuration_range(&config, 0), &storage, 1, @@ -552,7 +552,7 @@ mod tests { None, &[42], ).is_err()); - assert!(key_changes::( + assert!(key_changes::( configuration_range(&config, 0), &storage, 20, @@ -570,12 +570,12 @@ mod tests { // create drilldown iterator that records all trie nodes during drilldown let (remote_config, remote_storage) = prepare_for_drilldown(); - let remote_proof = key_changes_proof::( + let remote_proof = key_changes_proof::( configuration_range(&remote_config, 0), &remote_storage, 1, &AnchorBlockId { hash: Default::default(), number: 16 }, 16, None, &[42]).unwrap(); let (remote_config, remote_storage) = prepare_for_drilldown(); - let remote_proof_child = key_changes_proof::( + let remote_proof_child = key_changes_proof::( configuration_range(&remote_config, 0), &remote_storage, 1, &AnchorBlockId { hash: Default::default(), number: 16 }, 16, Some(&b"1"[..]), &[42]).unwrap(); @@ -584,13 +584,13 @@ mod tests { // create drilldown iterator that works the same, but only depends on trie let (local_config, local_storage) = prepare_for_drilldown(); local_storage.clear_storage(); - let local_result = key_changes_proof_check::( + let local_result = key_changes_proof_check::( configuration_range(&local_config, 0), &local_storage, remote_proof, 1, &AnchorBlockId { hash: Default::default(), number: 16 }, 16, None, &[42]); let (local_config, local_storage) = prepare_for_drilldown(); local_storage.clear_storage(); - let local_result_child = key_changes_proof_check::( + let local_result_child = key_changes_proof_check::( configuration_range(&local_config, 0), &local_storage, remote_proof_child, 1, &AnchorBlockId { hash: Default::default(), number: 16 }, 16, Some(&b"1"[..]), &[42]); @@ -621,7 +621,7 @@ mod tests { input[91 - 1].1.push(InputPair::DigestIndex(DigestIndex { block: 91, key: vec![42] }, vec![80])); let storage = InMemoryStorage::with_inputs(input, vec![]); - let drilldown_result = key_changes::( + let drilldown_result = key_changes::( config_range, &storage, 1, diff --git a/substrate/primitives/state-machine/src/changes_trie/prune.rs b/substrate/primitives/state-machine/src/changes_trie/prune.rs index f6be3223ae..87923dc2f5 100644 --- a/substrate/primitives/state-machine/src/changes_trie/prune.rs +++ b/substrate/primitives/state-machine/src/changes_trie/prune.rs @@ -114,14 +114,15 @@ fn prune_trie( mod tests { use std::collections::HashSet; use sp_trie::MemoryDB; - use sp_core::{H256, Blake2Hasher}; + use sp_core::H256; use crate::backend::insert_into_memory_db; use crate::changes_trie::storage::InMemoryStorage; use codec::Encode; + use sp_runtime::traits::BlakeTwo256; use super::*; fn prune_by_collect( - storage: &dyn Storage, + storage: &dyn Storage, first: u64, last: u64, current_block: u64, @@ -135,27 +136,26 @@ mod tests { #[test] fn prune_works() { - fn prepare_storage() -> InMemoryStorage { - + fn prepare_storage() -> InMemoryStorage { let child_key = ChildIndex { block: 67u64, storage_key: b"1".to_vec() }.encode(); - let mut mdb1 = MemoryDB::::default(); - let root1 = insert_into_memory_db::( + let mut mdb1 = MemoryDB::::default(); + let root1 = insert_into_memory_db::( &mut mdb1, vec![(vec![10], vec![20])]).unwrap(); - let mut mdb2 = MemoryDB::::default(); - let root2 = insert_into_memory_db::( + let mut mdb2 = MemoryDB::::default(); + let root2 = insert_into_memory_db::( &mut mdb2, vec![(vec![11], vec![21]), (vec![12], vec![22])], ).unwrap(); - let mut mdb3 = MemoryDB::::default(); - let ch_root3 = insert_into_memory_db::( + let mut mdb3 = MemoryDB::::default(); + let ch_root3 = insert_into_memory_db::( &mut mdb3, vec![(vec![110], vec![120])]).unwrap(); - let root3 = insert_into_memory_db::(&mut mdb3, vec![ + let root3 = insert_into_memory_db::(&mut mdb3, vec![ (vec![13], vec![23]), (vec![14], vec![24]), (child_key, ch_root3.as_ref().encode()), ]).unwrap(); - let mut mdb4 = MemoryDB::::default(); - let root4 = insert_into_memory_db::( + let mut mdb4 = MemoryDB::::default(); + let root4 = insert_into_memory_db::( &mut mdb4, vec![(vec![15], vec![25])], ).unwrap(); diff --git a/substrate/primitives/state-machine/src/in_memory_backend.rs b/substrate/primitives/state-machine/src/in_memory_backend.rs index 0a29468bbc..7e474d45b6 100644 --- a/substrate/primitives/state-machine/src/in_memory_backend.rs +++ b/substrate/primitives/state-machine/src/in_memory_backend.rs @@ -362,11 +362,12 @@ impl Backend for InMemory where H::Out: Codec { #[cfg(test)] mod tests { use super::*; + use sp_runtime::traits::BlakeTwo256; /// Assert in memory backend with only child trie keys works as trie backend. #[test] fn in_memory_with_child_trie_only() { - let storage = InMemory::::default(); + let storage = InMemory::::default(); let child_info = OwnedChildInfo::new_default(b"unique_id_1".to_vec()); let mut storage = storage.update( vec![( diff --git a/substrate/primitives/state-machine/src/lib.rs b/substrate/primitives/state-machine/src/lib.rs index 2c6245c70d..31d4f3a804 100644 --- a/substrate/primitives/state-machine/src/lib.rs +++ b/substrate/primitives/state-machine/src/lib.rs @@ -727,9 +727,8 @@ mod tests { use super::*; use super::ext::Ext; use super::changes_trie::Configuration as ChangesTrieConfig; - use sp_core::{ - Blake2Hasher, map, traits::{Externalities, RuntimeCode}, storage::ChildStorageKey, - }; + use sp_core::{map, traits::{Externalities, RuntimeCode}, storage::ChildStorageKey}; + use sp_runtime::traits::BlakeTwo256; #[derive(Clone)] struct DummyCodeExecutor { @@ -912,7 +911,7 @@ mod tests { ).unwrap(); // check proof locally - let local_result = execution_proof_check::( + let local_result = execution_proof_check::( remote_root, remote_proof, &mut Default::default(), @@ -935,7 +934,7 @@ mod tests { b"abc".to_vec() => b"2".to_vec(), b"bbb".to_vec() => b"3".to_vec() ]; - let mut state = InMemoryBackend::::from(initial); + let mut state = InMemoryBackend::::from(initial); let backend = state.as_trie_backend().unwrap(); let mut overlay = OverlayedChanges { committed: map![ @@ -978,7 +977,7 @@ mod tests { #[test] fn set_child_storage_works() { - let mut state = InMemoryBackend::::default(); + let mut state = InMemoryBackend::::default(); let backend = state.as_trie_backend().unwrap(); let mut overlay = OverlayedChanges::default(); let mut cache = StorageTransactionCache::default(); @@ -1025,12 +1024,12 @@ mod tests { let remote_root = remote_backend.storage_root(::std::iter::empty()).0; let remote_proof = prove_read(remote_backend, &[b"value2"]).unwrap(); // check proof locally - let local_result1 = read_proof_check::( + let local_result1 = read_proof_check::( remote_root, remote_proof.clone(), &[b"value2"], ).unwrap(); - let local_result2 = read_proof_check::( + let local_result2 = read_proof_check::( remote_root, remote_proof.clone(), &[&[0xff]], @@ -1050,13 +1049,13 @@ mod tests { CHILD_INFO_1, &[b"value3"], ).unwrap(); - let local_result1 = read_child_proof_check::( + let local_result1 = read_child_proof_check::( remote_root, remote_proof.clone(), b":child_storage:default:sub1", &[b"value3"], ).unwrap(); - let local_result2 = read_child_proof_check::( + let local_result2 = read_child_proof_check::( remote_root, remote_proof.clone(), b":child_storage:default:sub1", diff --git a/substrate/primitives/state-machine/src/proving_backend.rs b/substrate/primitives/state-machine/src/proving_backend.rs index 60d891a3f0..119fb59a72 100644 --- a/substrate/primitives/state-machine/src/proving_backend.rs +++ b/substrate/primitives/state-machine/src/proving_backend.rs @@ -308,16 +308,17 @@ mod tests { use crate::InMemoryBackend; use crate::trie_backend::tests::test_trie; use super::*; - use sp_core::{Blake2Hasher, storage::ChildStorageKey}; + use sp_core::storage::ChildStorageKey; use crate::proving_backend::create_proof_check_backend; use sp_trie::PrefixedMemoryDB; + use sp_runtime::traits::BlakeTwo256; const CHILD_INFO_1: ChildInfo<'static> = ChildInfo::new_default(b"unique_id_1"); const CHILD_INFO_2: ChildInfo<'static> = ChildInfo::new_default(b"unique_id_2"); fn test_proving<'a>( - trie_backend: &'a TrieBackend,Blake2Hasher>, - ) -> ProvingBackend<'a, PrefixedMemoryDB, Blake2Hasher> { + trie_backend: &'a TrieBackend,BlakeTwo256>, + ) -> ProvingBackend<'a, PrefixedMemoryDB, BlakeTwo256> { ProvingBackend::new(trie_backend) } @@ -338,7 +339,7 @@ mod tests { #[test] fn proof_is_invalid_when_does_not_contains_root() { use sp_core::H256; - let result = create_proof_check_backend::( + let result = create_proof_check_backend::( H256::from_low_u64_be(1), StorageProof::empty() ); @@ -361,7 +362,7 @@ mod tests { #[test] fn proof_recorded_and_checked() { let contents = (0..64).map(|i| (vec![i], Some(vec![i]))).collect::>(); - let in_memory = InMemoryBackend::::default(); + let in_memory = InMemoryBackend::::default(); let mut in_memory = in_memory.update(vec![(None, contents)]); let in_memory_root = in_memory.storage_root(::std::iter::empty()).0; (0..64).for_each(|i| assert_eq!(in_memory.storage(&[i]).unwrap().unwrap(), vec![i])); @@ -376,7 +377,7 @@ mod tests { let proof = proving.extract_proof(); - let proof_check = create_proof_check_backend::(in_memory_root.into(), proof).unwrap(); + let proof_check = create_proof_check_backend::(in_memory_root.into(), proof).unwrap(); assert_eq!(proof_check.storage(&[42]).unwrap().unwrap(), vec![42]); } @@ -393,7 +394,7 @@ mod tests { (Some((own2.clone(), CHILD_INFO_2.to_owned())), (10..15).map(|i| (vec![i], Some(vec![i]))).collect()), ]; - let in_memory = InMemoryBackend::::default(); + let in_memory = InMemoryBackend::::default(); let mut in_memory = in_memory.update(contents); let in_memory_root = in_memory.full_storage_root::<_, Vec<_>, _>( ::std::iter::empty(), @@ -425,7 +426,7 @@ mod tests { let proof = proving.extract_proof(); - let proof_check = create_proof_check_backend::( + let proof_check = create_proof_check_backend::( in_memory_root.into(), proof ).unwrap(); @@ -439,7 +440,7 @@ mod tests { assert_eq!(proving.child_storage(&own1[..], CHILD_INFO_1, &[64]), Ok(Some(vec![64]))); let proof = proving.extract_proof(); - let proof_check = create_proof_check_backend::( + let proof_check = create_proof_check_backend::( in_memory_root.into(), proof ).unwrap(); diff --git a/substrate/primitives/state-machine/src/testing.rs b/substrate/primitives/state-machine/src/testing.rs index 39a34509b7..aec42c7678 100644 --- a/substrate/primitives/state-machine/src/testing.rs +++ b/substrate/primitives/state-machine/src/testing.rs @@ -34,13 +34,12 @@ use sp_core::{ well_known_keys::{CHANGES_TRIE_CONFIG, CODE, HEAP_PAGES, is_child_storage_key}, Storage, }, - Blake2Hasher, }; use codec::Encode; use sp_externalities::{Extensions, Extension}; /// Simple HashMap-based Externalities impl. -pub struct TestExternalities +pub struct TestExternalities where H::Out: codec::Codec, { @@ -198,11 +197,12 @@ impl sp_externalities::ExtensionStore for TestExternalities where mod tests { use super::*; use sp_core::traits::Externalities; + use sp_runtime::traits::BlakeTwo256; use hex_literal::hex; #[test] fn commit_should_work() { - let mut ext = TestExternalities::::default(); + let mut ext = TestExternalities::::default(); let mut ext = ext.ext(); ext.set_storage(b"doe".to_vec(), b"reindeer".to_vec()); ext.set_storage(b"dog".to_vec(), b"puppy".to_vec()); @@ -213,7 +213,7 @@ mod tests { #[test] fn set_and_retrieve_code() { - let mut ext = TestExternalities::::default(); + let mut ext = TestExternalities::::default(); let mut ext = ext.ext(); let code = vec![1, 2, 3]; @@ -225,6 +225,6 @@ mod tests { #[test] fn check_send() { fn assert_send() {} - assert_send::>(); + assert_send::>(); } } diff --git a/substrate/primitives/state-machine/src/trie_backend.rs b/substrate/primitives/state-machine/src/trie_backend.rs index dbaae323c0..e64dd590e5 100644 --- a/substrate/primitives/state-machine/src/trie_backend.rs +++ b/substrate/primitives/state-machine/src/trie_backend.rs @@ -245,9 +245,10 @@ impl, H: Hasher> Backend for TrieBackend where #[cfg(test)] pub mod tests { use std::collections::HashSet; - use sp_core::{Blake2Hasher, H256}; + use sp_core::H256; use codec::Encode; use sp_trie::{TrieMut, PrefixedMemoryDB, trie_types::TrieDBMut, KeySpacedDBMut}; + use sp_runtime::traits::BlakeTwo256; use super::*; const CHILD_KEY_1: &[u8] = b":child_storage:default:sub1"; @@ -255,9 +256,9 @@ pub mod tests { const CHILD_UUID_1: &[u8] = b"unique_id_1"; const CHILD_INFO_1: ChildInfo<'static> = ChildInfo::new_default(CHILD_UUID_1); - fn test_db() -> (PrefixedMemoryDB, H256) { + fn test_db() -> (PrefixedMemoryDB, H256) { let mut root = H256::default(); - let mut mdb = PrefixedMemoryDB::::default(); + let mut mdb = PrefixedMemoryDB::::default(); { let mut mdb = KeySpacedDBMut::new(&mut mdb, CHILD_UUID_1); let mut trie = TrieDBMut::new(&mut mdb, &mut root); @@ -281,7 +282,7 @@ pub mod tests { (mdb, root) } - pub(crate) fn test_trie() -> TrieBackend, Blake2Hasher> { + pub(crate) fn test_trie() -> TrieBackend, BlakeTwo256> { let (mdb, root) = test_db(); TrieBackend::new(mdb, root) } @@ -312,7 +313,7 @@ pub mod tests { #[test] fn pairs_are_empty_on_empty_storage() { - assert!(TrieBackend::, Blake2Hasher>::new( + assert!(TrieBackend::, BlakeTwo256>::new( PrefixedMemoryDB::default(), Default::default(), ).pairs().is_empty()); diff --git a/substrate/primitives/trie/Cargo.toml b/substrate/primitives/trie/Cargo.toml index ddce910609..ff3c04b541 100644 --- a/substrate/primitives/trie/Cargo.toml +++ b/substrate/primitives/trie/Cargo.toml @@ -27,6 +27,7 @@ trie-bench = "0.20.0" trie-standardmap = "0.15.2" criterion = "0.2.11" hex-literal = "0.2.1" +sp-runtime = { version = "2.0.0-alpha.2", path = "../runtime" } [features] default = ["std"] diff --git a/substrate/primitives/trie/benches/bench.rs b/substrate/primitives/trie/benches/bench.rs index 72a53c18d2..d385b4bacd 100644 --- a/substrate/primitives/trie/benches/bench.rs +++ b/substrate/primitives/trie/benches/bench.rs @@ -20,11 +20,11 @@ criterion_main!(benches); fn benchmark(c: &mut Criterion) { trie_bench::standard_benchmark::< - sp_trie::Layout, + sp_trie::Layout, sp_trie::TrieStream, >(c, "substrate-blake2"); trie_bench::standard_benchmark::< - sp_trie::Layout, + sp_trie::Layout, sp_trie::TrieStream, >(c, "substrate-keccak"); } diff --git a/substrate/test-utils/client/src/lib.rs b/substrate/test-utils/client/src/lib.rs index afe11903d5..7d22abf3d8 100644 --- a/substrate/test-utils/client/src/lib.rs +++ b/substrate/test-utils/client/src/lib.rs @@ -33,7 +33,7 @@ pub use sp_keyring::{ ed25519::Keyring as Ed25519Keyring, sr25519::Keyring as Sr25519Keyring, }; -pub use sp_core::{Blake2Hasher, traits::BareCryptoStorePtr}; +pub use sp_core::traits::BareCryptoStorePtr; pub use sp_runtime::{Storage, StorageChild}; pub use sp_state_machine::ExecutionStrategy; pub use self::client_ext::{ClientExt, ClientBlockImportExt}; @@ -41,13 +41,13 @@ pub use self::client_ext::{ClientExt, ClientBlockImportExt}; use std::sync::Arc; use std::collections::HashMap; use sp_core::storage::{well_known_keys, ChildInfo}; -use sp_runtime::traits::Block as BlockT; +use sp_runtime::traits::{Block as BlockT, BlakeTwo256}; use sc_client::LocalCallExecutor; /// Test client light database backend. pub type LightBackend = sc_client::light::backend::Backend< sc_client_db::light::LightStorage, - Blake2Hasher, + BlakeTwo256, >; /// A genesis storage initialization trait. diff --git a/substrate/test-utils/runtime/client/src/block_builder_ext.rs b/substrate/test-utils/runtime/client/src/block_builder_ext.rs index 6b9a6f79ab..3a9f54d06c 100644 --- a/substrate/test-utils/runtime/client/src/block_builder_ext.rs +++ b/substrate/test-utils/runtime/client/src/block_builder_ext.rs @@ -19,7 +19,7 @@ use sp_api::{ApiExt, ProvideRuntimeApi}; use sp_core::ChangesTrieConfiguration; use sc_client_api::backend; -use sp_runtime::traits::HasherFor; +use sp_runtime::traits::HashFor; use sc_block_builder::BlockBuilderApi; @@ -50,7 +50,7 @@ impl<'a, A, B> BlockBuilderExt for sc_block_builder::BlockBuilder<'a, substrate_ B: backend::Backend, // Rust bug: https://github.com/rust-lang/rust/issues/24159 backend::StateBackendFor: - sp_api::StateBackend>, + sp_api::StateBackend>, { fn push_transfer(&mut self, transfer: substrate_test_runtime::Transfer) -> Result<(), sp_blockchain::Error> { self.push(transfer.into_signed_tx()) diff --git a/substrate/test-utils/runtime/client/src/lib.rs b/substrate/test-utils/runtime/client/src/lib.rs index 21cf94dfa6..9a50893024 100644 --- a/substrate/test-utils/runtime/client/src/lib.rs +++ b/substrate/test-utils/runtime/client/src/lib.rs @@ -33,7 +33,7 @@ pub use self::block_builder_ext::BlockBuilderExt; use sp_core::{sr25519, ChangesTrieConfiguration}; use sp_core::storage::{ChildInfo, Storage, StorageChild}; use substrate_test_runtime::genesismap::{GenesisConfig, additional_storage_with_genesis}; -use sp_runtime::traits::{Block as BlockT, Header as HeaderT, Hash as HashT, NumberFor, HasherFor}; +use sp_runtime::traits::{Block as BlockT, Header as HeaderT, Hash as HashT, NumberFor, HashFor}; use sc_client::{ light::fetcher::{ Fetcher, @@ -82,7 +82,7 @@ pub type LightExecutor = sc_client::light::call_executor::GenesisCallExecutor< sc_client::LocalCallExecutor< sc_client::light::backend::Backend< sc_client_db::light::LightStorage, - HasherFor + HashFor >, NativeExecutor > @@ -243,7 +243,7 @@ impl TestClientBuilderExt for TestClientBuilder< B: sc_client_api::backend::Backend + 'static, // Rust bug: https://github.com/rust-lang/rust/issues/24159 >::State: - sp_api::StateBackend>, + sp_api::StateBackend>, { fn genesis_init_mut(&mut self) -> &mut GenesisParameters { Self::genesis_init_mut(self) diff --git a/substrate/test-utils/runtime/client/src/trait_tests.rs b/substrate/test-utils/runtime/client/src/trait_tests.rs index 5ceab4355d..4af8aa37b6 100644 --- a/substrate/test-utils/runtime/client/src/trait_tests.rs +++ b/substrate/test-utils/runtime/client/src/trait_tests.rs @@ -29,7 +29,7 @@ use sc_client_api::blockchain::{Backend as BlockChainBackendT, HeaderBackend}; use substrate_test_client::sp_consensus::BlockOrigin; use substrate_test_runtime::{self, Transfer}; use sp_runtime::generic::BlockId; -use sp_runtime::traits::{Block as BlockT, HasherFor}; +use sp_runtime::traits::{Block as BlockT, HashFor}; use sc_block_builder::BlockBuilderProvider; /// helper to test the `leaves` implementation for various backends @@ -37,7 +37,7 @@ pub fn test_leaves_for_backend(backend: Arc) where B: backend::Backend, // Rust bug: https://github.com/rust-lang/rust/issues/24159 backend::StateBackendFor: - sp_api::StateBackend>, + sp_api::StateBackend>, { // block tree: // G -> A1 -> A2 -> A3 -> A4 -> A5 @@ -206,7 +206,7 @@ pub fn test_children_for_backend(backend: Arc) where B: backend::LocalBackend, // Rust bug: https://github.com/rust-lang/rust/issues/24159 >::State: - sp_api::StateBackend>, + sp_api::StateBackend>, { // block tree: // G -> A1 -> A2 -> A3 -> A4 -> A5 @@ -336,7 +336,7 @@ pub fn test_blockchain_query_by_number_gets_canonical(backend: Arc, // Rust bug: https://github.com/rust-lang/rust/issues/24159 >::State: - sp_api::StateBackend>, + sp_api::StateBackend>, { // block tree: // G -> A1 -> A2 -> A3 -> A4 -> A5 diff --git a/substrate/test-utils/runtime/src/lib.rs b/substrate/test-utils/runtime/src/lib.rs index 55e153103d..497de36c8b 100644 --- a/substrate/test-utils/runtime/src/lib.rs +++ b/substrate/test-utils/runtime/src/lib.rs @@ -25,7 +25,7 @@ pub mod system; use sp_std::{prelude::*, marker::PhantomData}; use codec::{Encode, Decode, Input, Error}; -use sp_core::{Blake2Hasher, OpaqueMetadata, RuntimeDebug, ChangesTrieConfiguration}; +use sp_core::{OpaqueMetadata, RuntimeDebug, ChangesTrieConfiguration}; use sp_application_crypto::{ed25519, sr25519, RuntimeAppPublic}; use trie_db::{TrieMut, Trie}; use sp_trie::PrefixedMemoryDB; @@ -419,7 +419,7 @@ fn code_using_trie() -> u64 { let mut root = sp_std::default::Default::default(); let _ = { let v = &pairs; - let mut t = TrieDBMut::::new(&mut mdb, &mut root); + let mut t = TrieDBMut::::new(&mut mdb, &mut root); for i in 0..v.len() { let key: &[u8]= &v[i].0; let val: &[u8] = &v[i].1; @@ -430,7 +430,7 @@ fn code_using_trie() -> u64 { t }; - if let Ok(trie) = TrieDB::::new(&mdb, &root) { + if let Ok(trie) = TrieDB::::new(&mdb, &root) { if let Ok(iter) = trie.iter() { let mut iter_pairs = Vec::new(); for pair in iter {