Make use of NLL in client crate (#1436)

* fix: set edition to 2018 in Cargo.toml.

* fix: refactor function to make use of NLL.

* fix: result of applying 'cargo fix --edition' command.

* fix: removes extern crate

* fix: remove module uses from lib.rs

* fix: tests imports
This commit is contained in:
Marcio Diaz
2019-01-16 11:49:26 +01:00
committed by Bastian Köcher
parent f0b4c87eb5
commit 9151349b2d
21 changed files with 130 additions and 175 deletions
+2 -2
View File
@@ -16,7 +16,7 @@
//! Substrate Client data backend
use error;
use crate::error;
use runtime_primitives::{generic::BlockId, Justification, StorageMap, ChildrenStorageMap};
use runtime_primitives::traits::{AuthorityIdFor, Block as BlockT, NumberFor};
use state_machine::backend::Backend as StateBackend;
@@ -109,7 +109,7 @@ pub trait Backend<Block, H>: AuxStore + Send + Sync where
/// Associated block insertion operation type.
type BlockImportOperation: BlockImportOperation<Block, H>;
/// Associated blockchain backend type.
type Blockchain: ::blockchain::Backend<Block>;
type Blockchain: crate::blockchain::Backend<Block>;
/// Associated state backend type.
type State: StateBackend<H>;
/// Changes trie storage.
@@ -18,6 +18,7 @@
use runtime_primitives::{traits::Block as BlockT, ApplyResult, CheckInherentError};
use rstd::vec::Vec;
use sr_api_macros::decl_runtime_apis;
decl_runtime_apis! {
/// The `BlockBuilder` api trait that provides required functions for building a block for a runtime.
@@ -18,16 +18,17 @@ use super::api::BlockBuilder as BlockBuilderApi;
use std::vec::Vec;
use std::marker::PhantomData;
use codec::Encode;
use blockchain::HeaderBackend;
use crate::blockchain::HeaderBackend;
use runtime_primitives::traits::{
Header as HeaderT, Hash, Block as BlockT, One, HashFor, ProvideRuntimeApi, ApiRef
};
use primitives::H256;
use runtime_primitives::generic::BlockId;
use runtime_api::Core;
use error;
use crate::runtime_api::Core;
use crate::error;
use runtime_primitives::ApplyOutcome;
/// Utility for building new (valid) blocks from a stream of extrinsics.
pub struct BlockBuilder<'a, Block, InherentData, A: ProvideRuntimeApi> where Block: BlockT {
header: <Block as BlockT>::Header,
@@ -82,27 +83,22 @@ where
/// can be validly executed (by executing it); if it is invalid, it'll be returned along with
/// the error. Otherwise, it will return a mutable reference to self (in order to chain).
pub fn push(&mut self, xt: <Block as BlockT>::Extrinsic) -> error::Result<()> {
fn impl_push<'a, T, Block: BlockT, InherentData>(
api: &mut ApiRef<'a, T>,
block_id: &BlockId<Block>,
xt: Block::Extrinsic,
extrinsics: &mut Vec<Block::Extrinsic>
) -> error::Result<()> where T: BlockBuilderApi<Block, InherentData> {
api.map_api_result(|api| {
match api.apply_extrinsic(block_id, &xt)? {
Ok(ApplyOutcome::Success) | Ok(ApplyOutcome::Fail) => {
extrinsics.push(xt);
Ok(())
}
Err(e) => {
Err(error::ErrorKind::ApplyExtrinsicFailed(e).into())
}
use crate::runtime_api::ApiExt;
let block_id = &self.block_id;
let extrinsics = &mut self.extrinsics;
self.api.map_api_result(|api| {
match api.apply_extrinsic(block_id, &xt)? {
Ok(ApplyOutcome::Success) | Ok(ApplyOutcome::Fail) => {
extrinsics.push(xt);
Ok(())
}
})
}
//FIXME: Please NLL, help me!
impl_push(&mut self.api, &self.block_id, xt, &mut self.extrinsics)
Err(e) => {
Err(error::ErrorKind::ApplyExtrinsicFailed(e).into())
}
}
})
}
/// Consume the builder to return a valid `Block` containing all pushed extrinsics.
+1 -1
View File
@@ -20,7 +20,7 @@ use runtime_primitives::traits::{AuthorityIdFor, Block as BlockT, Header as Head
use runtime_primitives::generic::BlockId;
use runtime_primitives::Justification;
use error::{ErrorKind, Result};
use crate::error::{ErrorKind, Result};
/// Blockchain database header backend. Does not perform any validation.
pub trait HeaderBackend<Block: BlockT>: Send + Sync {
+2 -2
View File
@@ -26,8 +26,8 @@ use hash_db::Hasher;
use trie::MemoryDB;
use primitives::{H256, Blake2Hasher};
use backend;
use error;
use crate::backend;
use crate::error;
/// Method call executor.
pub trait CallExecutor<B, H>
+1 -1
View File
@@ -35,7 +35,7 @@ use state_machine::backend::InMemory as InMemoryState;
use state_machine::{MemoryDB, TrieBackend, Backend as StateBackend,
prove_read_on_trie_backend, read_proof_check, read_proof_check_on_proving_backend};
use error::{Error as ClientError, ErrorKind as ClientErrorKind, Result as ClientResult};
use crate::error::{Error as ClientError, ErrorKind as ClientErrorKind, Result as ClientResult};
/// The size of each CHT. This value is passed to every CHT-related function from
/// production code. Other values are passed from tests.
+27 -17
View File
@@ -17,7 +17,7 @@
//! Substrate Client
use std::{marker::PhantomData, collections::{HashSet, BTreeMap}, sync::Arc};
use error::Error;
use crate::error::Error;
use futures::sync::mpsc;
use parking_lot::{Mutex, RwLock};
use runtime_primitives::{
@@ -30,7 +30,7 @@ use runtime_primitives::traits::{
ApiRef, ProvideRuntimeApi, Digest, DigestItem, AuthorityIdFor
};
use runtime_primitives::BuildStorage;
use runtime_api::{Core as CoreAPI, CallRuntimeAt, ConstructRuntimeApi};
use crate::runtime_api::{Core as CoreAPI, CallRuntimeAt, ConstructRuntimeApi};
use primitives::{Blake2Hasher, H256, ChangesTrieConfiguration, convert_hash};
use primitives::storage::{StorageKey, StorageData};
use primitives::storage::well_known_keys;
@@ -42,13 +42,23 @@ use state_machine::{
key_changes, key_changes_proof, OverlayedChanges
};
use backend::{self, BlockImportOperation};
use blockchain::{self, Info as ChainInfo, Backend as ChainBackend, HeaderBackend as ChainHeaderBackend};
use call_executor::{CallExecutor, LocalCallExecutor};
use crate::backend::{self, BlockImportOperation};
use crate::blockchain::{self, Info as ChainInfo, Backend as ChainBackend, HeaderBackend as ChainHeaderBackend};
use crate::call_executor::{CallExecutor, LocalCallExecutor};
use executor::{RuntimeVersion, RuntimeInfo};
use notifications::{StorageNotifications, StorageEventStream};
use light::{call_executor::prove_execution, fetcher::ChangesProof};
use {cht, error, in_mem, block_builder::{self, api::BlockBuilder as BlockBuilderAPI}, genesis, consensus};
use crate::notifications::{StorageNotifications, StorageEventStream};
use crate::light::{call_executor::prove_execution, fetcher::ChangesProof};
use crate::cht;
use crate::error;
use crate::in_mem;
use crate::block_builder::{self, api::BlockBuilder as BlockBuilderAPI};
use crate::genesis;
use consensus;
use substrate_telemetry::telemetry;
use slog::slog_info;
use log::{info, trace, warn};
use error_chain::bail;
/// Type that implements `futures::Stream` of block import events.
pub type ImportNotifications<Block> = mpsc::UnboundedReceiver<BlockImportNotification<Block>>;
@@ -236,7 +246,7 @@ impl<B, E, Block, RA> Client<B, E, Block, RA> where
genesis_block.deconstruct().0,
Some(vec![]),
None,
::backend::NewBlockState::Final
crate::backend::NewBlockState::Final
)?;
backend.commit_operation(op)?;
}
@@ -581,7 +591,7 @@ impl<B, E, Block, RA> Client<B, E, Block, RA> where
let (storage_update, changes_update, storage_changes) = match transaction.state()? {
Some(transaction_state) => {
let mut overlay = Default::default();
let mut r = self.executor.call_at_state(
let r = self.executor.call_at_state(
transaction_state,
&mut overlay,
"Core_execute_block",
@@ -618,11 +628,11 @@ impl<B, E, Block, RA> Client<B, E, Block, RA> where
ForkChoiceStrategy::Custom(v) => v,
};
let leaf_state = if finalized {
::backend::NewBlockState::Final
crate::backend::NewBlockState::Final
} else if is_new_best {
::backend::NewBlockState::Best
crate::backend::NewBlockState::Best
} else {
::backend::NewBlockState::Normal
crate::backend::NewBlockState::Normal
};
trace!("Imported {}, (#{}), best={}, origin={:?}", hash, import_headers.post().number(), is_new_best, origin);
@@ -695,7 +705,7 @@ impl<B, E, Block, RA> Client<B, E, Block, RA> where
let last_finalized = self.backend.blockchain().last_finalized()?;
if block == last_finalized { return Ok(()) }
let route_from_finalized = ::blockchain::tree_route(
let route_from_finalized = crate::blockchain::tree_route(
self.backend.blockchain(),
BlockId::Hash(last_finalized),
BlockId::Hash(block),
@@ -708,7 +718,7 @@ impl<B, E, Block, RA> Client<B, E, Block, RA> where
bail!(error::ErrorKind::NotInFinalizedChain);
}
let route_from_best = ::blockchain::tree_route(
let route_from_best = crate::blockchain::tree_route(
self.backend.blockchain(),
BlockId::Hash(best_block),
BlockId::Hash(block),
@@ -1198,11 +1208,11 @@ impl<B, E, Block, RA> backend::AuxStore for Client<B, E, Block, RA>
I: IntoIterator<Item=&'a(&'c [u8], &'c [u8])>,
D: IntoIterator<Item=&'a &'b [u8]>,
>(&self, insert: I, delete: D) -> error::Result<()> {
::backend::AuxStore::insert_aux(&*self.backend, insert, delete)
crate::backend::AuxStore::insert_aux(&*self.backend, insert, delete)
}
/// Query auxiliary data from key-value store.
fn get_aux(&self, key: &[u8]) -> error::Result<Option<Vec<u8>>> {
::backend::AuxStore::get_aux(&*self.backend, key)
crate::backend::AuxStore::get_aux(&*self.backend, key)
}
}
#[cfg(test)]
+1
View File
@@ -22,6 +22,7 @@ use std;
use state_machine;
use runtime_primitives::ApplyError;
use consensus;
use error_chain::*;
error_chain! {
links {
+3 -3
View File
@@ -42,18 +42,18 @@ mod tests {
use super::*;
use codec::{Encode, Decode, Joiner};
use keyring::Keyring;
use executor::NativeExecutionDispatch;
use executor::{NativeExecutionDispatch, native_executor_instance};
use state_machine::{execute, OverlayedChanges, ExecutionStrategy, InMemoryChangesTrieStorage};
use state_machine::backend::InMemory;
use test_client;
use test_client::runtime::genesismap::{GenesisConfig, additional_storage_with_genesis};
use test_client::runtime::{Hash, Transfer, Block, BlockNumber, Header, Digest, Extrinsic};
use runtime_primitives::traits::BlakeTwo256;
use primitives::{Blake2Hasher, ed25519::{Public, Pair}};
use hex::*;
native_executor_instance!(Executor, test_client::runtime::api::dispatch, test_client::runtime::native_version, include_bytes!("../../test-runtime/wasm/target/wasm32-unknown-unknown/release/substrate_test_runtime.compact.wasm"));
fn executor() -> ::executor::NativeExecutor<Executor> {
fn executor() -> executor::NativeExecutor<Executor> {
NativeExecutionDispatch::new()
}
+7 -7
View File
@@ -19,20 +19,20 @@
use std::collections::HashMap;
use std::sync::Arc;
use parking_lot::RwLock;
use error;
use backend::{self, NewBlockState};
use light;
use crate::error;
use crate::backend::{self, NewBlockState};
use crate::light;
use primitives::storage::well_known_keys;
use runtime_primitives::generic::BlockId;
use runtime_primitives::traits::{Block as BlockT, Header as HeaderT, Zero,
NumberFor, As, Digest, DigestItem, AuthorityIdFor};
use runtime_primitives::{Justification, StorageMap, ChildrenStorageMap};
use blockchain::{self, BlockStatus, HeaderBackend};
use crate::blockchain::{self, BlockStatus, HeaderBackend};
use state_machine::backend::{Backend as StateBackend, InMemory, Consolidate};
use state_machine::InMemoryChangesTrieStorage;
use hash_db::Hasher;
use heapsize::HeapSizeOf;
use leaves::LeafSet;
use crate::leaves::LeafSet;
use trie::MemoryDB;
struct PendingBlock<B: BlockT> {
@@ -166,7 +166,7 @@ impl<Block: BlockT> Blockchain<Block> {
justification: Option<Justification>,
body: Option<Vec<<Block as BlockT>::Extrinsic>>,
new_state: NewBlockState,
) -> ::error::Result<()> {
) -> crate::error::Result<()> {
let number = header.number().clone();
let best_tree_route = match new_state.is_best() {
false => None,
@@ -175,7 +175,7 @@ impl<Block: BlockT> Blockchain<Block> {
if &best_hash == header.parent_hash() {
None
} else {
let route = ::blockchain::tree_route(
let route = crate::blockchain::tree_route(
self,
BlockId::Hash(best_hash),
BlockId::Hash(*header.parent_hash()),
+1 -1
View File
@@ -19,7 +19,7 @@ use std::cmp::{Ord, Ordering};
use kvdb::{KeyValueDB, DBTransaction};
use runtime_primitives::traits::SimpleArithmetic;
use codec::{Encode, Decode};
use error;
use crate::error;
/// helper wrapper type to keep a list of block hashes ordered
/// by `number` descending in a `BTreeSet` which allows faster and simpler
+5 -58
View File
@@ -20,59 +20,6 @@
#![warn(missing_docs)]
#![recursion_limit="128"]
#[cfg(feature = "std")]
extern crate substrate_trie as trie;
extern crate parity_codec as codec;
extern crate substrate_primitives as primitives;
extern crate sr_primitives as runtime_primitives;
#[cfg(feature = "std")]
extern crate substrate_state_machine as state_machine;
#[cfg(feature = "std")]
extern crate substrate_consensus_common as consensus;
extern crate sr_version as runtime_version;
extern crate sr_std as rstd;
#[macro_use]
extern crate sr_api_macros;
#[cfg(test)]
extern crate substrate_keyring as keyring;
#[cfg(test)]
extern crate substrate_test_client as test_client;
#[cfg(feature = "std")]
#[macro_use]
extern crate substrate_telemetry;
#[cfg(feature = "std")]
#[macro_use]
extern crate slog; // needed until we can reexport `slog_info` from `substrate_telemetry`
#[cfg(feature = "std")]
extern crate fnv;
#[cfg(feature = "std")]
extern crate futures;
#[cfg(feature = "std")]
extern crate parking_lot;
#[cfg(feature = "std")]
extern crate hash_db;
#[cfg(feature = "std")]
extern crate heapsize;
#[cfg(feature = "std")]
extern crate kvdb;
#[cfg(feature = "std")]
#[macro_use]
extern crate error_chain;
#[cfg(feature = "std")]
#[macro_use]
extern crate log;
#[cfg(feature = "std")]
#[cfg_attr(test, macro_use)]
extern crate substrate_executor as executor;
#[cfg(test)]
#[macro_use]
extern crate hex_literal;
#[cfg(feature = "std")]
#[cfg(test)]
extern crate kvdb_memorydb;
#[macro_use]
pub mod runtime_api;
#[cfg(feature = "std")]
@@ -100,22 +47,22 @@ mod client;
mod notifications;
#[cfg(feature = "std")]
pub use blockchain::Info as ChainInfo;
pub use crate::blockchain::Info as ChainInfo;
#[cfg(feature = "std")]
pub use call_executor::{CallExecutor, LocalCallExecutor};
pub use crate::call_executor::{CallExecutor, LocalCallExecutor};
#[cfg(feature = "std")]
pub use client::{
pub use crate::client::{
new_with_backend,
new_in_mem,
BlockBody, BlockStatus, ImportNotifications, FinalityNotifications, BlockchainEvents,
BlockImportNotification, Client, ClientInfo, ChainHead,
};
#[cfg(feature = "std")]
pub use notifications::{StorageEventStream, StorageChangeSet};
pub use crate::notifications::{StorageEventStream, StorageChangeSet};
#[cfg(feature = "std")]
pub use state_machine::ExecutionStrategy;
#[cfg(feature = "std")]
pub use leaves::LeafSet;
pub use crate::leaves::LeafSet;
#[doc(inline)]
pub use sr_api_macros::{decl_runtime_apis, impl_runtime_apis};
+6 -6
View File
@@ -25,12 +25,12 @@ use runtime_primitives::{generic::BlockId, Justification, StorageMap, ChildrenSt
use state_machine::{Backend as StateBackend, InMemoryChangesTrieStorage, TrieBackend};
use runtime_primitives::traits::{Block as BlockT, NumberFor, AuthorityIdFor};
use in_mem;
use backend::{AuxStore, Backend as ClientBackend, BlockImportOperation, RemoteBackend, NewBlockState};
use blockchain::HeaderBackend as BlockchainHeaderBackend;
use error::{Error as ClientError, ErrorKind as ClientErrorKind, Result as ClientResult};
use light::blockchain::{Blockchain, Storage as BlockchainStorage};
use light::fetcher::{Fetcher, RemoteReadRequest};
use crate::in_mem;
use crate::backend::{AuxStore, Backend as ClientBackend, BlockImportOperation, RemoteBackend, NewBlockState};
use crate::blockchain::HeaderBackend as BlockchainHeaderBackend;
use crate::error::{Error as ClientError, ErrorKind as ClientErrorKind, Result as ClientResult};
use crate::light::blockchain::{Blockchain, Storage as BlockchainStorage};
use crate::light::fetcher::{Fetcher, RemoteReadRequest};
use hash_db::Hasher;
use trie::MemoryDB;
use heapsize::HeapSizeOf;
@@ -24,12 +24,12 @@ use parking_lot::Mutex;
use runtime_primitives::{Justification, generic::BlockId};
use runtime_primitives::traits::{Block as BlockT, Header as HeaderT, NumberFor, Zero, AuthorityIdFor};
use backend::{AuxStore, NewBlockState};
use blockchain::{Backend as BlockchainBackend, BlockStatus, Cache as BlockchainCache,
use crate::backend::{AuxStore, NewBlockState};
use crate::blockchain::{Backend as BlockchainBackend, BlockStatus, Cache as BlockchainCache,
HeaderBackend as BlockchainHeaderBackend, Info as BlockchainInfo};
use cht;
use error::{ErrorKind as ClientErrorKind, Result as ClientResult};
use light::fetcher::{Fetcher, RemoteHeaderRequest};
use crate::cht;
use crate::error::{ErrorKind as ClientErrorKind, Result as ClientResult};
use crate::light::fetcher::{Fetcher, RemoteHeaderRequest};
/// Light client blockchain storage.
pub trait Storage<Block: BlockT>: AuxStore + BlockchainHeaderBackend<Block> {
@@ -166,8 +166,8 @@ impl<S, F, Block> BlockchainBackend<Block> for Blockchain<S, F> where Block: Blo
pub mod tests {
use std::collections::HashMap;
use test_client::runtime::{Hash, Block, Header};
use blockchain::Info;
use light::fetcher::tests::OkCallFetcher;
use crate::blockchain::Info;
use crate::light::fetcher::tests::OkCallFetcher;
use super::*;
pub type DummyBlockchain = Blockchain<DummyStorage, OkCallFetcher>;
@@ -22,7 +22,7 @@ use std::marker::PhantomData;
use std::sync::Arc;
use futures::{IntoFuture, Future};
use codec::Encode;
use codec::{Encode, Decode};
use primitives::{H256, Blake2Hasher, convert_hash};
use runtime_primitives::generic::BlockId;
use runtime_primitives::traits::{As, Block as BlockT, Header as HeaderT};
@@ -30,12 +30,11 @@ use state_machine::{self, Backend as StateBackend, CodeExecutor, OverlayedChange
create_proof_check_backend, execution_proof_check_on_trie_backend, ExecutionManager};
use hash_db::Hasher;
use blockchain::Backend as ChainBackend;
use call_executor::CallExecutor;
use error::{Error as ClientError, ErrorKind as ClientErrorKind, Result as ClientResult};
use light::fetcher::{Fetcher, RemoteCallRequest};
use crate::blockchain::Backend as ChainBackend;
use crate::call_executor::CallExecutor;
use crate::error::{Error as ClientError, ErrorKind as ClientErrorKind, Result as ClientResult};
use crate::light::fetcher::{Fetcher, RemoteCallRequest};
use executor::{RuntimeVersion, NativeVersion};
use codec::Decode;
use heapsize::HeapSizeOf;
use trie::MemoryDB;
+10 -10
View File
@@ -28,10 +28,10 @@ use runtime_primitives::traits::{As, Block as BlockT, Header as HeaderT, NumberF
use state_machine::{CodeExecutor, ChangesTrieRootsStorage, ChangesTrieAnchorBlockId,
TrieBackend, read_proof_check, key_changes_proof_check, create_proof_check_backend_storage};
use cht;
use error::{Error as ClientError, ErrorKind as ClientErrorKind, Result as ClientResult};
use light::blockchain::{Blockchain, Storage as BlockchainStorage};
use light::call_executor::check_execution_proof;
use crate::cht;
use crate::error::{Error as ClientError, ErrorKind as ClientErrorKind, Result as ClientResult};
use crate::light::blockchain::{Blockchain, Storage as BlockchainStorage};
use crate::light::call_executor::check_execution_proof;
/// Remote call request.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
@@ -391,17 +391,17 @@ pub mod tests {
use futures::future::{ok, err, FutureResult};
use parking_lot::Mutex;
use keyring::Keyring;
use client::tests::prepare_client_with_key_changes;
use crate::client::tests::prepare_client_with_key_changes;
use executor::{self, NativeExecutionDispatch};
use error::Error as ClientError;
use crate::error::Error as ClientError;
use test_client::{self, TestClient, blockchain::HeaderBackend};
use test_client::runtime::{self, Hash, Block, Header};
use consensus::BlockOrigin;
use in_mem::{Blockchain as InMemoryBlockchain};
use light::fetcher::{Fetcher, FetchChecker, LightDataChecker,
use crate::in_mem::{Blockchain as InMemoryBlockchain};
use crate::light::fetcher::{Fetcher, FetchChecker, LightDataChecker,
RemoteCallRequest, RemoteHeaderRequest};
use light::blockchain::tests::{DummyStorage, DummyBlockchain};
use crate::light::blockchain::tests::{DummyStorage, DummyBlockchain};
use primitives::{twox_128, Blake2Hasher};
use primitives::storage::well_known_keys;
use runtime_primitives::generic::BlockId;
@@ -454,7 +454,7 @@ pub mod tests {
remote_block_header.clone(),
None,
None,
::backend::NewBlockState::Final,
crate::backend::NewBlockState::Final,
).unwrap();
let local_executor = test_client::LocalExecutor::new();
let local_checker = LightDataChecker::new(Arc::new(DummyBlockchain::new(DummyStorage::new())), local_executor);
+6 -6
View File
@@ -28,12 +28,12 @@ use runtime_primitives::BuildStorage;
use runtime_primitives::traits::Block as BlockT;
use state_machine::{CodeExecutor, ExecutionStrategy};
use client::Client;
use error::Result as ClientResult;
use light::backend::Backend;
use light::blockchain::{Blockchain, Storage as BlockchainStorage};
use light::call_executor::RemoteCallExecutor;
use light::fetcher::{Fetcher, LightDataChecker};
use crate::client::Client;
use crate::error::Result as ClientResult;
use crate::light::backend::Backend;
use crate::light::blockchain::{Blockchain, Storage as BlockchainStorage};
use crate::light::call_executor::RemoteCallExecutor;
use crate::light::fetcher::{Fetcher, LightDataChecker};
use hash_db::Hasher;
/// Create an instance of light client blockchain backend.
+2 -2
View File
@@ -32,10 +32,10 @@ pub use rstd::{slice, mem};
use rstd::result;
pub use codec::{Encode, Decode};
#[cfg(feature = "std")]
use error;
use crate::error;
use rstd::vec::Vec;
use primitives::OpaqueMetadata;
use sr_api_macros::decl_runtime_apis;
/// Something that can be constructed to a runtime api.
#[cfg(feature = "std")]