mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-04-26 09:57:56 +00:00
Run cargo fmt on the whole code base (#9394)
* Run cargo fmt on the whole code base * Second run * Add CI check * Fix compilation * More unnecessary braces * Handle weights * Use --all * Use correct attributes... * Fix UI tests * AHHHHHHHHH * 🤦 * Docs * Fix compilation * 🤷 * Please stop * 🤦 x 2 * More * make rustfmt.toml consistent with polkadot Co-authored-by: André Silva <andrerfosilva@gmail.com>
This commit is contained in:
@@ -17,14 +17,17 @@
|
||||
|
||||
//! Tool for creating the genesis block.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use sp_io::hashing::{blake2_256, twox_128};
|
||||
use super::{AuthorityId, AccountId, wasm_binary_unwrap, system};
|
||||
use codec::{Encode, KeyedVec, Joiner};
|
||||
use sp_core::{ChangesTrieConfiguration, map};
|
||||
use sp_core::storage::{well_known_keys, Storage};
|
||||
use sp_runtime::traits::{Block as BlockT, Hash as HashT, Header as HeaderT};
|
||||
use super::{system, wasm_binary_unwrap, AccountId, AuthorityId};
|
||||
use codec::{Encode, Joiner, KeyedVec};
|
||||
use sc_service::client::genesis;
|
||||
use sp_core::{
|
||||
map,
|
||||
storage::{well_known_keys, Storage},
|
||||
ChangesTrieConfiguration,
|
||||
};
|
||||
use sp_io::hashing::{blake2_256, twox_128};
|
||||
use sp_runtime::traits::{Block as BlockT, Hash as HashT, Header as HeaderT};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// Configuration of a general Substrate test genesis block.
|
||||
pub struct GenesisConfig {
|
||||
@@ -47,7 +50,7 @@ impl GenesisConfig {
|
||||
) -> Self {
|
||||
GenesisConfig {
|
||||
changes_trie_config,
|
||||
authorities: authorities,
|
||||
authorities,
|
||||
balances: endowed_accounts.into_iter().map(|a| (a, balance)).collect(),
|
||||
heap_pages_override,
|
||||
extra_storage,
|
||||
@@ -56,16 +59,23 @@ impl GenesisConfig {
|
||||
|
||||
pub fn genesis_map(&self) -> Storage {
|
||||
let wasm_runtime = wasm_binary_unwrap().to_vec();
|
||||
let mut map: BTreeMap<Vec<u8>, Vec<u8>> = self.balances.iter()
|
||||
.map(|&(ref account, balance)| (account.to_keyed_vec(b"balance:"), vec![].and(&balance)))
|
||||
let mut map: BTreeMap<Vec<u8>, Vec<u8>> = self
|
||||
.balances
|
||||
.iter()
|
||||
.map(|&(ref account, balance)| {
|
||||
(account.to_keyed_vec(b"balance:"), vec![].and(&balance))
|
||||
})
|
||||
.map(|(k, v)| (blake2_256(&k[..])[..].to_vec(), v.to_vec()))
|
||||
.chain(vec![
|
||||
(well_known_keys::CODE.into(), wasm_runtime),
|
||||
(
|
||||
well_known_keys::HEAP_PAGES.into(),
|
||||
vec![].and(&(self.heap_pages_override.unwrap_or(16 as u64))),
|
||||
),
|
||||
].into_iter())
|
||||
.chain(
|
||||
vec![
|
||||
(well_known_keys::CODE.into(), wasm_runtime),
|
||||
(
|
||||
well_known_keys::HEAP_PAGES.into(),
|
||||
vec![].and(&(self.heap_pages_override.unwrap_or(16 as u64))),
|
||||
),
|
||||
]
|
||||
.into_iter(),
|
||||
)
|
||||
.collect();
|
||||
if let Some(ref changes_trie_config) = self.changes_trie_config {
|
||||
map.insert(well_known_keys::CHANGES_TRIE_CONFIG.to_vec(), changes_trie_config.encode());
|
||||
@@ -75,28 +85,30 @@ impl GenesisConfig {
|
||||
map.extend(self.extra_storage.top.clone().into_iter());
|
||||
|
||||
// Assimilate the system genesis config.
|
||||
let mut storage = Storage { top: map, children_default: self.extra_storage.children_default.clone()};
|
||||
let mut storage =
|
||||
Storage { top: map, children_default: self.extra_storage.children_default.clone() };
|
||||
let mut config = system::GenesisConfig::default();
|
||||
config.authorities = self.authorities.clone();
|
||||
config.assimilate_storage(&mut storage).expect("Adding `system::GensisConfig` to the genesis");
|
||||
config
|
||||
.assimilate_storage(&mut storage)
|
||||
.expect("Adding `system::GensisConfig` to the genesis");
|
||||
|
||||
storage
|
||||
}
|
||||
}
|
||||
|
||||
pub fn insert_genesis_block(
|
||||
storage: &mut Storage,
|
||||
) -> sp_core::hash::H256 {
|
||||
pub fn insert_genesis_block(storage: &mut Storage) -> sp_core::hash::H256 {
|
||||
let child_roots = storage.children_default.iter().map(|(sk, child_content)| {
|
||||
let state_root = <<<crate::Block as BlockT>::Header as HeaderT>::Hashing as HashT>::trie_root(
|
||||
child_content.data.clone().into_iter().collect(),
|
||||
);
|
||||
let state_root =
|
||||
<<<crate::Block as BlockT>::Header as HeaderT>::Hashing as HashT>::trie_root(
|
||||
child_content.data.clone().into_iter().collect(),
|
||||
);
|
||||
(sk.clone(), state_root.encode())
|
||||
});
|
||||
// add child roots to storage
|
||||
storage.top.extend(child_roots);
|
||||
let state_root = <<<crate::Block as BlockT>::Header as HeaderT>::Hashing as HashT>::trie_root(
|
||||
storage.top.clone().into_iter().collect()
|
||||
storage.top.clone().into_iter().collect(),
|
||||
);
|
||||
let block: crate::Block = genesis::construct_genesis_block(state_root);
|
||||
let genesis_hash = block.header.hash();
|
||||
|
||||
@@ -23,45 +23,43 @@
|
||||
pub mod genesismap;
|
||||
pub mod system;
|
||||
|
||||
use sp_std::{prelude::*, marker::PhantomData};
|
||||
use codec::{Encode, Decode, Input, Error};
|
||||
use codec::{Decode, Encode, Error, Input};
|
||||
use sp_std::{marker::PhantomData, prelude::*};
|
||||
|
||||
use sp_application_crypto::{ecdsa, ed25519, sr25519, RuntimeAppPublic};
|
||||
use sp_core::{offchain::KeyTypeId, ChangesTrieConfiguration, OpaqueMetadata, RuntimeDebug};
|
||||
use sp_application_crypto::{ed25519, sr25519, ecdsa, RuntimeAppPublic};
|
||||
use trie_db::{TrieMut, Trie};
|
||||
use sp_trie::{PrefixedMemoryDB, StorageProof};
|
||||
use sp_trie::trie_types::{TrieDB, TrieDBMut};
|
||||
|
||||
use sp_api::{decl_runtime_apis, impl_runtime_apis};
|
||||
use sp_runtime::{
|
||||
create_runtime_str, impl_opaque_keys,
|
||||
ApplyExtrinsicResult, Perbill,
|
||||
transaction_validity::{
|
||||
TransactionValidity, ValidTransaction, TransactionValidityError, InvalidTransaction,
|
||||
TransactionSource,
|
||||
},
|
||||
traits::{
|
||||
BlindCheckable, BlakeTwo256, Block as BlockT, Extrinsic as ExtrinsicT,
|
||||
GetNodeBlockType, GetRuntimeBlockType, Verify, IdentityLookup,
|
||||
},
|
||||
use sp_trie::{
|
||||
trie_types::{TrieDB, TrieDBMut},
|
||||
PrefixedMemoryDB, StorageProof,
|
||||
};
|
||||
use trie_db::{Trie, TrieMut};
|
||||
|
||||
use cfg_if::cfg_if;
|
||||
use frame_support::{parameter_types, traits::KeyOwnerProofSystem, weights::RuntimeDbWeight};
|
||||
use frame_system::limits::{BlockLength, BlockWeights};
|
||||
use sp_api::{decl_runtime_apis, impl_runtime_apis};
|
||||
pub use sp_core::hash::H256;
|
||||
use sp_inherents::{CheckInherentsResult, InherentData};
|
||||
#[cfg(feature = "std")]
|
||||
use sp_runtime::traits::NumberFor;
|
||||
use sp_version::RuntimeVersion;
|
||||
pub use sp_core::hash::H256;
|
||||
use sp_runtime::{
|
||||
create_runtime_str, impl_opaque_keys,
|
||||
traits::{
|
||||
BlakeTwo256, BlindCheckable, Block as BlockT, Extrinsic as ExtrinsicT, GetNodeBlockType,
|
||||
GetRuntimeBlockType, IdentityLookup, Verify,
|
||||
},
|
||||
transaction_validity::{
|
||||
InvalidTransaction, TransactionSource, TransactionValidity, TransactionValidityError,
|
||||
ValidTransaction,
|
||||
},
|
||||
ApplyExtrinsicResult, Perbill,
|
||||
};
|
||||
#[cfg(any(feature = "std", test))]
|
||||
use sp_version::NativeVersion;
|
||||
use frame_support::{
|
||||
parameter_types,
|
||||
traits::KeyOwnerProofSystem,
|
||||
weights::RuntimeDbWeight,
|
||||
};
|
||||
use frame_system::limits::{BlockWeights, BlockLength};
|
||||
use sp_inherents::{CheckInherentsResult, InherentData};
|
||||
use cfg_if::cfg_if;
|
||||
use sp_version::RuntimeVersion;
|
||||
|
||||
// Ensure Babe and Aura use the same crypto to simplify things a bit.
|
||||
pub use sp_consensus_babe::{AuthorityId, Slot, AllowedSlots};
|
||||
pub use sp_consensus_babe::{AllowedSlots, AuthorityId, Slot};
|
||||
|
||||
pub type AuraId = sp_consensus_aura::sr25519::AuthorityId;
|
||||
|
||||
@@ -77,18 +75,19 @@ pub mod wasm_binary_logging_disabled {
|
||||
/// Wasm binary unwrapped. If built with `SKIP_WASM_BUILD`, the function panics.
|
||||
#[cfg(feature = "std")]
|
||||
pub fn wasm_binary_unwrap() -> &'static [u8] {
|
||||
WASM_BINARY.expect("Development wasm binary is not available. Testing is only \
|
||||
supported with the flag disabled.")
|
||||
WASM_BINARY.expect(
|
||||
"Development wasm binary is not available. Testing is only \
|
||||
supported with the flag disabled.",
|
||||
)
|
||||
}
|
||||
|
||||
/// Wasm binary unwrapped. If built with `SKIP_WASM_BUILD`, the function panics.
|
||||
#[cfg(feature = "std")]
|
||||
pub fn wasm_binary_logging_disabled_unwrap() -> &'static [u8] {
|
||||
wasm_binary_logging_disabled::WASM_BINARY
|
||||
.expect(
|
||||
"Development wasm binary is not available. Testing is only supported with the flag \
|
||||
disabled."
|
||||
)
|
||||
wasm_binary_logging_disabled::WASM_BINARY.expect(
|
||||
"Development wasm binary is not available. Testing is only supported with the flag \
|
||||
disabled.",
|
||||
)
|
||||
}
|
||||
|
||||
/// Test runtime version.
|
||||
@@ -110,10 +109,7 @@ fn version() -> RuntimeVersion {
|
||||
/// Native version.
|
||||
#[cfg(any(feature = "std", test))]
|
||||
pub fn native_version() -> NativeVersion {
|
||||
NativeVersion {
|
||||
runtime_version: VERSION,
|
||||
can_author_with: Default::default(),
|
||||
}
|
||||
NativeVersion { runtime_version: VERSION, can_author_with: Default::default() }
|
||||
}
|
||||
|
||||
/// Calls in transactions.
|
||||
@@ -130,12 +126,10 @@ impl Transfer {
|
||||
#[cfg(feature = "std")]
|
||||
pub fn into_signed_tx(self) -> Extrinsic {
|
||||
let signature = sp_keyring::AccountKeyring::from_public(&self.from)
|
||||
.expect("Creates keyring from public key.").sign(&self.encode()).into();
|
||||
Extrinsic::Transfer {
|
||||
transfer: self,
|
||||
signature,
|
||||
exhaust_resources_when_not_first: false,
|
||||
}
|
||||
.expect("Creates keyring from public key.")
|
||||
.sign(&self.encode())
|
||||
.into();
|
||||
Extrinsic::Transfer { transfer: self, signature, exhaust_resources_when_not_first: false }
|
||||
}
|
||||
|
||||
/// Convert into a signed extrinsic, which will only end up included in the block
|
||||
@@ -144,12 +138,10 @@ impl Transfer {
|
||||
#[cfg(feature = "std")]
|
||||
pub fn into_resources_exhausting_tx(self) -> Extrinsic {
|
||||
let signature = sp_keyring::AccountKeyring::from_public(&self.from)
|
||||
.expect("Creates keyring from public key.").sign(&self.encode()).into();
|
||||
Extrinsic::Transfer {
|
||||
transfer: self,
|
||||
signature,
|
||||
exhaust_resources_when_not_first: true,
|
||||
}
|
||||
.expect("Creates keyring from public key.")
|
||||
.sign(&self.encode())
|
||||
.into();
|
||||
Extrinsic::Transfer { transfer: self, signature, exhaust_resources_when_not_first: true }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -174,7 +166,10 @@ parity_util_mem::malloc_size_of_is_0!(Extrinsic); // non-opaque extrinsic does n
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl serde::Serialize for Extrinsic {
|
||||
fn serialize<S>(&self, seq: S) -> Result<S::Ok, S::Error> where S: ::serde::Serializer {
|
||||
fn serialize<S>(&self, seq: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: ::serde::Serializer,
|
||||
{
|
||||
self.using_encoded(|bytes| seq.serialize_bytes(bytes))
|
||||
}
|
||||
}
|
||||
@@ -185,21 +180,22 @@ impl BlindCheckable for Extrinsic {
|
||||
fn check(self) -> Result<Self, TransactionValidityError> {
|
||||
match self {
|
||||
Extrinsic::AuthoritiesChange(new_auth) => Ok(Extrinsic::AuthoritiesChange(new_auth)),
|
||||
Extrinsic::Transfer { transfer, signature, exhaust_resources_when_not_first } => {
|
||||
Extrinsic::Transfer { transfer, signature, exhaust_resources_when_not_first } =>
|
||||
if sp_runtime::verify_encoded_lazy(&signature, &transfer, &transfer.from) {
|
||||
Ok(Extrinsic::Transfer { transfer, signature, exhaust_resources_when_not_first })
|
||||
Ok(Extrinsic::Transfer {
|
||||
transfer,
|
||||
signature,
|
||||
exhaust_resources_when_not_first,
|
||||
})
|
||||
} else {
|
||||
Err(InvalidTransaction::BadProof.into())
|
||||
}
|
||||
},
|
||||
},
|
||||
Extrinsic::IncludeData(v) => Ok(Extrinsic::IncludeData(v)),
|
||||
Extrinsic::StorageChange(key, value) => Ok(Extrinsic::StorageChange(key, value)),
|
||||
Extrinsic::ChangesTrieConfigUpdate(new_config) =>
|
||||
Ok(Extrinsic::ChangesTrieConfigUpdate(new_config)),
|
||||
Extrinsic::OffchainIndexSet(key, value) =>
|
||||
Ok(Extrinsic::OffchainIndexSet(key, value)),
|
||||
Extrinsic::OffchainIndexClear(key) =>
|
||||
Ok(Extrinsic::OffchainIndexClear(key)),
|
||||
Extrinsic::OffchainIndexSet(key, value) => Ok(Extrinsic::OffchainIndexSet(key, value)),
|
||||
Extrinsic::OffchainIndexClear(key) => Ok(Extrinsic::OffchainIndexClear(key)),
|
||||
Extrinsic::Store(data) => Ok(Extrinsic::Store(data)),
|
||||
}
|
||||
}
|
||||
@@ -301,9 +297,7 @@ impl<B: BlockT> codec::EncodeLike for DecodeFails<B> {}
|
||||
impl<B: BlockT> DecodeFails<B> {
|
||||
/// Create a new instance.
|
||||
pub fn new() -> DecodeFails<B> {
|
||||
DecodeFails {
|
||||
_phantom: Default::default(),
|
||||
}
|
||||
DecodeFails { _phantom: Default::default() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -619,7 +613,8 @@ fn code_using_trie() -> u64 {
|
||||
let pairs = [
|
||||
(b"0103000000000000000464".to_vec(), b"0400000000".to_vec()),
|
||||
(b"0103000000000000000469".to_vec(), b"0401000000".to_vec()),
|
||||
].to_vec();
|
||||
]
|
||||
.to_vec();
|
||||
|
||||
let mut mdb = PrefixedMemoryDB::default();
|
||||
let mut root = sp_std::default::Default::default();
|
||||
@@ -627,10 +622,10 @@ fn code_using_trie() -> u64 {
|
||||
let v = &pairs;
|
||||
let mut t = TrieDBMut::<Hashing>::new(&mut mdb, &mut root);
|
||||
for i in 0..v.len() {
|
||||
let key: &[u8]= &v[i].0;
|
||||
let key: &[u8] = &v[i].0;
|
||||
let val: &[u8] = &v[i].1;
|
||||
if !t.insert(key, val).is_ok() {
|
||||
return 101;
|
||||
return 101
|
||||
}
|
||||
}
|
||||
t
|
||||
@@ -645,8 +640,12 @@ fn code_using_trie() -> u64 {
|
||||
}
|
||||
}
|
||||
iter_pairs.len() as u64
|
||||
} else { 102 }
|
||||
} else { 103 }
|
||||
} else {
|
||||
102
|
||||
}
|
||||
} else {
|
||||
103
|
||||
}
|
||||
}
|
||||
|
||||
impl_opaque_keys! {
|
||||
@@ -1206,29 +1205,15 @@ fn test_read_storage() {
|
||||
fn test_read_child_storage() {
|
||||
const STORAGE_KEY: &[u8] = b"unique_id_1";
|
||||
const KEY: &[u8] = b":read_child_storage";
|
||||
sp_io::default_child_storage::set(
|
||||
STORAGE_KEY,
|
||||
KEY,
|
||||
b"test",
|
||||
);
|
||||
sp_io::default_child_storage::set(STORAGE_KEY, KEY, b"test");
|
||||
|
||||
let mut v = [0u8; 4];
|
||||
let r = sp_io::default_child_storage::read(
|
||||
STORAGE_KEY,
|
||||
KEY,
|
||||
&mut v,
|
||||
0,
|
||||
);
|
||||
let r = sp_io::default_child_storage::read(STORAGE_KEY, KEY, &mut v, 0);
|
||||
assert_eq!(r, Some(4));
|
||||
assert_eq!(&v, b"test");
|
||||
|
||||
let mut v = [0u8; 4];
|
||||
let r = sp_io::default_child_storage::read(
|
||||
STORAGE_KEY,
|
||||
KEY,
|
||||
&mut v,
|
||||
8,
|
||||
);
|
||||
let r = sp_io::default_child_storage::read(STORAGE_KEY, KEY, &mut v, 8);
|
||||
assert_eq!(r, Some(0));
|
||||
assert_eq!(&v, &[0, 0, 0, 0]);
|
||||
}
|
||||
@@ -1236,10 +1221,7 @@ fn test_read_child_storage() {
|
||||
fn test_witness(proof: StorageProof, root: crate::Hash) {
|
||||
use sp_externalities::Externalities;
|
||||
let db: sp_trie::MemoryDB<crate::Hashing> = proof.into_memory_db();
|
||||
let backend = sp_state_machine::TrieBackend::<_, crate::Hashing>::new(
|
||||
db,
|
||||
root,
|
||||
);
|
||||
let backend = sp_state_machine::TrieBackend::<_, crate::Hashing>::new(db, root);
|
||||
let mut overlay = sp_state_machine::OverlayedChanges::default();
|
||||
let mut cache = sp_state_machine::StorageTransactionCache::<_, _, BlockNumber>::default();
|
||||
let mut ext = sp_state_machine::Ext::new(
|
||||
@@ -1259,18 +1241,16 @@ fn test_witness(proof: StorageProof, root: crate::Hash) {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use substrate_test_runtime_client::{
|
||||
prelude::*,
|
||||
sp_consensus::BlockOrigin,
|
||||
DefaultTestClientBuilderExt, TestClientBuilder,
|
||||
runtime::TestAPI,
|
||||
};
|
||||
use sp_api::ProvideRuntimeApi;
|
||||
use sp_runtime::generic::BlockId;
|
||||
use sp_core::storage::well_known_keys::HEAP_PAGES;
|
||||
use sp_state_machine::ExecutionStrategy;
|
||||
use codec::Encode;
|
||||
use sc_block_builder::BlockBuilderProvider;
|
||||
use sp_api::ProvideRuntimeApi;
|
||||
use sp_core::storage::well_known_keys::HEAP_PAGES;
|
||||
use sp_runtime::generic::BlockId;
|
||||
use sp_state_machine::ExecutionStrategy;
|
||||
use substrate_test_runtime_client::{
|
||||
prelude::*, runtime::TestAPI, sp_consensus::BlockOrigin, DefaultTestClientBuilderExt,
|
||||
TestClientBuilder,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn heap_pages_is_respected() {
|
||||
@@ -1307,9 +1287,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_storage() {
|
||||
let client = TestClientBuilder::new()
|
||||
.set_execution_strategy(ExecutionStrategy::Both)
|
||||
.build();
|
||||
let client =
|
||||
TestClientBuilder::new().set_execution_strategy(ExecutionStrategy::Both).build();
|
||||
let runtime_api = client.runtime_api();
|
||||
let block_id = BlockId::Number(client.chain_info().best_number);
|
||||
|
||||
@@ -1331,14 +1310,10 @@ mod tests {
|
||||
#[test]
|
||||
fn witness_backend_works() {
|
||||
let (db, root) = witness_backend();
|
||||
let backend = sp_state_machine::TrieBackend::<_, crate::Hashing>::new(
|
||||
db,
|
||||
root,
|
||||
);
|
||||
let backend = sp_state_machine::TrieBackend::<_, crate::Hashing>::new(db, root);
|
||||
let proof = sp_state_machine::prove_read(backend, vec![b"value3"]).unwrap();
|
||||
let client = TestClientBuilder::new()
|
||||
.set_execution_strategy(ExecutionStrategy::Both)
|
||||
.build();
|
||||
let client =
|
||||
TestClientBuilder::new().set_execution_strategy(ExecutionStrategy::Both).build();
|
||||
let runtime_api = client.runtime_api();
|
||||
let block_id = BlockId::Number(client.chain_info().best_number);
|
||||
|
||||
|
||||
@@ -18,25 +18,27 @@
|
||||
//! System manager: Handles all of the top-level stuff; executing block/transaction, setting code
|
||||
//! and depositing logs.
|
||||
|
||||
use sp_std::prelude::*;
|
||||
use sp_io::{
|
||||
storage::root as storage_root, storage::changes_root as storage_changes_root,
|
||||
hashing::blake2_256, trie,
|
||||
};
|
||||
use frame_support::storage;
|
||||
use frame_support::{decl_storage, decl_module};
|
||||
use sp_runtime::{
|
||||
traits::Header as _, generic, ApplyExtrinsicResult,
|
||||
transaction_validity::{
|
||||
TransactionValidity, ValidTransaction, InvalidTransaction, TransactionValidityError,
|
||||
},
|
||||
};
|
||||
use codec::{KeyedVec, Encode, Decode};
|
||||
use frame_system::Config;
|
||||
use crate::{
|
||||
AccountId, BlockNumber, Extrinsic, Transfer, H256 as Hash, Block, Header, Digest, AuthorityId
|
||||
AccountId, AuthorityId, Block, BlockNumber, Digest, Extrinsic, Header, Transfer, H256 as Hash,
|
||||
};
|
||||
use codec::{Decode, Encode, KeyedVec};
|
||||
use frame_support::{decl_module, decl_storage, storage};
|
||||
use frame_system::Config;
|
||||
use sp_core::{storage::well_known_keys, ChangesTrieConfiguration};
|
||||
use sp_io::{
|
||||
hashing::blake2_256,
|
||||
storage::{changes_root as storage_changes_root, root as storage_root},
|
||||
trie,
|
||||
};
|
||||
use sp_runtime::{
|
||||
generic,
|
||||
traits::Header as _,
|
||||
transaction_validity::{
|
||||
InvalidTransaction, TransactionValidity, TransactionValidityError, ValidTransaction,
|
||||
},
|
||||
ApplyExtrinsicResult,
|
||||
};
|
||||
use sp_std::prelude::*;
|
||||
|
||||
const NONCE_OF: &[u8] = b"nonce:";
|
||||
const BALANCE_OF: &[u8] = b"balance:";
|
||||
@@ -159,17 +161,17 @@ impl frame_support::traits::ExecuteBlock<Block> for BlockExecutor {
|
||||
/// This doesn't attempt to validate anything regarding the block.
|
||||
pub fn validate_transaction(utx: Extrinsic) -> TransactionValidity {
|
||||
if check_signature(&utx).is_err() {
|
||||
return InvalidTransaction::BadProof.into();
|
||||
return InvalidTransaction::BadProof.into()
|
||||
}
|
||||
|
||||
let tx = utx.transfer();
|
||||
let nonce_key = tx.from.to_keyed_vec(NONCE_OF);
|
||||
let expected_nonce: u64 = storage::hashed::get_or(&blake2_256, &nonce_key, 0);
|
||||
if tx.nonce < expected_nonce {
|
||||
return InvalidTransaction::Stale.into();
|
||||
return InvalidTransaction::Stale.into()
|
||||
}
|
||||
if tx.nonce > expected_nonce + 64 {
|
||||
return InvalidTransaction::Future.into();
|
||||
return InvalidTransaction::Future.into()
|
||||
}
|
||||
|
||||
let encode = |from: &AccountId, nonce: u64| (from, nonce).encode();
|
||||
@@ -181,20 +183,14 @@ pub fn validate_transaction(utx: Extrinsic) -> TransactionValidity {
|
||||
|
||||
let provides = vec![encode(&tx.from, tx.nonce)];
|
||||
|
||||
Ok(ValidTransaction {
|
||||
priority: tx.amount,
|
||||
requires,
|
||||
provides,
|
||||
longevity: 64,
|
||||
propagate: true,
|
||||
})
|
||||
Ok(ValidTransaction { priority: tx.amount, requires, provides, longevity: 64, propagate: true })
|
||||
}
|
||||
|
||||
/// Execute a transaction outside of the block execution function.
|
||||
/// This doesn't attempt to validate anything regarding the block.
|
||||
pub fn execute_transaction(utx: Extrinsic) -> ApplyExtrinsicResult {
|
||||
let extrinsic_index: u32 = storage::unhashed::get(well_known_keys::EXTRINSIC_INDEX)
|
||||
.unwrap_or_default();
|
||||
let extrinsic_index: u32 =
|
||||
storage::unhashed::get(well_known_keys::EXTRINSIC_INDEX).unwrap_or_default();
|
||||
let result = execute_transaction_backend(&utx, extrinsic_index);
|
||||
ExtrinsicData::insert(extrinsic_index, utx.encode());
|
||||
storage::unhashed::put(well_known_keys::EXTRINSIC_INDEX, &(extrinsic_index + 1));
|
||||
@@ -215,8 +211,8 @@ pub fn finalize_block() -> Header {
|
||||
|
||||
// This MUST come after all changes to storage are done. Otherwise we will fail the
|
||||
// “Storage root does not match that calculated” assertion.
|
||||
let storage_root = Hash::decode(&mut &storage_root()[..])
|
||||
.expect("`storage_root` is a valid hash");
|
||||
let storage_root =
|
||||
Hash::decode(&mut &storage_root()[..]).expect("`storage_root` is a valid hash");
|
||||
let storage_changes_root = storage_changes_root(&parent_hash.encode())
|
||||
.map(|r| Hash::decode(&mut &r[..]).expect("`storage_changes_root` is a valid hash"));
|
||||
|
||||
@@ -231,17 +227,11 @@ pub fn finalize_block() -> Header {
|
||||
|
||||
if let Some(new_config) = new_changes_trie_config {
|
||||
digest.push(generic::DigestItem::ChangesTrieSignal(
|
||||
generic::ChangesTrieSignal::NewConfiguration(new_config)
|
||||
generic::ChangesTrieSignal::NewConfiguration(new_config),
|
||||
));
|
||||
}
|
||||
|
||||
Header {
|
||||
number,
|
||||
extrinsics_root,
|
||||
state_root: storage_root,
|
||||
parent_hash,
|
||||
digest,
|
||||
}
|
||||
Header { number, extrinsics_root, state_root: storage_root, parent_hash, digest }
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
@@ -253,12 +243,11 @@ fn check_signature(utx: &Extrinsic) -> Result<(), TransactionValidityError> {
|
||||
fn execute_transaction_backend(utx: &Extrinsic, extrinsic_index: u32) -> ApplyExtrinsicResult {
|
||||
check_signature(utx)?;
|
||||
match utx {
|
||||
Extrinsic::Transfer { exhaust_resources_when_not_first: true, .. } if extrinsic_index != 0 =>
|
||||
Extrinsic::Transfer { exhaust_resources_when_not_first: true, .. }
|
||||
if extrinsic_index != 0 =>
|
||||
Err(InvalidTransaction::ExhaustsResources.into()),
|
||||
Extrinsic::Transfer { ref transfer, .. } =>
|
||||
execute_transfer_backend(transfer),
|
||||
Extrinsic::AuthoritiesChange(ref new_auth) =>
|
||||
execute_new_authorities_backend(new_auth),
|
||||
Extrinsic::Transfer { ref transfer, .. } => execute_transfer_backend(transfer),
|
||||
Extrinsic::AuthoritiesChange(ref new_auth) => execute_new_authorities_backend(new_auth),
|
||||
Extrinsic::IncludeData(_) => Ok(Ok(())),
|
||||
Extrinsic::StorageChange(key, value) =>
|
||||
execute_storage_change(key, value.as_ref().map(|v| &**v)),
|
||||
@@ -271,9 +260,8 @@ fn execute_transaction_backend(utx: &Extrinsic, extrinsic_index: u32) -> ApplyEx
|
||||
Extrinsic::OffchainIndexClear(key) => {
|
||||
sp_io::offchain_index::clear(&key);
|
||||
Ok(Ok(()))
|
||||
}
|
||||
Extrinsic::Store(data) =>
|
||||
execute_store(data.clone()),
|
||||
},
|
||||
Extrinsic::Store(data) => execute_store(data.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -282,7 +270,7 @@ fn execute_transfer_backend(tx: &Transfer) -> ApplyExtrinsicResult {
|
||||
let nonce_key = tx.from.to_keyed_vec(NONCE_OF);
|
||||
let expected_nonce: u64 = storage::hashed::get_or(&blake2_256, &nonce_key, 0);
|
||||
if !(tx.nonce == expected_nonce) {
|
||||
return Err(InvalidTransaction::Stale.into());
|
||||
return Err(InvalidTransaction::Stale.into())
|
||||
}
|
||||
|
||||
// increment nonce in storage
|
||||
@@ -294,7 +282,7 @@ fn execute_transfer_backend(tx: &Transfer) -> ApplyExtrinsicResult {
|
||||
|
||||
// enact transfer
|
||||
if !(tx.amount <= from_balance) {
|
||||
return Err(InvalidTransaction::Payment.into());
|
||||
return Err(InvalidTransaction::Payment.into())
|
||||
}
|
||||
let to_balance_key = tx.to.to_keyed_vec(BALANCE_OF);
|
||||
let to_balance: u64 = storage::hashed::get_or(&blake2_256, &to_balance_key, 0);
|
||||
@@ -323,12 +311,12 @@ fn execute_storage_change(key: &[u8], value: Option<&[u8]>) -> ApplyExtrinsicRes
|
||||
Ok(Ok(()))
|
||||
}
|
||||
|
||||
fn execute_changes_trie_config_update(new_config: Option<ChangesTrieConfiguration>) -> ApplyExtrinsicResult {
|
||||
fn execute_changes_trie_config_update(
|
||||
new_config: Option<ChangesTrieConfiguration>,
|
||||
) -> ApplyExtrinsicResult {
|
||||
match new_config.clone() {
|
||||
Some(new_config) => storage::unhashed::put_raw(
|
||||
well_known_keys::CHANGES_TRIE_CONFIG,
|
||||
&new_config.encode(),
|
||||
),
|
||||
Some(new_config) =>
|
||||
storage::unhashed::put_raw(well_known_keys::CHANGES_TRIE_CONFIG, &new_config.encode()),
|
||||
None => storage::unhashed::kill(well_known_keys::CHANGES_TRIE_CONFIG),
|
||||
}
|
||||
<NewChangesTrieConfig>::put(new_config);
|
||||
@@ -360,19 +348,18 @@ fn info_expect_equal_hash(given: &Hash, expected: &Hash) {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
use sp_io::TestExternalities;
|
||||
use crate::{wasm_binary_unwrap, Header, Transfer};
|
||||
use sc_executor::{native_executor_instance, NativeExecutor, WasmExecutionMethod};
|
||||
use sp_core::{
|
||||
map,
|
||||
traits::{CodeExecutor, RuntimeCode},
|
||||
NeverNativeValue,
|
||||
};
|
||||
use sp_io::{hashing::twox_128, TestExternalities};
|
||||
use substrate_test_runtime_client::{AccountKeyring, Sr25519Keyring};
|
||||
use crate::{Header, Transfer, wasm_binary_unwrap};
|
||||
use sp_core::{NeverNativeValue, map, traits::{CodeExecutor, RuntimeCode}};
|
||||
use sc_executor::{NativeExecutor, WasmExecutionMethod, native_executor_instance};
|
||||
use sp_io::hashing::twox_128;
|
||||
|
||||
// Declare an instance of the native executor dispatch for the test runtime.
|
||||
native_executor_instance!(
|
||||
NativeDispatch,
|
||||
crate::api::dispatch,
|
||||
crate::native_version
|
||||
);
|
||||
native_executor_instance!(NativeDispatch, crate::api::dispatch, crate::native_version);
|
||||
|
||||
fn executor() -> NativeExecutor<NativeDispatch> {
|
||||
NativeExecutor::new(WasmExecutionMethod::Interpreted, None, 8)
|
||||
@@ -382,7 +369,7 @@ mod tests {
|
||||
let authorities = vec![
|
||||
Sr25519Keyring::Alice.to_raw_public(),
|
||||
Sr25519Keyring::Bob.to_raw_public(),
|
||||
Sr25519Keyring::Charlie.to_raw_public()
|
||||
Sr25519Keyring::Charlie.to_raw_public(),
|
||||
];
|
||||
TestExternalities::new_with_code(
|
||||
wasm_binary_unwrap(),
|
||||
@@ -399,7 +386,10 @@ mod tests {
|
||||
)
|
||||
}
|
||||
|
||||
fn block_import_works<F>(block_executor: F) where F: Fn(Block, &mut TestExternalities) {
|
||||
fn block_import_works<F>(block_executor: F)
|
||||
where
|
||||
F: Fn(Block, &mut TestExternalities),
|
||||
{
|
||||
let h = Header {
|
||||
parent_hash: [69u8; 32].into(),
|
||||
number: 1,
|
||||
@@ -407,10 +397,7 @@ mod tests {
|
||||
extrinsics_root: Default::default(),
|
||||
digest: Default::default(),
|
||||
};
|
||||
let mut b = Block {
|
||||
header: h,
|
||||
extrinsics: vec![],
|
||||
};
|
||||
let mut b = Block { header: h, extrinsics: vec![] };
|
||||
|
||||
new_test_ext().execute_with(|| polish_block(&mut b));
|
||||
|
||||
@@ -419,7 +406,11 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn block_import_works_native() {
|
||||
block_import_works(|b, ext| ext.execute_with(|| { execute_block(b); }));
|
||||
block_import_works(|b, ext| {
|
||||
ext.execute_with(|| {
|
||||
execute_block(b);
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -432,19 +423,23 @@ mod tests {
|
||||
heap_pages: None,
|
||||
};
|
||||
|
||||
executor().call::<NeverNativeValue, fn() -> _>(
|
||||
&mut ext,
|
||||
&runtime_code,
|
||||
"Core_execute_block",
|
||||
&b.encode(),
|
||||
false,
|
||||
None,
|
||||
).0.unwrap();
|
||||
executor()
|
||||
.call::<NeverNativeValue, fn() -> _>(
|
||||
&mut ext,
|
||||
&runtime_code,
|
||||
"Core_execute_block",
|
||||
&b.encode(),
|
||||
false,
|
||||
None,
|
||||
)
|
||||
.0
|
||||
.unwrap();
|
||||
})
|
||||
}
|
||||
|
||||
fn block_import_with_transaction_works<F>(block_executor: F)
|
||||
where F: Fn(Block, &mut TestExternalities)
|
||||
where
|
||||
F: Fn(Block, &mut TestExternalities),
|
||||
{
|
||||
let mut b1 = Block {
|
||||
header: Header {
|
||||
@@ -454,14 +449,13 @@ mod tests {
|
||||
extrinsics_root: Default::default(),
|
||||
digest: Default::default(),
|
||||
},
|
||||
extrinsics: vec![
|
||||
Transfer {
|
||||
from: AccountKeyring::Alice.into(),
|
||||
to: AccountKeyring::Bob.into(),
|
||||
amount: 69,
|
||||
nonce: 0,
|
||||
}.into_signed_tx()
|
||||
],
|
||||
extrinsics: vec![Transfer {
|
||||
from: AccountKeyring::Alice.into(),
|
||||
to: AccountKeyring::Bob.into(),
|
||||
amount: 69,
|
||||
nonce: 0,
|
||||
}
|
||||
.into_signed_tx()],
|
||||
};
|
||||
|
||||
let mut dummy_ext = new_test_ext();
|
||||
@@ -481,13 +475,15 @@ mod tests {
|
||||
to: AccountKeyring::Alice.into(),
|
||||
amount: 27,
|
||||
nonce: 0,
|
||||
}.into_signed_tx(),
|
||||
}
|
||||
.into_signed_tx(),
|
||||
Transfer {
|
||||
from: AccountKeyring::Alice.into(),
|
||||
to: AccountKeyring::Charlie.into(),
|
||||
amount: 69,
|
||||
nonce: 1,
|
||||
}.into_signed_tx(),
|
||||
}
|
||||
.into_signed_tx(),
|
||||
],
|
||||
};
|
||||
|
||||
@@ -519,7 +515,11 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn block_import_with_transaction_works_native() {
|
||||
block_import_with_transaction_works(|b, ext| ext.execute_with(|| { execute_block(b); }));
|
||||
block_import_with_transaction_works(|b, ext| {
|
||||
ext.execute_with(|| {
|
||||
execute_block(b);
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -532,14 +532,17 @@ mod tests {
|
||||
heap_pages: None,
|
||||
};
|
||||
|
||||
executor().call::<NeverNativeValue, fn() -> _>(
|
||||
&mut ext,
|
||||
&runtime_code,
|
||||
"Core_execute_block",
|
||||
&b.encode(),
|
||||
false,
|
||||
None,
|
||||
).0.unwrap();
|
||||
executor()
|
||||
.call::<NeverNativeValue, fn() -> _>(
|
||||
&mut ext,
|
||||
&runtime_code,
|
||||
"Core_execute_block",
|
||||
&b.encode(),
|
||||
false,
|
||||
None,
|
||||
)
|
||||
.0
|
||||
.unwrap();
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user