[big refactor] Remove crate aliasing. (#4395)

* Rename: Phase 1.

* Unify codec.

* Fixing: Phase 2

* Fixing: Phase 3.

* Fixing: Phase 4.

* Fixing: Phase 5.

* Fixing: Phase 6.

* Fixing: Phase 7.

* Fixing: Phase 8. Tests

* Fixing: Phase 9. Tests!!!

* Fixing: Phase 10. Moar tests!

* Finally done!

* More fixes.

* Rename primitives:: to sp_core::

* Apply renames in finality-grandpa.

* Fix benches.

* Fix benches 2.

* Revert node-template.

* Fix frame-system in our modules.
This commit is contained in:
Tomasz Drwięga
2019-12-16 13:36:49 +01:00
committed by Gavin Wood
parent f14d98a439
commit 8778ca7dc8
485 changed files with 4023 additions and 4005 deletions
+13 -13
View File
@@ -5,36 +5,36 @@ authors = ["Parity Technologies <admin@parity.io>"]
edition = "2018"
[dependencies]
block-builder = { package = "sc-block-builder", path = "block-builder" }
client-api = { package = "sc-client-api", path = "api" }
sc-block-builder = { path = "block-builder" }
sc-client-api = { path = "api" }
codec = { package = "parity-scale-codec", version = "1.0.0", features = ["derive"] }
consensus = { package = "sp-consensus", path = "../primitives/consensus/common" }
sp-consensus = { path = "../primitives/consensus/common" }
derive_more = { version = "0.99.2" }
executor = { package = "sc-executor", path = "executor" }
externalities = { package = "sp-externalities", path = "../primitives/externalities" }
sc-executor = { path = "executor" }
sp-externalities = { path = "../primitives/externalities" }
fnv = { version = "1.0.6" }
futures = { version = "0.3.1", features = ["compat"] }
hash-db = { version = "0.15.2" }
hex-literal = { version = "0.2.1" }
inherents = { package = "sp-inherents", path = "../primitives/inherents" }
keyring = { package = "sp-keyring", path = "../primitives/keyring" }
sp-inherents = { path = "../primitives/inherents" }
sp-keyring = { path = "../primitives/keyring" }
kvdb = "0.1.1"
log = { version = "0.4.8" }
parking_lot = { version = "0.9.0" }
primitives = { package = "sp-core", path = "../primitives/core" }
sp-core = { path = "../primitives/core" }
sp-std = { path = "../primitives/std" }
runtime-version = { package = "sp-version", path = "../primitives/version" }
sp-version = { path = "../primitives/version" }
sp-api = { path = "../primitives/api" }
sp-runtime = { path = "../primitives/runtime" }
sp-blockchain = { path = "../primitives/blockchain" }
state-machine = { package = "sp-state-machine", path = "../primitives/state-machine" }
sp-state-machine = { path = "../primitives/state-machine" }
sc-telemetry = { path = "telemetry" }
trie = { package = "sp-trie", path = "../primitives/trie" }
sp-trie = { path = "../primitives/trie" }
tracing = "0.1.10"
[dev-dependencies]
env_logger = "0.7.0"
tempfile = "3.1.0"
test-client = { package = "substrate-test-runtime-client", path = "../test-utils/runtime/client" }
substrate-test-runtime-client = { path = "../test-utils/runtime/client" }
kvdb-memorydb = "0.1.2"
panic-handler = { package = "sp-panic-handler", path = "../primitives/panic-handler" }
sp-panic-handler = { path = "../primitives/panic-handler" }
+11 -11
View File
@@ -6,29 +6,29 @@ edition = "2018"
[dependencies]
codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false, features = ["derive"] }
consensus = { package = "sp-consensus", path = "../../primitives/consensus/common" }
sp-consensus = { path = "../../primitives/consensus/common" }
derive_more = { version = "0.99.2" }
executor = { package = "sc-executor", path = "../executor" }
externalities = { package = "sp-externalities", path = "../../primitives/externalities" }
sc-executor = { path = "../executor" }
sp-externalities = { path = "../../primitives/externalities" }
fnv = { version = "1.0.6" }
futures = { version = "0.3.1" }
hash-db = { version = "0.15.2", default-features = false }
sp-blockchain = { path = "../../primitives/blockchain" }
hex-literal = { version = "0.2.1" }
inherents = { package = "sp-inherents", path = "../../primitives/inherents", default-features = false }
keyring = { package = "sp-keyring", path = "../../primitives/keyring" }
sp-inherents = { path = "../../primitives/inherents", default-features = false }
sp-keyring = { path = "../../primitives/keyring" }
kvdb = "0.1.1"
log = { version = "0.4.8" }
parking_lot = { version = "0.9.0" }
primitives = { package = "sp-core", path = "../../primitives/core", default-features = false }
sp-core = { path = "../../primitives/core", default-features = false }
sp-std = { path = "../../primitives/std", default-features = false }
runtime-version = { package = "sp-version", path = "../../primitives/version", default-features = false }
sp-version = { path = "../../primitives/version", default-features = false }
sp-api = { path = "../../primitives/api" }
sp-runtime = { path = "../../primitives/runtime", default-features = false }
state-machine = { package = "sp-state-machine", path = "../../primitives/state-machine" }
sp-state-machine = { path = "../../primitives/state-machine" }
sc-telemetry = { path = "../telemetry" }
trie = { package = "sp-trie", path = "../../primitives/trie" }
txpool-api = { package = "sp-transaction-pool", path = "../../primitives/transaction-pool" }
sp-trie = { path = "../../primitives/trie" }
sp-transaction-pool = { path = "../../primitives/transaction-pool" }
[dev-dependencies]
test-primitives = { package = "sp-test-primitives", path = "../../primitives/test-primitives" }
sp-test-primitives = { path = "../../primitives/test-primitives" }
+5 -5
View File
@@ -18,12 +18,12 @@
use std::sync::Arc;
use std::collections::HashMap;
use primitives::ChangesTrieConfiguration;
use primitives::offchain::OffchainStorage;
use sp_core::ChangesTrieConfiguration;
use sp_core::offchain::OffchainStorage;
use sp_runtime::{generic::BlockId, Justification, Storage};
use sp_runtime::traits::{Block as BlockT, NumberFor};
use state_machine::backend::Backend as StateBackend;
use state_machine::{ChangesTrieStorage as StateChangesTrieStorage, ChangesTrieTransaction};
use sp_state_machine::backend::Backend as StateBackend;
use sp_state_machine::{ChangesTrieStorage as StateChangesTrieStorage, ChangesTrieTransaction};
use crate::{
blockchain::{
Backend as BlockchainBackend, well_known_cache_keys
@@ -31,7 +31,7 @@ use crate::{
light::RemoteBlockchain,
};
use sp_blockchain;
use consensus::BlockOrigin;
use sp_consensus::BlockOrigin;
use hash_db::Hasher;
use parking_lot::RwLock;
+11 -11
View File
@@ -21,14 +21,14 @@ use codec::{Encode, Decode};
use sp_runtime::{
generic::BlockId, traits::Block as BlockT, traits::NumberFor,
};
use state_machine::{
use sp_state_machine::{
self, OverlayedChanges, ExecutionManager, ExecutionStrategy,
ChangesTrieTransaction, StorageProof,
};
use executor::{RuntimeVersion, NativeVersion};
use externalities::Extensions;
use sc_executor::{RuntimeVersion, NativeVersion};
use sp_externalities::Extensions;
use hash_db::Hasher;
use primitives::{Blake2Hasher, NativeOrEncoded};
use sp_core::{Blake2Hasher, NativeOrEncoded};
use sp_api::{ProofRecorder, InitializeBlock};
use sp_blockchain;
@@ -41,7 +41,7 @@ where
H::Out: Ord,
{
/// Externalities error type.
type Error: state_machine::Error;
type Error: sp_state_machine::Error;
/// Execute a call to a contract on top of state in a block of given hash.
///
@@ -92,7 +92,7 @@ where
///
/// No changes are made.
fn call_at_state<
S: state_machine::Backend<H>,
S: sp_state_machine::Backend<H>,
F: FnOnce(
Result<NativeOrEncoded<R>, Self::Error>,
Result<NativeOrEncoded<R>, Self::Error>,
@@ -119,7 +119,7 @@ where
/// Execute a call to a contract on top of given state, gathering execution proof.
///
/// No changes are made.
fn prove_at_state<S: state_machine::Backend<H>>(
fn prove_at_state<S: sp_state_machine::Backend<H>>(
&self,
mut state: S,
overlay: &mut OverlayedChanges,
@@ -128,8 +128,8 @@ where
) -> Result<(Vec<u8>, StorageProof), sp_blockchain::Error> {
let trie_state = state.as_trie_backend()
.ok_or_else(||
Box::new(state_machine::ExecutionError::UnableToGenerateProof)
as Box<dyn state_machine::Error>
Box::new(sp_state_machine::ExecutionError::UnableToGenerateProof)
as Box<dyn sp_state_machine::Error>
)?;
self.prove_at_trie_state(trie_state, overlay, method, call_data)
}
@@ -137,9 +137,9 @@ where
/// Execute a call to a contract on top of given trie state, gathering execution proof.
///
/// No changes are made.
fn prove_at_trie_state<S: state_machine::TrieBackendStorage<H>>(
fn prove_at_trie_state<S: sp_state_machine::TrieBackendStorage<H>>(
&self,
trie_state: &state_machine::TrieBackend<S, H>,
trie_state: &sp_state_machine::TrieBackend<S, H>,
overlay: &mut OverlayedChanges,
method: &str,
call_data: &[u8]
+2 -2
View File
@@ -18,12 +18,12 @@
use std::collections::HashMap;
use futures::channel::mpsc;
use primitives::storage::StorageKey;
use sp_core::storage::StorageKey;
use sp_runtime::{
traits::{Block as BlockT, NumberFor},
generic::BlockId
};
use consensus::BlockOrigin;
use sp_consensus::BlockOrigin;
use crate::blockchain::Info;
use crate::notifications::StorageEventStream;
@@ -22,7 +22,7 @@
use std::sync::{Weak, Arc};
use codec::Decode;
use primitives::{
use sp_core::{
ExecutionContext,
offchain::{self, OffchainExt, TransactionPoolExt},
traits::{BareCryptoStorePtr, KeystoreExt},
@@ -31,8 +31,8 @@ use sp_runtime::{
generic::BlockId,
traits,
};
use state_machine::{ExecutionStrategy, ExecutionManager, DefaultHandler};
use externalities::Extensions;
use sp_state_machine::{ExecutionStrategy, ExecutionManager, DefaultHandler};
use sp_externalities::Extensions;
use parking_lot::RwLock;
/// Execution strategies settings.
@@ -70,7 +70,7 @@ impl Default for ExecutionStrategies {
pub struct ExecutionExtensions<Block: traits::Block> {
strategies: ExecutionStrategies,
keystore: Option<BareCryptoStorePtr>,
transaction_pool: RwLock<Option<Weak<dyn txpool_api::OffchainSubmitTransaction<Block>>>>,
transaction_pool: RwLock<Option<Weak<dyn sp_transaction_pool::OffchainSubmitTransaction<Block>>>>,
}
impl<Block: traits::Block> Default for ExecutionExtensions<Block> {
@@ -104,7 +104,7 @@ impl<Block: traits::Block> ExecutionExtensions<Block> {
/// extension to be a `Weak` reference.
/// That's also the reason why it's being registered lazily instead of
/// during initialisation.
pub fn register_transaction_pool(&self, pool: Weak<dyn txpool_api::OffchainSubmitTransaction<Block>>) {
pub fn register_transaction_pool(&self, pool: Weak<dyn sp_transaction_pool::OffchainSubmitTransaction<Block>>) {
*self.transaction_pool.write() = Some(pool);
}
@@ -165,7 +165,7 @@ impl<Block: traits::Block> ExecutionExtensions<Block> {
/// A wrapper type to pass `BlockId` to the actual transaction pool.
struct TransactionPoolAdapter<Block: traits::Block> {
at: BlockId<Block>,
pool: Arc<dyn txpool_api::OffchainSubmitTransaction<Block>>,
pool: Arc<dyn sp_transaction_pool::OffchainSubmitTransaction<Block>>,
}
impl<Block: traits::Block> offchain::TransactionPool for TransactionPoolAdapter<Block> {
+2 -2
View File
@@ -32,13 +32,13 @@ pub use client::*;
pub use light::*;
pub use notifications::*;
pub use state_machine::{StorageProof, ExecutionStrategy};
pub use sp_state_machine::{StorageProof, ExecutionStrategy};
/// Utility methods for the client.
pub mod utils {
use sp_blockchain::{HeaderBackend, HeaderMetadata, Error};
use primitives::H256;
use sp_core::H256;
use sp_runtime::traits::{Block as BlockT};
use std::borrow::Borrow;
+3 -3
View File
@@ -26,8 +26,8 @@ use sp_runtime::{
},
generic::BlockId
};
use primitives::ChangesTrieConfiguration;
use state_machine::StorageProof;
use sp_core::ChangesTrieConfiguration;
use sp_state_machine::StorageProof;
use sp_blockchain::{
HeaderMetadata, well_known_cache_keys, HeaderBackend, Cache as BlockchainCache,
Error as ClientError, Result as ClientResult,
@@ -304,7 +304,7 @@ pub mod tests {
use futures::future::Ready;
use parking_lot::Mutex;
use sp_blockchain::Error as ClientError;
use test_primitives::{Block, Header, Extrinsic};
use sp_test_primitives::{Block, Header, Extrinsic};
use super::*;
pub type OkCallFetcher = Mutex<Vec<u8>>;
+1 -1
View File
@@ -23,7 +23,7 @@ use std::{
use fnv::{FnvHashSet, FnvHashMap};
use futures::channel::mpsc;
use primitives::storage::{StorageKey, StorageData};
use sp_core::storage::{StorageKey, StorageData};
use sp_runtime::traits::Block as BlockT;
/// Storage change set
@@ -9,18 +9,18 @@ build = "build.rs"
prost-build = "0.5.0"
[dependencies]
authority-discovery-primitives = { package = "sp-authority-discovery", path = "../../primitives/authority-discovery" }
sp-authority-discovery = { path = "../../primitives/authority-discovery" }
bytes = "0.4.12"
client-api = { package = "sc-client-api", path = "../api" }
sc-client-api = { path = "../api" }
codec = { package = "parity-scale-codec", default-features = false, version = "1.0.3" }
derive_more = "0.99.2"
futures = "0.3.1"
futures-timer = "2.0"
keystore = { package = "sc-keystore", path = "../keystore" }
sc-keystore = { path = "../keystore" }
libp2p = { version = "0.13.0", default-features = false, features = ["secp256k1", "libp2p-websocket"] }
log = "0.4.8"
network = { package = "sc-network", path = "../network" }
primitives = { package = "sp-core", path = "../../primitives/core" }
sc-network = { path = "../network" }
sp-core = { path = "../../primitives/core" }
sp-blockchain = { path = "../../primitives/blockchain" }
prost = "0.5.0"
serde_json = "1.0.41"
@@ -29,6 +29,6 @@ sp-runtime = { path = "../../primitives/runtime" }
[dev-dependencies]
env_logger = "0.7.0"
parking_lot = "0.9.0"
peerset = { package = "sc-peerset", path = "../peerset" }
sc-peerset = { path = "../peerset" }
sp-test-primitives = { path = "../../primitives/test-primitives" }
sp-api = { path = "../../primitives/api" }
+13 -13
View File
@@ -55,18 +55,18 @@ use futures::task::{Context, Poll};
use futures::{Future, FutureExt, Stream, StreamExt};
use futures_timer::Delay;
use authority_discovery_primitives::{
use sp_authority_discovery::{
AuthorityDiscoveryApi, AuthorityId, AuthoritySignature, AuthorityPair
};
use client_api::blockchain::HeaderBackend;
use sc_client_api::blockchain::HeaderBackend;
use codec::{Decode, Encode};
use error::{Error, Result};
use log::{debug, error, log_enabled, warn};
use libp2p::Multiaddr;
use network::specialization::NetworkSpecialization;
use network::{DhtEvent, ExHashT};
use primitives::crypto::{key_types, Pair};
use primitives::traits::BareCryptoStorePtr;
use sc_network::specialization::NetworkSpecialization;
use sc_network::{DhtEvent, ExHashT};
use sp_core::crypto::{key_types, Pair};
use sp_core::traits::BareCryptoStorePtr;
use prost::Message;
use sp_runtime::generic::BlockId;
use sp_runtime::traits::{Block as BlockT, ProvideRuntimeApi};
@@ -501,7 +501,7 @@ pub trait NetworkProvider {
fn get_value(&self, key: &libp2p::kad::record::Key);
}
impl<B, S, H> NetworkProvider for network::NetworkService<B, S, H>
impl<B, S, H> NetworkProvider for sc_network::NetworkService<B, S, H>
where
B: BlockT + 'static,
S: NetworkSpecialization<B>,
@@ -551,7 +551,7 @@ mod tests {
use futures::channel::mpsc::channel;
use futures::executor::block_on;
use futures::future::poll_fn;
use primitives::{ExecutionContext, NativeOrEncoded, testing::KeyStore};
use sp_core::{ExecutionContext, NativeOrEncoded, testing::KeyStore};
use sp_runtime::traits::Zero;
use sp_runtime::traits::{ApiRef, Block as BlockT, NumberFor, ProvideRuntimeApi};
use std::sync::{Arc, Mutex};
@@ -642,8 +642,8 @@ mod tests {
Ok(None)
}
fn info(&self) -> client_api::blockchain::Info<Block> {
client_api::blockchain::Info {
fn info(&self) -> sc_client_api::blockchain::Info<Block> {
sc_client_api::blockchain::Info {
best_hash: Default::default(),
best_number: Zero::zero(),
finalized_hash: Default::default(),
@@ -655,8 +655,8 @@ mod tests {
fn status(
&self,
_id: BlockId<Block>,
) -> std::result::Result<client_api::blockchain::BlockStatus, sp_blockchain::Error> {
Ok(client_api::blockchain::BlockStatus::Unknown)
) -> std::result::Result<sc_client_api::blockchain::BlockStatus, sp_blockchain::Error> {
Ok(sc_client_api::blockchain::BlockStatus::Unknown)
}
fn number(
@@ -865,7 +865,7 @@ mod tests {
.encode(&mut signed_addresses)
.unwrap();
let dht_event = network::DhtEvent::ValueFound(vec![(authority_id_1, signed_addresses)]);
let dht_event = sc_network::DhtEvent::ValueFound(vec![(authority_id_1, signed_addresses)]);
dht_event_tx.try_send(dht_event).unwrap();
// Make authority discovery handle the event.
+9 -9
View File
@@ -9,18 +9,18 @@ log = "0.4.8"
futures = "0.3.1"
codec = { package = "parity-scale-codec", version = "1.0.0" }
sp-runtime = { path = "../../primitives/runtime" }
primitives = { package = "sp-core", path = "../../primitives/core" }
sp-core = { path = "../../primitives/core" }
sp-blockchain = { path = "../../primitives/blockchain" }
client = { package = "sc-client", path = "../" }
client-api = { package = "sc-client-api", path = "../api" }
consensus_common = { package = "sp-consensus", path = "../../primitives/consensus/common" }
inherents = { package = "sp-inherents", path = "../../primitives/inherents" }
sc-client = { path = "../" }
sc-client-api = { path = "../api" }
sp-consensus = { path = "../../primitives/consensus/common" }
sp-inherents = { path = "../../primitives/inherents" }
sc-telemetry = { path = "../telemetry" }
txpool-api = { package = "sp-transaction-pool", path = "../../primitives/transaction-pool" }
block-builder = { package = "sc-block-builder", path = "../block-builder" }
sp-transaction-pool = { path = "../../primitives/transaction-pool" }
sc-block-builder = { path = "../block-builder" }
tokio-executor = { version = "0.2.0-alpha.6", features = ["blocking"] }
[dev-dependencies]
txpool = { package = "sc-transaction-pool", path = "../../client/transaction-pool" }
test-client = { package = "substrate-test-runtime-client", path = "../../test-utils/runtime/client" }
sc-transaction-pool = { path = "../../client/transaction-pool" }
substrate-test-runtime-client = { path = "../../test-utils/runtime/client" }
parking_lot = "0.9"
@@ -19,23 +19,23 @@
// FIXME #1021 move this into sp-consensus
use std::{time, sync::Arc};
use client_api::CallExecutor;
use sc_client_api::CallExecutor;
use sp_blockchain;
use client::Client as SubstrateClient;
use sc_client::Client as SubstrateClient;
use codec::Decode;
use consensus_common::{evaluation};
use inherents::InherentData;
use sp_consensus::{evaluation};
use sp_inherents::InherentData;
use log::{error, info, debug, trace};
use primitives::{H256, Blake2Hasher, ExecutionContext};
use sp_core::{H256, Blake2Hasher, ExecutionContext};
use sp_runtime::{
traits::{
Block as BlockT, Hash as HashT, Header as HeaderT, ProvideRuntimeApi, DigestFor, BlakeTwo256
},
generic::BlockId,
};
use txpool_api::{TransactionPool, InPoolTransaction};
use sp_transaction_pool::{TransactionPool, InPoolTransaction};
use sc_telemetry::{telemetry, CONSENSUS_INFO};
use block_builder::BlockBuilderApi;
use sc_block_builder::BlockBuilderApi;
/// Proposer factory.
pub struct ProposerFactory<C, A> where A: TransactionPool {
@@ -48,7 +48,7 @@ pub struct ProposerFactory<C, A> where A: TransactionPool {
impl<B, E, Block, RA, A> ProposerFactory<SubstrateClient<B, E, Block, RA>, A>
where
A: TransactionPool<Block=Block> + 'static,
B: client_api::backend::Backend<Block, Blake2Hasher> + Send + Sync + 'static,
B: sc_client_api::backend::Backend<Block, Blake2Hasher> + Send + Sync + 'static,
E: CallExecutor<Block, Blake2Hasher> + Send + Sync + Clone + 'static,
Block: BlockT<Hash=H256>,
RA: Send + Sync + 'static,
@@ -82,11 +82,11 @@ where
}
}
impl<B, E, Block, RA, A> consensus_common::Environment<Block> for
impl<B, E, Block, RA, A> sp_consensus::Environment<Block> for
ProposerFactory<SubstrateClient<B, E, Block, RA>, A>
where
A: TransactionPool<Block=Block> + 'static,
B: client_api::backend::Backend<Block, Blake2Hasher> + Send + Sync + 'static,
B: sc_client_api::backend::Backend<Block, Blake2Hasher> + Send + Sync + 'static,
E: CallExecutor<Block, Blake2Hasher> + Send + Sync + Clone + 'static,
Block: BlockT<Hash=H256>,
RA: Send + Sync + 'static,
@@ -120,11 +120,11 @@ struct ProposerInner<Block: BlockT, C, A: TransactionPool> {
now: Box<dyn Fn() -> time::Instant + Send + Sync>,
}
impl<B, E, Block, RA, A> consensus_common::Proposer<Block> for
impl<B, E, Block, RA, A> sp_consensus::Proposer<Block> for
Proposer<Block, SubstrateClient<B, E, Block, RA>, A>
where
A: TransactionPool<Block=Block> + 'static,
B: client_api::backend::Backend<Block, Blake2Hasher> + Send + Sync + 'static,
B: sc_client_api::backend::Backend<Block, Blake2Hasher> + Send + Sync + 'static,
E: CallExecutor<Block, Blake2Hasher> + Send + Sync + Clone + 'static,
Block: BlockT<Hash=H256>,
RA: Send + Sync + 'static,
@@ -152,7 +152,7 @@ where
impl<Block, B, E, RA, A> ProposerInner<Block, SubstrateClient<B, E, Block, RA>, A> where
A: TransactionPool<Block=Block> + 'static,
B: client_api::backend::Backend<Block, Blake2Hasher> + Send + Sync + 'static,
B: sc_client_api::backend::Backend<Block, Blake2Hasher> + Send + Sync + 'static,
E: CallExecutor<Block, Blake2Hasher> + Send + Sync + Clone + 'static,
Block: BlockT<Hash=H256>,
RA: Send + Sync + 'static,
@@ -201,7 +201,7 @@ impl<Block, B, E, RA, A> ProposerInner<Block, SubstrateClient<B, E, Block, RA>,
let pending_tx_data = pending_tx.data().clone();
let pending_tx_hash = pending_tx.hash().clone();
trace!("[{:?}] Pushing to the block.", pending_tx_hash);
match block_builder::BlockBuilder::push(&mut block_builder, pending_tx_data) {
match sc_block_builder::BlockBuilder::push(&mut block_builder, pending_tx_data) {
Ok(()) => {
debug!("[{:?}] Pushed to the block.", pending_tx_hash);
}
@@ -266,9 +266,9 @@ mod tests {
use super::*;
use parking_lot::Mutex;
use consensus_common::Proposer;
use test_client::{self, runtime::{Extrinsic, Transfer}, AccountKeyring};
use txpool::{BasicPool, FullChainApi};
use sp_consensus::Proposer;
use substrate_test_runtime_client::{self, runtime::{Extrinsic, Transfer}, AccountKeyring};
use sc_transaction_pool::{BasicPool, FullChainApi};
fn extrinsic(nonce: u64) -> Extrinsic {
Transfer {
@@ -282,7 +282,7 @@ mod tests {
#[test]
fn should_cease_building_block_when_deadline_is_reached() {
// given
let client = Arc::new(test_client::new());
let client = Arc::new(substrate_test_runtime_client::new());
let txpool = Arc::new(BasicPool::new(Default::default(), FullChainApi::new(client.clone())));
futures::executor::block_on(
+4 -4
View File
@@ -20,12 +20,12 @@
//!
//! ```
//! # use sc_basic_authority::ProposerFactory;
//! # use consensus_common::{Environment, Proposer};
//! # use sp_consensus::{Environment, Proposer};
//! # use sp_runtime::generic::BlockId;
//! # use std::{sync::Arc, time::Duration};
//! # use test_client::{self, runtime::{Extrinsic, Transfer}, AccountKeyring};
//! # use txpool::{BasicPool, FullChainApi};
//! # let client = Arc::new(test_client::new());
//! # use substrate_test_runtime_client::{self, runtime::{Extrinsic, Transfer}, AccountKeyring};
//! # use sc_transaction_pool::{BasicPool, FullChainApi};
//! # let client = Arc::new(substrate_test_runtime_client::new());
//! # let txpool = Arc::new(BasicPool::new(Default::default(), FullChainApi::new(client.clone())));
//! // The first step is to create a `ProposerFactory`.
//! let mut proposer_factory = ProposerFactory {
+3 -3
View File
@@ -5,10 +5,10 @@ authors = ["Parity Technologies <admin@parity.io>"]
edition = "2018"
[dependencies]
state-machine = { package = "sp-state-machine", path = "../../primitives/state-machine" }
sp-state-machine = { path = "../../primitives/state-machine" }
sp-runtime = { path = "../../primitives/runtime" }
sp-blockchain = { path = "../../primitives/blockchain" }
primitives = { package = "sp-core", path = "../../primitives/core" }
sp-core = { path = "../../primitives/core" }
codec = { package = "parity-scale-codec", version = "1.0.6", features = ["derive"] }
runtime_api = { package = "sp-block-builder", path = "../../primitives/block-builder" }
sp-block-builder = { path = "../../primitives/block-builder" }
sp-api = { path = "../../primitives/api" }
+3 -3
View File
@@ -34,11 +34,11 @@ use sp_runtime::{
}
};
use sp_blockchain::{ApplyExtrinsicFailed, Error};
use primitives::ExecutionContext;
use state_machine::StorageProof;
use sp_core::ExecutionContext;
use sp_state_machine::StorageProof;
use sp_api::{Core, ApiExt, ApiErrorFor};
pub use runtime_api::BlockBuilder as BlockBuilderApi;
pub use sp_block_builder::BlockBuilder as BlockBuilderApi;
/// Utility for building new (valid) blocks from a stream of extrinsics.
+3 -3
View File
@@ -7,9 +7,9 @@ edition = "2018"
[dependencies]
sc-chain-spec-derive = { path = "./derive" }
impl-trait-for-tuples = "0.1.3"
network = { package = "sc-network", path = "../network" }
primitives = { package = "sp-core", path = "../../primitives/core" }
sc-network = { path = "../network" }
sp-core = { path = "../../primitives/core" }
serde = { version = "1.0.101", features = ["derive"] }
serde_json = "1.0.41"
sp-runtime = { path = "../../primitives/runtime" }
tel = { package = "sc-telemetry", path = "../telemetry" }
sc-telemetry = { path = "../telemetry" }
@@ -22,12 +22,12 @@ use std::fs::File;
use std::path::PathBuf;
use std::rc::Rc;
use serde::{Serialize, Deserialize};
use primitives::storage::{StorageKey, StorageData, ChildInfo, Storage, StorageChild};
use sp_core::storage::{StorageKey, StorageData, ChildInfo, Storage, StorageChild};
use sp_runtime::BuildStorage;
use serde_json as json;
use crate::RuntimeGenesis;
use network::Multiaddr;
use tel::TelemetryEndpoints;
use sc_network::Multiaddr;
use sc_telemetry::TelemetryEndpoints;
enum GenesisSource<G> {
File(PathBuf),
@@ -77,7 +77,7 @@ impl<'a, G: RuntimeGenesis, E> BuildStorage for &'a ChainSpec<G, E> {
Genesis::Raw(RawGenesis { top: map, children: children_map }) => Ok(Storage {
top: map.into_iter().map(|(k, v)| (k.0, v.0)).collect(),
children: children_map.into_iter().map(|(sk, child_content)| {
let child_info = ChildInfo::resolve_child_info(
let child_info = ChildInfo::resolve_child_info(
child_content.child_type,
child_content.child_info.as_slice(),
).expect("chainspec contains correct content").to_owned();
@@ -292,7 +292,7 @@ impl<G: RuntimeGenesis, E: serde::Serialize> ChainSpec<G, E> {
StorageKey(sk),
ChildRawStorage {
data: child.data.into_iter()
.map(|(k, v)| (StorageKey(k), StorageData(v)))
.map(|(k, v)| (StorageKey(k), StorageData(v)))
.collect(),
child_info: info.to_vec(),
child_type: ci_type,
+9 -9
View File
@@ -20,19 +20,19 @@ tokio = "0.2.1"
futures = { version = "0.3.1", features = ["compat"] }
fdlimit = "0.1.1"
serde_json = "1.0.41"
panic-handler = { package = "sp-panic-handler", path = "../../primitives/panic-handler" }
client-api = { package = "sc-client-api", path = "../api" }
sp-panic-handler = { path = "../../primitives/panic-handler" }
sc-client-api = { path = "../api" }
sp-blockchain = { path = "../../primitives/blockchain" }
network = { package = "sc-network", path = "../network" }
sc-network = { path = "../network" }
sp-runtime = { path = "../../primitives/runtime" }
primitives = { package = "sp-core", path = "../../primitives/core" }
service = { package = "sc-service", path = "../service", default-features = false }
state-machine = { package = "sp-state-machine", path = "../../primitives/state-machine" }
sp-core = { path = "../../primitives/core" }
sc-service = { path = "../service", default-features = false }
sp-state-machine = { path = "../../primitives/state-machine" }
sc-telemetry = { path = "../telemetry" }
keyring = { package = "sp-keyring", path = "../../primitives/keyring" }
sp-keyring = { path = "../../primitives/keyring" }
names = "0.11.0"
structopt = "0.3.3"
sc-tracing = { package = "sc-tracing", path = "../tracing" }
sc-tracing = { path = "../tracing" }
[target.'cfg(not(target_os = "unknown"))'.dependencies]
rpassword = "4.0.1"
@@ -42,5 +42,5 @@ tempfile = "3.1.0"
[features]
wasmtime = [
"service/wasmtime",
"sc-service/wasmtime",
]
+1 -1
View File
@@ -27,7 +27,7 @@ pub enum Error {
/// Cli error
Cli(clap::Error),
/// Service error
Service(service::Error),
Service(sc_service::Error),
/// Client error
Client(sp_blockchain::Error),
/// Input error
+2 -2
View File
@@ -16,11 +16,11 @@
//! Console informant. Prints sync progress and block events. Runs on the calling thread.
use client_api::BlockchainEvents;
use sc_client_api::BlockchainEvents;
use futures::{StreamExt, TryStreamExt, FutureExt, future, compat::Stream01CompatExt};
use log::{info, warn};
use sp_runtime::traits::Header;
use service::AbstractService;
use sc_service::AbstractService;
use std::time::Duration;
mod display;
@@ -15,11 +15,11 @@
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
use ansi_term::Colour;
use client_api::ClientInfo;
use sc_client_api::ClientInfo;
use log::info;
use network::SyncState;
use sc_network::SyncState;
use sp_runtime::traits::{Block as BlockT, CheckedDiv, NumberFor, Zero, Saturating};
use service::NetworkStatus;
use sc_service::NetworkStatus;
use std::{convert::{TryFrom, TryInto}, fmt, time};
/// State of the informant display system.
+30 -30
View File
@@ -26,20 +26,20 @@ mod execution_strategy;
pub mod error;
pub mod informant;
use client_api::execution_extensions::ExecutionStrategies;
use service::{
use sc_client_api::execution_extensions::ExecutionStrategies;
use sc_service::{
config::{Configuration, DatabaseConfig},
ServiceBuilderCommand,
RuntimeGenesis, ChainSpecExtension, PruningMode, ChainSpec,
};
use network::{
use sc_network::{
self,
multiaddr::Protocol,
config::{
NetworkConfiguration, TransportConfig, NonReservedPeerMode, NodeKeyConfig, build_multiaddr
},
};
use primitives::H256;
use sp_core::H256;
use std::{
io::{Write, Read, Seek, Cursor, stdin, stdout, ErrorKind}, iter, fs::{self, File},
@@ -200,12 +200,12 @@ where
I: IntoIterator,
<I as IntoIterator>::Item: Into<std::ffi::OsString> + Clone,
{
let full_version = service::config::full_version_from_strs(
let full_version = sc_service::config::full_version_from_strs(
version.version,
version.commit
);
panic_handler::set(version.support_url, &full_version);
sp_panic_handler::set(version.support_url, &full_version);
let matches = CoreParams::<CC, RP>::clap()
.name(version.executable_name)
.author(version.author)
@@ -333,7 +333,7 @@ impl<'a> ParseAndPrepareBuildSpec<'a> {
if spec.boot_nodes().is_empty() && !self.params.disable_default_bootnode {
let base_path = base_path(&self.params.shared_params, self.version);
let cfg = service::Configuration::<C,_,_>::default_with_spec_and_base_path(spec.clone(), Some(base_path));
let cfg = sc_service::Configuration::<C,_,_>::default_with_spec_and_base_path(spec.clone(), Some(base_path));
let node_key = node_key_config(
self.params.node_key_params,
&Some(cfg.in_chain_config_dir(DEFAULT_NETWORK_CONFIG_PATH).expect("We provided a base_path"))
@@ -348,7 +348,7 @@ impl<'a> ParseAndPrepareBuildSpec<'a> {
spec.add_boot_node(addr)
}
let json = service::chain_ops::build_spec(spec, raw_output)?;
let json = sc_service::chain_ops::build_spec(spec, raw_output)?;
print!("{}", json);
@@ -440,7 +440,7 @@ impl<'a> ParseAndPrepareImport<'a> {
Exit: IntoExit
{
let mut config = create_config_with_db_path(spec_factory, &self.params.shared_params, self.version)?;
fill_import_params(&mut config, &self.params.import_params, service::Roles::FULL)?;
fill_import_params(&mut config, &self.params.import_params, sc_service::Roles::FULL)?;
let file: Box<dyn ReadPlusSeek + Send> = match self.params.input {
Some(filename) => Box::new(File::open(filename)?),
@@ -500,7 +500,7 @@ impl<'a> CheckBlock<'a> {
Exit: IntoExit
{
let mut config = create_config_with_db_path(spec_factory, &self.params.shared_params, self.version)?;
fill_import_params(&mut config, &self.params.import_params, service::Roles::FULL)?;
fill_import_params(&mut config, &self.params.import_params, sc_service::Roles::FULL)?;
let input = if self.params.input.starts_with("0x") { &self.params.input[2..] } else { &self.params.input[..] };
let block_id = match FromStr::from_str(input) {
@@ -621,8 +621,8 @@ where
params.node_key.as_ref().map(parse_ed25519_secret).unwrap_or_else(||
Ok(params.node_key_file
.or_else(|| net_config_file(net_config_dir, NODE_KEY_ED25519_FILE))
.map(network::config::Secret::File)
.unwrap_or(network::config::Secret::New)))
.map(sc_network::config::Secret::File)
.unwrap_or(sc_network::config::Secret::New)))
.map(NodeKeyConfig::Ed25519)
}
}
@@ -639,11 +639,11 @@ fn invalid_node_key(e: impl std::fmt::Display) -> error::Error {
error::Error::Input(format!("Invalid node key: {}", e))
}
/// Parse a Ed25519 secret key from a hex string into a `network::Secret`.
fn parse_ed25519_secret(hex: &String) -> error::Result<network::config::Ed25519Secret> {
/// Parse a Ed25519 secret key from a hex string into a `sc_network::Secret`.
fn parse_ed25519_secret(hex: &String) -> error::Result<sc_network::config::Ed25519Secret> {
H256::from_str(&hex).map_err(invalid_node_key).and_then(|bytes|
network::config::identity::ed25519::SecretKey::from_bytes(bytes)
.map(network::config::Secret::Input)
sc_network::config::identity::ed25519::SecretKey::from_bytes(bytes)
.map(sc_network::config::Secret::Input)
.map_err(invalid_node_key))
}
@@ -728,7 +728,7 @@ fn input_keystore_password() -> Result<String, String> {
/// Fill the password field of the given config instance.
fn fill_config_keystore_password<C, G, E>(
config: &mut service::Configuration<C, G, E>,
config: &mut sc_service::Configuration<C, G, E>,
cli: &RunCmd,
) -> Result<(), String> {
config.keystore_password = if cli.password_interactive {
@@ -753,7 +753,7 @@ fn fill_config_keystore_password<C, G, E>(
pub fn fill_import_params<C, G, E>(
config: &mut Configuration<C, G, E>,
cli: &ImportParams,
role: service::Roles,
role: sc_service::Roles,
) -> error::Result<()>
where
C: Default,
@@ -774,10 +774,10 @@ pub fn fill_import_params<C, G, E>(
// unless `unsafe_pruning` is set.
config.pruning = match &cli.pruning {
Some(ref s) if s == "archive" => PruningMode::ArchiveAll,
None if role == service::Roles::AUTHORITY => PruningMode::ArchiveAll,
None if role == sc_service::Roles::AUTHORITY => PruningMode::ArchiveAll,
None => PruningMode::default(),
Some(s) => {
if role == service::Roles::AUTHORITY && !cli.unsafe_pruning {
if role == sc_service::Roles::AUTHORITY && !cli.unsafe_pruning {
return Err(error::Error::Input(
"Validators should run with state pruning disabled (i.e. archive). \
You can ignore this check with `--unsafe-pruning`.".to_string()
@@ -821,11 +821,11 @@ where
let is_authority = cli.validator || cli.sentry || is_dev || cli.keyring.account.is_some();
let role =
if cli.light {
service::Roles::LIGHT
sc_service::Roles::LIGHT
} else if is_authority {
service::Roles::AUTHORITY
sc_service::Roles::AUTHORITY
} else {
service::Roles::FULL
sc_service::Roles::FULL
};
fill_import_params(&mut config, &cli.import_params, role)?;
@@ -856,7 +856,7 @@ where
config.sentry_mode = cli.sentry;
config.offchain_worker = match (cli.offchain_worker, role) {
(params::OffchainWorkerEnabled::WhenValidating, service::Roles::AUTHORITY) => true,
(params::OffchainWorkerEnabled::WhenValidating, sc_service::Roles::AUTHORITY) => true,
(params::OffchainWorkerEnabled::Always, _) => true,
(params::OffchainWorkerEnabled::Never, _) => false,
(params::OffchainWorkerEnabled::WhenValidating, _) => false,
@@ -939,7 +939,7 @@ where
let spec = load_spec(cli, spec_factory)?;
let base_path = base_path(cli, version);
let mut config = service::Configuration::default_with_spec_and_base_path(
let mut config = sc_service::Configuration::default_with_spec_and_base_path(
spec.clone(),
Some(base_path),
);
@@ -1043,7 +1043,7 @@ fn kill_color(s: &str) -> String {
#[cfg(test)]
mod tests {
use super::*;
use network::config::identity::ed25519;
use sc_network::config::identity::ed25519;
#[test]
fn tests_node_name_good() {
@@ -1074,7 +1074,7 @@ mod tests {
node_key_file: None
};
node_key_config(params, &net_config_dir).and_then(|c| match c {
NodeKeyConfig::Ed25519(network::config::Secret::Input(ref ski))
NodeKeyConfig::Ed25519(sc_network::config::Secret::Input(ref ski))
if node_key_type == NodeKeyType::Ed25519 &&
&sk[..] == ski.as_ref() => Ok(()),
_ => Err(error::Error::Input("Unexpected node key config".into()))
@@ -1099,7 +1099,7 @@ mod tests {
node_key_file: Some(file.clone())
};
node_key_config(params, &net_config_dir).and_then(|c| match c {
NodeKeyConfig::Ed25519(network::config::Secret::File(ref f))
NodeKeyConfig::Ed25519(sc_network::config::Secret::File(ref f))
if node_key_type == NodeKeyType::Ed25519 && f == &file => Ok(()),
_ => Err(error::Error::Input("Unexpected node key config".into()))
})
@@ -1131,7 +1131,7 @@ mod tests {
let typ = params.node_key_type;
node_key_config::<String>(params, &None)
.and_then(|c| match c {
NodeKeyConfig::Ed25519(network::config::Secret::New)
NodeKeyConfig::Ed25519(sc_network::config::Secret::New)
if typ == NodeKeyType::Ed25519 => Ok(()),
_ => Err(error::Error::Input("Unexpected node key config".into()))
})
@@ -1144,7 +1144,7 @@ mod tests {
let typ = params.node_key_type;
node_key_config(params, &Some(net_config_dir.clone()))
.and_then(move |c| match c {
NodeKeyConfig::Ed25519(network::config::Secret::File(ref f))
NodeKeyConfig::Ed25519(sc_network::config::Secret::File(ref f))
if typ == NodeKeyType::Ed25519 &&
f == &dir.join(NODE_KEY_ED25519_FILE) => Ok(()),
_ => Err(error::Error::Input("Unexpected node key config".into()))
+14 -14
View File
@@ -32,13 +32,13 @@ macro_rules! impl_get_log_filter {
}
}
impl Into<client_api::ExecutionStrategy> for ExecutionStrategy {
fn into(self) -> client_api::ExecutionStrategy {
impl Into<sc_client_api::ExecutionStrategy> for ExecutionStrategy {
fn into(self) -> sc_client_api::ExecutionStrategy {
match self {
ExecutionStrategy::Native => client_api::ExecutionStrategy::NativeWhenPossible,
ExecutionStrategy::Wasm => client_api::ExecutionStrategy::AlwaysWasm,
ExecutionStrategy::Both => client_api::ExecutionStrategy::Both,
ExecutionStrategy::NativeElseWasm => client_api::ExecutionStrategy::NativeElseWasm,
ExecutionStrategy::Native => sc_client_api::ExecutionStrategy::NativeWhenPossible,
ExecutionStrategy::Wasm => sc_client_api::ExecutionStrategy::AlwaysWasm,
ExecutionStrategy::Both => sc_client_api::ExecutionStrategy::Both,
ExecutionStrategy::NativeElseWasm => sc_client_api::ExecutionStrategy::NativeElseWasm,
}
}
}
@@ -66,12 +66,12 @@ impl WasmExecutionMethod {
}
}
impl Into<service::config::WasmExecutionMethod> for WasmExecutionMethod {
fn into(self) -> service::config::WasmExecutionMethod {
impl Into<sc_service::config::WasmExecutionMethod> for WasmExecutionMethod {
fn into(self) -> sc_service::config::WasmExecutionMethod {
match self {
WasmExecutionMethod::Interpreted => service::config::WasmExecutionMethod::Interpreted,
WasmExecutionMethod::Interpreted => sc_service::config::WasmExecutionMethod::Interpreted,
#[cfg(feature = "wasmtime")]
WasmExecutionMethod::Compiled => service::config::WasmExecutionMethod::Compiled,
WasmExecutionMethod::Compiled => sc_service::config::WasmExecutionMethod::Compiled,
#[cfg(not(feature = "wasmtime"))]
WasmExecutionMethod::Compiled => panic!(
"Substrate must be compiled with \"wasmtime\" feature for compiled Wasm execution"
@@ -584,19 +584,19 @@ struct KeyringTestAccountCliValues {
help: String,
conflicts_with: Vec<String>,
name: String,
variant: keyring::Sr25519Keyring,
variant: sp_keyring::Sr25519Keyring,
}
lazy_static::lazy_static! {
/// The Cli values for all test accounts.
static ref TEST_ACCOUNTS_CLI_VALUES: Vec<KeyringTestAccountCliValues> = {
keyring::Sr25519Keyring::iter().map(|a| {
sp_keyring::Sr25519Keyring::iter().map(|a| {
let help = format!(
"Shortcut for `--name {} --validator` with session keys for `{}` added to keystore.",
a,
a,
);
let conflicts_with = keyring::Sr25519Keyring::iter()
let conflicts_with = sp_keyring::Sr25519Keyring::iter()
.filter(|b| a != *b)
.map(|b| b.to_string().to_lowercase())
.chain(std::iter::once("name".to_string()))
@@ -616,7 +616,7 @@ lazy_static::lazy_static! {
/// Wrapper for exposing the keyring test accounts into the Cli.
#[derive(Debug, Clone)]
pub struct Keyring {
pub account: Option<keyring::Sr25519Keyring>,
pub account: Option<sp_keyring::Sr25519Keyring>,
}
impl StructOpt for Keyring {
+14 -14
View File
@@ -6,38 +6,38 @@ description = "Aura consensus algorithm for substrate"
edition = "2018"
[dependencies]
app-crypto = { package = "sp-application-crypto", path = "../../../primitives/application-crypto" }
aura_primitives = { package = "sp-consensus-aura", path = "../../../primitives/consensus/aura" }
block-builder-api = { package = "sp-block-builder", path = "../../../primitives/block-builder" }
client = { package = "sc-client", path = "../../" }
client-api = { package = "sc-client-api", path = "../../api" }
sp-application-crypto = { path = "../../../primitives/application-crypto" }
sp-consensus-aura = { path = "../../../primitives/consensus/aura" }
sp-block-builder = { path = "../../../primitives/block-builder" }
sc-client = { path = "../../" }
sc-client-api = { path = "../../api" }
codec = { package = "parity-scale-codec", version = "1.0.0" }
consensus_common = { package = "sp-consensus", path = "../../../primitives/consensus/common" }
sp-consensus = { path = "../../../primitives/consensus/common" }
derive_more = "0.99.2"
futures = { version = "0.3.1", features = ["compat"] }
futures01 = { package = "futures", version = "0.1" }
futures-timer = "0.4.0"
inherents = { package = "sp-inherents", path = "../../../primitives/inherents" }
keystore = { package = "sc-keystore", path = "../../keystore" }
sp-inherents = { path = "../../../primitives/inherents" }
sc-keystore = { path = "../../keystore" }
log = "0.4.8"
parking_lot = "0.9.0"
primitives = { package = "sp-core", path = "../../../primitives/core" }
sp-core = { path = "../../../primitives/core" }
sp-blockchain = { path = "../../../primitives/blockchain" }
sp-io = { path = "../../../primitives/io" }
runtime_version = { package = "sp-version", path = "../../../primitives/version" }
slots = { package = "sc-consensus-slots", path = "../slots" }
sp-version = { path = "../../../primitives/version" }
sc-consensus-slots = { path = "../slots" }
sp-api = { path = "../../../primitives/api" }
sp-runtime = { path = "../../../primitives/runtime" }
sp-timestamp = { path = "../../../primitives/timestamp" }
sc-telemetry = { path = "../../telemetry" }
[dev-dependencies]
keyring = { package = "sp-keyring", path = "../../../primitives/keyring" }
sp-keyring = { path = "../../../primitives/keyring" }
sc-executor = { path = "../../executor" }
sc-network = { path = "../../network" }
sc-network-test = { path = "../../network/test" }
service = { package = "sc-service", path = "../../service" }
test-client = { package = "substrate-test-runtime-client", path = "../../../test-utils/runtime/client" }
sc-service = { path = "../../service" }
substrate-test-runtime-client = { path = "../../../test-utils/runtime/client" }
tokio = "0.1.22"
env_logger = "0.7.0"
tempfile = "3.1.0"
@@ -19,8 +19,8 @@
//! This implements the digests for AuRa, to allow the private
//! `CompatibleDigestItem` trait to appear in public interfaces.
use primitives::Pair;
use aura_primitives::AURA_ENGINE_ID;
use sp_core::Pair;
use sp_consensus_aura::AURA_ENGINE_ID;
use sp_runtime::generic::{DigestItem, OpaqueDigestItemId};
use codec::{Encode, Codec};
use std::fmt::Debug;
+48 -49
View File
@@ -31,28 +31,28 @@
use std::{sync::Arc, time::Duration, thread, marker::PhantomData, hash::Hash, fmt::Debug, pin::Pin};
use codec::{Encode, Decode, Codec};
use consensus_common::{
use sp_consensus::{
self, BlockImport, Environment, Proposer, CanAuthorWith, ForkChoiceStrategy, BlockImportParams,
BlockOrigin, Error as ConsensusError, SelectChain, SlotData,
};
use consensus_common::import_queue::{
use sp_consensus::import_queue::{
Verifier, BasicQueue, BoxBlockImport, BoxJustificationImport, BoxFinalityProofImport,
};
use client_api::backend::AuxStore;
use client::{
use sc_client_api::backend::AuxStore;
use sc_client::{
blockchain::ProvideCache, BlockOf
};
use sp_blockchain::{
Result as CResult, well_known_cache_keys::{self, Id as CacheKeyId},
};
use block_builder_api::BlockBuilder as BlockBuilderApi;
use sp_block_builder::BlockBuilder as BlockBuilderApi;
use sp_runtime::{generic::{BlockId, OpaqueDigestItemId}, Justification};
use sp_runtime::traits::{Block as BlockT, Header, DigestItemFor, ProvideRuntimeApi, Zero, Member};
use primitives::crypto::Pair;
use inherents::{InherentDataProviders, InherentData};
use sp_core::crypto::Pair;
use sp_inherents::{InherentDataProviders, InherentData};
use futures::prelude::*;
use parking_lot::Mutex;
@@ -65,21 +65,21 @@ use sp_timestamp::{
use sc_telemetry::{telemetry, CONSENSUS_TRACE, CONSENSUS_DEBUG, CONSENSUS_INFO};
use slots::{CheckedHeader, SlotWorker, SlotInfo, SlotCompatible};
use slots::check_equivocation;
use sc_consensus_slots::{CheckedHeader, SlotWorker, SlotInfo, SlotCompatible};
use sc_consensus_slots::check_equivocation;
use keystore::KeyStorePtr;
use sc_keystore::KeyStorePtr;
use sp_api::ApiExt;
pub use aura_primitives::{
pub use sp_consensus_aura::{
ConsensusLog, AuraApi, AURA_ENGINE_ID,
inherents::{
InherentType as AuraInherent,
AuraInherentData, INHERENT_IDENTIFIER, InherentDataProvider,
},
};
pub use consensus_common::SyncOracle;
pub use sp_consensus::SyncOracle;
pub use digest::CompatibleDigestItem;
mod digest;
@@ -88,7 +88,7 @@ type AuthorityId<P> = <P as Pair>::Public;
/// A slot duration. Create with `get_or_compute`.
#[derive(Clone, Copy, Debug, Encode, Decode, Hash, PartialOrd, Ord, PartialEq, Eq)]
pub struct SlotDuration(slots::SlotDuration<u64>);
pub struct SlotDuration(sc_consensus_slots::SlotDuration<u64>);
impl SlotDuration {
/// Either fetch the slot duration from disk or compute it from the genesis
@@ -100,7 +100,7 @@ impl SlotDuration {
C: AuxStore + ProvideRuntimeApi,
C::Api: AuraApi<B, A, Error = sp_blockchain::Error>,
{
slots::SlotDuration::get_or_compute(client, |a, b| a.slot_duration(b)).map(Self)
sc_consensus_slots::SlotDuration::get_or_compute(client, |a, b| a.slot_duration(b)).map(Self)
}
/// Get the slot duration in milliseconds.
@@ -133,11 +133,11 @@ impl SlotCompatible for AuraSlotCompatible {
fn extract_timestamp_and_slot(
&self,
data: &InherentData
) -> Result<(TimestampInherent, AuraInherent, std::time::Duration), consensus_common::Error> {
) -> Result<(TimestampInherent, AuraInherent, std::time::Duration), sp_consensus::Error> {
data.timestamp_inherent_data()
.and_then(|t| data.aura_inherent_data().map(|a| (t, a)))
.map_err(Into::into)
.map_err(consensus_common::Error::InherentData)
.map_err(sp_consensus::Error::InherentData)
.map(|(x, y)| (x, y, Default::default()))
}
}
@@ -154,7 +154,7 @@ pub fn start_aura<B, C, SC, E, I, P, SO, CAW, Error, H>(
force_authoring: bool,
keystore: KeyStorePtr,
can_author_with: CAW,
) -> Result<impl futures01::Future<Item = (), Error = ()>, consensus_common::Error> where
) -> Result<impl futures01::Future<Item = (), Error = ()>, sp_consensus::Error> where
B: BlockT<Header=H>,
C: ProvideRuntimeApi + BlockOf + ProvideCache<B> + AuxStore + Send + Sync,
C::Api: AuraApi<B, AuthorityId<P>>,
@@ -167,7 +167,7 @@ pub fn start_aura<B, C, SC, E, I, P, SO, CAW, Error, H>(
P::Signature: Hash + Member + Encode + Decode,
H: Header<Hash=B::Hash>,
I: BlockImport<B> + Send + Sync + 'static,
Error: ::std::error::Error + Send + From<::consensus_common::Error> + From<I::Error> + 'static,
Error: ::std::error::Error + Send + From<::sp_consensus::Error> + From<I::Error> + 'static,
SO: SyncOracle + Send + Sync + Clone,
CAW: CanAuthorWith<B> + Send,
{
@@ -184,7 +184,7 @@ pub fn start_aura<B, C, SC, E, I, P, SO, CAW, Error, H>(
&inherent_data_providers,
slot_duration.0.slot_duration()
)?;
Ok(slots::start_slot_worker::<_, _, _, _, _, AuraSlotCompatible, _>(
Ok(sc_consensus_slots::start_slot_worker::<_, _, _, _, _, AuraSlotCompatible, _>(
slot_duration.0,
select_chain,
worker,
@@ -205,7 +205,7 @@ struct AuraWorker<C, E, I, P, SO> {
_key_type: PhantomData<P>,
}
impl<H, B, C, E, I, P, Error, SO> slots::SimpleSlotWorker<B> for AuraWorker<C, E, I, P, SO> where
impl<H, B, C, E, I, P, Error, SO> sc_consensus_slots::SimpleSlotWorker<B> for AuraWorker<C, E, I, P, SO> where
B: BlockT<Header=H>,
C: ProvideRuntimeApi + BlockOf + ProvideCache<B> + Sync,
C::Api: AuraApi<B, AuthorityId<P>>,
@@ -218,7 +218,7 @@ impl<H, B, C, E, I, P, Error, SO> slots::SimpleSlotWorker<B> for AuraWorker<C, E
P::Public: Member + Encode + Decode + Hash,
P::Signature: Member + Encode + Decode + Hash + Debug,
SO: SyncOracle + Send + Clone,
Error: ::std::error::Error + Send + From<::consensus_common::Error> + From<I::Error> + 'static,
Error: ::std::error::Error + Send + From<::sp_consensus::Error> + From<I::Error> + 'static,
{
type EpochData = Vec<AuthorityId<P>>;
type Claim = P;
@@ -234,7 +234,7 @@ impl<H, B, C, E, I, P, Error, SO> slots::SimpleSlotWorker<B> for AuraWorker<C, E
self.block_import.clone()
}
fn epoch_data(&self, header: &B::Header, _slot_number: u64) -> Result<Self::EpochData, consensus_common::Error> {
fn epoch_data(&self, header: &B::Header, _slot_number: u64) -> Result<Self::EpochData, sp_consensus::Error> {
authorities(self.client.as_ref(), &BlockId::Hash(header.hash()))
}
@@ -252,7 +252,7 @@ impl<H, B, C, E, I, P, Error, SO> slots::SimpleSlotWorker<B> for AuraWorker<C, E
expected_author.and_then(|p| {
self.keystore.read()
.key_pair_by_type::<P>(&p, app_crypto::key_types::AURA).ok()
.key_pair_by_type::<P>(&p, sp_application_crypto::key_types::AURA).ok()
})
}
@@ -267,7 +267,7 @@ impl<H, B, C, E, I, P, Error, SO> slots::SimpleSlotWorker<B> for AuraWorker<C, E
&B::Hash,
Vec<B::Extrinsic>,
Self::Claim,
) -> consensus_common::BlockImportParams<B> + Send> {
) -> sp_consensus::BlockImportParams<B> + Send> {
Box::new(|header, header_hash, body, pair| {
// sign the pre-sealed hash of the block and then
// add it to a digest item.
@@ -297,9 +297,9 @@ impl<H, B, C, E, I, P, Error, SO> slots::SimpleSlotWorker<B> for AuraWorker<C, E
&mut self.sync_oracle
}
fn proposer(&mut self, block: &B::Header) -> Result<Self::Proposer, consensus_common::Error> {
fn proposer(&mut self, block: &B::Header) -> Result<Self::Proposer, sp_consensus::Error> {
self.env.init(block).map_err(|e| {
consensus_common::Error::ClientImport(format!("{:?}", e)).into()
sp_consensus::Error::ClientImport(format!("{:?}", e)).into()
})
}
@@ -343,12 +343,12 @@ impl<H, B: BlockT, C, E, I, P, Error, SO> SlotWorker<B> for AuraWorker<C, E, I,
P::Public: Member + Encode + Decode + Hash,
P::Signature: Member + Encode + Decode + Hash + Debug,
SO: SyncOracle + Send + Sync + Clone,
Error: ::std::error::Error + Send + From<::consensus_common::Error> + From<I::Error> + 'static,
Error: ::std::error::Error + Send + From<::sp_consensus::Error> + From<I::Error> + 'static,
{
type OnSlot = Pin<Box<dyn Future<Output = Result<(), consensus_common::Error>> + Send>>;
type OnSlot = Pin<Box<dyn Future<Output = Result<(), sp_consensus::Error>> + Send>>;
fn on_slot(&mut self, chain_head: B::Header, slot_info: SlotInfo) -> Self::OnSlot {
<Self as slots::SimpleSlotWorker<B>>::on_slot(self, chain_head, slot_info)
<Self as sc_consensus_slots::SimpleSlotWorker<B>>::on_slot(self, chain_head, slot_info)
}
}
@@ -416,7 +416,7 @@ fn check_header<C, B: BlockT, P: Pair, T>(
) -> Result<CheckedHeader<B::Header, (u64, DigestItemFor<B>)>, Error<B>> where
DigestItemFor<B>: CompatibleDigestItem<P>,
P::Signature: Decode,
C: client_api::backend::AuxStore,
C: sc_client_api::backend::AuxStore,
P::Public: Encode + Decode + PartialEq + Clone,
T: Send + Sync + 'static,
{
@@ -471,7 +471,7 @@ fn check_header<C, B: BlockT, P: Pair, T>(
pub struct AuraVerifier<C, P, T> {
client: Arc<C>,
phantom: PhantomData<P>,
inherent_data_providers: inherents::InherentDataProviders,
inherent_data_providers: sp_inherents::InherentDataProviders,
transaction_pool: Option<Arc<T>>,
}
@@ -531,7 +531,7 @@ impl<C, P, T> AuraVerifier<C, P, T>
#[forbid(deprecated)]
impl<B: BlockT, C, P, T> Verifier<B> for AuraVerifier<C, P, T> where
C: ProvideRuntimeApi + Send + Sync + client_api::backend::AuxStore + ProvideCache<B> + BlockOf,
C: ProvideRuntimeApi + Send + Sync + sc_client_api::backend::AuxStore + ProvideCache<B> + BlockOf,
C::Api: BlockBuilderApi<B> + AuraApi<B, AuthorityId<P>> + ApiExt<B, Error = sp_blockchain::Error>,
DigestItemFor<B>: CompatibleDigestItem<P>,
P: Pair + Send + Sync + 'static,
@@ -661,7 +661,7 @@ fn initialize_authorities_cache<A, B, C>(client: &C) -> Result<(), ConsensusErro
return Ok(());
}
let map_err = |error| consensus_common::Error::from(consensus_common::Error::ClientImport(
let map_err = |error| sp_consensus::Error::from(sp_consensus::Error::ClientImport(
format!(
"Error initializing authorities cache: {}",
error,
@@ -687,7 +687,7 @@ fn authorities<A, B, C>(client: &C, at: &BlockId<B>) -> Result<Vec<A>, Consensus
.and_then(|(_, _, v)| Decode::decode(&mut &v[..]).ok())
)
.or_else(|| AuraApi::authorities(&*client.runtime_api(), at).ok())
.ok_or_else(|| consensus_common::Error::InvalidAuthoritiesSet.into())
.ok_or_else(|| sp_consensus::Error::InvalidAuthoritiesSet.into())
}
/// The Aura import queue type.
@@ -697,12 +697,12 @@ pub type AuraImportQueue<B> = BasicQueue<B>;
fn register_aura_inherent_data_provider(
inherent_data_providers: &InherentDataProviders,
slot_duration: u64,
) -> Result<(), consensus_common::Error> {
) -> Result<(), sp_consensus::Error> {
if !inherent_data_providers.has_provider(&INHERENT_IDENTIFIER) {
inherent_data_providers
.register_provider(InherentDataProvider::new(slot_duration))
.map_err(Into::into)
.map_err(consensus_common::Error::InherentData)
.map_err(sp_consensus::Error::InherentData)
} else {
Ok(())
}
@@ -717,7 +717,7 @@ pub fn import_queue<B, C, P, T>(
client: Arc<C>,
inherent_data_providers: InherentDataProviders,
transaction_pool: Option<Arc<T>>,
) -> Result<AuraImportQueue<B>, consensus_common::Error> where
) -> Result<AuraImportQueue<B>, sp_consensus::Error> where
B: BlockT,
C: 'static + ProvideRuntimeApi + BlockOf + ProvideCache<B> + Send + Sync + AuxStore,
C::Api: BlockBuilderApi<B> + AuraApi<B, AuthorityId<P>> + ApiExt<B, Error = sp_blockchain::Error>,
@@ -747,24 +747,23 @@ pub fn import_queue<B, C, P, T>(
#[cfg(test)]
mod tests {
use super::*;
use consensus_common::NoNetwork as DummyOracle;
use sp_consensus::NoNetwork as DummyOracle;
use sc_network_test::{Block as TestBlock, *};
use sp_runtime::traits::{Block as BlockT, DigestFor};
use sc_network::config::ProtocolConfig;
use parking_lot::Mutex;
use tokio::runtime::current_thread;
use keyring::sr25519::Keyring;
use client::BlockchainEvents;
use test_client;
use aura_primitives::sr25519::AuthorityPair;
use sp_keyring::sr25519::Keyring;
use sc_client::BlockchainEvents;
use sp_consensus_aura::sr25519::AuthorityPair;
type Error = sp_blockchain::Error;
type TestClient = client::Client<
test_client::Backend,
test_client::Executor,
type TestClient = sc_client::Client<
substrate_test_runtime_client::Backend,
substrate_test_runtime_client::Executor,
TestBlock,
test_client::runtime::RuntimeApi
substrate_test_runtime_client::runtime::RuntimeApi
>;
struct DummyFactory(Arc<TestClient>);
@@ -875,7 +874,7 @@ mod tests {
let client = peer.client().as_full().expect("full clients are created").clone();
let select_chain = peer.select_chain().expect("full client has a select chain");
let keystore_path = tempfile::tempdir().expect("Creates keystore path");
let keystore = keystore::Store::open(keystore_path.path(), None).expect("Creates keystore.");
let keystore = sc_keystore::Store::open(keystore_path.path(), None).expect("Creates keystore.");
keystore.write().insert_ephemeral_from_seed::<AuthorityPair>(&key.to_seed())
.expect("Creates authority key");
@@ -906,7 +905,7 @@ mod tests {
inherent_data_providers,
false,
keystore,
consensus_common::AlwaysCanAuthor,
sp_consensus::AlwaysCanAuthor,
).expect("Starts aura");
runtime.spawn(aura);
@@ -923,7 +922,7 @@ mod tests {
#[test]
fn authorities_call_works() {
let client = test_client::new();
let client = substrate_test_runtime_client::new();
assert_eq!(client.info().chain.best_number, 0);
assert_eq!(authorities(&client, &BlockId::Number(0)).unwrap(), vec![
+16 -16
View File
@@ -7,26 +7,26 @@ edition = "2018"
[dependencies]
codec = { package = "parity-scale-codec", version = "1.0.0", features = ["derive"] }
babe_primitives = { package = "sp-consensus-babe", path = "../../../primitives/consensus/babe" }
primitives = { package = "sp-core", path = "../../../primitives/core" }
app-crypto = { package = "sp-application-crypto", path = "../../../primitives/application-crypto" }
sp-consensus-babe = { path = "../../../primitives/consensus/babe" }
sp-core = { path = "../../../primitives/core" }
sp-application-crypto = { path = "../../../primitives/application-crypto" }
num-bigint = "0.2.3"
num-rational = "0.2.2"
num-traits = "0.2.8"
runtime-version = { package = "sp-version", path = "../../../primitives/version" }
sp-version = { path = "../../../primitives/version" }
sp-io = { path = "../../../primitives/io" }
inherents = { package = "sp-inherents", path = "../../../primitives/inherents" }
sp-inherents = { path = "../../../primitives/inherents" }
sp-timestamp = { path = "../../../primitives/timestamp" }
sc-telemetry = { path = "../../telemetry" }
keystore = { package = "sc-keystore", path = "../../keystore" }
client-api = { package = "sc-client-api", path = "../../api" }
client = { package = "sc-client", path = "../../" }
sc-keystore = { path = "../../keystore" }
sc-client-api = { path = "../../api" }
sc-client = { path = "../../" }
sp-api = { path = "../../../primitives/api" }
block-builder-api = { package = "sp-block-builder", path = "../../../primitives/block-builder" }
sp-block-builder = { path = "../../../primitives/block-builder" }
sp-blockchain = { path = "../../../primitives/blockchain" }
consensus-common = { package = "sp-consensus", path = "../../../primitives/consensus/common" }
uncles = { package = "sc-consensus-uncles", path = "../uncles" }
slots = { package = "sc-consensus-slots", path = "../slots" }
sp-consensus = { path = "../../../primitives/consensus/common" }
sc-consensus-uncles = { path = "../uncles" }
sc-consensus-slots = { path = "../slots" }
sp-runtime = { path = "../../../primitives/runtime" }
fork-tree = { path = "../../../utils/fork-tree" }
futures = { version = "0.3.1", features = ["compat"] }
@@ -41,13 +41,13 @@ pdqselect = "0.1.0"
derive_more = "0.99.2"
[dev-dependencies]
keyring = { package = "sp-keyring", path = "../../../primitives/keyring" }
sp-keyring = { path = "../../../primitives/keyring" }
sc-executor = { path = "../../executor" }
sc-network = { path = "../../network" }
sc-network-test = { path = "../../network/test" }
service = { package = "sc-service", path = "../../service" }
test-client = { package = "substrate-test-runtime-client", path = "../../../test-utils/runtime/client" }
block-builder = { package = "sc-block-builder", path = "../../block-builder" }
sc-service = { path = "../../service" }
substrate-test-runtime-client = { path = "../../../test-utils/runtime/client" }
sc-block-builder = { path = "../../block-builder" }
tokio = "0.1.22"
env_logger = "0.7.0"
tempfile = "3.1.0"
@@ -17,13 +17,13 @@
//! BABE authority selection and slot claiming.
use merlin::Transcript;
use babe_primitives::{AuthorityId, BabeAuthorityWeight, BABE_ENGINE_ID, BABE_VRF_PREFIX};
use babe_primitives::{Epoch, SlotNumber, AuthorityPair, BabePreDigest, BabeConfiguration};
use primitives::{U256, blake2_256};
use sp_consensus_babe::{AuthorityId, BabeAuthorityWeight, BABE_ENGINE_ID, BABE_VRF_PREFIX};
use sp_consensus_babe::{Epoch, SlotNumber, AuthorityPair, BabePreDigest, BabeConfiguration};
use sp_core::{U256, blake2_256};
use codec::Encode;
use schnorrkel::vrf::VRFInOut;
use primitives::Pair;
use keystore::KeyStorePtr;
use sp_core::Pair;
use sc_keystore::KeyStorePtr;
/// Calculates the primary selection threshold for a given authority, taking
/// into account `c` (`1 - c` represents the probability of a slot being empty).
@@ -162,8 +162,8 @@ pub(super) fn claim_slot(
}
fn get_keypair(q: &AuthorityPair) -> &schnorrkel::Keypair {
use primitives::crypto::IsWrappedBy;
primitives::sr25519::Pair::from_ref(q).as_ref()
use sp_core::crypto::IsWrappedBy;
sp_core::sr25519::Pair::from_ref(q).as_ref()
}
/// Claim a primary slot if it is our turn. Returns `None` if it is not our turn.
@@ -19,10 +19,10 @@
use log::info;
use codec::{Decode, Encode};
use client_api::backend::AuxStore;
use sc_client_api::backend::AuxStore;
use sp_blockchain::{Result as ClientResult, Error as ClientError};
use sp_runtime::traits::Block as BlockT;
use babe_primitives::BabeBlockWeight;
use sp_consensus_babe::BabeBlockWeight;
use super::{epoch_changes::EpochChangesFor, SharedEpochChanges};
@@ -20,14 +20,14 @@
//! persistent DAG superimposed over the forks of the blockchain.
use std::sync::Arc;
use babe_primitives::{Epoch, SlotNumber, NextEpochDescriptor};
use sp_consensus_babe::{Epoch, SlotNumber, NextEpochDescriptor};
use fork_tree::ForkTree;
use parking_lot::{Mutex, MutexGuard};
use sp_runtime::traits::{Block as BlockT, NumberFor, One, Zero};
use codec::{Encode, Decode};
use client_api::utils::is_descendent_of;
use sc_client_api::utils::is_descendent_of;
use sp_blockchain::{HeaderMetadata, HeaderBackend, Error as ClientError};
use primitives::H256;
use sp_core::H256;
use std::ops::Add;
/// A builder for `is_descendent_of` functions.
+42 -42
View File
@@ -58,15 +58,15 @@
#![forbid(unsafe_code)]
#![warn(missing_docs)]
pub use babe_primitives::{
pub use sp_consensus_babe::{
BabeApi, ConsensusLog, BABE_ENGINE_ID, BabePreDigest, SlotNumber, BabeConfiguration,
CompatibleDigestItem,
};
pub use consensus_common::SyncOracle;
pub use sp_consensus::SyncOracle;
use std::{collections::HashMap, sync::Arc, u64, pin::Pin, time::{Instant, Duration}};
use babe_primitives;
use consensus_common::{ImportResult, CanAuthorWith};
use consensus_common::import_queue::{
use sp_consensus_babe;
use sp_consensus::{ImportResult, CanAuthorWith};
use sp_consensus::import_queue::{
BoxJustificationImport, BoxFinalityProofImport,
};
use sp_runtime::{generic::{BlockId, OpaqueDigestItemId}, Justification};
@@ -74,32 +74,32 @@ use sp_runtime::traits::{
Block as BlockT, Header, DigestItemFor, ProvideRuntimeApi,
Zero,
};
use keystore::KeyStorePtr;
use sc_keystore::KeyStorePtr;
use parking_lot::Mutex;
use primitives::{Blake2Hasher, H256, Pair};
use inherents::{InherentDataProviders, InherentData};
use sp_core::{Blake2Hasher, H256, Pair};
use sp_inherents::{InherentDataProviders, InherentData};
use sc_telemetry::{telemetry, CONSENSUS_TRACE, CONSENSUS_DEBUG};
use consensus_common::{
use sp_consensus::{
self, BlockImport, Environment, Proposer, BlockCheckParams,
ForkChoiceStrategy, BlockImportParams, BlockOrigin, Error as ConsensusError,
SelectChain, SlotData,
};
use babe_primitives::inherents::BabeInherentData;
use sp_consensus_babe::inherents::BabeInherentData;
use sp_timestamp::{TimestampInherentData, InherentType as TimestampInherent};
use consensus_common::import_queue::{Verifier, BasicQueue, CacheKeyId};
use client_api::{
use sp_consensus::import_queue::{Verifier, BasicQueue, CacheKeyId};
use sc_client_api::{
backend::{AuxStore, Backend},
call_executor::CallExecutor,
BlockchainEvents, ProvideUncles,
};
use client::Client;
use sc_client::Client;
use block_builder_api::BlockBuilder as BlockBuilderApi;
use sp_block_builder::BlockBuilder as BlockBuilderApi;
use slots::{CheckedHeader, check_equivocation};
use sc_consensus_slots::{CheckedHeader, check_equivocation};
use futures::prelude::*;
use log::{warn, debug, info, trace};
use slots::{SlotWorker, SlotInfo, SlotCompatible};
use sc_consensus_slots::{SlotWorker, SlotInfo, SlotCompatible};
use epoch_changes::descendent_query;
use sp_blockchain::{
Result as ClientResult, Error as ClientError,
@@ -115,7 +115,7 @@ mod epoch_changes;
mod authorship;
#[cfg(test)]
mod tests;
pub use babe_primitives::{
pub use sp_consensus_babe::{
AuthorityId, AuthorityPair, AuthoritySignature, Epoch, NextEpochDescriptor,
};
pub use epoch_changes::{EpochChanges, EpochChangesFor, SharedEpochChanges};
@@ -130,7 +130,7 @@ enum Error<B: BlockT> {
#[display(fmt = "Multiple BABE epoch change digests, rejecting!")]
MultipleEpochChangeDigests,
#[display(fmt = "Could not extract timestamp and slot: {:?}", _0)]
Extraction(consensus_common::Error),
Extraction(sp_consensus::Error),
#[display(fmt = "Could not fetch epoch at {:?}", _0)]
FetchEpoch(B::Hash),
#[display(fmt = "Header {:?} rejected: too far in the future", _0)]
@@ -172,7 +172,7 @@ enum Error<B: BlockT> {
#[display(fmt = "Checking inherents failed: {}", _0)]
CheckInherents(String),
Client(sp_blockchain::Error),
Runtime(inherents::Error),
Runtime(sp_inherents::Error),
ForkTree(Box<fork_tree::Error<sp_blockchain::Error>>),
}
@@ -201,7 +201,7 @@ macro_rules! babe_info {
// and `super::babe::Config` can be eliminated.
// https://github.com/paritytech/substrate/issues/2434
#[derive(Clone)]
pub struct Config(slots::SlotDuration<BabeConfiguration>);
pub struct Config(sc_consensus_slots::SlotDuration<BabeConfiguration>);
impl Config {
/// Either fetch the slot duration from disk or compute it from the genesis
@@ -210,7 +210,7 @@ impl Config {
C: AuxStore + ProvideRuntimeApi, C::Api: BabeApi<B, Error = sp_blockchain::Error>,
{
trace!(target: "babe", "Getting slot duration");
match slots::SlotDuration::get_or_compute(client, |a, b| a.configuration(b)).map(Self) {
match sc_consensus_slots::SlotDuration::get_or_compute(client, |a, b| a.configuration(b)).map(Self) {
Ok(s) => Ok(s),
Err(s) => {
warn!(target: "babe", "Failed to get slot duration");
@@ -289,7 +289,7 @@ pub fn start_babe<B, C, SC, E, I, SO, CAW, Error>(BabeParams {
can_author_with,
}: BabeParams<B, C, E, I, SO, SC, CAW>) -> Result<
impl futures01::Future<Item=(), Error=()>,
consensus_common::Error,
sp_consensus::Error,
> where
B: BlockT<Hash=H256>,
C: ProvideRuntimeApi + ProvideCache<B> + ProvideUncles<B> + BlockchainEvents<B>
@@ -300,7 +300,7 @@ pub fn start_babe<B, C, SC, E, I, SO, CAW, Error>(BabeParams {
E::Proposer: Proposer<B, Error=Error>,
<E::Proposer as Proposer<B>>::Create: Unpin + Send + 'static,
I: BlockImport<B,Error=ConsensusError> + Send + Sync + 'static,
Error: std::error::Error + Send + From<::consensus_common::Error> + From<I::Error> + 'static,
Error: std::error::Error + Send + From<::sp_consensus::Error> + From<I::Error> + 'static,
SO: SyncOracle + Send + Sync + Clone,
CAW: CanAuthorWith<B> + Send,
{
@@ -317,14 +317,14 @@ pub fn start_babe<B, C, SC, E, I, SO, CAW, Error>(BabeParams {
};
register_babe_inherent_data_provider(&inherent_data_providers, config.slot_duration())?;
uncles::register_uncles_inherent_data_provider(
sc_consensus_uncles::register_uncles_inherent_data_provider(
client.clone(),
select_chain.clone(),
&inherent_data_providers,
)?;
babe_info!("Starting BABE Authorship worker");
let slot_worker = slots::start_slot_worker(
let slot_worker = sc_consensus_slots::start_slot_worker(
config.0,
select_chain,
worker,
@@ -348,7 +348,7 @@ struct BabeWorker<B: BlockT, C, E, I, SO> {
config: Config,
}
impl<B, C, E, I, Error, SO> slots::SimpleSlotWorker<B> for BabeWorker<B, C, E, I, SO> where
impl<B, C, E, I, Error, SO> sc_consensus_slots::SimpleSlotWorker<B> for BabeWorker<B, C, E, I, SO> where
B: BlockT<Hash=H256>,
C: ProvideRuntimeApi + ProvideCache<B> + HeaderBackend<B> + HeaderMetadata<B, Error=ClientError>,
C::Api: BabeApi<B>,
@@ -357,7 +357,7 @@ impl<B, C, E, I, Error, SO> slots::SimpleSlotWorker<B> for BabeWorker<B, C, E, I
<E::Proposer as Proposer<B>>::Create: Unpin + Send + 'static,
I: BlockImport<B> + Send + Sync + 'static,
SO: SyncOracle + Send + Clone,
Error: std::error::Error + Send + From<::consensus_common::Error> + From<I::Error> + 'static,
Error: std::error::Error + Send + From<::sp_consensus::Error> + From<I::Error> + 'static,
{
type EpochData = Epoch;
type Claim = (BabePreDigest, AuthorityPair);
@@ -373,7 +373,7 @@ impl<B, C, E, I, Error, SO> slots::SimpleSlotWorker<B> for BabeWorker<B, C, E, I
self.block_import.clone()
}
fn epoch_data(&self, parent: &B::Header, slot_number: u64) -> Result<Self::EpochData, consensus_common::Error> {
fn epoch_data(&self, parent: &B::Header, slot_number: u64) -> Result<Self::EpochData, sp_consensus::Error> {
self.epoch_changes.lock().epoch_for_child_of(
descendent_query(&*self.client),
&parent.hash(),
@@ -383,7 +383,7 @@ impl<B, C, E, I, Error, SO> slots::SimpleSlotWorker<B> for BabeWorker<B, C, E, I
)
.map_err(|e| ConsensusError::ChainLookup(format!("{:?}", e)))?
.map(|e| e.into_inner())
.ok_or(consensus_common::Error::InvalidAuthoritiesSet)
.ok_or(sp_consensus::Error::InvalidAuthoritiesSet)
}
fn authorities_len(&self, epoch_data: &Self::EpochData) -> usize {
@@ -422,7 +422,7 @@ impl<B, C, E, I, Error, SO> slots::SimpleSlotWorker<B> for BabeWorker<B, C, E, I
&B::Hash,
Vec<B::Extrinsic>,
Self::Claim,
) -> consensus_common::BlockImportParams<B> + Send> {
) -> sp_consensus::BlockImportParams<B> + Send> {
Box::new(|header, header_hash, body, (_, pair)| {
// sign the pre-sealed hash of the block and then
// add it to a digest item.
@@ -455,9 +455,9 @@ impl<B, C, E, I, Error, SO> slots::SimpleSlotWorker<B> for BabeWorker<B, C, E, I
&mut self.sync_oracle
}
fn proposer(&mut self, block: &B::Header) -> Result<Self::Proposer, consensus_common::Error> {
fn proposer(&mut self, block: &B::Header) -> Result<Self::Proposer, sp_consensus::Error> {
self.env.init(block).map_err(|e| {
consensus_common::Error::ClientImport(format!("{:?}", e))
sp_consensus::Error::ClientImport(format!("{:?}", e))
})
}
@@ -510,12 +510,12 @@ impl<B, C, E, I, Error, SO> SlotWorker<B> for BabeWorker<B, C, E, I, SO> where
<E::Proposer as Proposer<B>>::Create: Unpin + Send + 'static,
I: BlockImport<B> + Send + Sync + 'static,
SO: SyncOracle + Send + Sync + Clone,
Error: std::error::Error + Send + From<::consensus_common::Error> + From<I::Error> + 'static,
Error: std::error::Error + Send + From<::sp_consensus::Error> + From<I::Error> + 'static,
{
type OnSlot = Pin<Box<dyn Future<Output = Result<(), consensus_common::Error>> + Send>>;
type OnSlot = Pin<Box<dyn Future<Output = Result<(), sp_consensus::Error>> + Send>>;
fn on_slot(&mut self, chain_head: B::Header, slot_info: SlotInfo) -> Self::OnSlot {
<Self as slots::SimpleSlotWorker<B>>::on_slot(self, chain_head, slot_info)
<Self as sc_consensus_slots::SimpleSlotWorker<B>>::on_slot(self, chain_head, slot_info)
}
}
@@ -571,12 +571,12 @@ impl SlotCompatible for TimeSource {
fn extract_timestamp_and_slot(
&self,
data: &InherentData,
) -> Result<(TimestampInherent, u64, std::time::Duration), consensus_common::Error> {
) -> Result<(TimestampInherent, u64, std::time::Duration), sp_consensus::Error> {
trace!(target: "babe", "extract timestamp");
data.timestamp_inherent_data()
.and_then(|t| data.babe_inherent_data().map(|a| (t, a)))
.map_err(Into::into)
.map_err(consensus_common::Error::InherentData)
.map_err(sp_consensus::Error::InherentData)
.map(|(x, y)| (x, y, self.0.lock().0.take().unwrap_or_default()))
}
}
@@ -592,7 +592,7 @@ pub struct BabeLink<Block: BlockT> {
pub struct BabeVerifier<B, E, Block: BlockT, RA, PRA> {
client: Arc<Client<B, E, Block, RA>>,
api: Arc<PRA>,
inherent_data_providers: inherents::InherentDataProviders,
inherent_data_providers: sp_inherents::InherentDataProviders,
config: Config,
epoch_changes: SharedEpochChanges<Block>,
time_source: TimeSource,
@@ -818,13 +818,13 @@ pub type BabeImportQueue<B> = BasicQueue<B>;
fn register_babe_inherent_data_provider(
inherent_data_providers: &InherentDataProviders,
slot_duration: u64,
) -> Result<(), consensus_common::Error> {
) -> Result<(), sp_consensus::Error> {
debug!(target: "babe", "Registering");
if !inherent_data_providers.has_provider(&babe_primitives::inherents::INHERENT_IDENTIFIER) {
if !inherent_data_providers.has_provider(&sp_consensus_babe::inherents::INHERENT_IDENTIFIER) {
inherent_data_providers
.register_provider(babe_primitives::inherents::InherentDataProvider::new(slot_duration))
.register_provider(sp_consensus_babe::inherents::InherentDataProvider::new(slot_duration))
.map_err(Into::into)
.map_err(consensus_common::Error::InherentData)
.map_err(sp_consensus::Error::InherentData)
} else {
Ok(())
}
+16 -17
View File
@@ -22,10 +22,10 @@
use super::*;
use authorship::claim_slot;
use babe_primitives::{AuthorityPair, SlotNumber};
use block_builder::BlockBuilder;
use consensus_common::NoNetwork as DummyOracle;
use consensus_common::import_queue::{
use sp_consensus_babe::{AuthorityPair, SlotNumber};
use sc_block_builder::BlockBuilder;
use sp_consensus::NoNetwork as DummyOracle;
use sp_consensus::import_queue::{
BoxBlockImport, BoxJustificationImport, BoxFinalityProofImport,
};
use sc_network_test::*;
@@ -33,8 +33,7 @@ use sc_network_test::{Block as TestBlock, PeersClient};
use sc_network::config::{BoxFinalityProofRequestBuilder, ProtocolConfig};
use sp_runtime::{generic::DigestItem, traits::{Block as BlockT, DigestFor}};
use tokio::runtime::current_thread;
use client_api::BlockchainEvents;
use test_client;
use sc_client_api::BlockchainEvents;
use log::debug;
use std::{time::Duration, cell::RefCell};
@@ -42,11 +41,11 @@ type Item = DigestItem<Hash>;
type Error = sp_blockchain::Error;
type TestClient = client::Client<
test_client::Backend,
test_client::Executor,
type TestClient = sc_client::Client<
substrate_test_runtime_client::Backend,
substrate_test_runtime_client::Executor,
TestBlock,
test_client::runtime::RuntimeApi,
substrate_test_runtime_client::runtime::RuntimeApi,
>;
#[derive(Copy, Clone, PartialEq)]
@@ -196,10 +195,10 @@ type TestExtrinsic = <TestBlock as BlockT>::Extrinsic;
pub struct TestVerifier {
inner: BabeVerifier<
test_client::Backend,
test_client::Executor,
substrate_test_runtime_client::Backend,
substrate_test_runtime_client::Executor,
TestBlock,
test_client::runtime::RuntimeApi,
substrate_test_runtime_client::runtime::RuntimeApi,
PeersFullClient,
>,
mutator: Mutator,
@@ -358,7 +357,7 @@ fn run_one_test(
let select_chain = peer.select_chain().expect("Full client has select_chain");
let keystore_path = tempfile::tempdir().expect("Creates keystore path");
let keystore = keystore::Store::open(keystore_path.path(), None).expect("Creates keystore");
let keystore = sc_keystore::Store::open(keystore_path.path(), None).expect("Creates keystore");
keystore.write().insert_ephemeral_from_seed::<AuthorityPair>(seed).expect("Generates authority key");
keystore_paths.push(keystore_path);
@@ -403,7 +402,7 @@ fn run_one_test(
force_authoring: false,
babe_link: data.link.clone(),
keystore,
can_author_with: consensus_common::AlwaysCanAuthor,
can_author_with: sp_consensus::AlwaysCanAuthor,
}).expect("Starts babe"));
}
@@ -483,7 +482,7 @@ fn sig_is_not_pre_digest() {
fn can_author_block() {
let _ = env_logger::try_init();
let keystore_path = tempfile::tempdir().expect("Creates keystore path");
let keystore = keystore::Store::open(keystore_path.path(), None).expect("Creates keystore");
let keystore = sc_keystore::Store::open(keystore_path.path(), None).expect("Creates keystore");
let pair = keystore.write().insert_ephemeral_from_seed::<AuthorityPair>("//Alice")
.expect("Generates authority pair");
@@ -634,7 +633,7 @@ fn importing_block_one_sets_genesis_epoch() {
#[test]
fn importing_epoch_change_block_prunes_tree() {
use client_api::Finalizer;
use sc_client_api::Finalizer;
let mut net = BabeTestNet::new(1);
@@ -17,10 +17,10 @@
//! Verification for BABE headers.
use schnorrkel::vrf::{VRFOutput, VRFProof};
use sp_runtime::{traits::Header, traits::DigestItemFor};
use primitives::{Pair, Public};
use babe_primitives::{Epoch, BabePreDigest, CompatibleDigestItem, AuthorityId};
use babe_primitives::{AuthoritySignature, SlotNumber, AuthorityIndex, AuthorityPair};
use slots::CheckedHeader;
use sp_core::{Pair, Public};
use sp_consensus_babe::{Epoch, BabePreDigest, CompatibleDigestItem, AuthorityId};
use sp_consensus_babe::{AuthoritySignature, SlotNumber, AuthorityIndex, AuthorityPair};
use sc_consensus_slots::CheckedHeader;
use log::{debug, trace};
use super::{find_pre_digest, babe_err, BlockT, Error};
use super::authorship::{make_transcript, calculate_primary_threshold, check_primary_threshold, secondary_slot_author};
+6 -6
View File
@@ -7,14 +7,14 @@ edition = "2018"
[dependencies]
codec = { package = "parity-scale-codec", version = "1.0.0", features = ["derive"] }
primitives = { package = "sp-core", path = "../../../primitives/core" }
sp-core = { path = "../../../primitives/core" }
sp-blockchain = { path = "../../../primitives/blockchain" }
sp-runtime = { path = "../../../primitives/runtime" }
client-api = { package = "sc-client-api", path = "../../api" }
block-builder-api = { package = "sp-block-builder", path = "../../../primitives/block-builder" }
inherents = { package = "sp-inherents", path = "../../../primitives/inherents" }
pow-primitives = { package = "sp-consensus-pow", path = "../../../primitives/consensus/pow" }
consensus-common = { package = "sp-consensus", path = "../../../primitives/consensus/common" }
sc-client-api = { path = "../../api" }
sp-block-builder = { path = "../../../primitives/block-builder" }
sp-inherents = { path = "../../../primitives/inherents" }
sp-consensus-pow = { path = "../../../primitives/consensus/pow" }
sp-consensus = { path = "../../../primitives/consensus/common" }
log = "0.4.8"
futures = { version = "0.3.1", features = ["compat"] }
sp-timestamp = { path = "../../../primitives/timestamp" }
+16 -16
View File
@@ -32,23 +32,23 @@
use std::sync::Arc;
use std::thread;
use std::collections::HashMap;
use client_api::{BlockOf, backend::AuxStore};
use sc_client_api::{BlockOf, backend::AuxStore};
use sp_blockchain::{HeaderBackend, ProvideCache, well_known_cache_keys::Id as CacheKeyId};
use block_builder_api::BlockBuilder as BlockBuilderApi;
use sp_block_builder::BlockBuilder as BlockBuilderApi;
use sp_runtime::{Justification, RuntimeString};
use sp_runtime::generic::{BlockId, Digest, DigestItem};
use sp_runtime::traits::{Block as BlockT, Header as HeaderT, ProvideRuntimeApi};
use sp_timestamp::{TimestampInherentData, InherentError as TIError};
use pow_primitives::{Seal, TotalDifficulty, POW_ENGINE_ID};
use primitives::H256;
use inherents::{InherentDataProviders, InherentData};
use consensus_common::{
use sp_consensus_pow::{Seal, TotalDifficulty, POW_ENGINE_ID};
use sp_core::H256;
use sp_inherents::{InherentDataProviders, InherentData};
use sp_consensus::{
BlockImportParams, BlockOrigin, ForkChoiceStrategy, SyncOracle, Environment, Proposer,
SelectChain, Error as ConsensusError, CanAuthorWith,
};
use consensus_common::import_queue::{BoxBlockImport, BasicQueue, Verifier};
use sp_consensus::import_queue::{BoxBlockImport, BasicQueue, Verifier};
use codec::{Encode, Decode};
use client_api;
use sc_client_api;
use log::*;
#[derive(derive_more::Display, Debug)]
@@ -74,7 +74,7 @@ pub enum Error<B: BlockT> {
#[display(fmt = "Error with block built on {:?}: {:?}", _0, _1)]
BlockBuiltError(B::Hash, ConsensusError),
#[display(fmt = "Creating inherents failed: {}", _0)]
CreateInherents(inherents::Error),
CreateInherents(sp_inherents::Error),
#[display(fmt = "Checking inherents failed: {}", _0)]
CheckInherents(String),
Client(sp_blockchain::Error),
@@ -151,7 +151,7 @@ pub trait PowAlgorithm<B: BlockT> {
pub struct PowVerifier<B: BlockT<Hash=H256>, C, S, Algorithm> {
client: Arc<C>,
algorithm: Algorithm,
inherent_data_providers: inherents::InherentDataProviders,
inherent_data_providers: sp_inherents::InherentDataProviders,
select_chain: Option<S>,
check_inherents_after: <<B as BlockT>::Header as HeaderT>::Number,
}
@@ -162,7 +162,7 @@ impl<B: BlockT<Hash=H256>, C, S, Algorithm> PowVerifier<B, C, S, Algorithm> {
algorithm: Algorithm,
check_inherents_after: <<B as BlockT>::Header as HeaderT>::Number,
select_chain: Option<S>,
inherent_data_providers: inherents::InherentDataProviders,
inherent_data_providers: sp_inherents::InherentDataProviders,
) -> Self {
Self { client, algorithm, inherent_data_providers, select_chain, check_inherents_after }
}
@@ -314,12 +314,12 @@ impl<B: BlockT<Hash=H256>, C, S, Algorithm> Verifier<B> for PowVerifier<B, C, S,
/// Register the PoW inherent data provider, if not registered already.
pub fn register_pow_inherent_data_provider(
inherent_data_providers: &InherentDataProviders,
) -> Result<(), consensus_common::Error> {
) -> Result<(), sp_consensus::Error> {
if !inherent_data_providers.has_provider(&sp_timestamp::INHERENT_IDENTIFIER) {
inherent_data_providers
.register_provider(sp_timestamp::InherentDataProvider)
.map_err(Into::into)
.map_err(consensus_common::Error::InherentData)
.map_err(sp_consensus::Error::InherentData)
} else {
Ok(())
}
@@ -336,7 +336,7 @@ pub fn import_queue<B, C, S, Algorithm>(
check_inherents_after: <<B as BlockT>::Header as HeaderT>::Number,
select_chain: Option<S>,
inherent_data_providers: InherentDataProviders,
) -> Result<PowImportQueue<B>, consensus_common::Error> where
) -> Result<PowImportQueue<B>, sp_consensus::Error> where
B: BlockT<Hash=H256>,
C: ProvideRuntimeApi + HeaderBackend<B> + BlockOf + ProvideCache<B> + AuxStore,
C: Send + Sync + AuxStore + 'static,
@@ -382,7 +382,7 @@ pub fn start_mine<B: BlockT<Hash=H256>, C, Algorithm, E, SO, S, CAW>(
mut sync_oracle: SO,
build_time: std::time::Duration,
select_chain: Option<S>,
inherent_data_providers: inherents::InherentDataProviders,
inherent_data_providers: sp_inherents::InherentDataProviders,
can_author_with: CAW,
) where
C: HeaderBackend<B> + AuxStore + 'static,
@@ -433,7 +433,7 @@ fn mine_loop<B: BlockT<Hash=H256>, C, Algorithm, E, SO, S, CAW>(
sync_oracle: &mut SO,
build_time: std::time::Duration,
select_chain: Option<&S>,
inherent_data_providers: &inherents::InherentDataProviders,
inherent_data_providers: &sp_inherents::InherentDataProviders,
can_author_with: &CAW,
) -> Result<(), Error<B>> where
C: HeaderBackend<B> + AuxStore,
+5 -5
View File
@@ -8,17 +8,17 @@ build = "build.rs"
[dependencies]
codec = { package = "parity-scale-codec", version = "1.0.0" }
client-api = { package = "sc-client-api", path = "../../api" }
primitives = { package = "sp-core", path = "../../../primitives/core" }
sc-client-api = { path = "../../api" }
sp-core = { path = "../../../primitives/core" }
sp-blockchain = { path = "../../../primitives/blockchain" }
sp-runtime = { path = "../../../primitives/runtime" }
sc-telemetry = { path = "../../telemetry" }
consensus_common = { package = "sp-consensus", path = "../../../primitives/consensus/common" }
inherents = { package = "sp-inherents", path = "../../../primitives/inherents" }
sp-consensus = { path = "../../../primitives/consensus/common" }
sp-inherents = { path = "../../../primitives/inherents" }
futures = "0.3.1"
futures-timer = "2.0"
parking_lot = "0.9.0"
log = "0.4.8"
[dev-dependencies]
test-client = { package = "substrate-test-runtime-client", path = "../../../test-utils/runtime/client" }
substrate-test-runtime-client = { path = "../../../test-utils/runtime/client" }
@@ -17,7 +17,7 @@
//! Schema for slots in the aux-db.
use codec::{Encode, Decode};
use client_api::backend::AuxStore;
use sc_client_api::backend::AuxStore;
use sp_blockchain::{Result as ClientResult, Error as ClientError};
use sp_runtime::traits::Header;
@@ -151,10 +151,10 @@ pub fn check_equivocation<C, H, P>(
#[cfg(test)]
mod test {
use primitives::{sr25519, Pair};
use primitives::hash::H256;
use sp_core::{sr25519, Pair};
use sp_core::hash::H256;
use sp_runtime::testing::{Header as HeaderTest, Digest as DigestTest};
use test_client;
use substrate_test_runtime_client;
use super::{MAX_SLOT_CAPACITY, PRUNING_BOUND, check_equivocation};
@@ -175,7 +175,7 @@ mod test {
#[test]
fn check_equivocation_works() {
let client = test_client::new();
let client = substrate_test_runtime_client::new();
let (pair, _seed) = sr25519::Pair::generate();
let public = pair.public();
+12 -12
View File
@@ -31,23 +31,23 @@ use slots::Slots;
pub use aux_schema::{check_equivocation, MAX_SLOT_CAPACITY, PRUNING_BOUND};
use codec::{Decode, Encode};
use consensus_common::{BlockImport, Proposer, SyncOracle, SelectChain, CanAuthorWith, SlotData};
use sp_consensus::{BlockImport, Proposer, SyncOracle, SelectChain, CanAuthorWith, SlotData};
use futures::{prelude::*, future::{self, Either}};
use futures_timer::Delay;
use inherents::{InherentData, InherentDataProviders};
use sp_inherents::{InherentData, InherentDataProviders};
use log::{debug, error, info, warn};
use sp_runtime::generic::BlockId;
use sp_runtime::traits::{ApiRef, Block as BlockT, Header, ProvideRuntimeApi};
use std::{fmt::Debug, ops::Deref, pin::Pin, sync::Arc, time::{Instant, Duration}};
use sc_telemetry::{telemetry, CONSENSUS_DEBUG, CONSENSUS_WARN, CONSENSUS_INFO};
use parking_lot::Mutex;
use client_api;
use sc_client_api;
/// A worker that should be invoked at every new slot.
pub trait SlotWorker<B: BlockT> {
/// The type of the future that will be returned when a new slot is
/// triggered.
type OnSlot: Future<Output = Result<(), consensus_common::Error>>;
type OnSlot: Future<Output = Result<(), sp_consensus::Error>>;
/// Called when a new slot is triggered.
fn on_slot(&mut self, chain_head: B::Header, slot_info: SlotInfo) -> Self::OnSlot;
@@ -80,7 +80,7 @@ pub trait SimpleSlotWorker<B: BlockT> {
/// Returns the epoch data necessary for authoring. For time-dependent epochs,
/// use the provided slot number as a canonical source of time.
fn epoch_data(&self, header: &B::Header, slot_number: u64) -> Result<Self::EpochData, consensus_common::Error>;
fn epoch_data(&self, header: &B::Header, slot_number: u64) -> Result<Self::EpochData, sp_consensus::Error>;
/// Returns the number of authorities given the epoch data.
fn authorities_len(&self, epoch_data: &Self::EpochData) -> usize;
@@ -102,7 +102,7 @@ pub trait SimpleSlotWorker<B: BlockT> {
&B::Hash,
Vec<B::Extrinsic>,
Self::Claim,
) -> consensus_common::BlockImportParams<B> + Send>;
) -> sp_consensus::BlockImportParams<B> + Send>;
/// Whether to force authoring if offline.
fn force_authoring(&self) -> bool;
@@ -111,7 +111,7 @@ pub trait SimpleSlotWorker<B: BlockT> {
fn sync_oracle(&mut self) -> &mut Self::SyncOracle;
/// Returns a `Proposer` to author on top of the given block.
fn proposer(&mut self, block: &B::Header) -> Result<Self::Proposer, consensus_common::Error>;
fn proposer(&mut self, block: &B::Header) -> Result<Self::Proposer, sp_consensus::Error>;
/// Remaining duration of the slot.
fn slot_remaining_duration(&self, slot_info: &SlotInfo) -> Duration {
@@ -134,7 +134,7 @@ pub trait SimpleSlotWorker<B: BlockT> {
/// Implements the `on_slot` functionality from `SlotWorker`.
fn on_slot(&mut self, chain_head: B::Header, slot_info: SlotInfo)
-> Pin<Box<dyn Future<Output = Result<(), consensus_common::Error>> + Send>> where
-> Pin<Box<dyn Future<Output = Result<(), sp_consensus::Error>> + Send>> where
Self: Send + Sync,
<Self::Proposer as Proposer<B>>::Create: Unpin + Send + 'static,
{
@@ -222,7 +222,7 @@ pub trait SimpleSlotWorker<B: BlockT> {
logs,
},
slot_remaining_duration,
).map_err(|e| consensus_common::Error::ClientImport(format!("{:?}", e)));
).map_err(|e| sp_consensus::Error::ClientImport(format!("{:?}", e)));
let delay: Box<dyn Future<Output=()> + Unpin + Send> = match proposing_remaining_duration {
Some(r) => Box::new(Delay::new(r)),
None => Box::new(future::pending()),
@@ -239,7 +239,7 @@ pub trait SimpleSlotWorker<B: BlockT> {
telemetry!(CONSENSUS_INFO; "slots.discarding_proposal_took_too_long";
"slot" => slot_number,
);
Err(consensus_common::Error::ClientImport("Timeout in the Slots proposer".into()))
Err(sp_consensus::Error::ClientImport("Timeout in the Slots proposer".into()))
},
}));
@@ -293,7 +293,7 @@ pub trait SlotCompatible {
fn extract_timestamp_and_slot(
&self,
inherent: &InherentData,
) -> Result<(u64, u64, std::time::Duration), consensus_common::Error>;
) -> Result<(u64, u64, std::time::Duration), sp_consensus::Error>;
/// Get the difference between chain time and local time. Defaults to
/// always returning zero.
@@ -417,7 +417,7 @@ impl<T: Clone> SlotDuration<T> {
/// `slot_key` is marked as `'static`, as it should really be a
/// compile-time constant.
pub fn get_or_compute<B: BlockT, C, CB>(client: &C, cb: CB) -> sp_blockchain::Result<Self> where
C: client_api::backend::AuxStore,
C: sc_client_api::backend::AuxStore,
C: ProvideRuntimeApi,
CB: FnOnce(ApiRef<C::Api>, &BlockId<B>) -> sp_blockchain::Result<T>,
T: SlotData + Encode + Decode + Debug,
@@ -19,9 +19,9 @@
//! This is used instead of `futures_timer::Interval` because it was unreliable.
use super::SlotCompatible;
use consensus_common::Error;
use sp_consensus::Error;
use futures::{prelude::*, task::Context, task::Poll};
use inherents::{InherentData, InherentDataProviders};
use sp_inherents::{InherentData, InherentDataProviders};
use std::{pin::Pin, time::{Duration, Instant}};
use futures_timer::Delay;
@@ -135,7 +135,7 @@ impl<SC: SlotCompatible + Unpin> Stream for Slots<SC> {
let inherent_data = match self.inherent_data_providers.create_inherent_data() {
Ok(id) => id,
Err(err) => return Poll::Ready(Some(Err(consensus_common::Error::InherentData(err)))),
Err(err) => return Poll::Ready(Some(Err(sp_consensus::Error::InherentData(err)))),
};
let result = self.timestamp_extractor.extract_timestamp_and_slot(&inherent_data);
let (timestamp, slot_num, offset) = match result {
+4 -4
View File
@@ -6,10 +6,10 @@ description = "Generic uncle inclusion utilities for consensus"
edition = "2018"
[dependencies]
client-api = { package = "sc-client-api", path = "../../api" }
primitives = { package = "sp-core", path = "../../../primitives/core" }
sc-client-api = { path = "../../api" }
sp-core = { path = "../../../primitives/core" }
sp-runtime = { path = "../../../primitives/runtime" }
sp-authorship = { path = "../../../primitives/authorship" }
consensus_common = { package = "sp-consensus", path = "../../../primitives/consensus/common" }
inherents = { package = "sp-inherents", path = "../../../primitives/inherents" }
sp-consensus = { path = "../../../primitives/consensus/common" }
sp-inherents = { path = "../../../primitives/inherents" }
log = "0.4.8"
+5 -5
View File
@@ -19,10 +19,10 @@
#![deny(warnings)]
#![forbid(unsafe_code, missing_docs)]
use consensus_common::SelectChain;
use inherents::{InherentDataProviders};
use sp_consensus::SelectChain;
use sp_inherents::{InherentDataProviders};
use log::warn;
use client_api::ProvideUncles;
use sc_client_api::ProvideUncles;
use sp_runtime::traits::{Block as BlockT, Header};
use std::sync::Arc;
use sp_authorship;
@@ -35,7 +35,7 @@ pub fn register_uncles_inherent_data_provider<B, C, SC>(
client: Arc<C>,
select_chain: SC,
inherent_data_providers: &InherentDataProviders,
) -> Result<(), consensus_common::Error> where
) -> Result<(), sp_consensus::Error> where
B: BlockT,
C: ProvideUncles<B> + Send + Sync + 'static,
SC: SelectChain<B> + 'static,
@@ -60,7 +60,7 @@ pub fn register_uncles_inherent_data_provider<B, C, SC>(
}
}
}))
.map_err(|err| consensus_common::Error::InherentData(err.into()))?;
.map_err(|err| sp_consensus::Error::InherentData(err.into()))?;
}
Ok(())
}
+9 -9
View File
@@ -12,21 +12,21 @@ kvdb-rocksdb = { version = "0.2", optional = true }
kvdb-memorydb = "0.1.2"
linked-hash-map = "0.5.2"
hash-db = "0.15.2"
client-api = { package = "sc-client-api", path = "../api" }
primitives = { package = "sp-core", path = "../../primitives/core" }
sc-client-api = { path = "../api" }
sp-core = { path = "../../primitives/core" }
sp-runtime = { path = "../../primitives/runtime" }
client = { package = "sc-client", path = "../" }
state-machine = { package = "sp-state-machine", path = "../../primitives/state-machine" }
sc-client = { path = "../" }
sp-state-machine = { path = "../../primitives/state-machine" }
codec = { package = "parity-scale-codec", version = "1.0.0", features = ["derive"] }
executor = { package = "sc-executor", path = "../executor" }
state_db = { package = "sc-state-db", path = "../state-db" }
trie = { package = "sp-trie", path = "../../primitives/trie" }
consensus_common = { package = "sp-consensus", path = "../../primitives/consensus/common" }
sc-executor = { path = "../executor" }
sc-state-db = { path = "../state-db" }
sp-trie = { path = "../../primitives/trie" }
sp-consensus = { path = "../../primitives/consensus/common" }
sp-blockchain = { path = "../../primitives/blockchain" }
[dev-dependencies]
sp-keyring = { path = "../../primitives/keyring" }
test-client = { package = "substrate-test-runtime-client", path = "../../test-utils/runtime/client" }
substrate-test-runtime-client = { path = "../../test-utils/runtime/client" }
env_logger = "0.7.0"
quickcheck = "0.9"
+1 -1
View File
@@ -724,7 +724,7 @@ fn read_forks<Block: BlockT, T: CacheItemT, S: Storage<Block, T>>(
#[cfg(test)]
pub mod tests {
use test_client::runtime::H256;
use substrate_test_runtime_client::runtime::H256;
use sp_runtime::testing::{Header, Block as RawBlock, ExtrinsicWrapper};
use sp_runtime::traits::Header as HeaderT;
use crate::cache::list_storage::tests::{DummyStorage, FaultyStorage, DummyTransaction};
+1 -1
View File
@@ -21,7 +21,7 @@ use parking_lot::RwLock;
use kvdb::{KeyValueDB, DBTransaction};
use client_api::blockchain::{well_known_cache_keys::{self, Id as CacheKeyId}, Cache as BlockchainCache};
use sc_client_api::blockchain::{well_known_cache_keys::{self, Id as CacheKeyId}, Cache as BlockchainCache};
use sp_blockchain::Result as ClientResult;
use codec::{Encode, Decode};
use sp_runtime::generic::BlockId;
+84 -86
View File
@@ -39,9 +39,9 @@ use std::path::PathBuf;
use std::io;
use std::collections::{HashMap, HashSet};
use client_api::{execution_extensions::ExecutionExtensions, ForkBlocks};
use client_api::backend::NewBlockState;
use client_api::backend::{StorageCollection, ChildStorageCollection};
use sc_client_api::{execution_extensions::ExecutionExtensions, ForkBlocks};
use sc_client_api::backend::NewBlockState;
use sc_client_api::backend::{StorageCollection, ChildStorageCollection};
use sp_blockchain::{
Result as ClientResult, Error as ClientError,
well_known_cache_keys, HeaderBackend,
@@ -49,10 +49,10 @@ use sp_blockchain::{
use codec::{Decode, Encode};
use hash_db::{Hasher, Prefix};
use kvdb::{KeyValueDB, DBTransaction};
use trie::{MemoryDB, PrefixedMemoryDB, prefixed_key};
use sp_trie::{MemoryDB, PrefixedMemoryDB, prefixed_key};
use parking_lot::{Mutex, RwLock};
use primitives::{H256, Blake2Hasher, ChangesTrieConfiguration, convert_hash, traits::CodeExecutor};
use primitives::storage::{well_known_keys, ChildInfo};
use sp_core::{H256, Blake2Hasher, ChangesTrieConfiguration, convert_hash, traits::CodeExecutor};
use sp_core::storage::{well_known_keys, ChildInfo};
use sp_runtime::{
generic::{BlockId, DigestItem}, Justification, Storage,
BuildStorage,
@@ -60,21 +60,21 @@ use sp_runtime::{
use sp_runtime::traits::{
Block as BlockT, Header as HeaderT, NumberFor, Zero, One, SaturatedConversion
};
use executor::RuntimeInfo;
use state_machine::{
use sc_executor::RuntimeInfo;
use sp_state_machine::{
DBValue, ChangesTrieTransaction, ChangesTrieCacheAction, ChangesTrieBuildCache,
backend::Backend as StateBackend,
};
use crate::utils::{Meta, db_err, meta_keys, read_db, read_meta};
use client::leaves::{LeafSet, FinalizationDisplaced};
use state_db::StateDb;
use sc_client::leaves::{LeafSet, FinalizationDisplaced};
use sc_state_db::StateDb;
use sp_blockchain::{CachedHeaderMetadata, HeaderMetadata, HeaderMetadataCache};
use crate::storage_cache::{CachingState, SharedCache, new_shared_cache};
use log::{trace, debug, warn};
pub use state_db::PruningMode;
pub use sc_state_db::PruningMode;
#[cfg(feature = "test-helpers")]
use client::in_mem::Backend as InMemoryBackend;
use sc_client::in_mem::Backend as InMemoryBackend;
const CANONICALIZATION_DELAY: u64 = 4096;
const MIN_BLOCKS_TO_KEEP_CHANGES_TRIES_FOR: u32 = 32768;
@@ -83,7 +83,7 @@ const MIN_BLOCKS_TO_KEEP_CHANGES_TRIES_FOR: u32 = 32768;
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 = state_machine::TrieBackend<Arc<dyn state_machine::Storage<Blake2Hasher>>, Blake2Hasher>;
pub type DbState = sp_state_machine::TrieBackend<Arc<dyn sp_state_machine::Storage<Blake2Hasher>>, Blake2Hasher>;
/// Re-export the KVDB trait so that one can pass an implementation of it.
pub use kvdb;
@@ -239,7 +239,7 @@ impl<B: BlockT> StateBackend<Blake2Hasher> for RefTrackingState<B> {
fn as_trie_backend(
&mut self,
) -> Option<&state_machine::TrieBackend<Self::TrieBackendStorage, Blake2Hasher>> {
) -> Option<&sp_state_machine::TrieBackend<Self::TrieBackendStorage, Blake2Hasher>> {
self.state.as_trie_backend()
}
}
@@ -278,9 +278,9 @@ pub fn new_client<E, S, Block, RA>(
fork_blocks: ForkBlocks<Block>,
execution_extensions: ExecutionExtensions<Block>,
) -> Result<(
client::Client<
sc_client::Client<
Backend<Block>,
client::LocalCallExecutor<Backend<Block>, E>,
sc_client::LocalCallExecutor<Backend<Block>, E>,
Block,
RA,
>,
@@ -294,9 +294,9 @@ pub fn new_client<E, S, Block, RA>(
S: BuildStorage,
{
let backend = Arc::new(Backend::new(settings, CANONICALIZATION_DELAY)?);
let executor = client::LocalCallExecutor::new(backend.clone(), executor);
let executor = sc_client::LocalCallExecutor::new(backend.clone(), executor);
Ok((
client::Client::new(backend.clone(), executor, genesis_storage, fork_blocks, execution_extensions)?,
sc_client::Client::new(backend.clone(), executor, genesis_storage, fork_blocks, execution_extensions)?,
backend,
))
}
@@ -326,7 +326,7 @@ struct PendingBlock<Block: BlockT> {
// wrapper that implements trait required for state_db
struct StateMetaDb<'a>(&'a dyn KeyValueDB);
impl<'a> state_db::MetaDb for StateMetaDb<'a> {
impl<'a> sc_state_db::MetaDb for StateMetaDb<'a> {
type Error = io::Error;
fn get_meta(&self, key: &[u8]) -> Result<Option<Vec<u8>>, Self::Error> {
@@ -379,14 +379,14 @@ impl<Block: BlockT> BlockchainDb<Block> {
}
}
impl<Block: BlockT> client::blockchain::HeaderBackend<Block> for BlockchainDb<Block> {
impl<Block: BlockT> sc_client::blockchain::HeaderBackend<Block> for BlockchainDb<Block> {
fn header(&self, id: BlockId<Block>) -> ClientResult<Option<Block::Header>> {
utils::read_header(&*self.db, columns::KEY_LOOKUP, columns::HEADER, id)
}
fn info(&self) -> client::blockchain::Info<Block> {
fn info(&self) -> sc_client::blockchain::Info<Block> {
let meta = self.meta.read();
client::blockchain::Info {
sc_client::blockchain::Info {
best_hash: meta.best_hash,
best_number: meta.best_number,
genesis_hash: meta.genesis_hash,
@@ -395,7 +395,7 @@ impl<Block: BlockT> client::blockchain::HeaderBackend<Block> for BlockchainDb<Bl
}
}
fn status(&self, id: BlockId<Block>) -> ClientResult<client::blockchain::BlockStatus> {
fn status(&self, id: BlockId<Block>) -> ClientResult<sc_client::blockchain::BlockStatus> {
let exists = match id {
BlockId::Hash(_) => read_db(
&*self.db,
@@ -406,8 +406,8 @@ impl<Block: BlockT> client::blockchain::HeaderBackend<Block> for BlockchainDb<Bl
BlockId::Number(n) => n <= self.meta.read().best_number,
};
match exists {
true => Ok(client::blockchain::BlockStatus::InChain),
false => Ok(client::blockchain::BlockStatus::Unknown),
true => Ok(sc_client::blockchain::BlockStatus::InChain),
false => Ok(sc_client::blockchain::BlockStatus::Unknown),
}
}
@@ -423,7 +423,7 @@ impl<Block: BlockT> client::blockchain::HeaderBackend<Block> for BlockchainDb<Bl
}
}
impl<Block: BlockT> client::blockchain::Backend<Block> for BlockchainDb<Block> {
impl<Block: BlockT> sc_client::blockchain::Backend<Block> for BlockchainDb<Block> {
fn body(&self, id: BlockId<Block>) -> ClientResult<Option<Vec<Block::Extrinsic>>> {
match read_db(&*self.db, columns::KEY_LOOKUP, columns::BODY, id)? {
Some(body) => match Decode::decode(&mut &body[..]) {
@@ -452,7 +452,7 @@ impl<Block: BlockT> client::blockchain::Backend<Block> for BlockchainDb<Block> {
Ok(self.meta.read().finalized_hash.clone())
}
fn cache(&self) -> Option<Arc<dyn client::blockchain::Cache<Block>>> {
fn cache(&self) -> Option<Arc<dyn sc_client::blockchain::Cache<Block>>> {
None
}
@@ -465,8 +465,8 @@ impl<Block: BlockT> client::blockchain::Backend<Block> for BlockchainDb<Block> {
}
}
impl<Block: BlockT> client::blockchain::ProvideCache<Block> for BlockchainDb<Block> {
fn cache(&self) -> Option<Arc<dyn client::blockchain::Cache<Block>>> {
impl<Block: BlockT> sc_client::blockchain::ProvideCache<Block> for BlockchainDb<Block> {
fn cache(&self) -> Option<Arc<dyn sc_client::blockchain::Cache<Block>>> {
None
}
}
@@ -522,7 +522,7 @@ impl<Block: BlockT, H: Hasher> BlockImportOperation<Block, H> {
}
}
impl<Block> client_api::backend::BlockImportOperation<Block, Blake2Hasher>
impl<Block> sc_client_api::backend::BlockImportOperation<Block, Blake2Hasher>
for BlockImportOperation<Block, Blake2Hasher> where Block: BlockT<Hash=H256>,
{
type State = CachingState<Blake2Hasher, RefTrackingState<Block>, Block>;
@@ -630,7 +630,7 @@ struct StorageDb<Block: BlockT> {
pub state_db: StateDb<Block::Hash, Vec<u8>>,
}
impl<Block: BlockT> state_machine::Storage<Blake2Hasher> for StorageDb<Block> {
impl<Block: BlockT> sp_state_machine::Storage<Blake2Hasher> for StorageDb<Block> {
fn get(&self, key: &H256, prefix: Prefix) -> Result<Option<DBValue>, String> {
let key = prefixed_key::<Blake2Hasher>(key, prefix);
self.state_db.get(&key, self).map(|r| r.map(|v| DBValue::from_slice(&v)))
@@ -638,7 +638,7 @@ impl<Block: BlockT> state_machine::Storage<Blake2Hasher> for StorageDb<Block> {
}
}
impl<Block: BlockT> state_db::NodeDb for StorageDb<Block> {
impl<Block: BlockT> sc_state_db::NodeDb for StorageDb<Block> {
type Error = io::Error;
type Key = [u8];
@@ -653,12 +653,12 @@ impl DbGenesisStorage {
pub fn new() -> Self {
let mut root = H256::default();
let mut mdb = MemoryDB::<Blake2Hasher>::default();
state_machine::TrieDBMut::<Blake2Hasher>::new(&mut mdb, &mut root);
sp_state_machine::TrieDBMut::<Blake2Hasher>::new(&mut mdb, &mut root);
DbGenesisStorage(root)
}
}
impl state_machine::Storage<Blake2Hasher> for DbGenesisStorage {
impl sp_state_machine::Storage<Blake2Hasher> for DbGenesisStorage {
fn get(&self, _key: &H256, _prefix: Prefix) -> Result<Option<DBValue>, String> {
Ok(None)
}
@@ -700,11 +700,11 @@ impl<Block: BlockT<Hash=H256>> DbChangesTrieStorage<Block> {
None => return,
};
state_machine::prune_changes_tries(
sp_state_machine::prune_changes_tries(
config,
&*self,
min_blocks_to_keep.into(),
&state_machine::ChangesTrieAnchorBlockId {
&sp_state_machine::ChangesTrieAnchorBlockId {
hash: convert_hash(&block_hash),
number: block_num,
},
@@ -712,7 +712,7 @@ impl<Block: BlockT<Hash=H256>> DbChangesTrieStorage<Block> {
}
}
impl<Block> client_api::backend::PrunableStateChangesTrieStorage<Block, Blake2Hasher>
impl<Block> sc_client_api::backend::PrunableStateChangesTrieStorage<Block, Blake2Hasher>
for DbChangesTrieStorage<Block>
where
Block: BlockT<Hash=H256>,
@@ -723,7 +723,7 @@ where
best_finalized_block: NumberFor<Block>,
) -> NumberFor<Block> {
match self.min_blocks_to_keep {
Some(min_blocks_to_keep) => state_machine::oldest_non_pruned_changes_trie(
Some(min_blocks_to_keep) => sp_state_machine::oldest_non_pruned_changes_trie(
config,
min_blocks_to_keep.into(),
best_finalized_block,
@@ -733,7 +733,7 @@ where
}
}
impl<Block> state_machine::ChangesTrieRootsStorage<Blake2Hasher, NumberFor<Block>>
impl<Block> sp_state_machine::ChangesTrieRootsStorage<Blake2Hasher, NumberFor<Block>>
for DbChangesTrieStorage<Block>
where
Block: BlockT<Hash=H256>,
@@ -741,11 +741,11 @@ where
fn build_anchor(
&self,
hash: H256,
) -> Result<state_machine::ChangesTrieAnchorBlockId<H256, NumberFor<Block>>, String> {
) -> Result<sp_state_machine::ChangesTrieAnchorBlockId<H256, NumberFor<Block>>, String> {
utils::read_header::<Block>(&*self.db, columns::KEY_LOOKUP, columns::HEADER, BlockId::Hash(hash))
.map_err(|e| e.to_string())
.and_then(|maybe_header| maybe_header.map(|header|
state_machine::ChangesTrieAnchorBlockId {
sp_state_machine::ChangesTrieAnchorBlockId {
hash,
number: *header.number(),
}
@@ -754,7 +754,7 @@ where
fn root(
&self,
anchor: &state_machine::ChangesTrieAnchorBlockId<H256, NumberFor<Block>>,
anchor: &sp_state_machine::ChangesTrieAnchorBlockId<H256, NumberFor<Block>>,
block: NumberFor<Block>,
) -> Result<Option<H256>, String> {
// check API requirement: we can't get NEXT block(s) based on anchor
@@ -800,12 +800,12 @@ where
}
}
impl<Block> state_machine::ChangesTrieStorage<Blake2Hasher, NumberFor<Block>>
impl<Block> sp_state_machine::ChangesTrieStorage<Blake2Hasher, NumberFor<Block>>
for DbChangesTrieStorage<Block>
where
Block: BlockT<Hash=H256>,
{
fn as_roots_storage(&self) -> &dyn state_machine::ChangesTrieRootsStorage<Blake2Hasher, NumberFor<Block>> {
fn as_roots_storage(&self) -> &dyn sp_state_machine::ChangesTrieRootsStorage<Blake2Hasher, NumberFor<Block>> {
self
}
@@ -870,7 +870,7 @@ impl<Block: BlockT<Hash=H256>> Backend<Block> {
let is_archive_pruning = config.pruning.is_archive();
let blockchain = BlockchainDb::new(db.clone())?;
let meta = blockchain.meta.clone();
let map_e = |e: state_db::Error<io::Error>| ::sp_blockchain::Error::from(format!("State database error: {:?}", e));
let map_e = |e: sc_state_db::Error<io::Error>| ::sp_blockchain::Error::from(format!("State database error: {:?}", e));
let state_db: StateDb<_, _> = StateDb::new(config.pruning.clone(), &StateMetaDb(&*db)).map_err(map_e)?;
let storage_db = StorageDb {
db: db.clone(),
@@ -904,8 +904,8 @@ impl<Block: BlockT<Hash=H256>> Backend<Block> {
/// Returns in-memory blockchain that contains the same set of blocks that the self.
#[cfg(feature = "test-helpers")]
pub fn as_in_memory(&self) -> InMemoryBackend<Block, Blake2Hasher> {
use client_api::backend::{Backend as ClientBackend, BlockImportOperation};
use client::blockchain::Backend as BlockchainBackend;
use sc_client_api::backend::{Backend as ClientBackend, BlockImportOperation};
use sc_client::blockchain::Backend as BlockchainBackend;
let inmem = InMemoryBackend::<Block, Blake2Hasher>::new();
@@ -965,7 +965,7 @@ impl<Block: BlockT<Hash=H256>> Backend<Block> {
match cached_changes_trie_config.clone() {
Some(cached_changes_trie_config) => Ok(cached_changes_trie_config),
None => {
use client_api::backend::Backend;
use sc_client_api::backend::Backend;
let changes_trie_config = self
.state_at(BlockId::Hash(block))?
.storage(well_known_keys::CHANGES_TRIE_CONFIG)?
@@ -1109,14 +1109,14 @@ impl<Block: BlockT<Hash=H256>> Backend<Block> {
let hash = if new_canonical == number_u64 {
hash
} else {
::client::blockchain::HeaderBackend::hash(&self.blockchain, new_canonical.saturated_into())?
::sc_client::blockchain::HeaderBackend::hash(&self.blockchain, new_canonical.saturated_into())?
.expect("existence of block with number `new_canonical` \
implies existence of blocks with all numbers before it; qed")
};
trace!(target: "db", "Canonicalize block #{} ({:?})", new_canonical, hash);
let commit = self.storage.state_db.canonicalize_block(&hash)
.map_err(|e: state_db::Error<io::Error>| sp_blockchain::Error::from(format!("State database error: {:?}", e)))?;
.map_err(|e: sc_state_db::Error<io::Error>| sp_blockchain::Error::from(format!("State database error: {:?}", e)))?;
apply_state_commit(transaction, commit);
};
@@ -1190,7 +1190,7 @@ impl<Block: BlockT<Hash=H256>> Backend<Block> {
}
let finalized = if operation.commit_state {
let mut changeset: state_db::ChangeSet<Vec<u8>> = state_db::ChangeSet::default();
let mut changeset: sc_state_db::ChangeSet<Vec<u8>> = sc_state_db::ChangeSet::default();
for (key, (val, rc)) in operation.db_updates.drain() {
if rc > 0 {
changeset.inserted.push((key, val.to_vec()));
@@ -1200,7 +1200,7 @@ impl<Block: BlockT<Hash=H256>> Backend<Block> {
}
let number_u64 = number.saturated_into::<u64>();
let commit = self.storage.state_db.insert_block(&hash, number_u64, &pending_block.header.parent_hash(), changeset)
.map_err(|e: state_db::Error<io::Error>| sp_blockchain::Error::from(format!("State database error: {:?}", e)))?;
.map_err(|e: sc_state_db::Error<io::Error>| sp_blockchain::Error::from(format!("State database error: {:?}", e)))?;
apply_state_commit(&mut transaction, commit);
// Check if need to finalize. Genesis is always finalized instantly.
@@ -1253,7 +1253,7 @@ impl<Block: BlockT<Hash=H256>> Backend<Block> {
};
let cache_update = if let Some(set_head) = operation.set_head {
if let Some(header) = ::client::blockchain::HeaderBackend::header(&self.blockchain, set_head)? {
if let Some(header) = ::sc_client::blockchain::HeaderBackend::header(&self.blockchain, set_head)? {
let number = header.number();
let hash = header.hash();
@@ -1336,7 +1336,7 @@ impl<Block: BlockT<Hash=H256>> Backend<Block> {
transaction.put(columns::META, meta_keys::FINALIZED_BLOCK, &lookup_key);
let commit = self.storage.state_db.canonicalize_block(&f_hash)
.map_err(|e: state_db::Error<io::Error>| sp_blockchain::Error::from(format!("State database error: {:?}", e)))?;
.map_err(|e: sc_state_db::Error<io::Error>| sp_blockchain::Error::from(format!("State database error: {:?}", e)))?;
apply_state_commit(transaction, commit);
let changes_trie_config = self.changes_trie_config(parent_hash)?;
@@ -1355,7 +1355,7 @@ impl<Block: BlockT<Hash=H256>> Backend<Block> {
}
}
fn apply_state_commit(transaction: &mut DBTransaction, commit: state_db::CommitSet<Vec<u8>>) {
fn apply_state_commit(transaction: &mut DBTransaction, commit: sc_state_db::CommitSet<Vec<u8>>) {
for (key, val) in commit.data.inserted.into_iter() {
transaction.put(columns::STATE, &key[..], &val);
}
@@ -1370,7 +1370,7 @@ fn apply_state_commit(transaction: &mut DBTransaction, commit: state_db::CommitS
}
}
impl<Block> client_api::backend::AuxStore for Backend<Block> where Block: BlockT<Hash=H256> {
impl<Block> sc_client_api::backend::AuxStore for Backend<Block> where Block: BlockT<Hash=H256> {
fn insert_aux<
'a,
'b: 'a,
@@ -1394,7 +1394,7 @@ impl<Block> client_api::backend::AuxStore for Backend<Block> where Block: BlockT
}
}
impl<Block> client_api::backend::Backend<Block, Blake2Hasher> for Backend<Block> where Block: BlockT<Hash=H256> {
impl<Block> sc_client_api::backend::Backend<Block, Blake2Hasher> for Backend<Block> where Block: BlockT<Hash=H256> {
type BlockImportOperation = BlockImportOperation<Block, Blake2Hasher>;
type Blockchain = BlockchainDb<Block>;
type State = CachingState<Blake2Hasher, RefTrackingState<Block>, Block>;
@@ -1530,7 +1530,7 @@ impl<Block> client_api::backend::Backend<Block, Blake2Hasher> for Backend<Block>
}
fn state_at(&self, block: BlockId<Block>) -> ClientResult<Self::State> {
use client::blockchain::HeaderBackend as BcHeaderBackend;
use sc_client::blockchain::HeaderBackend as BcHeaderBackend;
// special case for genesis initialization
match block {
@@ -1568,7 +1568,7 @@ impl<Block> client_api::backend::Backend<Block, Blake2Hasher> for Backend<Block>
if self.is_archive {
match self.blockchain.header(BlockId::Hash(hash.clone())) {
Ok(Some(header)) => {
state_machine::Storage::get(self.storage.as_ref(), &header.state_root(), (&[], None)).unwrap_or(None).is_some()
sp_state_machine::Storage::get(self.storage.as_ref(), &header.state_root(), (&[], None)).unwrap_or(None).is_some()
},
_ => false,
}
@@ -1590,7 +1590,7 @@ impl<Block> client_api::backend::Backend<Block, Blake2Hasher> for Backend<Block>
}
}
impl<Block> client_api::backend::LocalBackend<Block, Blake2Hasher> for Backend<Block>
impl<Block> sc_client_api::backend::LocalBackend<Block, Blake2Hasher> for Backend<Block>
where Block: BlockT<Hash=H256> {}
/// TODO: remove me in #3201
@@ -1604,15 +1604,13 @@ mod tests {
use hash_db::{HashDB, EMPTY_PREFIX};
use super::*;
use crate::columns;
use client_api::backend::{Backend as BTrait, BlockImportOperation as Op};
use client::blockchain::Backend as BLBTrait;
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};
use sp_runtime::traits::{Hash, BlakeTwo256};
use state_machine::{TrieMut, TrieDBMut, ChangesTrieRootsStorage, ChangesTrieStorage};
use sp_state_machine::{TrieMut, TrieDBMut, ChangesTrieRootsStorage, ChangesTrieStorage};
use sp_blockchain::{lowest_common_ancestor, tree_route};
use test_client;
type Block = RawBlock<ExtrinsicWrapper<u64>>;
fn prepare_changes(changes: Vec<(Vec<u8>, Vec<u8>)>) -> (H256, MemoryDB<Blake2Hasher>) {
@@ -1849,7 +1847,7 @@ mod tests {
backend.commit_operation(op).unwrap();
assert_eq!(backend.storage.db.get(
columns::STATE,
&trie::prefixed_key::<Blake2Hasher>(&key, EMPTY_PREFIX)
&sp_trie::prefixed_key::<Blake2Hasher>(&key, EMPTY_PREFIX)
).unwrap().unwrap(), &b"hello"[..]);
hash
};
@@ -1886,7 +1884,7 @@ mod tests {
backend.commit_operation(op).unwrap();
assert_eq!(backend.storage.db.get(
columns::STATE,
&trie::prefixed_key::<Blake2Hasher>(&key, EMPTY_PREFIX)
&sp_trie::prefixed_key::<Blake2Hasher>(&key, EMPTY_PREFIX)
).unwrap().unwrap(), &b"hello"[..]);
hash
};
@@ -1924,7 +1922,7 @@ mod tests {
assert!(backend.storage.db.get(
columns::STATE,
&trie::prefixed_key::<Blake2Hasher>(&key, EMPTY_PREFIX)
&sp_trie::prefixed_key::<Blake2Hasher>(&key, EMPTY_PREFIX)
).unwrap().is_some());
hash
};
@@ -1958,7 +1956,7 @@ mod tests {
backend.commit_operation(op).unwrap();
assert!(backend.storage.db.get(
columns::STATE,
&trie::prefixed_key::<Blake2Hasher>(&key, EMPTY_PREFIX)
&sp_trie::prefixed_key::<Blake2Hasher>(&key, EMPTY_PREFIX)
).unwrap().is_none());
}
@@ -1967,7 +1965,7 @@ mod tests {
backend.finalize_block(BlockId::Number(3), None).unwrap();
assert!(backend.storage.db.get(
columns::STATE,
&trie::prefixed_key::<Blake2Hasher>(&key, EMPTY_PREFIX)
&sp_trie::prefixed_key::<Blake2Hasher>(&key, EMPTY_PREFIX)
).unwrap().is_none());
}
@@ -1979,7 +1977,7 @@ mod tests {
let check_changes = |backend: &Backend<Block>, block: u64, changes: Vec<(Vec<u8>, Vec<u8>)>| {
let (changes_root, mut changes_trie_update) = prepare_changes(changes);
let anchor = state_machine::ChangesTrieAnchorBlockId {
let anchor = sp_state_machine::ChangesTrieAnchorBlockId {
hash: backend.blockchain().header(BlockId::Number(block)).unwrap().unwrap().hash(),
number: block
};
@@ -2033,21 +2031,21 @@ mod tests {
// branch1: when asking for finalized block hash
let (changes1_root, _) = prepare_changes(changes1);
let anchor = state_machine::ChangesTrieAnchorBlockId { hash: block2_1_1, number: 4 };
let anchor = sp_state_machine::ChangesTrieAnchorBlockId { hash: block2_1_1, number: 4 };
assert_eq!(backend.changes_tries_storage.root(&anchor, 1), Ok(Some(changes1_root)));
// branch2: when asking for finalized block hash
let anchor = state_machine::ChangesTrieAnchorBlockId { hash: block2_2_1, number: 4 };
let anchor = sp_state_machine::ChangesTrieAnchorBlockId { hash: block2_2_1, number: 4 };
assert_eq!(backend.changes_tries_storage.root(&anchor, 1), Ok(Some(changes1_root)));
// branch1: when asking for non-finalized block hash (search by traversal)
let (changes2_1_0_root, _) = prepare_changes(changes2_1_0);
let anchor = state_machine::ChangesTrieAnchorBlockId { hash: block2_1_1, number: 4 };
let anchor = sp_state_machine::ChangesTrieAnchorBlockId { hash: block2_1_1, number: 4 };
assert_eq!(backend.changes_tries_storage.root(&anchor, 3), Ok(Some(changes2_1_0_root)));
// branch2: when asking for non-finalized block hash (search using canonicalized hint)
let (changes2_2_0_root, _) = prepare_changes(changes2_2_0);
let anchor = state_machine::ChangesTrieAnchorBlockId { hash: block2_2_1, number: 4 };
let anchor = sp_state_machine::ChangesTrieAnchorBlockId { hash: block2_2_1, number: 4 };
assert_eq!(backend.changes_tries_storage.root(&anchor, 3), Ok(Some(changes2_2_0_root)));
// finalize first block of branch2 (block2_2_0)
@@ -2059,7 +2057,7 @@ mod tests {
// branch1: when asking for finalized block of other branch
// => result is incorrect (returned for the block of branch1), but this is expected,
// because the other fork is abandoned (forked before finalized header)
let anchor = state_machine::ChangesTrieAnchorBlockId { hash: block2_1_1, number: 4 };
let anchor = sp_state_machine::ChangesTrieAnchorBlockId { hash: block2_1_1, number: 4 };
assert_eq!(backend.changes_tries_storage.root(&anchor, 3), Ok(Some(changes2_2_0_root)));
}
@@ -2090,7 +2088,7 @@ mod tests {
backend.changes_tries_storage.meta.write().finalized_number = 13;
// check that roots of all tries are in the columns::CHANGES_TRIE
let anchor = state_machine::ChangesTrieAnchorBlockId { hash: block13, number: 13 };
let anchor = sp_state_machine::ChangesTrieAnchorBlockId { hash: block13, number: 13 };
fn read_changes_trie_root(backend: &Backend<Block>, num: u64) -> H256 {
backend.blockchain().header(BlockId::Number(num)).unwrap().unwrap().digest().logs().iter()
.find(|i| i.as_changes_trie_root().is_some()).unwrap().as_changes_trie_root().unwrap().clone()
@@ -2161,7 +2159,7 @@ mod tests {
let block6 = insert_header(&backend, 6, block5, vec![(b"key_at_6".to_vec(), b"val_at_6".to_vec())], Default::default());
// check that roots of all tries are in the columns::CHANGES_TRIE
let anchor = state_machine::ChangesTrieAnchorBlockId { hash: block6, number: 6 };
let anchor = sp_state_machine::ChangesTrieAnchorBlockId { hash: block6, number: 6 };
fn read_changes_trie_root(backend: &Backend<Block>, num: u64) -> H256 {
backend.blockchain().header(BlockId::Number(num)).unwrap().unwrap().digest().logs().iter()
.find(|i| i.as_changes_trie_root().is_some()).unwrap().as_changes_trie_root().unwrap().clone()
@@ -2348,20 +2346,20 @@ mod tests {
#[test]
fn test_leaves_with_complex_block_tree() {
let backend: Arc<Backend<test_client::runtime::Block>> = Arc::new(Backend::new_test(20, 20));
test_client::trait_tests::test_leaves_for_backend(backend);
let backend: Arc<Backend<substrate_test_runtime_client::runtime::Block>> = Arc::new(Backend::new_test(20, 20));
substrate_test_runtime_client::trait_tests::test_leaves_for_backend(backend);
}
#[test]
fn test_children_with_complex_block_tree() {
let backend: Arc<Backend<test_client::runtime::Block>> = Arc::new(Backend::new_test(20, 20));
test_client::trait_tests::test_children_for_backend(backend);
let backend: Arc<Backend<substrate_test_runtime_client::runtime::Block>> = Arc::new(Backend::new_test(20, 20));
substrate_test_runtime_client::trait_tests::test_children_for_backend(backend);
}
#[test]
fn test_blockchain_query_by_number_gets_canonical() {
let backend: Arc<Backend<test_client::runtime::Block>> = Arc::new(Backend::new_test(20, 20));
test_client::trait_tests::test_blockchain_query_by_number_gets_canonical(backend);
let backend: Arc<Backend<substrate_test_runtime_client::runtime::Block>> = Arc::new(Backend::new_test(20, 20));
substrate_test_runtime_client::trait_tests::test_blockchain_query_by_number_gets_canonical(backend);
}
#[test]
@@ -2390,7 +2388,7 @@ mod tests {
#[test]
fn test_aux() {
let backend: Backend<test_client::runtime::Block> = Backend::new_test(0, 0);
let backend: Backend<substrate_test_runtime_client::runtime::Block> = Backend::new_test(0, 0);
assert!(backend.get_aux(b"test").unwrap().is_none());
backend.insert_aux(&[(&b"test"[..], &b"hello"[..])], &[]).unwrap();
assert_eq!(b"hello", &backend.get_aux(b"test").unwrap().unwrap()[..]);
@@ -2400,7 +2398,7 @@ mod tests {
#[test]
fn test_finalize_block_with_justification() {
use client::blockchain::{Backend as BlockChainBackend};
use sc_client::blockchain::{Backend as BlockChainBackend};
let backend = Backend::<Block>::new_test(10, 10);
+7 -7
View File
@@ -22,20 +22,20 @@ use parking_lot::RwLock;
use kvdb::{KeyValueDB, DBTransaction};
use client_api::backend::{AuxStore, NewBlockState};
use client::blockchain::{
use sc_client_api::backend::{AuxStore, NewBlockState};
use sc_client::blockchain::{
BlockStatus, Cache as BlockchainCache,Info as BlockchainInfo,
};
use client::cht;
use sc_client::cht;
use sp_blockchain::{
CachedHeaderMetadata, HeaderMetadata, HeaderMetadataCache,
Error as ClientError, Result as ClientResult,
HeaderBackend as BlockchainHeaderBackend,
well_known_cache_keys,
};
use client::light::blockchain::Storage as LightBlockchainStorage;
use sc_client::light::blockchain::Storage as LightBlockchainStorage;
use codec::{Decode, Encode};
use primitives::Blake2Hasher;
use sp_core::Blake2Hasher;
use sp_runtime::generic::{DigestItem, BlockId};
use sp_runtime::traits::{Block as BlockT, Header as HeaderT, Zero, One, NumberFor};
use crate::cache::{DbCacheSync, DbCache, ComplexBlockId, EntryType as CacheEntryType};
@@ -559,14 +559,14 @@ fn cht_key<N: TryInto<u32>>(cht_type: u8, block: N) -> ClientResult<[u8; 5]> {
#[cfg(test)]
pub(crate) mod tests {
use client::cht;
use sc_client::cht;
use sp_runtime::generic::DigestItem;
use sp_runtime::testing::{H256 as Hash, Header, Block as RawBlock, ExtrinsicWrapper};
use sp_blockchain::{lowest_common_ancestor, tree_route};
use super::*;
type Block = RawBlock<ExtrinsicWrapper<u32>>;
type AuthorityId = primitives::ed25519::Public;
type AuthorityId = sp_core::ed25519::Public;
pub fn default_header(parent: &Hash, number: u64) -> Header {
Header {
+2 -2
View File
@@ -56,7 +56,7 @@ impl LocalStorage {
}
}
impl primitives::offchain::OffchainStorage for LocalStorage {
impl sp_core::offchain::OffchainStorage for LocalStorage {
fn set(&mut self, prefix: &[u8], key: &[u8], value: &[u8]) {
let key: Vec<u8> = prefix.iter().chain(key).cloned().collect();
let mut tx = self.db.transaction();
@@ -117,7 +117,7 @@ impl primitives::offchain::OffchainStorage for LocalStorage {
#[cfg(test)]
mod tests {
use super::*;
use primitives::offchain::OffchainStorage;
use sp_core::offchain::OffchainStorage;
#[test]
fn should_compare_and_set_and_clear_the_locks_map() {
+8 -8
View File
@@ -22,11 +22,11 @@ use parking_lot::{Mutex, RwLock, RwLockUpgradableReadGuard};
use linked_hash_map::{LinkedHashMap, Entry};
use hash_db::Hasher;
use sp_runtime::traits::{Block as BlockT, Header};
use primitives::hexdisplay::HexDisplay;
use primitives::storage::ChildInfo;
use state_machine::{backend::Backend as StateBackend, TrieBackend};
use sp_core::hexdisplay::HexDisplay;
use sp_core::storage::ChildInfo;
use sp_state_machine::{backend::Backend as StateBackend, TrieBackend};
use log::trace;
use client_api::backend::{StorageCollection, ChildStorageCollection};
use sc_client_api::backend::{StorageCollection, ChildStorageCollection};
use std::hash::Hash as StdHash;
const STATE_CACHE_BLOCKS: usize = 12;
@@ -642,8 +642,8 @@ impl<H: Hasher, S: StateBackend<H>, B: BlockT> StateBackend<H> for CachingState<
mod tests {
use super::*;
use sp_runtime::testing::{H256, Block as RawBlock, ExtrinsicWrapper};
use state_machine::backend::InMemory;
use primitives::Blake2Hasher;
use sp_state_machine::backend::InMemory;
use sp_core::Blake2Hasher;
type Block = RawBlock<ExtrinsicWrapper<u32>>;
@@ -890,8 +890,8 @@ mod qc {
use super::*;
use sp_runtime::testing::{H256, Block as RawBlock, ExtrinsicWrapper};
use state_machine::backend::InMemory;
use primitives::Blake2Hasher;
use sp_state_machine::backend::InMemory;
use sp_core::Blake2Hasher;
type Block = RawBlock<ExtrinsicWrapper<u32>>;
+1 -1
View File
@@ -26,7 +26,7 @@ use kvdb_rocksdb::{Database, DatabaseConfig};
use log::debug;
use codec::Decode;
use trie::DBValue;
use sp_trie::DBValue;
use sp_runtime::generic::BlockId;
use sp_runtime::traits::{
Block as BlockT, Header as HeaderT, Zero,
+11 -12
View File
@@ -8,17 +8,17 @@ edition = "2018"
derive_more = "0.99.2"
codec = { package = "parity-scale-codec", version = "1.0.0" }
sp-io = { path = "../../primitives/io" }
primitives = { package = "sp-core", path = "../../primitives/core" }
trie = { package = "sp-trie", path = "../../primitives/trie" }
serializer = { package = "sp-serializer", path = "../../primitives/serializer" }
runtime_version = { package = "sp-version", path = "../../primitives/version" }
panic-handler = { package = "sp-panic-handler", path = "../../primitives/panic-handler" }
sp-core = { path = "../../primitives/core" }
sp-trie = { path = "../../primitives/trie" }
sp-serializer = { path = "../../primitives/serializer" }
sp-version = { path = "../../primitives/version" }
sp-panic-handler = { path = "../../primitives/panic-handler" }
wasmi = "0.6.2"
parity-wasm = "0.41.0"
lazy_static = "1.4.0"
wasm-interface = { package = "sp-wasm-interface", path = "../../primitives/wasm-interface" }
runtime-interface = { package = "sp-runtime-interface", path = "../../primitives/runtime-interface" }
externalities = { package = "sp-externalities", path = "../../primitives/externalities" }
sp-wasm-interface = { path = "../../primitives/wasm-interface" }
sp-runtime-interface = { path = "../../primitives/runtime-interface" }
sp-externalities = { path = "../../primitives/externalities" }
parking_lot = "0.9.0"
log = "0.4.8"
libsecp256k1 = "0.3.2"
@@ -36,10 +36,9 @@ wasmtime-runtime = { version = "0.8", optional = true }
assert_matches = "1.3.0"
wabt = "0.9.2"
hex-literal = "0.2.1"
runtime-test = { package = "sc-runtime-test", path = "runtime-test" }
test-runtime = { package = "substrate-test-runtime", path = "../../test-utils/runtime" }
runtime-interface = { package = "sp-runtime-interface", path = "../../primitives/runtime-interface" }
state_machine = { package = "sp-state-machine", path = "../../primitives/state-machine" }
sc-runtime-test = { path = "runtime-test" }
substrate-test-runtime = { path = "../../test-utils/runtime" }
sp-state-machine = { path = "../../primitives/state-machine" }
test-case = "0.3.3"
[features]
@@ -8,13 +8,13 @@ build = "build.rs"
[dependencies]
sp-std = { path = "../../../primitives/std", default-features = false }
sp-io = { path = "../../../primitives/io", default-features = false }
sandbox = { package = "sp-sandbox", path = "../../../primitives/sandbox", default-features = false }
primitives = { package = "sp-core", path = "../../../primitives/core", default-features = false }
sp-runtime = { package = "sp-runtime", path = "../../../primitives/runtime", default-features = false }
sp-sandbox = { path = "../../../primitives/sandbox", default-features = false }
sp-core = { path = "../../../primitives/core", default-features = false }
sp-runtime = { path = "../../../primitives/runtime", default-features = false }
[build-dependencies]
wasm-builder-runner = { package = "substrate-wasm-builder-runner", path = "../../../utils/wasm-builder-runner", version = "1.0.4" }
[features]
default = [ "std" ]
std = ["sp-io/std", "sandbox/std", "sp-std/std"]
std = ["sp-io/std", "sp-sandbox/std", "sp-std/std"]
@@ -16,9 +16,9 @@ use sp_io::{
#[cfg(not(feature = "std"))]
use sp_runtime::{print, traits::{BlakeTwo256, Hash}};
#[cfg(not(feature = "std"))]
use primitives::{ed25519, sr25519};
use sp_core::{ed25519, sr25519};
primitives::wasm_export_functions! {
sp_core::wasm_export_functions! {
fn test_data_in(input: Vec<u8>) -> Vec<u8> {
print("set_storage");
storage::set(b"input", &input);
@@ -112,8 +112,8 @@ primitives::wasm_export_functions! {
execute_sandboxed(
&code,
&[
sandbox::TypedValue::I32(0x12345678),
sandbox::TypedValue::I64(0x1234567887654321),
sp_sandbox::TypedValue::I32(0x12345678),
sp_sandbox::TypedValue::I64(0x1234567887654321),
],
).is_ok()
}
@@ -122,10 +122,10 @@ primitives::wasm_export_functions! {
let ok = match execute_sandboxed(
&code,
&[
sandbox::TypedValue::I32(0x1336),
sp_sandbox::TypedValue::I32(0x1336),
]
) {
Ok(sandbox::ReturnValue::Value(sandbox::TypedValue::I32(0x1337))) => true,
Ok(sp_sandbox::ReturnValue::Value(sp_sandbox::TypedValue::I32(0x1337))) => true,
_ => false,
};
@@ -133,19 +133,19 @@ primitives::wasm_export_functions! {
}
fn test_sandbox_instantiate(code: Vec<u8>) -> u8 {
let env_builder = sandbox::EnvironmentDefinitionBuilder::new();
let code = match sandbox::Instance::new(&code, &env_builder, &mut ()) {
let env_builder = sp_sandbox::EnvironmentDefinitionBuilder::new();
let code = match sp_sandbox::Instance::new(&code, &env_builder, &mut ()) {
Ok(_) => 0,
Err(sandbox::Error::Module) => 1,
Err(sandbox::Error::Execution) => 2,
Err(sandbox::Error::OutOfBounds) => 3,
Err(sp_sandbox::Error::Module) => 1,
Err(sp_sandbox::Error::Execution) => 2,
Err(sp_sandbox::Error::OutOfBounds) => 3,
};
code
}
fn test_offchain_local_storage() -> bool {
let kind = primitives::offchain::StorageKind::PERSISTENT;
let kind = sp_core::offchain::StorageKind::PERSISTENT;
assert_eq!(sp_io::offchain::local_storage_get(kind, b"test"), None);
sp_io::offchain::local_storage_set(kind, b"test", b"asd");
assert_eq!(sp_io::offchain::local_storage_get(kind, b"test"), Some(b"asd".to_vec()));
@@ -161,7 +161,7 @@ primitives::wasm_export_functions! {
}
fn test_offchain_local_storage_with_none() {
let kind = primitives::offchain::StorageKind::PERSISTENT;
let kind = sp_core::offchain::StorageKind::PERSISTENT;
assert_eq!(sp_io::offchain::local_storage_get(kind, b"test"), None);
let res = sp_io::offchain::local_storage_compare_and_set(kind, b"test", None, b"value");
@@ -170,7 +170,7 @@ primitives::wasm_export_functions! {
}
fn test_offchain_http() -> bool {
use primitives::offchain::HttpRequestStatus;
use sp_core::offchain::HttpRequestStatus;
let run = || -> Option<()> {
let id = sp_io::offchain::http_request_start(
"POST",
@@ -201,45 +201,45 @@ primitives::wasm_export_functions! {
#[cfg(not(feature = "std"))]
fn execute_sandboxed(
code: &[u8],
args: &[sandbox::TypedValue],
) -> Result<sandbox::ReturnValue, sandbox::HostError> {
args: &[sp_sandbox::TypedValue],
) -> Result<sp_sandbox::ReturnValue, sp_sandbox::HostError> {
struct State {
counter: u32,
}
fn env_assert(
_e: &mut State,
args: &[sandbox::TypedValue],
) -> Result<sandbox::ReturnValue, sandbox::HostError> {
args: &[sp_sandbox::TypedValue],
) -> Result<sp_sandbox::ReturnValue, sp_sandbox::HostError> {
if args.len() != 1 {
return Err(sandbox::HostError);
return Err(sp_sandbox::HostError);
}
let condition = args[0].as_i32().ok_or_else(|| sandbox::HostError)?;
let condition = args[0].as_i32().ok_or_else(|| sp_sandbox::HostError)?;
if condition != 0 {
Ok(sandbox::ReturnValue::Unit)
Ok(sp_sandbox::ReturnValue::Unit)
} else {
Err(sandbox::HostError)
Err(sp_sandbox::HostError)
}
}
fn env_inc_counter(
e: &mut State,
args: &[sandbox::TypedValue],
) -> Result<sandbox::ReturnValue, sandbox::HostError> {
args: &[sp_sandbox::TypedValue],
) -> Result<sp_sandbox::ReturnValue, sp_sandbox::HostError> {
if args.len() != 1 {
return Err(sandbox::HostError);
return Err(sp_sandbox::HostError);
}
let inc_by = args[0].as_i32().ok_or_else(|| sandbox::HostError)?;
let inc_by = args[0].as_i32().ok_or_else(|| sp_sandbox::HostError)?;
e.counter += inc_by as u32;
Ok(sandbox::ReturnValue::Value(sandbox::TypedValue::I32(e.counter as i32)))
Ok(sp_sandbox::ReturnValue::Value(sp_sandbox::TypedValue::I32(e.counter as i32)))
}
let mut state = State { counter: 0 };
let env_builder = {
let mut env_builder = sandbox::EnvironmentDefinitionBuilder::new();
let mut env_builder = sp_sandbox::EnvironmentDefinitionBuilder::new();
env_builder.add_host_func("env", "assert", env_assert);
env_builder.add_host_func("env", "inc_counter", env_inc_counter);
let memory = match sandbox::Memory::new(1, Some(16)) {
let memory = match sp_sandbox::Memory::new(1, Some(16)) {
Ok(m) => m,
Err(_) => unreachable!("
Memory::new() can return Err only if parameters are borked; \
@@ -251,8 +251,8 @@ fn execute_sandboxed(
env_builder
};
let mut instance = sandbox::Instance::new(code, &env_builder, &mut state)?;
let mut instance = sp_sandbox::Instance::new(code, &env_builder, &mut state)?;
let result = instance.invoke("call", args, &mut state);
result.map_err(|_| sandbox::HostError)
result.map_err(|_| sp_sandbox::HostError)
}
+1 -1
View File
@@ -50,7 +50,7 @@ use crate::error::{Error, Result};
use log::trace;
use std::convert::{TryFrom, TryInto};
use std::ops::Range;
use wasm_interface::{Pointer, WordSize};
use sp_wasm_interface::{Pointer, WordSize};
// The pointers need to be aligned to 8 bytes. This is because the
// maximum value type handled by wasm32 is u64.
@@ -18,12 +18,12 @@
use codec::Encode;
use std::{convert::TryFrom, str};
use primitives::{
use sp_core::{
blake2_128, blake2_256, twox_64, twox_128, twox_256, ed25519, sr25519, keccak_256, Blake2Hasher, Pair,
crypto::KeyTypeId, offchain,
};
use trie::{TrieConfiguration, trie_types::Layout};
use wasm_interface::{
use sp_trie::{TrieConfiguration, trie_types::Layout};
use sp_wasm_interface::{
Pointer, WordSize, WritePrimitive, ReadPrimitive, FunctionContext, Result as WResult,
};
+2 -2
View File
@@ -16,7 +16,7 @@
//! Rust executor possible errors.
use serializer;
use sp_serializer;
use wasmi;
#[cfg(feature = "wasmtime")]
use wasmtime_jit::{ActionError, SetupError};
@@ -28,7 +28,7 @@ pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, derive_more::Display, derive_more::From)]
pub enum Error {
/// Unserializable Data
InvalidData(serializer::Error),
InvalidData(sp_serializer::Error),
/// Trap occured during execution
Trap(wasmi::Trap),
/// Wasmi loading/instantiating error
@@ -18,15 +18,15 @@ mod sandbox;
use codec::{Encode, Decode};
use hex_literal::hex;
use primitives::{
use sp_core::{
Blake2Hasher, blake2_128, blake2_256, ed25519, sr25519, map, Pair,
offchain::{OffchainExt, testing},
traits::Externalities,
};
use runtime_test::WASM_BINARY;
use state_machine::TestExternalities as CoreTestExternalities;
use sc_runtime_test::WASM_BINARY;
use sp_state_machine::TestExternalities as CoreTestExternalities;
use test_case::test_case;
use trie::{TrieConfiguration, trie_types::Layout};
use sp_trie::{TrieConfiguration, trie_types::Layout};
use crate::WasmExecutionMethod;
@@ -128,7 +128,7 @@ fn storage_should_work(wasm_method: WasmExecutionMethod) {
assert_eq!(output, b"all ok!".to_vec().encode());
}
let expected = TestExternalities::new(primitives::storage::Storage {
let expected = TestExternalities::new(sp_core::storage::Storage {
top: map![
b"input".to_vec() => b"Hello world".to_vec(),
b"foo".to_vec() => b"bar".to_vec(),
@@ -165,7 +165,7 @@ fn clear_prefix_should_work(wasm_method: WasmExecutionMethod) {
assert_eq!(output, b"all ok!".to_vec().encode());
}
let expected = TestExternalities::new(primitives::storage::Storage {
let expected = TestExternalities::new(sp_core::storage::Storage {
top: map![
b"aaa".to_vec() => b"1".to_vec(),
b"aab".to_vec() => b"2".to_vec(),
@@ -443,7 +443,7 @@ fn ordered_trie_root_should_work(wasm_method: WasmExecutionMethod) {
#[test_case(WasmExecutionMethod::Interpreted)]
#[cfg_attr(feature = "wasmtime", test_case(WasmExecutionMethod::Compiled))]
fn offchain_local_storage_should_work(wasm_method: WasmExecutionMethod) {
use primitives::offchain::OffchainStorage;
use sp_core::offchain::OffchainStorage;
let mut ext = TestExternalities::default();
let (offchain, state) = testing::TestOffchainExt::new();
@@ -18,7 +18,7 @@ use super::{TestExternalities, call_in_wasm};
use crate::WasmExecutionMethod;
use codec::Encode;
use runtime_test::WASM_BINARY;
use sc_runtime_test::WASM_BINARY;
use test_case::test_case;
use wabt;
+5 -5
View File
@@ -46,12 +46,12 @@ mod integration_tests;
pub mod error;
pub use wasmi;
pub use native_executor::{with_native_environment, NativeExecutor, NativeExecutionDispatch};
pub use runtime_version::{RuntimeVersion, NativeVersion};
pub use sp_version::{RuntimeVersion, NativeVersion};
pub use codec::Codec;
#[doc(hidden)]
pub use primitives::traits::Externalities;
pub use sp_core::traits::Externalities;
#[doc(hidden)]
pub use wasm_interface;
pub use sp_wasm_interface;
pub use wasm_runtime::WasmExecutionMethod;
/// Call the given `function` in the given wasm `code`.
@@ -64,7 +64,7 @@ pub use wasm_runtime::WasmExecutionMethod;
/// - `heap_pages`: The number of heap pages to allocate.
///
/// Returns the `Vec<u8>` that contains the return value of the function.
pub fn call_in_wasm<E: Externalities, HF: wasm_interface::HostFunctions>(
pub fn call_in_wasm<E: Externalities, HF: sp_wasm_interface::HostFunctions>(
function: &str,
call_data: &[u8],
execution_method: WasmExecutionMethod,
@@ -93,7 +93,7 @@ pub trait RuntimeInfo {
#[cfg(test)]
mod tests {
use super::*;
use runtime_test::WASM_BINARY;
use sc_runtime_test::WASM_BINARY;
use sp_io::TestExternalities;
#[test]
@@ -19,17 +19,17 @@ use crate::{
wasm_runtime::{RuntimesCache, WasmExecutionMethod, WasmRuntime},
};
use runtime_version::{NativeVersion, RuntimeVersion};
use sp_version::{NativeVersion, RuntimeVersion};
use codec::{Decode, Encode};
use primitives::{NativeOrEncoded, traits::{CodeExecutor, Externalities}};
use sp_core::{NativeOrEncoded, traits::{CodeExecutor, Externalities}};
use log::trace;
use std::{result, cell::RefCell, panic::{UnwindSafe, AssertUnwindSafe}};
use wasm_interface::{HostFunctions, Function};
use sp_wasm_interface::{HostFunctions, Function};
thread_local! {
static RUNTIMES_CACHE: RefCell<RuntimesCache> = RefCell::new(RuntimesCache::new());
@@ -43,7 +43,7 @@ pub(crate) fn safe_call<F, U>(f: F) -> Result<U>
{
// Substrate uses custom panic hook that terminates process on panic. Disable
// termination for the native call.
let _guard = panic_handler::AbortGuard::force_unwind();
let _guard = sp_panic_handler::AbortGuard::force_unwind();
std::panic::catch_unwind(f).map_err(|_| Error::Runtime)
}
@@ -53,7 +53,7 @@ pub(crate) fn safe_call<F, U>(f: F) -> Result<U>
pub fn with_native_environment<F, U>(ext: &mut dyn Externalities, f: F) -> Result<U>
where F: UnwindSafe + FnOnce() -> U
{
externalities::set_and_run_with_externalities(ext, move || safe_call(f))
sp_externalities::set_and_run_with_externalities(ext, move || safe_call(f))
}
/// Delegate for dispatching a CodeExecutor call.
@@ -267,8 +267,8 @@ impl<D: NativeExecutionDispatch> CodeExecutor for NativeExecutor<D> {
/// ```
/// sc_executor::native_executor_instance!(
/// pub MyExecutor,
/// test_runtime::api::dispatch,
/// test_runtime::native_version,
/// substrate_test_runtime::api::dispatch,
/// substrate_test_runtime::native_version,
/// );
/// ```
///
@@ -278,7 +278,7 @@ impl<D: NativeExecutionDispatch> CodeExecutor for NativeExecutor<D> {
/// executor aware of the host functions for these interfaces.
///
/// ```
/// # use runtime_interface::runtime_interface;
/// # use sp_runtime_interface::runtime_interface;
///
/// #[runtime_interface]
/// trait MyInterface {
@@ -289,8 +289,8 @@ impl<D: NativeExecutionDispatch> CodeExecutor for NativeExecutor<D> {
///
/// sc_executor::native_executor_instance!(
/// pub MyExecutor,
/// test_runtime::api::dispatch,
/// test_runtime::native_version,
/// substrate_test_runtime::api::dispatch,
/// substrate_test_runtime::native_version,
/// my_interface::HostFunctions,
/// );
/// ```
@@ -337,7 +337,7 @@ macro_rules! native_executor_instance {
#[cfg(test)]
mod tests {
use super::*;
use runtime_interface::runtime_interface;
use sp_runtime_interface::runtime_interface;
#[runtime_interface]
trait MyInterface {
@@ -348,8 +348,8 @@ mod tests {
native_executor_instance!(
pub MyExecutor,
test_runtime::api::dispatch,
test_runtime::native_version,
substrate_test_runtime::api::dispatch,
substrate_test_runtime::native_version,
(my_interface::HostFunctions, my_interface::HostFunctions),
);
+2 -2
View File
@@ -21,12 +21,12 @@
use crate::error::{Result, Error};
use std::{collections::HashMap, rc::Rc};
use codec::{Decode, Encode};
use primitives::sandbox as sandbox_primitives;
use sp_core::sandbox as sandbox_primitives;
use wasmi::{
Externals, ImportResolver, MemoryInstance, MemoryRef, Module, ModuleInstance,
ModuleRef, RuntimeArgs, RuntimeValue, Trap, TrapKind, memory_units::Pages,
};
use wasm_interface::{Pointer, WordSize};
use sp_wasm_interface::{Pointer, WordSize};
/// Index of a function inside the supervisor.
///
@@ -26,12 +26,12 @@ use log::{trace, warn};
use codec::Decode;
use primitives::{storage::well_known_keys, traits::Externalities};
use sp_core::{storage::well_known_keys, traits::Externalities};
use runtime_version::RuntimeVersion;
use sp_version::RuntimeVersion;
use std::{collections::hash_map::{Entry, HashMap}, panic::AssertUnwindSafe};
use wasm_interface::Function;
use sp_wasm_interface::Function;
/// The Substrate Wasm runtime.
pub trait WasmRuntime {
@@ -259,7 +259,7 @@ fn create_versioned_wasm_runtime<E: Externalities>(
#[cfg(test)]
mod tests {
use wasm_interface::HostFunctions;
use sp_wasm_interface::HostFunctions;
#[test]
fn host_functions_are_equal() {
+15 -15
View File
@@ -16,28 +16,28 @@
//! Utilities for defining the wasm host environment.
use wasm_interface::{Pointer, WordSize};
use sp_wasm_interface::{Pointer, WordSize};
/// Converts arguments into respective WASM types.
#[macro_export]
macro_rules! convert_args {
() => ([]);
( $( $t:ty ),* ) => ( [ $( <$t as $crate::wasm_interface::IntoValue>::VALUE_TYPE, )* ] );
( $( $t:ty ),* ) => ( [ $( <$t as $crate::sp_wasm_interface::IntoValue>::VALUE_TYPE, )* ] );
}
/// Generates a WASM signature for given list of parameters.
#[macro_export]
macro_rules! gen_signature {
( ( $( $params: ty ),* ) ) => (
$crate::wasm_interface::Signature {
$crate::sp_wasm_interface::Signature {
args: std::borrow::Cow::Borrowed(&convert_args!( $( $params ),* )[..]),
return_value: None,
}
);
( ( $( $params: ty ),* ) -> $returns:ty ) => (
$crate::wasm_interface::Signature {
$crate::sp_wasm_interface::Signature {
args: std::borrow::Cow::Borrowed(&convert_args!( $( $params ),* )[..]),
return_value: Some(<$returns as $crate::wasm_interface::IntoValue>::VALUE_TYPE),
return_value: Some(<$returns as $crate::sp_wasm_interface::IntoValue>::VALUE_TYPE),
}
);
}
@@ -63,18 +63,18 @@ macro_rules! gen_functions {
struct $name;
#[allow(unused)]
impl $crate::wasm_interface::Function for $name {
impl $crate::sp_wasm_interface::Function for $name {
fn name(&self) -> &str {
stringify!($name)
}
fn signature(&self) -> $crate::wasm_interface::Signature {
fn signature(&self) -> $crate::sp_wasm_interface::Signature {
gen_signature!( ( $( $params ),* ) $( -> $returns )? )
}
fn execute(
&self,
context: &mut dyn $crate::wasm_interface::FunctionContext,
args: &mut dyn Iterator<Item=$crate::wasm_interface::Value>,
) -> ::std::result::Result<Option<$crate::wasm_interface::Value>, String> {
context: &mut dyn $crate::sp_wasm_interface::FunctionContext,
args: &mut dyn Iterator<Item=$crate::sp_wasm_interface::Value>,
) -> ::std::result::Result<Option<$crate::sp_wasm_interface::Value>, String> {
let mut $context = context;
marshall! {
args,
@@ -83,7 +83,7 @@ macro_rules! gen_functions {
}
}
&$name as &dyn $crate::wasm_interface::Function
&$name as &dyn $crate::sp_wasm_interface::Function
},
}
$context,
@@ -103,7 +103,7 @@ macro_rules! unmarshall_args {
$(
let $names : $params =
$args_iter.next()
.and_then(|val| <$params as $crate::wasm_interface::TryFromValue>::try_from_value(val))
.and_then(|val| <$params as $crate::sp_wasm_interface::TryFromValue>::try_from_value(val))
.expect(
"`$args_iter` comes from an argument of Externals::execute_function;
args to an external call always matches the signature of the external;
@@ -140,7 +140,7 @@ macro_rules! marshall {
unmarshall_args!($body, $args_iter, $( $names : $params ),*)
});
let r = body()?;
return Ok(Some($crate::wasm_interface::IntoValue::into_value(r)))
return Ok(Some($crate::sp_wasm_interface::IntoValue::into_value(r)))
});
( $args_iter:ident, ( $( $names:ident : $params:ty ),* ) => $body:tt ) => ({
let body = $crate::wasm_utils::constrain_closure::<(), _>(|| {
@@ -162,9 +162,9 @@ macro_rules! impl_wasm_host_interface {
)*
}
) => (
impl $crate::wasm_interface::HostFunctions for $interface_name {
impl $crate::sp_wasm_interface::HostFunctions for $interface_name {
#[allow(non_camel_case_types)]
fn host_functions() -> Vec<&'static dyn $crate::wasm_interface::Function> {
fn host_functions() -> Vec<&'static dyn $crate::sp_wasm_interface::Function> {
gen_functions!(
$context,
$( $name( $( $names: $params ),* ) $( -> $returns )? { $( $body )* } )*
@@ -23,14 +23,14 @@ use wasmi::{
};
use crate::error::{Error, WasmError};
use codec::{Encode, Decode};
use primitives::{sandbox as sandbox_primitives, traits::Externalities};
use sp_core::{sandbox as sandbox_primitives, traits::Externalities};
use crate::sandbox;
use crate::allocator;
use crate::wasm_utils::interpret_runtime_api_result;
use crate::wasm_runtime::WasmRuntime;
use log::{error, trace};
use parity_wasm::elements::{deserialize_buffer, DataSegment, Instruction, Module as RawModule};
use wasm_interface::{
use sp_wasm_interface::{
FunctionContext, Pointer, WordSize, Sandbox, MemoryId, Result as WResult, Function,
};
@@ -273,7 +273,7 @@ impl<'a> wasmi::ModuleImportResolver for Resolver<'a> {
fn resolve_func(&self, name: &str, signature: &wasmi::Signature)
-> std::result::Result<wasmi::FuncRef, wasmi::Error>
{
let signature = wasm_interface::Signature::from(signature);
let signature = sp_wasm_interface::Signature::from(signature);
for (function_index, function) in self.0.iter().enumerate() {
if name == function.name() {
if signature == function.signature() {
@@ -364,7 +364,7 @@ fn call_in_wasm_module(
let offset = fec.allocate_memory(data.len() as u32)?;
fec.write_memory(offset, data)?;
let result = externalities::set_and_run_with_externalities(
let result = sp_externalities::set_and_run_with_externalities(
ext,
|| module_instance.invoke_export(
method,
@@ -25,12 +25,12 @@ use codec::{Decode, Encode};
use cranelift_codegen::ir;
use cranelift_codegen::isa::TargetFrontendConfig;
use log::trace;
use primitives::sandbox as sandbox_primitives;
use sp_core::sandbox as sandbox_primitives;
use std::{cmp, mem, ptr};
use wasmtime_environ::translate_signature;
use wasmtime_jit::{ActionError, Compiler};
use wasmtime_runtime::{Export, VMCallerCheckedAnyfunc, VMContext, wasmtime_call_trampoline};
use wasm_interface::{
use sp_wasm_interface::{
FunctionContext, MemoryId, Pointer, Result as WResult, Sandbox, Signature, Value, ValueType,
WordSize,
};
@@ -33,7 +33,7 @@ use std::cell::RefCell;
use std::collections::HashMap;
use std::convert::TryFrom;
use std::rc::Rc;
use wasm_interface::{Pointer, WordSize, Function};
use sp_wasm_interface::{Pointer, WordSize, Function};
use wasmtime_environ::{Module, translate_signature};
use wasmtime_jit::{
ActionOutcome, ActionError, CodeMemory, CompilationStrategy, CompiledModule, Compiler, Context,
@@ -175,7 +175,7 @@ fn call_method(
let args = [RuntimeValue::I32(u32::from(data_ptr) as i32), RuntimeValue::I32(data_len as i32)];
// Invoke the function in the runtime.
let outcome = externalities::set_and_run_with_externalities(ext, || {
let outcome = sp_externalities::set_and_run_with_externalities(ext, || {
context
.invoke(&mut instance, method, &args[..])
.map_err(Error::Wasmtime)
@@ -26,7 +26,7 @@ use cranelift_codegen::print_errors::pretty_error;
use wasmtime_jit::{CodeMemory, Compiler};
use wasmtime_environ::CompiledFunction;
use wasmtime_runtime::{VMContext, VMFunctionBody};
use wasm_interface::{Function, Value, ValueType};
use sp_wasm_interface::{Function, Value, ValueType};
use std::{cmp, panic::{self, AssertUnwindSafe}, ptr};
use crate::error::{Error, WasmError};
@@ -18,7 +18,7 @@ use crate::error::{Error, Result};
use cranelift_codegen::{ir, isa};
use std::ops::Range;
use wasm_interface::{Pointer, Signature, ValueType};
use sp_wasm_interface::{Pointer, Signature, ValueType};
/// Read data from a slice of memory into a destination buffer.
///
+17 -17
View File
@@ -12,31 +12,31 @@ futures-timer = "2.0.2"
log = "0.4.8"
parking_lot = "0.9.0"
rand = "0.7.2"
codec = { package = "parity-scale-codec", version = "1.0.0", features = ["derive"] }
parity-scale-codec = { version = "1.0.0", features = ["derive"] }
sp-runtime = { path = "../../primitives/runtime" }
consensus_common = { package = "sp-consensus", path = "../../primitives/consensus/common" }
primitives = { package = "sp-core", path = "../../primitives/core" }
sp-consensus = { path = "../../primitives/consensus/common" }
sp-core = { path = "../../primitives/core" }
sc-telemetry = { path = "../telemetry" }
keystore = { package = "sc-keystore", path = "../keystore" }
sc-keystore = { path = "../keystore" }
serde_json = "1.0.41"
client-api = { package = "sc-client-api", path = "../api" }
client = { package = "sc-client", path = "../" }
inherents = { package = "sp-inherents", path = "../../primitives/inherents" }
sc-client-api = { path = "../api" }
sc-client = { path = "../" }
sp-inherents = { path = "../../primitives/inherents" }
sp-blockchain = { path = "../../primitives/blockchain" }
network = { package = "sc-network", path = "../network" }
network-gossip = { package = "sc-network-gossip", path = "../network-gossip" }
sc-network = { path = "../network" }
sc-network-gossip = { path = "../network-gossip" }
sp-finality-tracker = { path = "../../primitives/finality-tracker" }
fg_primitives = { package = "sp-finality-grandpa", path = "../../primitives/finality-grandpa" }
grandpa = { package = "finality-grandpa", version = "0.10.1", features = ["derive-codec"] }
sp-finality-grandpa = { path = "../../primitives/finality-grandpa" }
finality-grandpa = { version = "0.10.1", features = ["derive-codec"] }
[dev-dependencies]
grandpa = { package = "finality-grandpa", version = "0.10.1", features = ["derive-codec", "test-helpers"] }
network = { package = "sc-network", path = "../network" }
finality-grandpa = { version = "0.10.1", features = ["derive-codec", "test-helpers"] }
sc-network = { path = "../network" }
sc-network-test = { path = "../network/test" }
keyring = { package = "sp-keyring", path = "../../primitives/keyring" }
test-client = { package = "substrate-test-runtime-client", path = "../../test-utils/runtime/client"}
babe_primitives = { package = "sp-consensus-babe", path = "../../primitives/consensus/babe" }
state_machine = { package = "sp-state-machine", path = "../../primitives/state-machine" }
sp-keyring = { path = "../../primitives/keyring" }
substrate-test-runtime-client = { path = "../../test-utils/runtime/client"}
sp-consensus-babe = { path = "../../primitives/consensus/babe" }
sp-state-machine = { path = "../../primitives/state-machine" }
env_logger = "0.7.0"
tokio = "0.1.22"
tempfile = "3.1.0"
@@ -18,11 +18,11 @@
use fork_tree::ForkTree;
use parking_lot::RwLock;
use grandpa::voter_set::VoterSet;
use codec::{Encode, Decode};
use finality_grandpa::voter_set::VoterSet;
use parity_scale_codec::{Encode, Decode};
use log::{debug, info};
use sc_telemetry::{telemetry, CONSENSUS_INFO};
use fg_primitives::{AuthorityId, AuthorityList};
use sp_finality_grandpa::{AuthorityId, AuthorityList};
use std::cmp::Ord;
use std::fmt::Debug;
@@ -403,7 +403,7 @@ pub(crate) struct PendingChange<H, N> {
}
impl<H: Decode, N: Decode> Decode for PendingChange<H, N> {
fn decode<I: codec::Input>(value: &mut I) -> Result<Self, codec::Error> {
fn decode<I: parity_scale_codec::Input>(value: &mut I) -> Result<Self, parity_scale_codec::Error> {
let next_authorities = Decode::decode(value)?;
let delay = Decode::decode(value)?;
let canon_height = Decode::decode(value)?;
@@ -431,7 +431,7 @@ impl<H, N: Add<Output=N> + Clone> PendingChange<H, N> {
#[cfg(test)]
mod tests {
use super::*;
use primitives::crypto::Public;
use sp_core::crypto::Public;
fn static_is_descendent_of<A>(value: bool)
-> impl Fn(&A, &A) -> Result<bool, std::io::Error>
@@ -18,14 +18,14 @@
use std::fmt::Debug;
use std::sync::Arc;
use codec::{Encode, Decode};
use client_api::backend::AuxStore;
use parity_scale_codec::{Encode, Decode};
use sc_client_api::backend::AuxStore;
use sp_blockchain::{Result as ClientResult, Error as ClientError};
use fork_tree::ForkTree;
use grandpa::round::State as RoundState;
use finality_grandpa::round::State as RoundState;
use sp_runtime::traits::{Block as BlockT, NumberFor};
use log::{info, warn};
use fg_primitives::{AuthorityList, SetId, RoundNumber};
use sp_finality_grandpa::{AuthorityList, SetId, RoundNumber};
use crate::authorities::{AuthoritySet, SharedAuthoritySet, PendingChange, DelayKind};
use crate::consensus_changes::{SharedConsensusChanges, ConsensusChanges};
@@ -439,14 +439,14 @@ pub(crate) fn load_authorities<B: AuxStore, H: Decode, N: Decode>(backend: &B)
#[cfg(test)]
mod test {
use fg_primitives::AuthorityId;
use primitives::H256;
use test_client;
use sp_finality_grandpa::AuthorityId;
use sp_core::H256;
use substrate_test_runtime_client;
use super::*;
#[test]
fn load_decode_from_v0_migrates_data_format() {
let client = test_client::new();
let client = substrate_test_runtime_client::new();
let authorities = vec![(AuthorityId::default(), 100)];
let set_id = 3;
@@ -482,7 +482,7 @@ mod test {
);
// should perform the migration
load_persistent::<test_client::runtime::Block, _, _>(
load_persistent::<substrate_test_runtime_client::runtime::Block, _, _>(
&client,
H256::random(),
0,
@@ -494,7 +494,7 @@ mod test {
Some(2),
);
let PersistentData { authority_set, set_state, .. } = load_persistent::<test_client::runtime::Block, _, _>(
let PersistentData { authority_set, set_state, .. } = load_persistent::<substrate_test_runtime_client::runtime::Block, _, _>(
&client,
H256::random(),
0,
@@ -534,7 +534,7 @@ mod test {
#[test]
fn load_decode_from_v1_migrates_data_format() {
let client = test_client::new();
let client = substrate_test_runtime_client::new();
let authorities = vec![(AuthorityId::default(), 100)];
let set_id = 3;
@@ -572,7 +572,7 @@ mod test {
);
// should perform the migration
load_persistent::<test_client::runtime::Block, _, _>(
load_persistent::<substrate_test_runtime_client::runtime::Block, _, _>(
&client,
H256::random(),
0,
@@ -584,7 +584,7 @@ mod test {
Some(2),
);
let PersistentData { authority_set, set_state, .. } = load_persistent::<test_client::runtime::Block, _, _>(
let PersistentData { authority_set, set_state, .. } = load_persistent::<substrate_test_runtime_client::runtime::Block, _, _>(
&client,
H256::random(),
0,
@@ -624,11 +624,11 @@ mod test {
#[test]
fn write_read_concluded_rounds() {
let client = test_client::new();
let client = substrate_test_runtime_client::new();
let hash = H256::random();
let round_state = RoundState::genesis((hash, 0));
let completed_round = CompletedRound::<test_client::runtime::Block> {
let completed_round = CompletedRound::<substrate_test_runtime_client::runtime::Block> {
number: 42,
state: round_state.clone(),
base: round_state.prevote_ghost.unwrap(),
@@ -642,7 +642,7 @@ mod test {
round_number.using_encoded(|n| key.extend(n));
assert_eq!(
load_decode::<_, CompletedRound::<test_client::runtime::Block>>(&client, &key).unwrap(),
load_decode::<_, CompletedRound::<substrate_test_runtime_client::runtime::Block>>(&client, &key).unwrap(),
Some(completed_round),
);
}
@@ -83,10 +83,10 @@
//! We only send polite messages to peers,
use sp_runtime::traits::{NumberFor, Block as BlockT, Zero};
use network_gossip::{GossipEngine, MessageIntent, ValidatorContext};
use network::{config::Roles, PeerId, ReputationChange};
use codec::{Encode, Decode};
use fg_primitives::AuthorityId;
use sc_network_gossip::{GossipEngine, MessageIntent, ValidatorContext};
use sc_network::{config::Roles, PeerId, ReputationChange};
use parity_scale_codec::{Encode, Decode};
use sp_finality_grandpa::AuthorityId;
use sc_telemetry::{telemetry, CONSENSUS_DEBUG};
use log::{trace, debug, warn};
@@ -908,15 +908,15 @@ impl<Block: BlockT> Inner<Block> {
// too many equivocations (we exceed the fault-tolerance bound).
for vote in last_completed_round.votes {
match vote.message {
grandpa::Message::Prevote(prevote) => {
prevotes.push(grandpa::SignedPrevote {
finality_grandpa::Message::Prevote(prevote) => {
prevotes.push(finality_grandpa::SignedPrevote {
prevote,
signature: vote.signature,
id: vote.id,
});
},
grandpa::Message::Precommit(precommit) => {
precommits.push(grandpa::SignedPrecommit {
finality_grandpa::Message::Precommit(precommit) => {
precommits.push(finality_grandpa::SignedPrecommit {
precommit,
signature: vote.signature,
id: vote.id,
@@ -1280,7 +1280,7 @@ impl<Block: BlockT> GossipValidator<Block> {
}
}
impl<Block: BlockT> network_gossip::Validator<Block> for GossipValidator<Block> {
impl<Block: BlockT> sc_network_gossip::Validator<Block> for GossipValidator<Block> {
fn new_peer(&self, context: &mut dyn ValidatorContext<Block>, who: &PeerId, roles: Roles) {
let packet = {
let mut inner = self.inner.write();
@@ -1306,7 +1306,7 @@ impl<Block: BlockT> network_gossip::Validator<Block> for GossipValidator<Block>
}
fn validate(&self, context: &mut dyn ValidatorContext<Block>, who: &PeerId, data: &[u8])
-> network_gossip::ValidationResult<Block::Hash>
-> sc_network_gossip::ValidationResult<Block::Hash>
{
let (action, broadcast_topics, peer_reply) = self.do_validate(who, data);
@@ -1323,15 +1323,15 @@ impl<Block: BlockT> network_gossip::Validator<Block> for GossipValidator<Block>
Action::Keep(topic, cb) => {
self.report(who.clone(), cb);
context.broadcast_message(topic, data.to_vec(), false);
network_gossip::ValidationResult::ProcessAndKeep(topic)
sc_network_gossip::ValidationResult::ProcessAndKeep(topic)
}
Action::ProcessAndDiscard(topic, cb) => {
self.report(who.clone(), cb);
network_gossip::ValidationResult::ProcessAndDiscard(topic)
sc_network_gossip::ValidationResult::ProcessAndDiscard(topic)
}
Action::Discard(cb) => {
self.report(who.clone(), cb);
network_gossip::ValidationResult::Discard
sc_network_gossip::ValidationResult::Discard
}
}
}
@@ -1502,9 +1502,9 @@ impl<B: BlockT> Future for ReportingTask<B> {
mod tests {
use super::*;
use super::environment::SharedVoterSetState;
use network_gossip::Validator as GossipValidatorT;
use sc_network_gossip::Validator as GossipValidatorT;
use sc_network_test::Block;
use primitives::{crypto::Public, H256};
use sp_core::{crypto::Public, H256};
// some random config (not really needed)
fn config() -> crate::Config {
@@ -1726,7 +1726,7 @@ mod tests {
round: Round(1),
set_id: SetId(set_id),
message: SignedMessage::<Block> {
message: grandpa::Message::Prevote(grandpa::Prevote {
message: finality_grandpa::Message::Prevote(finality_grandpa::Prevote {
target_hash: Default::default(),
target_number: 10,
}),
@@ -1739,7 +1739,7 @@ mod tests {
round: Round(1),
set_id: SetId(set_id),
message: SignedMessage::<Block> {
message: grandpa::Message::Prevote(grandpa::Prevote {
message: finality_grandpa::Message::Prevote(finality_grandpa::Prevote {
target_hash: Default::default(),
target_number: 10,
}),
@@ -1770,7 +1770,7 @@ mod tests {
let mut inner = val.inner.write();
inner.validate_catch_up_message(&peer, &FullCatchUpMessage {
set_id: SetId(set_id),
message: grandpa::CatchUp {
message: finality_grandpa::CatchUp {
round_number: 10,
prevotes: Default::default(),
precommits: Default::default(),
@@ -1806,7 +1806,7 @@ mod tests {
completed_rounds.push(environment::CompletedRound {
number: 2,
state: grandpa::round::State::genesis(Default::default()),
state: finality_grandpa::round::State::genesis(Default::default()),
base: Default::default(),
votes: Default::default(),
});
@@ -31,13 +31,13 @@ use std::sync::Arc;
use futures::{prelude::*, future::Executor as _, sync::mpsc};
use futures03::{compat::Compat, stream::StreamExt, future::FutureExt as _, future::TryFutureExt as _};
use grandpa::Message::{Prevote, Precommit, PrimaryPropose};
use grandpa::{voter, voter_set::VoterSet};
use finality_grandpa::Message::{Prevote, Precommit, PrimaryPropose};
use finality_grandpa::{voter, voter_set::VoterSet};
use log::{debug, trace};
use network::ReputationChange;
use network_gossip::{GossipEngine, Network};
use codec::{Encode, Decode};
use primitives::Pair;
use sc_network::ReputationChange;
use sc_network_gossip::{GossipEngine, Network};
use parity_scale_codec::{Encode, Decode};
use sp_core::Pair;
use sp_runtime::traits::{Block as BlockT, Hash as HashT, Header as HeaderT, NumberFor};
use sc_telemetry::{telemetry, CONSENSUS_DEBUG, CONSENSUS_INFO};
@@ -49,7 +49,7 @@ use crate::environment::HasVoted;
use gossip::{
GossipMessage, FullCatchUpMessage, FullCommitMessage, VoteMessage, GossipValidator
};
use fg_primitives::{
use sp_finality_grandpa::{
AuthorityPair, AuthorityId, AuthoritySignature, SetId as SetIdNumber, RoundNumber,
};
@@ -59,11 +59,11 @@ mod periodic;
#[cfg(test)]
mod tests;
pub use fg_primitives::GRANDPA_ENGINE_ID;
pub use sp_finality_grandpa::GRANDPA_ENGINE_ID;
// cost scalars for reporting peers.
mod cost {
use network::ReputationChange as Rep;
use sc_network::ReputationChange as Rep;
pub(super) const PAST_REJECTION: Rep = Rep::new(-50, "Grandpa: Past message");
pub(super) const BAD_SIGNATURE: Rep = Rep::new(-100, "Grandpa: Bad signature");
pub(super) const MALFORMED_CATCH_UP: Rep = Rep::new(-1000, "Grandpa: Malformed cath-up");
@@ -87,7 +87,7 @@ mod cost {
// benefit scalars for reporting peers.
mod benefit {
use network::ReputationChange as Rep;
use sc_network::ReputationChange as Rep;
pub(super) const NEIGHBOR_MESSAGE: Rep = Rep::new(100, "Grandpa: Neighbor message");
pub(super) const ROUND_MESSAGE: Rep = Rep::new(100, "Grandpa: Round message");
pub(super) const BASIC_VALIDATED_CATCH_UP: Rep = Rep::new(200, "Grandpa: Catch-up message");
@@ -356,7 +356,7 @@ impl<B: BlockT> NetworkBridge<B> {
/// If the given vector of peers is empty then the underlying implementation
/// should make a best effort to fetch the block from any peers it is
/// connected to (NOTE: this assumption will change in the future #3629).
pub(crate) fn set_sync_fork_request(&self, peers: Vec<network::PeerId>, hash: B::Hash, number: NumberFor<B>) {
pub(crate) fn set_sync_fork_request(&self, peers: Vec<sc_network::PeerId>, hash: B::Hash, number: NumberFor<B>) {
self.gossip_engine.set_sync_fork_request(peers, hash, number)
}
}
@@ -370,7 +370,7 @@ fn incoming_global<B: BlockT>(
) -> impl Stream<Item = CommunicationIn<B>, Error = Error> {
let process_commit = move |
msg: FullCommitMessage<B>,
mut notification: network_gossip::TopicNotification,
mut notification: sc_network_gossip::TopicNotification,
gossip_engine: &mut GossipEngine<B>,
gossip_validator: &Arc<GossipValidator<B>>,
voters: &VoterSet<AuthorityId>,
@@ -432,7 +432,7 @@ fn incoming_global<B: BlockT>(
let process_catch_up = move |
msg: FullCatchUpMessage<B>,
mut notification: network_gossip::TopicNotification,
mut notification: sc_network_gossip::TopicNotification,
gossip_engine: &mut GossipEngine<B>,
gossip_validator: &Arc<GossipValidator<B>>,
voters: &VoterSet<AuthorityId>,
@@ -557,15 +557,15 @@ impl<Block: BlockT> Sink for OutgoingMessages<Block>
fn start_send(&mut self, mut msg: Message<Block>) -> StartSend<Message<Block>, Error> {
// if we've voted on this round previously under the same key, send that vote instead
match &mut msg {
grandpa::Message::PrimaryPropose(ref mut vote) =>
finality_grandpa::Message::PrimaryPropose(ref mut vote) =>
if let Some(propose) = self.has_voted.propose() {
*vote = propose.clone();
},
grandpa::Message::Prevote(ref mut vote) =>
finality_grandpa::Message::Prevote(ref mut vote) =>
if let Some(prevote) = self.has_voted.prevote() {
*vote = prevote.clone();
},
grandpa::Message::Precommit(ref mut vote) =>
finality_grandpa::Message::Precommit(ref mut vote) =>
if let Some(precommit) = self.has_voted.precommit() {
*vote = precommit.clone();
},
@@ -660,7 +660,7 @@ fn check_compact_commit<Block: BlockT>(
.enumerate()
{
use crate::communication::gossip::Misbehavior;
use grandpa::Message as GrandpaMessage;
use finality_grandpa::Message as GrandpaMessage;
if let Err(()) = check_message_sig::<Block>(
&GrandpaMessage::Precommit(precommit.clone()),
@@ -772,7 +772,7 @@ fn check_catch_up<Block: BlockT>(
// check signatures on all contained prevotes.
let signatures_checked = check_signatures::<Block, _>(
msg.prevotes.iter().map(|vote| {
(grandpa::Message::Prevote(vote.prevote.clone()), &vote.id, &vote.signature)
(finality_grandpa::Message::Prevote(vote.prevote.clone()), &vote.id, &vote.signature)
}),
msg.round_number,
set_id.0,
@@ -782,7 +782,7 @@ fn check_catch_up<Block: BlockT>(
// check signatures on all contained precommits.
let _ = check_signatures::<Block, _>(
msg.precommits.iter().map(|vote| {
(grandpa::Message::Precommit(vote.precommit.clone()), &vote.id, &vote.signature)
(finality_grandpa::Message::Precommit(vote.precommit.clone()), &vote.id, &vote.signature)
}),
msg.round_number,
set_id.0,
@@ -18,15 +18,15 @@
use std::time::{Instant, Duration};
use codec::Encode;
use parity_scale_codec::Encode;
use futures::prelude::*;
use futures::sync::mpsc;
use futures_timer::Delay;
use futures03::future::{FutureExt as _, TryFutureExt as _};
use log::{debug, warn};
use network::PeerId;
use network_gossip::GossipEngine;
use sc_network::PeerId;
use sc_network_gossip::GossipEngine;
use sp_runtime::traits::{NumberFor, Block as BlockT};
use super::gossip::{NeighborPacket, GossipMessage};
@@ -47,7 +47,7 @@ impl<B: BlockT> NeighborPacketSender<B> {
/// Send a neighbor packet for the background worker to gossip to peers.
pub fn send(
&self,
who: Vec<network::PeerId>,
who: Vec<sc_network::PeerId>,
neighbor_packet: NeighborPacket<NumberFor<B>>,
) {
if let Err(err) = self.0.unbounded_send((who, neighbor_packet)) {
@@ -18,24 +18,24 @@
use futures::sync::mpsc;
use futures::prelude::*;
use network::{Event as NetworkEvent, PeerId, config::Roles};
use sc_network::{Event as NetworkEvent, PeerId, config::Roles};
use sc_network_test::{Block, Hash};
use network_gossip::Validator;
use sc_network_gossip::Validator;
use tokio::runtime::current_thread;
use std::sync::Arc;
use keyring::Ed25519Keyring;
use codec::Encode;
use sp_keyring::Ed25519Keyring;
use parity_scale_codec::Encode;
use sp_runtime::{ConsensusEngineId, traits::NumberFor};
use std::{pin::Pin, task::{Context, Poll}};
use crate::environment::SharedVoterSetState;
use fg_primitives::{AuthorityList, GRANDPA_ENGINE_ID};
use sp_finality_grandpa::{AuthorityList, GRANDPA_ENGINE_ID};
use super::gossip::{self, GossipValidator};
use super::{AuthorityId, VoterSet, Round, SetId};
enum Event {
EventStream(mpsc::UnboundedSender<NetworkEvent>),
WriteNotification(network::PeerId, Vec<u8>),
Report(network::PeerId, network::ReputationChange),
WriteNotification(sc_network::PeerId, Vec<u8>),
Report(sc_network::PeerId, sc_network::ReputationChange),
Announce(Hash),
}
@@ -44,7 +44,7 @@ struct TestNetwork {
sender: mpsc::UnboundedSender<Event>,
}
impl network_gossip::Network<Block> for TestNetwork {
impl sc_network_gossip::Network<Block> for TestNetwork {
fn event_stream(&self)
-> Box<dyn futures::Stream<Item = NetworkEvent, Error = ()> + Send> {
let (tx, rx) = mpsc::unbounded();
@@ -52,7 +52,7 @@ impl network_gossip::Network<Block> for TestNetwork {
Box::new(rx)
}
fn report_peer(&self, who: network::PeerId, cost_benefit: network::ReputationChange) {
fn report_peer(&self, who: sc_network::PeerId, cost_benefit: sc_network::ReputationChange) {
let _ = self.sender.unbounded_send(Event::Report(who, cost_benefit));
}
@@ -70,19 +70,19 @@ impl network_gossip::Network<Block> for TestNetwork {
fn set_sync_fork_request(
&self,
_peers: Vec<network::PeerId>,
_peers: Vec<sc_network::PeerId>,
_hash: Hash,
_number: NumberFor<Block>,
) {}
}
impl network_gossip::ValidatorContext<Block> for TestNetwork {
impl sc_network_gossip::ValidatorContext<Block> for TestNetwork {
fn broadcast_topic(&mut self, _: Hash, _: bool) { }
fn broadcast_message(&mut self, _: Hash, _: Vec<u8>, _: bool) { }
fn send_message(&mut self, who: &network::PeerId, data: Vec<u8>) {
<Self as network_gossip::Network<Block>>::write_notification(
fn send_message(&mut self, who: &sc_network::PeerId, data: Vec<u8>) {
<Self as sc_network_gossip::Network<Block>>::write_notification(
self,
who.clone(),
GRANDPA_ENGINE_ID,
@@ -90,7 +90,7 @@ impl network_gossip::ValidatorContext<Block> for TestNetwork {
);
}
fn send_topic(&mut self, _: &network::PeerId, _: Hash, _: bool) { }
fn send_topic(&mut self, _: &sc_network::PeerId, _: Hash, _: bool) { }
}
struct Tester {
@@ -132,8 +132,8 @@ fn config() -> crate::Config {
fn voter_set_state() -> SharedVoterSetState<Block> {
use crate::authorities::AuthoritySet;
use crate::environment::VoterSetState;
use grandpa::round::State as RoundState;
use primitives::H256;
use finality_grandpa::round::State as RoundState;
use sp_core::H256;
let state = RoundState::genesis((H256::zero(), 0));
let base = state.prevote_ghost.unwrap();
@@ -193,11 +193,11 @@ fn make_ids(keys: &[Ed25519Keyring]) -> AuthorityList {
struct NoopContext;
impl network_gossip::ValidatorContext<Block> for NoopContext {
impl sc_network_gossip::ValidatorContext<Block> for NoopContext {
fn broadcast_topic(&mut self, _: Hash, _: bool) { }
fn broadcast_message(&mut self, _: Hash, _: Vec<u8>, _: bool) { }
fn send_message(&mut self, _: &network::PeerId, _: Vec<u8>) { }
fn send_topic(&mut self, _: &network::PeerId, _: Hash, _: bool) { }
fn send_message(&mut self, _: &sc_network::PeerId, _: Vec<u8>) { }
fn send_topic(&mut self, _: &sc_network::PeerId, _: Hash, _: bool) { }
}
#[test]
@@ -213,9 +213,9 @@ fn good_commit_leads_to_relay() {
let target_hash: Hash = [1; 32].into();
let target_number = 500;
let precommit = grandpa::Precommit { target_hash: target_hash.clone(), target_number };
let precommit = finality_grandpa::Precommit { target_hash: target_hash.clone(), target_number };
let payload = super::localized_payload(
round, set_id, &grandpa::Message::Precommit(precommit.clone())
round, set_id, &finality_grandpa::Message::Precommit(precommit.clone())
);
let mut precommits = Vec::new();
@@ -224,11 +224,11 @@ fn good_commit_leads_to_relay() {
for (i, key) in private.iter().enumerate() {
precommits.push(precommit.clone());
let signature = fg_primitives::AuthoritySignature::from(key.sign(&payload[..]));
let signature = sp_finality_grandpa::AuthoritySignature::from(key.sign(&payload[..]));
auth_data.push((signature, public[i].0.clone()))
}
grandpa::CompactCommit {
finality_grandpa::CompactCommit {
target_hash,
target_number,
precommits,
@@ -242,14 +242,14 @@ fn good_commit_leads_to_relay() {
message: commit,
}).encode();
let id = network::PeerId::random();
let id = sc_network::PeerId::random();
let global_topic = super::global_topic::<Block>(set_id);
let threads_pool = futures03::executor::ThreadPool::new().unwrap();
let test = make_test_network(&threads_pool).0
.and_then(move |tester| {
// register a peer.
tester.gossip_validator.new_peer(&mut NoopContext, &id, network::config::Roles::FULL);
tester.gossip_validator.new_peer(&mut NoopContext, &id, sc_network::config::Roles::FULL);
Ok((tester, id))
})
.and_then(move |(tester, id)| {
@@ -291,8 +291,8 @@ fn good_commit_leads_to_relay() {
let handle_commit = commits_in.into_future()
.map(|(item, _)| {
match item.unwrap() {
grandpa::voter::CommunicationIn::Commit(_, _, mut callback) => {
callback.run(grandpa::voter::CommitProcessingOutcome::good());
finality_grandpa::voter::CommunicationIn::Commit(_, _, mut callback) => {
callback.run(finality_grandpa::voter::CommitProcessingOutcome::good());
},
_ => panic!("commit expected"),
}
@@ -330,9 +330,9 @@ fn bad_commit_leads_to_report() {
let target_hash: Hash = [1; 32].into();
let target_number = 500;
let precommit = grandpa::Precommit { target_hash: target_hash.clone(), target_number };
let precommit = finality_grandpa::Precommit { target_hash: target_hash.clone(), target_number };
let payload = super::localized_payload(
round, set_id, &grandpa::Message::Precommit(precommit.clone())
round, set_id, &finality_grandpa::Message::Precommit(precommit.clone())
);
let mut precommits = Vec::new();
@@ -341,11 +341,11 @@ fn bad_commit_leads_to_report() {
for (i, key) in private.iter().enumerate() {
precommits.push(precommit.clone());
let signature = fg_primitives::AuthoritySignature::from(key.sign(&payload[..]));
let signature = sp_finality_grandpa::AuthoritySignature::from(key.sign(&payload[..]));
auth_data.push((signature, public[i].0.clone()))
}
grandpa::CompactCommit {
finality_grandpa::CompactCommit {
target_hash,
target_number,
precommits,
@@ -359,14 +359,14 @@ fn bad_commit_leads_to_report() {
message: commit,
}).encode();
let id = network::PeerId::random();
let id = sc_network::PeerId::random();
let global_topic = super::global_topic::<Block>(set_id);
let threads_pool = futures03::executor::ThreadPool::new().unwrap();
let test = make_test_network(&threads_pool).0
.and_then(move |tester| {
// register a peer.
tester.gossip_validator.new_peer(&mut NoopContext, &id, network::config::Roles::FULL);
tester.gossip_validator.new_peer(&mut NoopContext, &id, sc_network::config::Roles::FULL);
Ok((tester, id))
})
.and_then(move |(tester, id)| {
@@ -408,8 +408,8 @@ fn bad_commit_leads_to_report() {
let handle_commit = commits_in.into_future()
.map(|(item, _)| {
match item.unwrap() {
grandpa::voter::CommunicationIn::Commit(_, _, mut callback) => {
callback.run(grandpa::voter::CommitProcessingOutcome::bad());
finality_grandpa::voter::CommunicationIn::Commit(_, _, mut callback) => {
callback.run(finality_grandpa::voter::CommitProcessingOutcome::bad());
},
_ => panic!("commit expected"),
}
@@ -435,14 +435,14 @@ fn bad_commit_leads_to_report() {
#[test]
fn peer_with_higher_view_leads_to_catch_up_request() {
let id = network::PeerId::random();
let id = sc_network::PeerId::random();
let threads_pool = futures03::executor::ThreadPool::new().unwrap();
let (tester, mut net) = make_test_network(&threads_pool);
let test = tester
.and_then(move |tester| {
// register a peer with authority role.
tester.gossip_validator.new_peer(&mut NoopContext, &id, network::config::Roles::AUTHORITY);
tester.gossip_validator.new_peer(&mut NoopContext, &id, sc_network::config::Roles::AUTHORITY);
Ok((tester, id))
})
.and_then(move |(tester, id)| {
@@ -459,7 +459,7 @@ fn peer_with_higher_view_leads_to_catch_up_request() {
// neighbor packets are always discard
match result {
network_gossip::ValidationResult::Discard => {},
sc_network_gossip::ValidationResult::Discard => {},
_ => panic!("wrong expected outcome from neighbor validation"),
}
@@ -15,7 +15,7 @@
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
use std::sync::Arc;
use codec::{Encode, Decode};
use parity_scale_codec::{Encode, Decode};
/// Consensus-related data changes tracker.
#[derive(Clone, Debug, Encode, Decode)]
@@ -20,28 +20,28 @@ use std::sync::Arc;
use std::time::Duration;
use log::{debug, warn, info};
use codec::{Decode, Encode};
use parity_scale_codec::{Decode, Encode};
use futures::prelude::*;
use futures03::future::{FutureExt as _, TryFutureExt as _};
use futures_timer::Delay;
use parking_lot::RwLock;
use sp_blockchain::{HeaderBackend, Error as ClientError};
use client_api::{
use sc_client_api::{
BlockchainEvents,
backend::{Backend},
Finalizer,
call_executor::CallExecutor,
utils::is_descendent_of,
};
use client::{
use sc_client::{
apply_aux, Client,
};
use grandpa::{
use finality_grandpa::{
BlockNumberOps, Equivocation, Error as GrandpaError, round::State as RoundState,
voter, voter_set::VoterSet,
};
use primitives::{Blake2Hasher, H256, Pair};
use sp_core::{Blake2Hasher, H256, Pair};
use sp_runtime::generic::BlockId;
use sp_runtime::traits::{
Block as BlockT, Header as HeaderT, NumberFor, One, Zero,
@@ -53,16 +53,16 @@ use crate::{
PrimaryPropose, SignedMessage, NewAuthoritySet, VoterCommand,
};
use consensus_common::SelectChain;
use sp_consensus::SelectChain;
use crate::authorities::{AuthoritySet, SharedAuthoritySet};
use crate::consensus_changes::SharedConsensusChanges;
use crate::justification::GrandpaJustification;
use crate::until_imported::UntilVoteTargetImported;
use crate::voting_rule::VotingRule;
use fg_primitives::{AuthorityId, AuthoritySignature, SetId, RoundNumber};
use sp_finality_grandpa::{AuthorityId, AuthoritySignature, SetId, RoundNumber};
type HistoricalVotes<Block> = grandpa::HistoricalVotes<
type HistoricalVotes<Block> = finality_grandpa::HistoricalVotes<
<Block as BlockT>::Hash,
NumberFor<Block>,
AuthoritySignature,
@@ -105,10 +105,10 @@ impl<Block: BlockT> Encode for CompletedRounds<Block> {
}
}
impl<Block: BlockT> codec::EncodeLike for CompletedRounds<Block> {}
impl<Block: BlockT> parity_scale_codec::EncodeLike for CompletedRounds<Block> {}
impl<Block: BlockT> Decode for CompletedRounds<Block> {
fn decode<I: codec::Input>(value: &mut I) -> Result<Self, codec::Error> {
fn decode<I: parity_scale_codec::Input>(value: &mut I) -> Result<Self, parity_scale_codec::Error> {
<(Vec<CompletedRound<Block>>, SetId, Vec<AuthorityId>)>::decode(value)
.map(|(rounds, set_id, voters)| CompletedRounds {
rounds: rounds.into(),
@@ -406,7 +406,7 @@ impl<B, E, Block: BlockT, RA, SC, VR> Environment<B, E, Block, RA, SC, VR> {
}
impl<Block: BlockT<Hash=H256>, B, E, RA, SC, VR>
grandpa::Chain<Block::Hash, NumberFor<Block>>
finality_grandpa::Chain<Block::Hash, NumberFor<Block>>
for Environment<B, E, Block, RA, SC, VR>
where
Block: 'static,
@@ -572,11 +572,11 @@ where
// regular round message streams
type In = Box<dyn Stream<
Item = ::grandpa::SignedMessage<Block::Hash, NumberFor<Block>, Self::Signature, Self::Id>,
Item = ::finality_grandpa::SignedMessage<Block::Hash, NumberFor<Block>, Self::Signature, Self::Id>,
Error = Self::Error,
> + Send>;
type Out = Box<dyn Sink<
SinkItem = ::grandpa::Message<Block::Hash, NumberFor<Block>>,
SinkItem = ::finality_grandpa::Message<Block::Hash, NumberFor<Block>>,
SinkError = Self::Error,
> + Send>;
@@ -906,7 +906,7 @@ where
fn prevote_equivocation(
&self,
_round: RoundNumber,
equivocation: ::grandpa::Equivocation<Self::Id, Prevote<Block>, Self::Signature>
equivocation: ::finality_grandpa::Equivocation<Self::Id, Prevote<Block>, Self::Signature>
) {
warn!(target: "afg", "Detected prevote equivocation in the finality worker: {:?}", equivocation);
// nothing yet; this could craft misbehavior reports of some kind.
@@ -39,20 +39,20 @@ use std::sync::Arc;
use log::{trace, warn};
use sp_blockchain::{Backend as BlockchainBackend, Error as ClientError, Result as ClientResult};
use client_api::{
use sc_client_api::{
backend::Backend, CallExecutor, StorageProof,
light::{FetchChecker, RemoteReadRequest},
};
use client::Client;
use codec::{Encode, Decode};
use grandpa::BlockNumberOps;
use sc_client::Client;
use parity_scale_codec::{Encode, Decode};
use finality_grandpa::BlockNumberOps;
use sp_runtime::{
Justification, generic::BlockId,
traits::{NumberFor, Block as BlockT, Header as HeaderT, One},
};
use primitives::{H256, Blake2Hasher, storage::StorageKey};
use sp_core::{H256, Blake2Hasher, storage::StorageKey};
use sc_telemetry::{telemetry, CONSENSUS_INFO};
use fg_primitives::{AuthorityId, AuthorityList, VersionedAuthorityList, GRANDPA_AUTHORITIES_KEY};
use sp_finality_grandpa::{AuthorityId, AuthorityList, VersionedAuthorityList, GRANDPA_AUTHORITIES_KEY};
use crate::justification::GrandpaJustification;
@@ -154,7 +154,7 @@ impl<B, Block: BlockT<Hash=H256>> FinalityProofProvider<B, Block>
}
}
impl<B, Block> network::FinalityProofProvider<Block> for FinalityProofProvider<B, Block>
impl<B, Block> sc_network::FinalityProofProvider<Block> for FinalityProofProvider<B, Block>
where
Block: BlockT<Hash=H256>,
NumberFor<Block>: BlockNumberOps,
@@ -580,11 +580,11 @@ impl<Block: BlockT<Hash=H256>> ProvableJustification<Block::Header> for GrandpaJ
#[cfg(test)]
pub(crate) mod tests {
use test_client::runtime::{Block, Header, H256};
use client_api::NewBlockState;
use test_client::client::in_mem::Blockchain as InMemoryBlockchain;
use substrate_test_runtime_client::runtime::{Block, Header, H256};
use sc_client_api::NewBlockState;
use substrate_test_runtime_client::sc_client::in_mem::Blockchain as InMemoryBlockchain;
use super::*;
use primitives::crypto::Public;
use sp_core::crypto::Public;
type FinalityProof = super::FinalityProof<Header>;
+10 -10
View File
@@ -17,25 +17,25 @@
use std::{sync::Arc, collections::HashMap};
use log::{debug, trace, info};
use codec::Encode;
use parity_scale_codec::Encode;
use futures::sync::mpsc;
use parking_lot::RwLockWriteGuard;
use sp_blockchain::{HeaderBackend, BlockStatus, well_known_cache_keys};
use client_api::{backend::Backend, CallExecutor, utils::is_descendent_of};
use client::Client;
use consensus_common::{
use sc_client_api::{backend::Backend, CallExecutor, utils::is_descendent_of};
use sc_client::Client;
use sp_consensus::{
BlockImport, Error as ConsensusError,
BlockCheckParams, BlockImportParams, ImportResult, JustificationImport,
SelectChain,
};
use fg_primitives::{GRANDPA_ENGINE_ID, ScheduledChange, ConsensusLog};
use sp_finality_grandpa::{GRANDPA_ENGINE_ID, ScheduledChange, ConsensusLog};
use sp_runtime::Justification;
use sp_runtime::generic::{BlockId, OpaqueDigestItemId};
use sp_runtime::traits::{
Block as BlockT, DigestFor, Header as HeaderT, NumberFor, Zero,
};
use primitives::{H256, Blake2Hasher};
use sp_core::{H256, Blake2Hasher};
use crate::{Error, CommandOrError, NewAuthoritySet, VoterCommand};
use crate::authorities::{AuthoritySet, SharedAuthoritySet, DelayKind, PendingChange};
@@ -76,7 +76,7 @@ impl<B, E, Block: BlockT<Hash=H256>, RA, SC: Clone> Clone for
impl<B, E, Block: BlockT<Hash=H256>, RA, SC> JustificationImport<Block>
for GrandpaBlockImport<B, E, Block, RA, SC> where
NumberFor<Block>: grandpa::BlockNumberOps,
NumberFor<Block>: finality_grandpa::BlockNumberOps,
B: Backend<Block, Blake2Hasher> + 'static,
E: CallExecutor<Block, Blake2Hasher> + 'static + Clone + Send + Sync,
DigestFor<Block>: Encode,
@@ -204,7 +204,7 @@ fn find_forced_change<B: BlockT>(header: &B::Header)
impl<B, E, Block: BlockT<Hash=H256>, RA, SC>
GrandpaBlockImport<B, E, Block, RA, SC>
where
NumberFor<Block>: grandpa::BlockNumberOps,
NumberFor<Block>: finality_grandpa::BlockNumberOps,
B: Backend<Block, Blake2Hasher> + 'static,
E: CallExecutor<Block, Blake2Hasher> + 'static + Clone + Send + Sync,
DigestFor<Block>: Encode,
@@ -381,7 +381,7 @@ where
impl<B, E, Block: BlockT<Hash=H256>, RA, SC> BlockImport<Block>
for GrandpaBlockImport<B, E, Block, RA, SC> where
NumberFor<Block>: grandpa::BlockNumberOps,
NumberFor<Block>: finality_grandpa::BlockNumberOps,
B: Backend<Block, Blake2Hasher> + 'static,
E: CallExecutor<Block, Blake2Hasher> + 'static + Clone + Send + Sync,
DigestFor<Block>: Encode,
@@ -532,7 +532,7 @@ impl<B, E, Block: BlockT<Hash=H256>, RA, SC>
impl<B, E, Block: BlockT<Hash=H256>, RA, SC>
GrandpaBlockImport<B, E, Block, RA, SC>
where
NumberFor<Block>: grandpa::BlockNumberOps,
NumberFor<Block>: finality_grandpa::BlockNumberOps,
B: Backend<Block, Blake2Hasher> + 'static,
E: CallExecutor<Block, Blake2Hasher> + 'static + Clone + Send + Sync,
RA: Send + Sync,
@@ -16,16 +16,16 @@
use std::collections::{HashMap, HashSet};
use client::Client;
use client_api::{CallExecutor, backend::Backend};
use sc_client::Client;
use sc_client_api::{CallExecutor, backend::Backend};
use sp_blockchain::Error as ClientError;
use codec::{Encode, Decode};
use grandpa::voter_set::VoterSet;
use grandpa::{Error as GrandpaError};
use parity_scale_codec::{Encode, Decode};
use finality_grandpa::voter_set::VoterSet;
use finality_grandpa::{Error as GrandpaError};
use sp_runtime::generic::BlockId;
use sp_runtime::traits::{NumberFor, Block as BlockT, Header as HeaderT};
use primitives::{H256, Blake2Hasher};
use fg_primitives::AuthorityId;
use sp_core::{H256, Blake2Hasher};
use sp_finality_grandpa::AuthorityId;
use crate::{Commit, Error};
use crate::communication;
@@ -98,7 +98,7 @@ impl<Block: BlockT<Hash=H256>> GrandpaJustification<Block> {
set_id: u64,
voters: &VoterSet<AuthorityId>,
) -> Result<GrandpaJustification<Block>, ClientError> where
NumberFor<Block>: grandpa::BlockNumberOps,
NumberFor<Block>: finality_grandpa::BlockNumberOps,
{
let justification = GrandpaJustification::<Block>::decode(&mut &*encoded)
@@ -115,13 +115,13 @@ impl<Block: BlockT<Hash=H256>> GrandpaJustification<Block> {
/// Validate the commit and the votes' ancestry proofs.
pub(crate) fn verify(&self, set_id: u64, voters: &VoterSet<AuthorityId>) -> Result<(), ClientError>
where
NumberFor<Block>: grandpa::BlockNumberOps,
NumberFor<Block>: finality_grandpa::BlockNumberOps,
{
use grandpa::Chain;
use finality_grandpa::Chain;
let ancestry_chain = AncestryChain::<Block>::new(&self.votes_ancestries);
match grandpa::validate_commit(
match finality_grandpa::validate_commit(
&self.commit,
voters,
&ancestry_chain,
@@ -136,7 +136,7 @@ impl<Block: BlockT<Hash=H256>> GrandpaJustification<Block> {
let mut visited_hashes = HashSet::new();
for signed in self.commit.precommits.iter() {
if let Err(_) = communication::check_message_sig::<Block>(
&grandpa::Message::Precommit(signed.precommit.clone()),
&finality_grandpa::Message::Precommit(signed.precommit.clone()),
&signed.id,
&signed.signature,
self.round,
@@ -179,7 +179,7 @@ impl<Block: BlockT<Hash=H256>> GrandpaJustification<Block> {
}
}
/// A utility trait implementing `grandpa::Chain` using a given set of headers.
/// A utility trait implementing `finality_grandpa::Chain` using a given set of headers.
/// This is useful when validating commits, using the given set of headers to
/// verify a valid ancestry route to the target commit block.
struct AncestryChain<Block: BlockT> {
@@ -198,8 +198,8 @@ impl<Block: BlockT> AncestryChain<Block> {
}
}
impl<Block: BlockT> grandpa::Chain<Block::Hash, NumberFor<Block>> for AncestryChain<Block> where
NumberFor<Block>: grandpa::BlockNumberOps
impl<Block: BlockT> finality_grandpa::Chain<Block::Hash, NumberFor<Block>> for AncestryChain<Block> where
NumberFor<Block>: finality_grandpa::BlockNumberOps
{
fn ancestry(&self, base: Block::Hash, block: Block::Hash) -> Result<Vec<Block::Hash>, GrandpaError> {
let mut route = Vec::new();
+32 -32
View File
@@ -55,23 +55,23 @@
use futures::prelude::*;
use log::{debug, error, info};
use futures::sync::mpsc;
use client_api::{BlockchainEvents, CallExecutor, backend::Backend, ExecutionStrategy};
use sc_client_api::{BlockchainEvents, CallExecutor, backend::Backend, ExecutionStrategy};
use sp_blockchain::{HeaderBackend, Error as ClientError};
use client::Client;
use codec::{Decode, Encode};
use sc_client::Client;
use parity_scale_codec::{Decode, Encode};
use sp_runtime::generic::BlockId;
use sp_runtime::traits::{NumberFor, Block as BlockT, DigestFor, Zero};
use keystore::KeyStorePtr;
use inherents::InherentDataProviders;
use consensus_common::SelectChain;
use primitives::{H256, Blake2Hasher, Pair};
use sc_keystore::KeyStorePtr;
use sp_inherents::InherentDataProviders;
use sp_consensus::SelectChain;
use sp_core::{H256, Blake2Hasher, Pair};
use sc_telemetry::{telemetry, CONSENSUS_INFO, CONSENSUS_DEBUG, CONSENSUS_WARN};
use serde_json;
use sp_finality_tracker;
use grandpa::Error as GrandpaError;
use grandpa::{voter, BlockNumberOps, voter_set::VoterSet};
use finality_grandpa::Error as GrandpaError;
use finality_grandpa::{voter, BlockNumberOps, voter_set::VoterSet};
use std::{fmt, io};
use std::sync::Arc;
@@ -90,7 +90,7 @@ mod observer;
mod until_imported;
mod voting_rule;
pub use network_gossip::Network;
pub use sc_network_gossip::Network;
pub use finality_proof::FinalityProofProvider;
pub use justification::GrandpaJustification;
pub use light_import::light_block_import;
@@ -104,18 +104,18 @@ use environment::{Environment, VoterSetState};
use import::GrandpaBlockImport;
use until_imported::UntilGlobalMessageBlocksImported;
use communication::NetworkBridge;
use fg_primitives::{AuthorityList, AuthorityPair, AuthoritySignature, SetId};
use sp_finality_grandpa::{AuthorityList, AuthorityPair, AuthoritySignature, SetId};
// Re-export these two because it's just so damn convenient.
pub use fg_primitives::{AuthorityId, ScheduledChange};
pub use sp_finality_grandpa::{AuthorityId, ScheduledChange};
#[cfg(test)]
mod tests;
/// A GRANDPA message for a substrate chain.
pub type Message<Block> = grandpa::Message<<Block as BlockT>::Hash, NumberFor<Block>>;
pub type Message<Block> = finality_grandpa::Message<<Block as BlockT>::Hash, NumberFor<Block>>;
/// A signed message.
pub type SignedMessage<Block> = grandpa::SignedMessage<
pub type SignedMessage<Block> = finality_grandpa::SignedMessage<
<Block as BlockT>::Hash,
NumberFor<Block>,
AuthoritySignature,
@@ -123,27 +123,27 @@ pub type SignedMessage<Block> = grandpa::SignedMessage<
>;
/// A primary propose message for this chain's block type.
pub type PrimaryPropose<Block> = grandpa::PrimaryPropose<<Block as BlockT>::Hash, NumberFor<Block>>;
pub type PrimaryPropose<Block> = finality_grandpa::PrimaryPropose<<Block as BlockT>::Hash, NumberFor<Block>>;
/// A prevote message for this chain's block type.
pub type Prevote<Block> = grandpa::Prevote<<Block as BlockT>::Hash, NumberFor<Block>>;
pub type Prevote<Block> = finality_grandpa::Prevote<<Block as BlockT>::Hash, NumberFor<Block>>;
/// A precommit message for this chain's block type.
pub type Precommit<Block> = grandpa::Precommit<<Block as BlockT>::Hash, NumberFor<Block>>;
pub type Precommit<Block> = finality_grandpa::Precommit<<Block as BlockT>::Hash, NumberFor<Block>>;
/// A catch up message for this chain's block type.
pub type CatchUp<Block> = grandpa::CatchUp<
pub type CatchUp<Block> = finality_grandpa::CatchUp<
<Block as BlockT>::Hash,
NumberFor<Block>,
AuthoritySignature,
AuthorityId,
>;
/// A commit message for this chain's block type.
pub type Commit<Block> = grandpa::Commit<
pub type Commit<Block> = finality_grandpa::Commit<
<Block as BlockT>::Hash,
NumberFor<Block>,
AuthoritySignature,
AuthorityId,
>;
/// A compact commit message for this chain's block type.
pub type CompactCommit<Block> = grandpa::CompactCommit<
pub type CompactCommit<Block> = finality_grandpa::CompactCommit<
<Block as BlockT>::Hash,
NumberFor<Block>,
AuthoritySignature,
@@ -152,7 +152,7 @@ pub type CompactCommit<Block> = grandpa::CompactCommit<
/// A global communication input stream for commits and catch up messages. Not
/// exposed publicly, used internally to simplify types in the communication
/// layer.
type CommunicationIn<Block> = grandpa::voter::CommunicationIn<
type CommunicationIn<Block> = finality_grandpa::voter::CommunicationIn<
<Block as BlockT>::Hash,
NumberFor<Block>,
AuthoritySignature,
@@ -162,7 +162,7 @@ type CommunicationIn<Block> = grandpa::voter::CommunicationIn<
/// Global communication input stream for commits and catch up messages, with
/// the hash type not being derived from the block, useful for forcing the hash
/// to some type (e.g. `H256`) when the compiler can't do the inference.
type CommunicationInH<Block, H> = grandpa::voter::CommunicationIn<
type CommunicationInH<Block, H> = finality_grandpa::voter::CommunicationIn<
H,
NumberFor<Block>,
AuthoritySignature,
@@ -171,7 +171,7 @@ type CommunicationInH<Block, H> = grandpa::voter::CommunicationIn<
/// A global communication sink for commits. Not exposed publicly, used
/// internally to simplify types in the communication layer.
type CommunicationOut<Block> = grandpa::voter::CommunicationOut<
type CommunicationOut<Block> = finality_grandpa::voter::CommunicationOut<
<Block as BlockT>::Hash,
NumberFor<Block>,
AuthoritySignature,
@@ -181,7 +181,7 @@ type CommunicationOut<Block> = grandpa::voter::CommunicationOut<
/// Global communication sink for commits with the hash type not being derived
/// from the block, useful for forcing the hash to some type (e.g. `H256`) when
/// the compiler can't do the inference.
type CommunicationOutH<Block, H> = grandpa::voter::CommunicationOut<
type CommunicationOutH<Block, H> = finality_grandpa::voter::CommunicationOut<
H,
NumberFor<Block>,
AuthoritySignature,
@@ -207,7 +207,7 @@ pub struct Config {
/// Some local identifier of the voter.
pub name: Option<String>,
/// The keystore that manages the keys of this node.
pub keystore: Option<keystore::KeyStorePtr>,
pub keystore: Option<sc_keystore::KeyStorePtr>,
}
impl Config {
@@ -273,13 +273,13 @@ pub(crate) trait BlockSyncRequester<Block: BlockT> {
/// If the given vector of peers is empty then the underlying implementation
/// should make a best effort to fetch the block from any peers it is
/// connected to (NOTE: this assumption will change in the future #3629).
fn set_sync_fork_request(&self, peers: Vec<network::PeerId>, hash: Block::Hash, number: NumberFor<Block>);
fn set_sync_fork_request(&self, peers: Vec<sc_network::PeerId>, hash: Block::Hash, number: NumberFor<Block>);
}
impl<Block> BlockSyncRequester<Block> for NetworkBridge<Block> where
Block: BlockT,
{
fn set_sync_fork_request(&self, peers: Vec<network::PeerId>, hash: Block::Hash, number: NumberFor<Block>) {
fn set_sync_fork_request(&self, peers: Vec<sc_network::PeerId>, hash: Block::Hash, number: NumberFor<Block>) {
NetworkBridge::set_sync_fork_request(self, peers, hash, number)
}
}
@@ -332,8 +332,8 @@ impl<H, N> From<ClientError> for CommandOrError<H, N> {
}
}
impl<H, N> From<grandpa::Error> for CommandOrError<H, N> {
fn from(e: grandpa::Error) -> Self {
impl<H, N> From<finality_grandpa::Error> for CommandOrError<H, N> {
fn from(e: finality_grandpa::Error) -> Self {
CommandOrError::Error(Error::from(e))
}
}
@@ -496,7 +496,7 @@ fn global_communication<Block: BlockT<Hash=H256>, B, E, RA>(
fn register_finality_tracker_inherent_data_provider<B, E, Block: BlockT<Hash=H256>, RA>(
client: Arc<Client<B, E, Block, RA>>,
inherent_data_providers: &InherentDataProviders,
) -> Result<(), consensus_common::Error> where
) -> Result<(), sp_consensus::Error> where
B: Backend<Block, Blake2Hasher> + 'static,
E: CallExecutor<Block, Blake2Hasher> + Send + Sync + 'static,
RA: Send + Sync + 'static,
@@ -514,7 +514,7 @@ fn register_finality_tracker_inherent_data_provider<B, E, Block: BlockT<Hash=H25
Ok(info.finalized_number)
}
}))
.map_err(|err| consensus_common::Error::InherentData(err.into()))
.map_err(|err| sp_consensus::Error::InherentData(err.into()))
} else {
Ok(())
}
@@ -902,7 +902,7 @@ pub fn setup_disabled_grandpa<B, E, Block: BlockT<Hash=H256>, RA, N>(
client: Arc<Client<B, E, Block, RA>>,
inherent_data_providers: &InherentDataProviders,
network: N,
) -> Result<(), consensus_common::Error> where
) -> Result<(), sp_consensus::Error> where
B: Backend<Block, Blake2Hasher> + 'static,
E: CallExecutor<Block, Blake2Hasher> + Send + Sync + 'static,
RA: Send + Sync + 'static,
@@ -18,21 +18,21 @@ use std::collections::HashMap;
use std::sync::Arc;
use log::{info, trace, warn};
use parking_lot::RwLock;
use client::Client;
use client_api::{CallExecutor, backend::{AuxStore, Backend, Finalizer}};
use sc_client::Client;
use sc_client_api::{CallExecutor, backend::{AuxStore, Backend, Finalizer}};
use sp_blockchain::{HeaderBackend, Error as ClientError, well_known_cache_keys};
use codec::{Encode, Decode};
use consensus_common::{
use parity_scale_codec::{Encode, Decode};
use sp_consensus::{
import_queue::Verifier,
BlockOrigin, BlockImport, FinalityProofImport, BlockImportParams, ImportResult, ImportedAux,
BlockCheckParams, Error as ConsensusError,
};
use network::config::{BoxFinalityProofRequestBuilder, FinalityProofRequestBuilder};
use sc_network::config::{BoxFinalityProofRequestBuilder, FinalityProofRequestBuilder};
use sp_runtime::Justification;
use sp_runtime::traits::{NumberFor, Block as BlockT, Header as HeaderT, DigestFor};
use fg_primitives::{self, AuthorityList};
use sp_finality_grandpa::{self, AuthorityList};
use sp_runtime::generic::BlockId;
use primitives::{H256, Blake2Hasher};
use sp_core::{H256, Blake2Hasher};
use crate::GenesisAuthoritySetProvider;
use crate::aux_schema::load_decode;
@@ -120,7 +120,7 @@ impl<B, E, Block: BlockT<Hash=H256>, RA> GrandpaLightBlockImport<B, E, Block, RA
impl<B, E, Block: BlockT<Hash=H256>, RA> BlockImport<Block>
for GrandpaLightBlockImport<B, E, Block, RA> where
NumberFor<Block>: grandpa::BlockNumberOps,
NumberFor<Block>: finality_grandpa::BlockNumberOps,
B: Backend<Block, Blake2Hasher> + 'static,
E: CallExecutor<Block, Blake2Hasher> + 'static + Clone + Send + Sync,
DigestFor<Block>: Encode,
@@ -148,7 +148,7 @@ impl<B, E, Block: BlockT<Hash=H256>, RA> BlockImport<Block>
impl<B, E, Block: BlockT<Hash=H256>, RA> FinalityProofImport<Block>
for GrandpaLightBlockImport<B, E, Block, RA> where
NumberFor<Block>: grandpa::BlockNumberOps,
NumberFor<Block>: finality_grandpa::BlockNumberOps,
B: Backend<Block, Blake2Hasher> + 'static,
E: CallExecutor<Block, Blake2Hasher> + 'static + Clone + Send + Sync,
DigestFor<Block>: Encode,
@@ -194,7 +194,7 @@ impl LightAuthoritySet {
/// Get a genesis set with given authorities.
pub fn genesis(initial: AuthorityList) -> Self {
LightAuthoritySet {
set_id: fg_primitives::SetId::default(),
set_id: sp_finality_grandpa::SetId::default(),
authorities: initial,
}
}
@@ -242,7 +242,7 @@ fn do_import_block<B, C, Block: BlockT<Hash=H256>, J>(
+ BlockImport<Block>
+ Clone,
B: Backend<Block, Blake2Hasher> + 'static,
NumberFor<Block>: grandpa::BlockNumberOps,
NumberFor<Block>: finality_grandpa::BlockNumberOps,
DigestFor<Block>: Encode,
J: ProvableJustification<Block::Header>,
{
@@ -306,7 +306,7 @@ fn do_import_finality_proof<B, C, Block: BlockT<Hash=H256>, J>(
+ Clone,
B: Backend<Block, Blake2Hasher> + 'static,
DigestFor<Block>: Encode,
NumberFor<Block>: grandpa::BlockNumberOps,
NumberFor<Block>: finality_grandpa::BlockNumberOps,
J: ProvableJustification<Block::Header>,
{
let authority_set_id = data.authority_set.set_id();
@@ -369,7 +369,7 @@ fn do_import_justification<B, C, Block: BlockT<Hash=H256>, J>(
+ Finalizer<Block, Blake2Hasher, B>
+ Clone,
B: Backend<Block, Blake2Hasher> + 'static,
NumberFor<Block>: grandpa::BlockNumberOps,
NumberFor<Block>: finality_grandpa::BlockNumberOps,
J: ProvableJustification<Block::Header>,
{
// with justification, we have two cases
@@ -440,7 +440,7 @@ fn do_finalize_block<B, C, Block: BlockT<Hash=H256>>(
+ Finalizer<Block, Blake2Hasher, B>
+ Clone,
B: Backend<Block, Blake2Hasher> + 'static,
NumberFor<Block>: grandpa::BlockNumberOps,
NumberFor<Block>: finality_grandpa::BlockNumberOps,
{
// finalize the block
client.finalize_block(BlockId::Hash(hash), Some(justification), true).map_err(|e| {
@@ -540,11 +540,11 @@ fn on_post_finalization_error(error: ClientError, value_type: &str) -> Consensus
#[cfg(test)]
pub mod tests {
use super::*;
use consensus_common::ForkChoiceStrategy;
use fg_primitives::AuthorityId;
use primitives::{H256, crypto::Public};
use test_client::client::in_mem::Blockchain as InMemoryAuxStore;
use test_client::runtime::{Block, Header};
use sp_consensus::ForkChoiceStrategy;
use sp_finality_grandpa::AuthorityId;
use sp_core::{H256, crypto::Public};
use substrate_test_runtime_client::sc_client::in_mem::Blockchain as InMemoryAuxStore;
use substrate_test_runtime_client::runtime::{Block, Header};
use crate::tests::TestApi;
use crate::finality_proof::tests::TestJustification;
@@ -554,7 +554,7 @@ pub mod tests {
impl<B, E, Block: BlockT<Hash=H256>, RA> Clone
for NoJustificationsImport<B, E, Block, RA> where
NumberFor<Block>: grandpa::BlockNumberOps,
NumberFor<Block>: finality_grandpa::BlockNumberOps,
B: Backend<Block, Blake2Hasher> + 'static,
E: CallExecutor<Block, Blake2Hasher> + 'static + Clone + Send + Sync,
DigestFor<Block>: Encode,
@@ -567,7 +567,7 @@ pub mod tests {
impl<B, E, Block: BlockT<Hash=H256>, RA> BlockImport<Block>
for NoJustificationsImport<B, E, Block, RA> where
NumberFor<Block>: grandpa::BlockNumberOps,
NumberFor<Block>: finality_grandpa::BlockNumberOps,
B: Backend<Block, Blake2Hasher> + 'static,
E: CallExecutor<Block, Blake2Hasher> + 'static + Clone + Send + Sync,
DigestFor<Block>: Encode,
@@ -594,7 +594,7 @@ pub mod tests {
impl<B, E, Block: BlockT<Hash=H256>, RA> FinalityProofImport<Block>
for NoJustificationsImport<B, E, Block, RA> where
NumberFor<Block>: grandpa::BlockNumberOps,
NumberFor<Block>: finality_grandpa::BlockNumberOps,
B: Backend<Block, Blake2Hasher> + 'static,
E: CallExecutor<Block, Blake2Hasher> + 'static + Clone + Send + Sync,
DigestFor<Block>: Encode,
@@ -637,7 +637,7 @@ pub mod tests {
new_cache: HashMap<well_known_cache_keys::Id, Vec<u8>>,
justification: Option<Justification>,
) -> ImportResult {
let (client, _backend) = test_client::new_light();
let (client, _backend) = substrate_test_runtime_client::new_light();
let mut import_data = LightImportData {
last_finalized: Default::default(),
authority_set: LightAuthoritySet::genesis(vec![(AuthorityId::from_slice(&[1; 32]), 1)]),
@@ -19,16 +19,16 @@ use std::sync::Arc;
use futures::prelude::*;
use futures::{future, sync::mpsc};
use grandpa::{
use finality_grandpa::{
BlockNumberOps, Error as GrandpaError, voter, voter_set::VoterSet
};
use log::{debug, info, warn};
use consensus_common::SelectChain;
use client_api::{CallExecutor, backend::Backend};
use client::Client;
use sp_consensus::SelectChain;
use sc_client_api::{CallExecutor, backend::Backend};
use sc_client::Client;
use sp_runtime::traits::{NumberFor, Block as BlockT};
use primitives::{H256, Blake2Hasher};
use sp_core::{H256, Blake2Hasher};
use crate::{
global_communication, CommandOrError, CommunicationIn, Config, environment,
@@ -37,11 +37,11 @@ use crate::{
use crate::authorities::SharedAuthoritySet;
use crate::communication::NetworkBridge;
use crate::consensus_changes::SharedConsensusChanges;
use fg_primitives::AuthorityId;
use sp_finality_grandpa::AuthorityId;
struct ObserverChain<'a, Block: BlockT, B, E, RA>(&'a Client<B, E, Block, RA>);
impl<'a, Block: BlockT<Hash=H256>, B, E, RA> grandpa::Chain<Block::Hash, NumberFor<Block>>
impl<'a, Block: BlockT<Hash=H256>, B, E, RA> finality_grandpa::Chain<Block::Hash, NumberFor<Block>>
for ObserverChain<'a, Block, B, E, RA> where
B: Backend<Block, Blake2Hasher>,
E: CallExecutor<Block, Blake2Hasher>,
@@ -84,7 +84,7 @@ fn grandpa_observer<B, E, Block: BlockT<Hash=H256>, RA, S, F>(
let observer = commits.fold(last_finalized_number, move |last_finalized_number, global| {
let (round, commit, callback) = match global {
voter::CommunicationIn::Commit(round, commit, callback) => {
let commit = grandpa::Commit::from(commit);
let commit = finality_grandpa::Commit::from(commit);
(round, commit, callback)
},
voter::CommunicationIn::CatchUp(..) => {
@@ -99,7 +99,7 @@ fn grandpa_observer<B, E, Block: BlockT<Hash=H256>, RA, S, F>(
return future::ok(last_finalized_number);
}
let validation_result = match grandpa::validate_commit(
let validation_result = match finality_grandpa::validate_commit(
&commit,
&voters,
&ObserverChain(&*client),
@@ -130,14 +130,14 @@ fn grandpa_observer<B, E, Block: BlockT<Hash=H256>, RA, S, F>(
// and that implies that the next round has started.
note_round(round + 1);
grandpa::process_commit_validation_result(validation_result, callback);
finality_grandpa::process_commit_validation_result(validation_result, callback);
// proceed processing with new finalized block number
future::ok(finalized_number)
} else {
debug!(target: "afg", "Received invalid commit: ({:?}, {:?})", round, commit);
grandpa::process_commit_validation_result(validation_result, callback);
finality_grandpa::process_commit_validation_result(validation_result, callback);
// commit is invalid, continue processing commits with the current state
future::ok(last_finalized_number)
@@ -207,7 +207,7 @@ struct ObserverWork<B: BlockT<Hash=H256>, E, Backend, RA> {
client: Arc<Client<Backend, E, B, RA>>,
network: NetworkBridge<B>,
persistent_data: PersistentData<B>,
keystore: Option<keystore::KeyStorePtr>,
keystore: Option<sc_keystore::KeyStorePtr>,
voter_commands_rx: mpsc::UnboundedReceiver<VoterCommand<B::Hash, NumberFor<B>>>,
}
@@ -223,7 +223,7 @@ where
client: Arc<Client<Bk, E, B, RA>>,
network: NetworkBridge<B>,
persistent_data: PersistentData<B>,
keystore: Option<keystore::KeyStorePtr>,
keystore: Option<sc_keystore::KeyStorePtr>,
voter_commands_rx: mpsc::UnboundedReceiver<VoterCommand<B::Hash, NumberFor<B>>>,
) -> Self {
+31 -31
View File
@@ -20,26 +20,26 @@ use super::*;
use environment::HasVoted;
use sc_network_test::{Block, DummySpecialization, Hash, TestNetFactory, Peer, PeersClient};
use sc_network_test::{PassThroughVerifier};
use network::config::{ProtocolConfig, Roles, BoxFinalityProofRequestBuilder};
use sc_network::config::{ProtocolConfig, Roles, BoxFinalityProofRequestBuilder};
use parking_lot::Mutex;
use futures_timer::Delay;
use futures03::{StreamExt as _, TryStreamExt as _};
use tokio::runtime::current_thread;
use keyring::Ed25519Keyring;
use client::LongestChain;
use sp_keyring::Ed25519Keyring;
use sc_client::LongestChain;
use sp_blockchain::Result;
use sp_api::{Core, RuntimeVersion, ApiExt, StorageProof};
use test_client::{self, runtime::BlockNumber};
use consensus_common::{BlockOrigin, ForkChoiceStrategy, ImportedAux, BlockImportParams, ImportResult};
use consensus_common::import_queue::{BoxBlockImport, BoxJustificationImport, BoxFinalityProofImport};
use substrate_test_runtime_client::{self, runtime::BlockNumber};
use sp_consensus::{BlockOrigin, ForkChoiceStrategy, ImportedAux, BlockImportParams, ImportResult};
use sp_consensus::import_queue::{BoxBlockImport, BoxJustificationImport, BoxFinalityProofImport};
use std::collections::{HashMap, HashSet};
use std::result;
use codec::Decode;
use parity_scale_codec::Decode;
use sp_runtime::traits::{ApiRef, ProvideRuntimeApi, Header as HeaderT};
use sp_runtime::generic::{BlockId, DigestItem};
use primitives::{NativeOrEncoded, ExecutionContext, crypto::Public};
use fg_primitives::{GRANDPA_ENGINE_ID, AuthorityList, GrandpaApi};
use state_machine::{backend::InMemory, prove_read, read_proof_check};
use sp_core::{NativeOrEncoded, ExecutionContext, crypto::Public};
use sp_finality_grandpa::{GRANDPA_ENGINE_ID, AuthorityList, GrandpaApi};
use sp_state_machine::{backend::InMemory, prove_read, read_proof_check};
use std::{pin::Pin, task};
use authorities::AuthoritySet;
@@ -50,11 +50,11 @@ type PeerData =
Mutex<
Option<
LinkHalf<
test_client::Backend,
test_client::Executor,
substrate_test_runtime_client::Backend,
substrate_test_runtime_client::Executor,
Block,
test_client::runtime::RuntimeApi,
LongestChain<test_client::Backend, Block>
substrate_test_runtime_client::runtime::RuntimeApi,
LongestChain<substrate_test_runtime_client::Backend, Block>
>
>
>;
@@ -151,7 +151,7 @@ impl TestNetFactory for GrandpaTestNet {
fn make_finality_proof_provider(
&self,
client: PeersClient
) -> Option<Arc<dyn network::FinalityProofProvider<Block>>> {
) -> Option<Arc<dyn sc_network::FinalityProofProvider<Block>>> {
match client {
PeersClient::Full(_, ref backend) => {
let authorities_provider = Arc::new(self.test_config.clone());
@@ -328,7 +328,7 @@ fn make_ids(keys: &[Ed25519Keyring]) -> AuthorityList {
fn create_keystore(authority: Ed25519Keyring) -> (KeyStorePtr, tempfile::TempDir) {
let keystore_path = tempfile::tempdir().expect("Creates keystore path");
let keystore = keystore::Store::open(keystore_path.path(), None).expect("Creates keystore");
let keystore = sc_keystore::Store::open(keystore_path.path(), None).expect("Creates keystore");
keystore.write().insert_ephemeral_from_seed::<AuthorityPair>(&authority.to_seed())
.expect("Creates authority key");
@@ -441,7 +441,7 @@ fn run_to_completion(
fn add_scheduled_change(block: &mut Block, change: ScheduledChange<BlockNumber>) {
block.header.digest_mut().push(DigestItem::Consensus(
GRANDPA_ENGINE_ID,
fg_primitives::ConsensusLog::ScheduledChange(change).encode(),
sp_finality_grandpa::ConsensusLog::ScheduledChange(change).encode(),
));
}
@@ -452,7 +452,7 @@ fn add_forced_change(
) {
block.header.digest_mut().push(DigestItem::Consensus(
GRANDPA_ENGINE_ID,
fg_primitives::ConsensusLog::ForcedChange(median_last_finalized, change).encode(),
sp_finality_grandpa::ConsensusLog::ForcedChange(median_last_finalized, change).encode(),
));
}
@@ -740,7 +740,7 @@ fn justification_is_emitted_when_consensus_data_changes() {
let mut net = GrandpaTestNet::new(TestApi::new(make_ids(peers)), 3);
// import block#1 WITH consensus data change
let new_authorities = vec![babe_primitives::AuthorityId::from_slice(&[42; 32])];
let new_authorities = vec![sp_consensus_babe::AuthorityId::from_slice(&[42; 32])];
net.peer(0).push_authorities_change_block(new_authorities);
net.block_until_sync(&mut runtime);
let net = Arc::new(Mutex::new(net));
@@ -1241,7 +1241,7 @@ fn voter_persists_its_votes() {
if state.compare_and_swap(0, 1, Ordering::SeqCst) == 0 {
// the first message we receive should be a prevote from alice.
let prevote = match signed.message {
grandpa::Message::Prevote(prevote) => prevote,
finality_grandpa::Message::Prevote(prevote) => prevote,
_ => panic!("voter should prevote."),
};
@@ -1276,19 +1276,19 @@ fn voter_persists_its_votes() {
voter_tx.unbounded_send(()).unwrap();
// and we push our own prevote for block 30
let prevote = grandpa::Prevote {
let prevote = finality_grandpa::Prevote {
target_number: 30,
target_hash: block_30_hash,
};
round_tx.lock().start_send(grandpa::Message::Prevote(prevote)).unwrap();
round_tx.lock().start_send(finality_grandpa::Message::Prevote(prevote)).unwrap();
Ok(())
}).map_err(|_| panic!()))
} else if state.compare_and_swap(1, 2, Ordering::SeqCst) == 1 {
// the next message we receive should be our own prevote
let prevote = match signed.message {
grandpa::Message::Prevote(prevote) => prevote,
finality_grandpa::Message::Prevote(prevote) => prevote,
_ => panic!("We should receive our own prevote."),
};
@@ -1305,7 +1305,7 @@ fn voter_persists_its_votes() {
// we then receive a precommit from alice for block 15
// even though we casted a prevote for block 30
let precommit = match signed.message {
grandpa::Message::Precommit(precommit) => precommit,
finality_grandpa::Message::Precommit(precommit) => precommit,
_ => panic!("voter should precommit."),
};
@@ -1388,7 +1388,7 @@ fn finality_proof_is_fetched_by_light_client_when_consensus_data_changes() {
// import block#1 WITH consensus data change. Light client ignores justification
// && instead fetches finality proof for block #1
net.peer(0).push_authorities_change_block(vec![babe_primitives::AuthorityId::from_slice(&[42; 32])]);
net.peer(0).push_authorities_change_block(vec![sp_consensus_babe::AuthorityId::from_slice(&[42; 32])]);
let net = Arc::new(Mutex::new(net));
run_to_completion(&mut runtime, &threads_pool, 1, net.clone(), peers);
net.lock().block_until_sync(&mut runtime);
@@ -1453,7 +1453,7 @@ fn empty_finality_proof_is_returned_to_light_client_when_authority_set_is_differ
// normally it will reach light client, but because of the forced change, it will not
net.lock().peer(0).push_blocks(8, false); // best is #9
net.lock().peer(0).push_authorities_change_block(
vec![babe_primitives::AuthorityId::from_slice(&[42; 32])]
vec![sp_consensus_babe::AuthorityId::from_slice(&[42; 32])]
); // #10
net.lock().peer(0).push_blocks(1, false); // best is #11
net.lock().block_until_sync(&mut runtime);
@@ -1589,7 +1589,7 @@ fn voter_catches_up_to_latest_round_when_behind() {
#[test]
fn grandpa_environment_respects_voting_rules() {
use grandpa::Chain;
use finality_grandpa::Chain;
use sc_network_test::TestClient;
let threads_pool = futures03::executor::ThreadPool::new().unwrap();
@@ -1741,22 +1741,22 @@ fn imports_justification_for_regular_blocks_on_import() {
let round = 1;
let set_id = 0;
let precommit = grandpa::Precommit {
let precommit = finality_grandpa::Precommit {
target_hash: block_hash,
target_number: *block.header.number(),
};
let msg = grandpa::Message::Precommit(precommit.clone());
let msg = finality_grandpa::Message::Precommit(precommit.clone());
let encoded = communication::localized_payload(round, set_id, &msg);
let signature = peers[0].sign(&encoded[..]).into();
let precommit = grandpa::SignedPrecommit {
let precommit = finality_grandpa::SignedPrecommit {
precommit,
signature,
id: peers[0].public().into(),
};
let commit = grandpa::Commit {
let commit = finality_grandpa::Commit {
target_hash: block_hash,
target_number: *block.header.number(),
precommits: vec![precommit],
@@ -29,19 +29,19 @@ use super::{
};
use log::{debug, warn};
use client_api::{BlockImportNotification, ImportNotifications};
use sc_client_api::{BlockImportNotification, ImportNotifications};
use futures::prelude::*;
use futures::stream::Fuse;
use futures_timer::Delay;
use futures03::{StreamExt as _, TryStreamExt as _};
use grandpa::voter;
use finality_grandpa::voter;
use parking_lot::Mutex;
use sp_runtime::traits::{Block as BlockT, Header as HeaderT, NumberFor};
use std::collections::{HashMap, VecDeque};
use std::sync::{atomic::{AtomicUsize, Ordering}, Arc};
use std::time::{Duration, Instant};
use fg_primitives::AuthorityId;
use sp_finality_grandpa::AuthorityId;
const LOG_PENDING_INTERVAL: Duration = Duration::from_secs(15);
@@ -475,13 +475,13 @@ mod tests {
use super::*;
use crate::{CatchUp, CompactCommit};
use tokio::runtime::current_thread::Runtime;
use test_client::runtime::{Block, Hash, Header};
use consensus_common::BlockOrigin;
use client_api::BlockImportNotification;
use substrate_test_runtime_client::runtime::{Block, Hash, Header};
use sp_consensus::BlockOrigin;
use sc_client_api::BlockImportNotification;
use futures::future::Either;
use futures_timer::Delay;
use futures03::{channel::mpsc, future::FutureExt as _, future::TryFutureExt as _};
use grandpa::Precommit;
use finality_grandpa::Precommit;
#[derive(Clone)]
struct TestChainState {
@@ -543,7 +543,7 @@ mod tests {
}
impl BlockSyncRequesterT<Block> for TestBlockSyncRequester {
fn set_sync_fork_request(&self, _peers: Vec<network::PeerId>, hash: Hash, number: NumberFor<Block>) {
fn set_sync_fork_request(&self, _peers: Vec<sc_network::PeerId>, hash: Hash, number: NumberFor<Block>) {
self.requests.lock().push((hash, number));
}
}
@@ -741,10 +741,10 @@ mod tests {
let h3 = make_header(7);
let signed_prevote = |header: &Header| {
grandpa::SignedPrevote {
finality_grandpa::SignedPrevote {
id: Default::default(),
signature: Default::default(),
prevote: grandpa::Prevote {
prevote: finality_grandpa::Prevote {
target_hash: header.hash(),
target_number: *header.number(),
},
@@ -752,10 +752,10 @@ mod tests {
};
let signed_precommit = |header: &Header| {
grandpa::SignedPrecommit {
finality_grandpa::SignedPrecommit {
id: Default::default(),
signature: Default::default(),
precommit: grandpa::Precommit {
precommit: finality_grandpa::Precommit {
target_hash: header.hash(),
target_number: *header.number(),
},
@@ -772,7 +772,7 @@ mod tests {
signed_precommit(&h2),
];
let unknown_catch_up = grandpa::CatchUp {
let unknown_catch_up = finality_grandpa::CatchUp {
round_number: 1,
prevotes,
precommits,
@@ -807,10 +807,10 @@ mod tests {
let h3 = make_header(7);
let signed_prevote = |header: &Header| {
grandpa::SignedPrevote {
finality_grandpa::SignedPrevote {
id: Default::default(),
signature: Default::default(),
prevote: grandpa::Prevote {
prevote: finality_grandpa::Prevote {
target_hash: header.hash(),
target_number: *header.number(),
},
@@ -818,10 +818,10 @@ mod tests {
};
let signed_precommit = |header: &Header| {
grandpa::SignedPrecommit {
finality_grandpa::SignedPrecommit {
id: Default::default(),
signature: Default::default(),
precommit: grandpa::Precommit {
precommit: finality_grandpa::Precommit {
target_hash: header.hash(),
target_number: *header.number(),
},
@@ -838,7 +838,7 @@ mod tests {
signed_precommit(&h2),
];
let unknown_catch_up = grandpa::CatchUp {
let unknown_catch_up = finality_grandpa::CatchUp {
round_number: 1,
prevotes,
precommits,
@@ -22,7 +22,7 @@
use std::sync::Arc;
use client_api::blockchain::HeaderBackend;
use sc_client_api::blockchain::HeaderBackend;
use sp_runtime::generic::BlockId;
use sp_runtime::traits::{Block as BlockT, Header, NumberFor, One, Zero};
+2 -2
View File
@@ -6,8 +6,8 @@ edition = "2018"
[dependencies]
derive_more = "0.99.2"
primitives = { package = "sp-core", path = "../../primitives/core" }
app-crypto = { package = "sp-application-crypto", path = "../../primitives/application-crypto" }
sp-core = { path = "../../primitives/core" }
sp-application-crypto = { path = "../../primitives/application-crypto" }
hex = "0.4.0"
rand = "0.7.2"
serde_json = "1.0.41"
+3 -3
View File
@@ -20,11 +20,11 @@
use std::{collections::HashMap, path::PathBuf, fs::{self, File}, io::{self, Write}, sync::Arc};
use primitives::{
use sp_core::{
crypto::{KeyTypeId, Pair as PairT, Public, IsWrappedBy, Protected}, traits::BareCryptoStore,
};
use app_crypto::{AppKey, AppPublic, AppPair, ed25519, sr25519};
use sp_application_crypto::{AppKey, AppPublic, AppPair, ed25519, sr25519};
use parking_lot::RwLock;
@@ -318,7 +318,7 @@ impl BareCryptoStore for Store {
mod tests {
use super::*;
use tempfile::TempDir;
use primitives::{testing::{SR25519}, crypto::{Ss58Codec}};
use sp_core::{testing::{SR25519}, crypto::{Ss58Codec}};
#[test]
fn basic_store() {
+1 -1
View File
@@ -13,6 +13,6 @@ futures = { version = "0.3.1", features = ["compat"] }
futures-timer = "0.4.0"
lru = "0.1.2"
libp2p = { version = "0.13.0", default-features = false, features = ["libp2p-websocket"] }
network = { package = "sc-network", path = "../network" }
sc-network = { path = "../network" }
parking_lot = "0.9.0"
sp-runtime = { path = "../../primitives/runtime" }
@@ -17,9 +17,9 @@
use crate::Network;
use crate::state_machine::{ConsensusGossip, Validator, TopicNotification};
use network::Context;
use network::message::generic::ConsensusMessage;
use network::{Event, ReputationChange};
use sc_network::Context;
use sc_network::message::generic::ConsensusMessage;
use sc_network::{Event, ReputationChange};
use futures::{prelude::*, channel::mpsc, compat::Compat01As03, task::SpawnExt as _};
use libp2p::PeerId;
@@ -215,7 +215,7 @@ impl<B: BlockT> GossipEngine<B> {
/// Send addressed message to the given peers. The message is not kept or multicast
/// later on.
pub fn send_message(&self, who: Vec<network::PeerId>, data: Vec<u8>) {
pub fn send_message(&self, who: Vec<sc_network::PeerId>, data: Vec<u8>) {
let mut inner = self.inner.lock();
let inner = &mut *inner;
@@ -244,7 +244,7 @@ impl<B: BlockT> GossipEngine<B> {
///
/// Note: this method isn't strictly related to gossiping and should eventually be moved
/// somewhere else.
pub fn set_sync_fork_request(&self, peers: Vec<network::PeerId>, hash: B::Hash, number: NumberFor<B>) {
pub fn set_sync_fork_request(&self, peers: Vec<sc_network::PeerId>, hash: B::Hash, number: NumberFor<B>) {
self.inner.lock().context_ext.set_sync_fork_request(peers, hash, number);
}
}
@@ -287,7 +287,7 @@ impl<B: BlockT, N: Network<B>> Context<B> for ContextOverService<N> {
trait ContextExt<B: BlockT> {
fn announce(&self, block: B::Hash, associated_data: Vec<u8>);
fn set_sync_fork_request(&self, peers: Vec<network::PeerId>, hash: B::Hash, number: NumberFor<B>);
fn set_sync_fork_request(&self, peers: Vec<sc_network::PeerId>, hash: B::Hash, number: NumberFor<B>);
}
impl<B: BlockT, N: Network<B>> ContextExt<B> for ContextOverService<N> {
@@ -295,7 +295,7 @@ impl<B: BlockT, N: Network<B>> ContextExt<B> for ContextOverService<N> {
Network::announce(&self.network, block, associated_data)
}
fn set_sync_fork_request(&self, peers: Vec<network::PeerId>, hash: B::Hash, number: NumberFor<B>) {
fn set_sync_fork_request(&self, peers: Vec<sc_network::PeerId>, hash: B::Hash, number: NumberFor<B>) {
Network::set_sync_fork_request(&self.network, peers, hash, number)
}
}
+2 -2
View File
@@ -59,7 +59,7 @@ pub use self::state_machine::{TopicNotification, MessageIntent};
pub use self::state_machine::{Validator, ValidatorContext, ValidationResult};
pub use self::state_machine::DiscardAll;
use network::{specialization::NetworkSpecialization, Event, ExHashT, NetworkService, PeerId, ReputationChange};
use sc_network::{specialization::NetworkSpecialization, Event, ExHashT, NetworkService, PeerId, ReputationChange};
use sp_runtime::{traits::{Block as BlockT, NumberFor}, ConsensusEngineId};
use std::sync::Arc;
@@ -134,7 +134,7 @@ impl<B: BlockT, S: NetworkSpecialization<B>, H: ExHashT> Network<B> for Arc<Netw
NetworkService::announce_block(self, block, associated_data)
}
fn set_sync_fork_request(&self, peers: Vec<network::PeerId>, hash: B::Hash, number: NumberFor<B>) {
fn set_sync_fork_request(&self, peers: Vec<sc_network::PeerId>, hash: B::Hash, number: NumberFor<B>) {
NetworkService::set_sync_fork_request(self, peers, hash, number)
}
}
@@ -24,9 +24,9 @@ use lru::LruCache;
use libp2p::PeerId;
use sp_runtime::traits::{Block as BlockT, Hash, HashFor};
use sp_runtime::ConsensusEngineId;
pub use network::message::generic::{Message, ConsensusMessage};
use network::Context;
use network::config::Roles;
pub use sc_network::message::generic::{Message, ConsensusMessage};
use sc_network::Context;
use sc_network::config::Roles;
// FIXME: Add additional spam/DoS attack protection: https://github.com/paritytech/substrate/issues/1115
const KNOWN_MESSAGES_CACHE_SIZE: usize = 4096;
@@ -34,7 +34,7 @@ const KNOWN_MESSAGES_CACHE_SIZE: usize = 4096;
const REBROADCAST_INTERVAL: time::Duration = time::Duration::from_secs(30);
mod rep {
use network::ReputationChange as Rep;
use sc_network::ReputationChange as Rep;
/// Reputation change when a peer sends us a gossip message that we didn't know about.
pub const GOSSIP_SUCCESS: Rep = Rep::new(1 << 4, "Successfull gossip");
/// Reputation change when a peer sends us a gossip message that we already knew about.
+12 -12
View File
@@ -24,16 +24,16 @@ rustc-hex = "2.0.1"
rand = "0.7.2"
libp2p = { version = "0.13.0", default-features = false, features = ["libp2p-websocket"] }
fork-tree = { path = "../../utils/fork-tree" }
consensus = { package = "sp-consensus", path = "../../primitives/consensus/common" }
client = { package = "sc-client", path = "../" }
client-api = { package = "sc-client-api", path = "../api" }
sp-consensus = { path = "../../primitives/consensus/common" }
sc-client = { path = "../" }
sc-client-api = { path = "../api" }
sp-blockchain = { path = "../../primitives/blockchain" }
sp-runtime = { path = "../../primitives/runtime" }
sp-arithmetic = { path = "../../primitives/arithmetic" }
primitives = { package = "sp-core", path = "../../primitives/core" }
block-builder = { package = "sc-block-builder", path = "../block-builder" }
sp-core = { path = "../../primitives/core" }
sc-block-builder = { path = "../block-builder" }
codec = { package = "parity-scale-codec", version = "1.0.0", features = ["derive"] }
peerset = { package = "sc-peerset", path = "../peerset" }
sc-peerset = { path = "../peerset" }
serde = { version = "1.0.101", features = ["derive"] }
serde_json = "1.0.41"
slog = { version = "2.5.2", features = ["nested-values"] }
@@ -42,18 +42,18 @@ smallvec = "0.6.10"
tokio-io = "0.1.12"
tokio = { version = "0.1.22", optional = true }
unsigned-varint = { version = "0.2.2", features = ["codec"] }
keyring = { package = "sp-keyring", path = "../../primitives/keyring", optional = true }
test_client = { package = "substrate-test-client", path = "../../test-utils/client", optional = true }
test-client = { package = "substrate-test-runtime-client", path = "../../test-utils/runtime/client", optional = true }
sp-keyring = { path = "../../primitives/keyring", optional = true }
substrate-test-client = { path = "../../test-utils/client", optional = true }
substrate-test-runtime-client = { path = "../../test-utils/runtime/client", optional = true }
erased-serde = "0.3.9"
void = "1.0.2"
zeroize = "1.0.0"
babe-primitives = { package = "sp-consensus-babe", path = "../../primitives/consensus/babe" }
sp-consensus-babe = { path = "../../primitives/consensus/babe" }
[dev-dependencies]
sp-test-primitives = { path = "../../primitives/test-primitives" }
env_logger = "0.7.0"
keyring = { package = "sp-keyring", path = "../../primitives/keyring" }
sp-keyring = { path = "../../primitives/keyring" }
quickcheck = "0.9.0"
rand = "0.7.2"
tempfile = "3.1.0"
@@ -61,4 +61,4 @@ tokio = "0.1.22"
[features]
default = []
test-helpers = ["keyring", "test-client", "tokio"]
test-helpers = ["sp-keyring", "substrate-test-runtime-client", "tokio"]
+1 -1
View File
@@ -20,7 +20,6 @@ use crate::{
};
use crate::{ExHashT, specialization::NetworkSpecialization};
use crate::protocol::{CustomMessageOutcome, Protocol};
use consensus::{BlockOrigin, import_queue::{IncomingBlock, Origin}};
use futures::prelude::*;
use libp2p::NetworkBehaviour;
use libp2p::core::{Multiaddr, PeerId, PublicKey};
@@ -28,6 +27,7 @@ use libp2p::kad::record;
use libp2p::swarm::{NetworkBehaviourAction, NetworkBehaviourEventProcess};
use libp2p::core::{nodes::Substream, muxing::StreamMuxerBox};
use log::{debug, warn};
use sp_consensus::{BlockOrigin, import_queue::{IncomingBlock, Origin}};
use sp_runtime::{traits::{Block as BlockT, NumberFor}, Justification};
use std::iter;
use void;
+6 -6
View File
@@ -16,15 +16,15 @@
//! Blockchain access trait
use client::Client as SubstrateClient;
use sc_client::Client as SubstrateClient;
use sp_blockchain::Error;
use client_api::{ChangesProof, StorageProof, ClientInfo, CallExecutor};
use consensus::{BlockImport, BlockStatus, Error as ConsensusError};
use sc_client_api::{ChangesProof, StorageProof, ClientInfo, CallExecutor};
use sp_consensus::{BlockImport, BlockStatus, Error as ConsensusError};
use sp_runtime::traits::{Block as BlockT, Header as HeaderT};
use sp_runtime::generic::{BlockId};
use sp_runtime::Justification;
use primitives::{H256, Blake2Hasher};
use primitives::storage::{StorageKey, ChildInfo};
use sp_core::{H256, Blake2Hasher};
use sp_core::storage::{StorageKey, ChildInfo};
/// Local client abstraction for the network.
pub trait Client<Block: BlockT>: Send + Sync {
@@ -93,7 +93,7 @@ impl<Block: BlockT> FinalityProofProvider<Block> for () {
}
impl<B, E, Block, RA> Client<Block> for SubstrateClient<B, E, Block, RA> where
B: client_api::backend::Backend<Block, Blake2Hasher> + Send + Sync + 'static,
B: sc_client_api::backend::Backend<Block, Blake2Hasher> + Send + Sync + 'static,
E: CallExecutor<Block, Blake2Hasher> + Send + Sync + 'static,
Self: BlockImport<Block, Error=ConsensusError>,
Block: BlockT<Hash=H256>,
+1 -1
View File
@@ -26,7 +26,7 @@ use crate::chain::{Client, FinalityProofProvider};
use crate::on_demand_layer::OnDemand;
use crate::service::{ExHashT, TransactionPool};
use bitflags::bitflags;
use consensus::{block_validation::BlockAnnounceValidator, import_queue::ImportQueue};
use sp_consensus::{block_validation::BlockAnnounceValidator, import_queue::ImportQueue};
use sp_runtime::traits::{Block as BlockT};
use libp2p::identity::{Keypair, ed25519};
use libp2p::wasm_ext;
+1 -1
View File
@@ -63,7 +63,7 @@ use libp2p::multiaddr::Protocol;
use log::{debug, info, trace, warn};
use std::{cmp, collections::VecDeque, time::Duration};
use tokio_io::{AsyncRead, AsyncWrite};
use primitives::hexdisplay::HexDisplay;
use sp_core::hexdisplay::HexDisplay;
/// Implementation of `NetworkBehaviour` that discovers the nodes on the network.
pub struct DiscoveryBehaviour<TSubstream> {
+1 -1
View File
@@ -195,7 +195,7 @@ pub use libp2p::multiaddr;
pub use message::{generic as generic_message, RequestId, Status as StatusMessage};
pub use on_demand_layer::{OnDemand, RemoteResponse};
pub use peerset::ReputationChange;
pub use sc_peerset::ReputationChange;
// Used by the `construct_simple_protocol!` macro.
#[doc(hidden)]
@@ -23,7 +23,7 @@ use futures::{prelude::*, sync::mpsc, sync::oneshot};
use futures03::compat::{Compat01As03, Future01CompatExt as _};
use parking_lot::Mutex;
use sp_blockchain::Error as ClientError;
use client_api::{Fetcher, FetchChecker, RemoteHeaderRequest,
use sc_client_api::{Fetcher, FetchChecker, RemoteHeaderRequest,
RemoteCallRequest, RemoteReadRequest, RemoteChangesRequest,
RemoteReadChildRequest, RemoteBodyRequest};
use sp_runtime::traits::{Block as BlockT, Header as HeaderT, NumberFor};
+15 -15
View File
@@ -24,8 +24,8 @@ use libp2p::{Multiaddr, PeerId};
use libp2p::core::{ConnectedPoint, nodes::Substream, muxing::StreamMuxerBox};
use libp2p::swarm::{ProtocolsHandler, IntoProtocolsHandler};
use libp2p::swarm::{NetworkBehaviour, NetworkBehaviourAction, PollParameters};
use primitives::storage::{StorageKey, ChildInfo};
use consensus::{
use sp_core::storage::{StorageKey, ChildInfo};
use sp_consensus::{
BlockOrigin,
block_validation::BlockAnnounceValidator,
import_queue::{BlockImportResult, BlockImportError, IncomingBlock, Origin}
@@ -50,7 +50,7 @@ use std::fmt::Write;
use std::{cmp, num::NonZeroUsize, time};
use log::{log, Level, trace, debug, warn, error};
use crate::chain::{Client, FinalityProofProvider};
use client_api::{FetchChecker, ChangesProof, StorageProof};
use sc_client_api::{FetchChecker, ChangesProof, StorageProof};
use crate::error;
use util::LruHashSet;
@@ -89,7 +89,7 @@ const MAX_CONSENSUS_MESSAGES: usize = 256;
const LIGHT_MAXIMAL_BLOCKS_DIFFERENCE: u64 = 8192;
mod rep {
use peerset::ReputationChange as Rep;
use sc_peerset::ReputationChange as Rep;
/// Reputation change when a peer is "clogged", meaning that it's not fast enough to process our
/// messages.
pub const CLOGGED_PEER: Rep = Rep::new(-(1 << 12), "Clogged message queue");
@@ -140,7 +140,7 @@ pub struct Protocol<B: BlockT, S: NetworkSpecialization<B>, H: ExHashT> {
// Connected peers pending Status message.
handshaking_peers: HashMap<PeerId, HandshakingPeer>,
/// Used to report reputation changes.
peerset_handle: peerset::PeersetHandle,
peerset_handle: sc_peerset::PeersetHandle,
transaction_pool: Arc<dyn TransactionPool<H, B>>,
/// When asked for a proof of finality, we use this struct to build one.
finality_proof_provider: Option<Arc<dyn FinalityProofProvider<B>>>,
@@ -195,11 +195,11 @@ pub struct PeerInfo<B: BlockT> {
struct LightDispatchIn<'a> {
behaviour: &'a mut LegacyProto<Substream<StreamMuxerBox>>,
peerset: peerset::PeersetHandle,
peerset: sc_peerset::PeersetHandle,
}
impl<'a, B: BlockT> LightDispatchNetwork<B> for LightDispatchIn<'a> {
fn report_peer(&mut self, who: &PeerId, reputation: peerset::ReputationChange) {
fn report_peer(&mut self, who: &PeerId, reputation: sc_peerset::ReputationChange) {
self.peerset.report_peer(who.clone(), reputation)
}
@@ -323,7 +323,7 @@ impl<'a, B: BlockT> LightDispatchNetwork<B> for LightDispatchIn<'a> {
pub trait Context<B: BlockT> {
/// Adjusts the reputation of the peer. Use this to point out that a peer has been malign or
/// irresponsible or appeared lazy.
fn report_peer(&mut self, who: PeerId, reputation: peerset::ReputationChange);
fn report_peer(&mut self, who: PeerId, reputation: sc_peerset::ReputationChange);
/// Force disconnecting from a peer. Use this when a peer misbehaved.
fn disconnect_peer(&mut self, who: PeerId);
@@ -339,21 +339,21 @@ pub trait Context<B: BlockT> {
struct ProtocolContext<'a, B: 'a + BlockT, H: 'a + ExHashT> {
behaviour: &'a mut LegacyProto<Substream<StreamMuxerBox>>,
context_data: &'a mut ContextData<B, H>,
peerset_handle: &'a peerset::PeersetHandle,
peerset_handle: &'a sc_peerset::PeersetHandle,
}
impl<'a, B: BlockT + 'a, H: 'a + ExHashT> ProtocolContext<'a, B, H> {
fn new(
context_data: &'a mut ContextData<B, H>,
behaviour: &'a mut LegacyProto<Substream<StreamMuxerBox>>,
peerset_handle: &'a peerset::PeersetHandle,
peerset_handle: &'a sc_peerset::PeersetHandle,
) -> Self {
ProtocolContext { context_data, peerset_handle, behaviour }
}
}
impl<'a, B: BlockT + 'a, H: ExHashT + 'a> Context<B> for ProtocolContext<'a, B, H> {
fn report_peer(&mut self, who: PeerId, reputation: peerset::ReputationChange) {
fn report_peer(&mut self, who: PeerId, reputation: sc_peerset::ReputationChange) {
self.peerset_handle.report_peer(who, reputation)
}
@@ -437,9 +437,9 @@ impl<B: BlockT, S: NetworkSpecialization<B>, H: ExHashT> Protocol<B, S, H> {
finality_proof_provider: Option<Arc<dyn FinalityProofProvider<B>>>,
finality_proof_request_builder: Option<BoxFinalityProofRequestBuilder<B>>,
protocol_id: ProtocolId,
peerset_config: peerset::PeersetConfig,
peerset_config: sc_peerset::PeersetConfig,
block_announce_validator: Box<dyn BlockAnnounceValidator<B> + Send>
) -> error::Result<(Protocol<B, S, H>, peerset::PeersetHandle)> {
) -> error::Result<(Protocol<B, S, H>, sc_peerset::PeersetHandle)> {
let info = chain.info();
let sync = ChainSync::new(
config.roles,
@@ -459,7 +459,7 @@ impl<B: BlockT, S: NetworkSpecialization<B>, H: ExHashT> Protocol<B, S, H> {
imp_p
};
let (peerset, peerset_handle) = peerset::Peerset::from_config(peerset_config);
let (peerset, peerset_handle) = sc_peerset::Peerset::from_config(peerset_config);
let versions = &((MIN_VERSION as u8)..=(CURRENT_VERSION as u8)).collect::<Vec<u8>>();
let behaviour = LegacyProto::new(protocol_id, versions, peerset);
@@ -853,7 +853,7 @@ impl<B: BlockT, S: NetworkSpecialization<B>, H: ExHashT> Protocol<B, S, H> {
}
/// Adjusts the reputation of a node.
pub fn report_peer(&self, who: PeerId, reputation: peerset::ReputationChange) {
pub fn report_peer(&self, who: PeerId, reputation: sc_peerset::ReputationChange) {
self.peerset_handle.report_peer(who, reputation)
}

Some files were not shown because too many files have changed in this diff Show More