Run cargo fmt on the whole code base (#9394)

* Run cargo fmt on the whole code base

* Second run

* Add CI check

* Fix compilation

* More unnecessary braces

* Handle weights

* Use --all

* Use correct attributes...

* Fix UI tests

* AHHHHHHHHH

* 🤦

* Docs

* Fix compilation

* 🤷

* Please stop

* 🤦 x 2

* More

* make rustfmt.toml consistent with polkadot

Co-authored-by: André Silva <andrerfosilva@gmail.com>
This commit is contained in:
Bastian Köcher
2021-07-21 16:32:32 +02:00
committed by GitHub
parent d451c38c1c
commit 7b56ab15b4
1010 changed files with 53339 additions and 51208 deletions
+7 -4
View File
@@ -25,8 +25,8 @@ fn main() {
mod cli {
include!("src/cli.rs");
use std::{fs, env, path::Path};
use sc_cli::structopt::clap::Shell;
use std::{env, fs, path::Path};
use substrate_build_script_utils::{generate_cargo_keys, rerun_if_git_head_changed};
pub fn main() {
@@ -51,9 +51,12 @@ mod cli {
Some(dir) => dir,
};
let path = Path::new(&outdir)
.parent().unwrap()
.parent().unwrap()
.parent().unwrap()
.parent()
.unwrap()
.parent()
.unwrap()
.parent()
.unwrap()
.join("completion-scripts");
fs::create_dir(&path).ok();
+5 -10
View File
@@ -17,18 +17,14 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use crate::chain_spec::ChainSpec;
use browser_utils::{browser_configuration, init_logging, set_console_error_panic_hook, Client};
use log::info;
use wasm_bindgen::prelude::*;
use browser_utils::{
Client,
browser_configuration, init_logging, set_console_error_panic_hook,
};
/// Starts the client.
#[wasm_bindgen]
pub fn start_client(chain_spec: Option<String>, log_level: String) -> Result<Client, JsValue> {
start_inner(chain_spec, log_level)
.map_err(|err| JsValue::from_str(&err.to_string()))
start_inner(chain_spec, log_level).map_err(|err| JsValue::from_str(&err.to_string()))
}
fn start_inner(
@@ -53,10 +49,9 @@ fn start_inner(
info!("👤 Role: {:?}", config.role);
// Create the service. This is the most heavy initialization step.
let (task_manager, rpc_handlers) =
crate::service::new_light_base(config)
.map(|(components, rpc_handlers, _, _, _)| (components, rpc_handlers))
.map_err(|e| format!("{:?}", e))?;
let (task_manager, rpc_handlers) = crate::service::new_light_base(config)
.map(|(components, rpc_handlers, _, _, _)| (components, rpc_handlers))
.map_err(|e| format!("{:?}", e))?;
Ok(browser_utils::start_client(task_manager, rpc_handlers))
}
+171 -146
View File
@@ -18,25 +18,26 @@
//! Substrate chain configurations.
use sc_chain_spec::ChainSpecExtension;
use sp_core::{Pair, Public, crypto::UncheckedInto, sr25519};
use serde::{Serialize, Deserialize};
use node_runtime::{
AuthorityDiscoveryConfig, BabeConfig, BalancesConfig, CouncilConfig,
DemocracyConfig, GrandpaConfig, ImOnlineConfig, SessionConfig, SessionKeys, StakerStatus,
StakingConfig, ElectionsConfig, IndicesConfig, SocietyConfig, SudoConfig, SystemConfig,
TechnicalCommitteeConfig, wasm_binary_unwrap, MAX_NOMINATIONS,
};
use node_runtime::Block;
use node_runtime::constants::currency::*;
use sc_service::ChainType;
use grandpa_primitives::AuthorityId as GrandpaId;
use hex_literal::hex;
use node_runtime::{
constants::currency::*, wasm_binary_unwrap, AuthorityDiscoveryConfig, BabeConfig,
BalancesConfig, Block, CouncilConfig, DemocracyConfig, ElectionsConfig, GrandpaConfig,
ImOnlineConfig, IndicesConfig, SessionConfig, SessionKeys, SocietyConfig, StakerStatus,
StakingConfig, SudoConfig, SystemConfig, TechnicalCommitteeConfig, MAX_NOMINATIONS,
};
use pallet_im_online::sr25519::AuthorityId as ImOnlineId;
use sc_chain_spec::ChainSpecExtension;
use sc_service::ChainType;
use sc_telemetry::TelemetryEndpoints;
use grandpa_primitives::{AuthorityId as GrandpaId};
use sp_consensus_babe::{AuthorityId as BabeId};
use pallet_im_online::sr25519::{AuthorityId as ImOnlineId};
use serde::{Deserialize, Serialize};
use sp_authority_discovery::AuthorityId as AuthorityDiscoveryId;
use sp_runtime::{Perbill, traits::{Verify, IdentifyAccount}};
use sp_consensus_babe::AuthorityId as BabeId;
use sp_core::{crypto::UncheckedInto, sr25519, Pair, Public};
use sp_runtime::{
traits::{IdentifyAccount, Verify},
Perbill,
};
pub use node_primitives::{AccountId, Balance, Signature};
pub use node_runtime::GenesisConfig;
@@ -59,10 +60,7 @@ pub struct Extensions {
}
/// Specialized `ChainSpec`.
pub type ChainSpec = sc_service::GenericChainSpec<
GenesisConfig,
Extensions,
>;
pub type ChainSpec = sc_service::GenericChainSpec<GenesisConfig, Extensions>;
/// Flaming Fir testnet generator
pub fn flaming_fir_config() -> Result<ChainSpec, String> {
ChainSpec::from_json_bytes(&include_bytes!("../res/flaming-fir.json")[..])
@@ -84,65 +82,94 @@ fn staging_testnet_config_genesis() -> GenesisConfig {
// and
// for i in 1 2 3 4 ; do for j in session; do subkey --ed25519 inspect "$secret"//fir//$j//$i; done; done
let initial_authorities: Vec<(AccountId, AccountId, GrandpaId, BabeId, ImOnlineId, AuthorityDiscoveryId)> = vec![(
// 5Fbsd6WXDGiLTxunqeK5BATNiocfCqu9bS1yArVjCgeBLkVy
hex!["9c7a2ee14e565db0c69f78c7b4cd839fbf52b607d867e9e9c5a79042898a0d12"].into(),
// 5EnCiV7wSHeNhjW3FSUwiJNkcc2SBkPLn5Nj93FmbLtBjQUq
hex!["781ead1e2fa9ccb74b44c19d29cb2a7a4b5be3972927ae98cd3877523976a276"].into(),
// 5Fb9ayurnxnaXj56CjmyQLBiadfRCqUbL2VWNbbe1nZU6wiC
hex!["9becad03e6dcac03cee07edebca5475314861492cdfc96a2144a67bbe9699332"].unchecked_into(),
// 5EZaeQ8djPcq9pheJUhgerXQZt9YaHnMJpiHMRhwQeinqUW8
hex!["6e7e4eb42cbd2e0ab4cae8708ce5509580b8c04d11f6758dbf686d50fe9f9106"].unchecked_into(),
// 5EZaeQ8djPcq9pheJUhgerXQZt9YaHnMJpiHMRhwQeinqUW8
hex!["6e7e4eb42cbd2e0ab4cae8708ce5509580b8c04d11f6758dbf686d50fe9f9106"].unchecked_into(),
// 5EZaeQ8djPcq9pheJUhgerXQZt9YaHnMJpiHMRhwQeinqUW8
hex!["6e7e4eb42cbd2e0ab4cae8708ce5509580b8c04d11f6758dbf686d50fe9f9106"].unchecked_into(),
),(
// 5ERawXCzCWkjVq3xz1W5KGNtVx2VdefvZ62Bw1FEuZW4Vny2
hex!["68655684472b743e456907b398d3a44c113f189e56d1bbfd55e889e295dfde78"].into(),
// 5Gc4vr42hH1uDZc93Nayk5G7i687bAQdHHc9unLuyeawHipF
hex!["c8dc79e36b29395413399edaec3e20fcca7205fb19776ed8ddb25d6f427ec40e"].into(),
// 5EockCXN6YkiNCDjpqqnbcqd4ad35nU4RmA1ikM4YeRN4WcE
hex!["7932cff431e748892fa48e10c63c17d30f80ca42e4de3921e641249cd7fa3c2f"].unchecked_into(),
// 5DhLtiaQd1L1LU9jaNeeu9HJkP6eyg3BwXA7iNMzKm7qqruQ
hex!["482dbd7297a39fa145c570552249c2ca9dd47e281f0c500c971b59c9dcdcd82e"].unchecked_into(),
// 5DhLtiaQd1L1LU9jaNeeu9HJkP6eyg3BwXA7iNMzKm7qqruQ
hex!["482dbd7297a39fa145c570552249c2ca9dd47e281f0c500c971b59c9dcdcd82e"].unchecked_into(),
// 5DhLtiaQd1L1LU9jaNeeu9HJkP6eyg3BwXA7iNMzKm7qqruQ
hex!["482dbd7297a39fa145c570552249c2ca9dd47e281f0c500c971b59c9dcdcd82e"].unchecked_into(),
),(
// 5DyVtKWPidondEu8iHZgi6Ffv9yrJJ1NDNLom3X9cTDi98qp
hex!["547ff0ab649283a7ae01dbc2eb73932eba2fb09075e9485ff369082a2ff38d65"].into(),
// 5FeD54vGVNpFX3PndHPXJ2MDakc462vBCD5mgtWRnWYCpZU9
hex!["9e42241d7cd91d001773b0b616d523dd80e13c6c2cab860b1234ef1b9ffc1526"].into(),
// 5E1jLYfLdUQKrFrtqoKgFrRvxM3oQPMbf6DfcsrugZZ5Bn8d
hex!["5633b70b80a6c8bb16270f82cca6d56b27ed7b76c8fd5af2986a25a4788ce440"].unchecked_into(),
// 5DhKqkHRkndJu8vq7pi2Q5S3DfftWJHGxbEUNH43b46qNspH
hex!["482a3389a6cf42d8ed83888cfd920fec738ea30f97e44699ada7323f08c3380a"].unchecked_into(),
// 5DhKqkHRkndJu8vq7pi2Q5S3DfftWJHGxbEUNH43b46qNspH
hex!["482a3389a6cf42d8ed83888cfd920fec738ea30f97e44699ada7323f08c3380a"].unchecked_into(),
// 5DhKqkHRkndJu8vq7pi2Q5S3DfftWJHGxbEUNH43b46qNspH
hex!["482a3389a6cf42d8ed83888cfd920fec738ea30f97e44699ada7323f08c3380a"].unchecked_into(),
),(
// 5HYZnKWe5FVZQ33ZRJK1rG3WaLMztxWrrNDb1JRwaHHVWyP9
hex!["f26cdb14b5aec7b2789fd5ca80f979cef3761897ae1f37ffb3e154cbcc1c2663"].into(),
// 5EPQdAQ39WQNLCRjWsCk5jErsCitHiY5ZmjfWzzbXDoAoYbn
hex!["66bc1e5d275da50b72b15de072a2468a5ad414919ca9054d2695767cf650012f"].into(),
// 5DMa31Hd5u1dwoRKgC4uvqyrdK45RHv3CpwvpUC1EzuwDit4
hex!["3919132b851ef0fd2dae42a7e734fe547af5a6b809006100f48944d7fae8e8ef"].unchecked_into(),
// 5C4vDQxA8LTck2xJEy4Yg1hM9qjDt4LvTQaMo4Y8ne43aU6x
hex!["00299981a2b92f878baaf5dbeba5c18d4e70f2a1fcd9c61b32ea18daf38f4378"].unchecked_into(),
// 5C4vDQxA8LTck2xJEy4Yg1hM9qjDt4LvTQaMo4Y8ne43aU6x
hex!["00299981a2b92f878baaf5dbeba5c18d4e70f2a1fcd9c61b32ea18daf38f4378"].unchecked_into(),
// 5C4vDQxA8LTck2xJEy4Yg1hM9qjDt4LvTQaMo4Y8ne43aU6x
hex!["00299981a2b92f878baaf5dbeba5c18d4e70f2a1fcd9c61b32ea18daf38f4378"].unchecked_into(),
)];
let initial_authorities: Vec<(
AccountId,
AccountId,
GrandpaId,
BabeId,
ImOnlineId,
AuthorityDiscoveryId,
)> = vec![
(
// 5Fbsd6WXDGiLTxunqeK5BATNiocfCqu9bS1yArVjCgeBLkVy
hex!["9c7a2ee14e565db0c69f78c7b4cd839fbf52b607d867e9e9c5a79042898a0d12"].into(),
// 5EnCiV7wSHeNhjW3FSUwiJNkcc2SBkPLn5Nj93FmbLtBjQUq
hex!["781ead1e2fa9ccb74b44c19d29cb2a7a4b5be3972927ae98cd3877523976a276"].into(),
// 5Fb9ayurnxnaXj56CjmyQLBiadfRCqUbL2VWNbbe1nZU6wiC
hex!["9becad03e6dcac03cee07edebca5475314861492cdfc96a2144a67bbe9699332"]
.unchecked_into(),
// 5EZaeQ8djPcq9pheJUhgerXQZt9YaHnMJpiHMRhwQeinqUW8
hex!["6e7e4eb42cbd2e0ab4cae8708ce5509580b8c04d11f6758dbf686d50fe9f9106"]
.unchecked_into(),
// 5EZaeQ8djPcq9pheJUhgerXQZt9YaHnMJpiHMRhwQeinqUW8
hex!["6e7e4eb42cbd2e0ab4cae8708ce5509580b8c04d11f6758dbf686d50fe9f9106"]
.unchecked_into(),
// 5EZaeQ8djPcq9pheJUhgerXQZt9YaHnMJpiHMRhwQeinqUW8
hex!["6e7e4eb42cbd2e0ab4cae8708ce5509580b8c04d11f6758dbf686d50fe9f9106"]
.unchecked_into(),
),
(
// 5ERawXCzCWkjVq3xz1W5KGNtVx2VdefvZ62Bw1FEuZW4Vny2
hex!["68655684472b743e456907b398d3a44c113f189e56d1bbfd55e889e295dfde78"].into(),
// 5Gc4vr42hH1uDZc93Nayk5G7i687bAQdHHc9unLuyeawHipF
hex!["c8dc79e36b29395413399edaec3e20fcca7205fb19776ed8ddb25d6f427ec40e"].into(),
// 5EockCXN6YkiNCDjpqqnbcqd4ad35nU4RmA1ikM4YeRN4WcE
hex!["7932cff431e748892fa48e10c63c17d30f80ca42e4de3921e641249cd7fa3c2f"]
.unchecked_into(),
// 5DhLtiaQd1L1LU9jaNeeu9HJkP6eyg3BwXA7iNMzKm7qqruQ
hex!["482dbd7297a39fa145c570552249c2ca9dd47e281f0c500c971b59c9dcdcd82e"]
.unchecked_into(),
// 5DhLtiaQd1L1LU9jaNeeu9HJkP6eyg3BwXA7iNMzKm7qqruQ
hex!["482dbd7297a39fa145c570552249c2ca9dd47e281f0c500c971b59c9dcdcd82e"]
.unchecked_into(),
// 5DhLtiaQd1L1LU9jaNeeu9HJkP6eyg3BwXA7iNMzKm7qqruQ
hex!["482dbd7297a39fa145c570552249c2ca9dd47e281f0c500c971b59c9dcdcd82e"]
.unchecked_into(),
),
(
// 5DyVtKWPidondEu8iHZgi6Ffv9yrJJ1NDNLom3X9cTDi98qp
hex!["547ff0ab649283a7ae01dbc2eb73932eba2fb09075e9485ff369082a2ff38d65"].into(),
// 5FeD54vGVNpFX3PndHPXJ2MDakc462vBCD5mgtWRnWYCpZU9
hex!["9e42241d7cd91d001773b0b616d523dd80e13c6c2cab860b1234ef1b9ffc1526"].into(),
// 5E1jLYfLdUQKrFrtqoKgFrRvxM3oQPMbf6DfcsrugZZ5Bn8d
hex!["5633b70b80a6c8bb16270f82cca6d56b27ed7b76c8fd5af2986a25a4788ce440"]
.unchecked_into(),
// 5DhKqkHRkndJu8vq7pi2Q5S3DfftWJHGxbEUNH43b46qNspH
hex!["482a3389a6cf42d8ed83888cfd920fec738ea30f97e44699ada7323f08c3380a"]
.unchecked_into(),
// 5DhKqkHRkndJu8vq7pi2Q5S3DfftWJHGxbEUNH43b46qNspH
hex!["482a3389a6cf42d8ed83888cfd920fec738ea30f97e44699ada7323f08c3380a"]
.unchecked_into(),
// 5DhKqkHRkndJu8vq7pi2Q5S3DfftWJHGxbEUNH43b46qNspH
hex!["482a3389a6cf42d8ed83888cfd920fec738ea30f97e44699ada7323f08c3380a"]
.unchecked_into(),
),
(
// 5HYZnKWe5FVZQ33ZRJK1rG3WaLMztxWrrNDb1JRwaHHVWyP9
hex!["f26cdb14b5aec7b2789fd5ca80f979cef3761897ae1f37ffb3e154cbcc1c2663"].into(),
// 5EPQdAQ39WQNLCRjWsCk5jErsCitHiY5ZmjfWzzbXDoAoYbn
hex!["66bc1e5d275da50b72b15de072a2468a5ad414919ca9054d2695767cf650012f"].into(),
// 5DMa31Hd5u1dwoRKgC4uvqyrdK45RHv3CpwvpUC1EzuwDit4
hex!["3919132b851ef0fd2dae42a7e734fe547af5a6b809006100f48944d7fae8e8ef"]
.unchecked_into(),
// 5C4vDQxA8LTck2xJEy4Yg1hM9qjDt4LvTQaMo4Y8ne43aU6x
hex!["00299981a2b92f878baaf5dbeba5c18d4e70f2a1fcd9c61b32ea18daf38f4378"]
.unchecked_into(),
// 5C4vDQxA8LTck2xJEy4Yg1hM9qjDt4LvTQaMo4Y8ne43aU6x
hex!["00299981a2b92f878baaf5dbeba5c18d4e70f2a1fcd9c61b32ea18daf38f4378"]
.unchecked_into(),
// 5C4vDQxA8LTck2xJEy4Yg1hM9qjDt4LvTQaMo4Y8ne43aU6x
hex!["00299981a2b92f878baaf5dbeba5c18d4e70f2a1fcd9c61b32ea18daf38f4378"]
.unchecked_into(),
),
];
// generated with secret: subkey inspect "$secret"/fir
let root_key: AccountId = hex![
// 5Ff3iXP75ruzroPWRP2FYBHWnmGGBSb63857BgnzCoXNxfPo
"9ee5e5bdc0ec239eb164f865ecc345ce4c88e76ee002e0f7e318097347471809"
].into();
]
.into();
let endowed_accounts: Vec<AccountId> = vec![root_key.clone()];
@@ -158,8 +185,10 @@ pub fn staging_testnet_config() -> ChainSpec {
ChainType::Live,
staging_testnet_config_genesis,
boot_nodes,
Some(TelemetryEndpoints::new(vec![(STAGING_TELEMETRY_URL.to_string(), 0)])
.expect("Staging telemetry url is valid; qed")),
Some(
TelemetryEndpoints::new(vec![(STAGING_TELEMETRY_URL.to_string(), 0)])
.expect("Staging telemetry url is valid; qed"),
),
None,
None,
Default::default(),
@@ -174,21 +203,17 @@ pub fn get_from_seed<TPublic: Public>(seed: &str) -> <TPublic::Pair as Pair>::Pu
}
/// Helper function to generate an account ID from seed
pub fn get_account_id_from_seed<TPublic: Public>(seed: &str) -> AccountId where
AccountPublic: From<<TPublic::Pair as Pair>::Public>
pub fn get_account_id_from_seed<TPublic: Public>(seed: &str) -> AccountId
where
AccountPublic: From<<TPublic::Pair as Pair>::Public>,
{
AccountPublic::from(get_from_seed::<TPublic>(seed)).into_account()
}
/// Helper function to generate stash, controller and session key from seed
pub fn authority_keys_from_seed(seed: &str) -> (
AccountId,
AccountId,
GrandpaId,
BabeId,
ImOnlineId,
AuthorityDiscoveryId,
) {
pub fn authority_keys_from_seed(
seed: &str,
) -> (AccountId, AccountId, GrandpaId, BabeId, ImOnlineId, AuthorityDiscoveryId) {
(
get_account_id_from_seed::<sr25519::Public>(&format!("{}//stash", seed)),
get_account_id_from_seed::<sr25519::Public>(seed),
@@ -230,11 +255,15 @@ pub fn testnet_genesis(
]
});
// endow all authorities and nominators.
initial_authorities.iter().map(|x| &x.0).chain(initial_nominators.iter()).for_each(|x| {
if !endowed_accounts.contains(&x) {
endowed_accounts.push(x.clone())
}
});
initial_authorities
.iter()
.map(|x| &x.0)
.chain(initial_nominators.iter())
.for_each(|x| {
if !endowed_accounts.contains(&x) {
endowed_accounts.push(x.clone())
}
});
// stakers: all validators and nominators.
let mut rng = rand::thread_rng();
@@ -266,22 +295,20 @@ pub fn testnet_genesis(
changes_trie_config: Default::default(),
},
balances: BalancesConfig {
balances: endowed_accounts.iter().cloned()
.map(|x| (x, ENDOWMENT))
.collect()
},
indices: IndicesConfig {
indices: vec![],
balances: endowed_accounts.iter().cloned().map(|x| (x, ENDOWMENT)).collect(),
},
indices: IndicesConfig { indices: vec![] },
session: SessionConfig {
keys: initial_authorities.iter().map(|x| {
(x.0.clone(), x.0.clone(), session_keys(
x.2.clone(),
x.3.clone(),
x.4.clone(),
x.5.clone(),
))
}).collect::<Vec<_>>(),
keys: initial_authorities
.iter()
.map(|x| {
(
x.0.clone(),
x.0.clone(),
session_keys(x.2.clone(), x.3.clone(), x.4.clone(), x.5.clone()),
)
})
.collect::<Vec<_>>(),
},
staking: StakingConfig {
validator_count: initial_authorities.len() as u32,
@@ -289,47 +316,42 @@ pub fn testnet_genesis(
invulnerables: initial_authorities.iter().map(|x| x.0.clone()).collect(),
slash_reward_fraction: Perbill::from_percent(10),
stakers,
.. Default::default()
..Default::default()
},
democracy: DemocracyConfig::default(),
elections: ElectionsConfig {
members: endowed_accounts.iter()
.take((num_endowed_accounts + 1) / 2)
.cloned()
.map(|member| (member, STASH))
.collect(),
members: endowed_accounts
.iter()
.take((num_endowed_accounts + 1) / 2)
.cloned()
.map(|member| (member, STASH))
.collect(),
},
council: CouncilConfig::default(),
technical_committee: TechnicalCommitteeConfig {
members: endowed_accounts.iter()
.take((num_endowed_accounts + 1) / 2)
.cloned()
.collect(),
members: endowed_accounts
.iter()
.take((num_endowed_accounts + 1) / 2)
.cloned()
.collect(),
phantom: Default::default(),
},
sudo: SudoConfig {
key: root_key,
},
sudo: SudoConfig { key: root_key },
babe: BabeConfig {
authorities: vec![],
epoch_config: Some(node_runtime::BABE_GENESIS_EPOCH_CONFIG),
},
im_online: ImOnlineConfig {
keys: vec![],
},
authority_discovery: AuthorityDiscoveryConfig {
keys: vec![],
},
grandpa: GrandpaConfig {
authorities: vec![],
},
im_online: ImOnlineConfig { keys: vec![] },
authority_discovery: AuthorityDiscoveryConfig { keys: vec![] },
grandpa: GrandpaConfig { authorities: vec![] },
technical_membership: Default::default(),
treasury: Default::default(),
society: SocietyConfig {
members: endowed_accounts.iter()
.take((num_endowed_accounts + 1) / 2)
.cloned()
.collect(),
members: endowed_accounts
.iter()
.take((num_endowed_accounts + 1) / 2)
.cloned()
.collect(),
pot: 0,
max_members: 999,
},
@@ -341,9 +363,7 @@ pub fn testnet_genesis(
fn development_config_genesis() -> GenesisConfig {
testnet_genesis(
vec![
authority_keys_from_seed("Alice"),
],
vec![authority_keys_from_seed("Alice")],
vec![],
get_account_id_from_seed::<sr25519::Public>("Alice"),
None,
@@ -367,10 +387,7 @@ pub fn development_config() -> ChainSpec {
fn local_testnet_genesis() -> GenesisConfig {
testnet_genesis(
vec![
authority_keys_from_seed("Alice"),
authority_keys_from_seed("Bob"),
],
vec![authority_keys_from_seed("Alice"), authority_keys_from_seed("Bob")],
vec![],
get_account_id_from_seed::<sr25519::Public>("Alice"),
None,
@@ -401,9 +418,7 @@ pub(crate) mod tests {
fn local_testnet_genesis_instant_single() -> GenesisConfig {
testnet_genesis(
vec![
authority_keys_from_seed("Alice"),
],
vec![authority_keys_from_seed("Alice")],
vec![],
get_account_id_from_seed::<sr25519::Public>("Alice"),
None,
@@ -446,14 +461,24 @@ pub(crate) mod tests {
sc_service_test::connectivity(
integration_test_config_with_two_authorities(),
|config| {
let NewFullBase { task_manager, client, network, transaction_pool, .. }
= new_full_base(config,|_, _| ())?;
Ok(sc_service_test::TestNetComponents::new(task_manager, client, network, transaction_pool))
let NewFullBase { task_manager, client, network, transaction_pool, .. } =
new_full_base(config, |_, _| ())?;
Ok(sc_service_test::TestNetComponents::new(
task_manager,
client,
network,
transaction_pool,
))
},
|config| {
let (keep_alive, _, client, network, transaction_pool) = new_light_base(config)?;
Ok(sc_service_test::TestNetComponents::new(keep_alive, client, network, transaction_pool))
}
Ok(sc_service_test::TestNetComponents::new(
keep_alive,
client,
network,
transaction_pool,
))
},
);
}
+1 -1
View File
@@ -16,7 +16,7 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use sc_cli::{RunCmd, KeySubcommand, SignCmd, VanityCmd, VerifyCmd};
use sc_cli::{KeySubcommand, RunCmd, SignCmd, VanityCmd, VerifyCmd};
use structopt::StructOpt;
/// An overarching CLI command definition.
+36 -39
View File
@@ -16,12 +16,11 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use crate::{chain_spec, service, Cli, Subcommand};
use crate::{chain_spec, service, service::new_partial, Cli, Subcommand};
use node_executor::Executor;
use node_runtime::{Block, RuntimeApi};
use sc_cli::{Result, SubstrateCli, RuntimeVersion, Role, ChainSpec};
use sc_cli::{ChainSpec, Result, Role, RuntimeVersion, SubstrateCli};
use sc_service::PartialComponents;
use crate::service::new_partial;
impl SubstrateCli for Cli {
fn impl_name() -> String {
@@ -49,17 +48,19 @@ impl SubstrateCli for Cli {
}
fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {
let spec =
match id {
"" => return Err("Please specify which chain you want to run, e.g. --dev or --chain=local".into()),
"dev" => Box::new(chain_spec::development_config()),
"local" => Box::new(chain_spec::local_testnet_config()),
"fir" | "flaming-fir" => Box::new(chain_spec::flaming_fir_config()?),
"staging" => Box::new(chain_spec::staging_testnet_config()),
path => Box::new(chain_spec::ChainSpec::from_json_file(
std::path::PathBuf::from(path),
)?),
};
let spec = match id {
"" =>
return Err(
"Please specify which chain you want to run, e.g. --dev or --chain=local"
.into(),
),
"dev" => Box::new(chain_spec::development_config()),
"local" => Box::new(chain_spec::local_testnet_config()),
"fir" | "flaming-fir" => Box::new(chain_spec::flaming_fir_config()?),
"staging" => Box::new(chain_spec::staging_testnet_config()),
path =>
Box::new(chain_spec::ChainSpec::from_json_file(std::path::PathBuf::from(path))?),
};
Ok(spec)
}
@@ -79,24 +80,25 @@ pub fn run() -> Result<()> {
match config.role {
Role::Light => service::new_light(config),
_ => service::new_full(config),
}.map_err(sc_cli::Error::Service)
}
.map_err(sc_cli::Error::Service)
})
}
},
Some(Subcommand::Inspect(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.sync_run(|config| cmd.run::<Block, RuntimeApi, Executor>(config))
}
Some(Subcommand::Benchmark(cmd)) => {
},
Some(Subcommand::Benchmark(cmd)) =>
if cfg!(feature = "runtime-benchmarks") {
let runner = cli.create_runner(cmd)?;
runner.sync_run(|config| cmd.run::<Block, Executor>(config))
} else {
Err("Benchmarking wasn't enabled when building the node. \
You can enable it with `--features runtime-benchmarks`.".into())
}
}
You can enable it with `--features runtime-benchmarks`."
.into())
},
Some(Subcommand::Key(cmd)) => cmd.run(&cli),
Some(Subcommand::Sign(cmd)) => cmd.run(),
Some(Subcommand::Verify(cmd)) => cmd.run(),
@@ -108,32 +110,30 @@ pub fn run() -> Result<()> {
Some(Subcommand::CheckBlock(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.async_run(|config| {
let PartialComponents { client, task_manager, import_queue, ..}
= new_partial(&config)?;
let PartialComponents { client, task_manager, import_queue, .. } =
new_partial(&config)?;
Ok((cmd.run(client, import_queue), task_manager))
})
},
Some(Subcommand::ExportBlocks(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.async_run(|config| {
let PartialComponents { client, task_manager, ..}
= new_partial(&config)?;
let PartialComponents { client, task_manager, .. } = new_partial(&config)?;
Ok((cmd.run(client, config.database), task_manager))
})
},
Some(Subcommand::ExportState(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.async_run(|config| {
let PartialComponents { client, task_manager, ..}
= new_partial(&config)?;
let PartialComponents { client, task_manager, .. } = new_partial(&config)?;
Ok((cmd.run(client, config.chain_spec), task_manager))
})
},
Some(Subcommand::ImportBlocks(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.async_run(|config| {
let PartialComponents { client, task_manager, import_queue, ..}
= new_partial(&config)?;
let PartialComponents { client, task_manager, import_queue, .. } =
new_partial(&config)?;
Ok((cmd.run(client, import_queue), task_manager))
})
},
@@ -144,8 +144,7 @@ pub fn run() -> Result<()> {
Some(Subcommand::Revert(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.async_run(|config| {
let PartialComponents { client, task_manager, backend, ..}
= new_partial(&config)?;
let PartialComponents { client, task_manager, backend, .. } = new_partial(&config)?;
Ok((cmd.run(client, backend), task_manager))
})
},
@@ -156,18 +155,16 @@ pub fn run() -> Result<()> {
// we don't need any of the components of new_partial, just a runtime, or a task
// manager to do `async_run`.
let registry = config.prometheus_config.as_ref().map(|cfg| &cfg.registry);
let task_manager = sc_service::TaskManager::new(
config.task_executor.clone(),
registry,
).map_err(|e| sc_cli::Error::Service(sc_service::Error::Prometheus(e)))?;
let task_manager =
sc_service::TaskManager::new(config.task_executor.clone(), registry)
.map_err(|e| sc_cli::Error::Service(sc_service::Error::Prometheus(e)))?;
Ok((cmd.run::<Block, Executor>(config), task_manager))
})
},
#[cfg(not(feature = "try-runtime"))]
Some(Subcommand::TryRuntime) => {
Err("TryRuntime wasn't enabled when building the node. \
You can enable it with `--features try-runtime`.".into())
},
Some(Subcommand::TryRuntime) => Err("TryRuntime wasn't enabled when building the node. \
You can enable it with `--features try-runtime`."
.into()),
}
}
+238 -240
View File
@@ -20,20 +20,17 @@
//! Service implementation. Specialized wrapper over substrate service.
use std::sync::Arc;
use sc_consensus_babe;
use futures::prelude::*;
use node_executor::Executor;
use node_primitives::Block;
use node_runtime::RuntimeApi;
use sc_service::{
config::Configuration, error::Error as ServiceError, RpcHandlers, TaskManager,
};
use sc_network::{Event, NetworkService};
use sp_runtime::traits::Block as BlockT;
use futures::prelude::*;
use sc_client_api::{ExecutorProvider, RemoteBackend};
use node_executor::Executor;
use sc_consensus_babe::{self, SlotProportion};
use sc_network::{Event, NetworkService};
use sc_service::{config::Configuration, error::Error as ServiceError, RpcHandlers, TaskManager};
use sc_telemetry::{Telemetry, TelemetryWorker};
use sc_consensus_babe::SlotProportion;
use sp_runtime::traits::Block as BlockT;
use std::sync::Arc;
type FullClient = sc_service::TFullClient<Block, RuntimeApi, Executor>;
type FullBackend = sc_service::TFullBackend<Block>;
@@ -44,25 +41,29 @@ type LightClient = sc_service::TLightClient<Block, RuntimeApi, Executor>;
pub fn new_partial(
config: &Configuration,
) -> Result<sc_service::PartialComponents<
FullClient, FullBackend, FullSelectChain,
sp_consensus::DefaultImportQueue<Block, FullClient>,
sc_transaction_pool::FullPool<Block, FullClient>,
(
impl Fn(
node_rpc::DenyUnsafe,
sc_rpc::SubscriptionTaskExecutor,
) -> node_rpc::IoHandler,
) -> Result<
sc_service::PartialComponents<
FullClient,
FullBackend,
FullSelectChain,
sp_consensus::DefaultImportQueue<Block, FullClient>,
sc_transaction_pool::FullPool<Block, FullClient>,
(
sc_consensus_babe::BabeBlockImport<Block, FullClient, FullGrandpaBlockImport>,
grandpa::LinkHalf<Block, FullClient, FullSelectChain>,
sc_consensus_babe::BabeLink<Block>,
impl Fn(node_rpc::DenyUnsafe, sc_rpc::SubscriptionTaskExecutor) -> node_rpc::IoHandler,
(
sc_consensus_babe::BabeBlockImport<Block, FullClient, FullGrandpaBlockImport>,
grandpa::LinkHalf<Block, FullClient, FullSelectChain>,
sc_consensus_babe::BabeLink<Block>,
),
grandpa::SharedVoterState,
Option<Telemetry>,
),
grandpa::SharedVoterState,
Option<Telemetry>,
)
>, ServiceError> {
let telemetry = config.telemetry_endpoints.clone()
>,
ServiceError,
> {
let telemetry = config
.telemetry_endpoints
.clone()
.filter(|x| !x.is_empty())
.map(|endpoints| -> Result<_, sc_telemetry::Error> {
let worker = TelemetryWorker::new(16)?;
@@ -78,11 +79,10 @@ pub fn new_partial(
)?;
let client = Arc::new(client);
let telemetry = telemetry
.map(|(worker, telemetry)| {
task_manager.spawn_handle().spawn("telemetry", worker.run());
telemetry
});
let telemetry = telemetry.map(|(worker, telemetry)| {
task_manager.spawn_handle().spawn("telemetry", worker.run());
telemetry
});
let select_chain = sc_consensus::LongestChain::new(backend.clone());
@@ -115,21 +115,19 @@ pub fn new_partial(
Some(Box::new(justification_import)),
client.clone(),
select_chain.clone(),
move |_, ()| {
async move {
let timestamp = sp_timestamp::InherentDataProvider::from_system_time();
move |_, ()| async move {
let timestamp = sp_timestamp::InherentDataProvider::from_system_time();
let slot =
sp_consensus_babe::inherents::InherentDataProvider::from_timestamp_and_duration(
*timestamp,
slot_duration,
);
let slot =
sp_consensus_babe::inherents::InherentDataProvider::from_timestamp_and_duration(
*timestamp,
slot_duration,
);
let uncles =
sp_authorship::InherentDataProvider::<<Block as BlockT>::Header>::check_inherents();
let uncles =
sp_authorship::InherentDataProvider::<<Block as BlockT>::Header>::check_inherents();
Ok((timestamp, slot, uncles))
}
Ok((timestamp, slot, uncles))
},
&task_manager.spawn_essential_handle(),
config.prometheus_registry(),
@@ -213,7 +211,7 @@ pub fn new_full_base(
with_startup_data: impl FnOnce(
&sc_consensus_babe::BabeBlockImport<Block, FullClient, FullGrandpaBlockImport>,
&sc_consensus_babe::BabeLink<Block>,
)
),
) -> Result<NewFullBase, ServiceError> {
let sc_service::PartialComponents {
client,
@@ -238,7 +236,7 @@ pub fn new_full_base(
task_manager.spawn_handle(),
backend.clone(),
import_setup.1.shared_authority_set().clone(),
)
),
);
let (network, system_rpc_tx, network_starter) =
@@ -254,7 +252,10 @@ pub fn new_full_base(
if config.offchain_worker.enabled {
sc_service::build_offchain_workers(
&config, task_manager.spawn_handle(), client.clone(), network.clone(),
&config,
task_manager.spawn_handle(),
client.clone(),
network.clone(),
);
}
@@ -266,22 +267,20 @@ pub fn new_full_base(
let enable_grandpa = !config.disable_grandpa;
let prometheus_registry = config.prometheus_registry().cloned();
let _rpc_handlers = sc_service::spawn_tasks(
sc_service::SpawnTasksParams {
config,
backend: backend.clone(),
client: client.clone(),
keystore: keystore_container.sync_keystore(),
network: network.clone(),
rpc_extensions_builder: Box::new(rpc_extensions_builder),
transaction_pool: transaction_pool.clone(),
task_manager: &mut task_manager,
on_demand: None,
remote_blockchain: None,
system_rpc_tx,
telemetry: telemetry.as_mut(),
},
)?;
let _rpc_handlers = sc_service::spawn_tasks(sc_service::SpawnTasksParams {
config,
backend: backend.clone(),
client: client.clone(),
keystore: keystore_container.sync_keystore(),
network: network.clone(),
rpc_extensions_builder: Box::new(rpc_extensions_builder),
transaction_pool: transaction_pool.clone(),
task_manager: &mut task_manager,
on_demand: None,
remote_blockchain: None,
system_rpc_tx,
telemetry: telemetry.as_mut(),
})?;
let (block_import, grandpa_link, babe_link) = import_setup;
@@ -343,36 +342,37 @@ pub fn new_full_base(
// Spawn authority discovery module.
if role.is_authority() {
let authority_discovery_role = sc_authority_discovery::Role::PublishAndDiscover(
keystore_container.keystore(),
);
let dht_event_stream = network.event_stream("authority-discovery")
.filter_map(|e| async move { match e {
Event::Dht(e) => Some(e),
_ => None,
}});
let (authority_discovery_worker, _service) = sc_authority_discovery::new_worker_and_service_with_config(
sc_authority_discovery::WorkerConfig {
publish_non_global_ips: auth_disc_publish_non_global_ips,
..Default::default()
},
client.clone(),
network.clone(),
Box::pin(dht_event_stream),
authority_discovery_role,
prometheus_registry.clone(),
);
let authority_discovery_role =
sc_authority_discovery::Role::PublishAndDiscover(keystore_container.keystore());
let dht_event_stream =
network.event_stream("authority-discovery").filter_map(|e| async move {
match e {
Event::Dht(e) => Some(e),
_ => None,
}
});
let (authority_discovery_worker, _service) =
sc_authority_discovery::new_worker_and_service_with_config(
sc_authority_discovery::WorkerConfig {
publish_non_global_ips: auth_disc_publish_non_global_ips,
..Default::default()
},
client.clone(),
network.clone(),
Box::pin(dht_event_stream),
authority_discovery_role,
prometheus_registry.clone(),
);
task_manager.spawn_handle().spawn("authority-discovery-worker", authority_discovery_worker.run());
task_manager
.spawn_handle()
.spawn("authority-discovery-worker", authority_discovery_worker.run());
}
// if the node isn't actively participating in consensus then it doesn't
// need a keystore, regardless of which protocol we use below.
let keystore = if role.is_authority() {
Some(keystore_container.sync_keystore())
} else {
None
};
let keystore =
if role.is_authority() { Some(keystore_container.sync_keystore()) } else { None };
let config = grandpa::Config {
// FIXME #1578 make this available through chainspec
@@ -404,46 +404,41 @@ pub fn new_full_base(
// the GRANDPA voter task is considered infallible, i.e.
// if it fails we take down the service with it.
task_manager.spawn_essential_handle().spawn_blocking(
"grandpa-voter",
grandpa::run_grandpa_voter(grandpa_config)?
);
task_manager
.spawn_essential_handle()
.spawn_blocking("grandpa-voter", grandpa::run_grandpa_voter(grandpa_config)?);
}
network_starter.start_network();
Ok(NewFullBase {
task_manager,
client,
network,
transaction_pool,
})
Ok(NewFullBase { task_manager, client, network, transaction_pool })
}
/// Builds a new service for a full client.
pub fn new_full(
config: Configuration,
) -> Result<TaskManager, ServiceError> {
new_full_base(config, |_, _| ()).map(|NewFullBase { task_manager, .. }| {
task_manager
})
pub fn new_full(config: Configuration) -> Result<TaskManager, ServiceError> {
new_full_base(config, |_, _| ()).map(|NewFullBase { task_manager, .. }| task_manager)
}
pub fn new_light_base(
mut config: Configuration,
) -> Result<(
TaskManager,
RpcHandlers,
Arc<LightClient>,
Arc<NetworkService<Block, <Block as BlockT>::Hash>>,
Arc<sc_transaction_pool::LightPool<Block, LightClient, sc_network::config::OnDemand<Block>>>
), ServiceError> {
let telemetry = config.telemetry_endpoints.clone()
) -> Result<
(
TaskManager,
RpcHandlers,
Arc<LightClient>,
Arc<NetworkService<Block, <Block as BlockT>::Hash>>,
Arc<
sc_transaction_pool::LightPool<Block, LightClient, sc_network::config::OnDemand<Block>>,
>,
),
ServiceError,
> {
let telemetry = config
.telemetry_endpoints
.clone()
.filter(|x| !x.is_empty())
.map(|endpoints| -> Result<_, sc_telemetry::Error> {
#[cfg(feature = "browser")]
let transport = Some(
sc_telemetry::ExtTransport::new(libp2p_wasm_ext::ffi::websocket_transport())
);
let transport = Some(sc_telemetry::ExtTransport::new(libp2p_wasm_ext::ffi::websocket_transport()));
#[cfg(not(feature = "browser"))]
let transport = None;
@@ -459,11 +454,10 @@ pub fn new_light_base(
telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),
)?;
let mut telemetry = telemetry
.map(|(worker, telemetry)| {
task_manager.spawn_handle().spawn("telemetry", worker.run());
telemetry
});
let mut telemetry = telemetry.map(|(worker, telemetry)| {
task_manager.spawn_handle().spawn("telemetry", worker.run());
telemetry
});
config.network.extra_sets.push(grandpa::grandpa_peers_set_config());
@@ -567,71 +561,60 @@ pub fn new_light_base(
let rpc_extensions = node_rpc::create_light(light_deps);
let rpc_handlers =
sc_service::spawn_tasks(sc_service::SpawnTasksParams {
on_demand: Some(on_demand),
remote_blockchain: Some(backend.remote_blockchain()),
rpc_extensions_builder: Box::new(sc_service::NoopRpcExtensionBuilder(rpc_extensions)),
client: client.clone(),
transaction_pool: transaction_pool.clone(),
keystore: keystore_container.sync_keystore(),
config, backend, system_rpc_tx,
network: network.clone(),
task_manager: &mut task_manager,
telemetry: telemetry.as_mut(),
})?;
let rpc_handlers = sc_service::spawn_tasks(sc_service::SpawnTasksParams {
on_demand: Some(on_demand),
remote_blockchain: Some(backend.remote_blockchain()),
rpc_extensions_builder: Box::new(sc_service::NoopRpcExtensionBuilder(rpc_extensions)),
client: client.clone(),
transaction_pool: transaction_pool.clone(),
keystore: keystore_container.sync_keystore(),
config,
backend,
system_rpc_tx,
network: network.clone(),
task_manager: &mut task_manager,
telemetry: telemetry.as_mut(),
})?;
network_starter.start_network();
Ok((
task_manager,
rpc_handlers,
client,
network,
transaction_pool,
))
Ok((task_manager, rpc_handlers, client, network, transaction_pool))
}
/// Builds a new service for a light client.
pub fn new_light(
config: Configuration,
) -> Result<TaskManager, ServiceError> {
new_light_base(config).map(|(task_manager, _, _, _, _)| {
task_manager
})
pub fn new_light(config: Configuration) -> Result<TaskManager, ServiceError> {
new_light_base(config).map(|(task_manager, _, _, _, _)| task_manager)
}
#[cfg(test)]
mod tests {
use std::{sync::Arc, borrow::Cow, convert::TryInto};
use sc_consensus_babe::{CompatibleDigestItem, BabeIntermediate, INTERMEDIATE_KEY};
use sc_consensus_epochs::descendent_query;
use sp_consensus::{
Environment, Proposer, BlockImportParams, BlockOrigin, ForkChoiceStrategy, BlockImport,
};
use node_primitives::{Block, DigestItem, Signature};
use node_runtime::{BalancesCall, Call, UncheckedExtrinsic, Address};
use node_runtime::constants::{currency::CENTS, time::SLOT_DURATION};
use crate::service::{new_full_base, new_light_base, NewFullBase};
use codec::Encode;
use sp_core::{
crypto::Pair as CryptoPair,
H256,
Public
use node_primitives::{Block, DigestItem, Signature};
use node_runtime::{
constants::{currency::CENTS, time::SLOT_DURATION},
Address, BalancesCall, Call, UncheckedExtrinsic,
};
use sp_keystore::{SyncCryptoStorePtr, SyncCryptoStore};
use sc_client_api::BlockBackend;
use sc_consensus_babe::{BabeIntermediate, CompatibleDigestItem, INTERMEDIATE_KEY};
use sc_consensus_epochs::descendent_query;
use sc_keystore::LocalKeystore;
use sc_service_test::TestNetNode;
use sc_transaction_pool_api::{ChainEvent, MaintainedTransactionPool};
use sp_consensus::{
BlockImport, BlockImportParams, BlockOrigin, Environment, ForkChoiceStrategy, Proposer,
};
use sp_core::{crypto::Pair as CryptoPair, Public, H256};
use sp_inherents::InherentDataProvider;
use sp_keyring::AccountKeyring;
use sp_keystore::{SyncCryptoStore, SyncCryptoStorePtr};
use sp_runtime::{
generic::{BlockId, Era, Digest, SignedPayload},
traits::{Block as BlockT, Header as HeaderT},
traits::Verify,
generic::{BlockId, Digest, Era, SignedPayload},
key_types::BABE,
traits::{Block as BlockT, Header as HeaderT, IdentifyAccount, Verify},
RuntimeAppPublic,
};
use sp_timestamp;
use sp_keyring::AccountKeyring;
use sc_service_test::TestNetNode;
use crate::service::{new_full_base, new_light_base, NewFullBase};
use sp_runtime::{key_types::BABE, traits::IdentifyAccount, RuntimeAppPublic};
use sc_transaction_pool_api::{MaintainedTransactionPool, ChainEvent};
use sc_client_api::BlockBackend;
use sc_keystore::LocalKeystore;
use sp_inherents::InherentDataProvider;
use std::{borrow::Cow, convert::TryInto, sync::Arc};
type AccountPublic = <Signature as Verify>::Signer;
@@ -641,10 +624,12 @@ mod tests {
#[ignore]
fn test_sync() {
let keystore_path = tempfile::tempdir().expect("Creates keystore path");
let keystore: SyncCryptoStorePtr = Arc::new(LocalKeystore::open(keystore_path.path(), None)
.expect("Creates keystore"));
let alice: sp_consensus_babe::AuthorityId = SyncCryptoStore::sr25519_generate_new(&*keystore, BABE, Some("//Alice"))
.expect("Creates authority pair").into();
let keystore: SyncCryptoStorePtr =
Arc::new(LocalKeystore::open(keystore_path.path(), None).expect("Creates keystore"));
let alice: sp_consensus_babe::AuthorityId =
SyncCryptoStore::sr25519_generate_new(&*keystore, BABE, Some("//Alice"))
.expect("Creates authority pair")
.into();
let chain_spec = crate::chain_spec::tests::integration_test_config_with_single_authority();
@@ -660,25 +645,31 @@ mod tests {
chain_spec,
|config| {
let mut setup_handles = None;
let NewFullBase {
task_manager, client, network, transaction_pool, ..
} = new_full_base(config,
|
block_import: &sc_consensus_babe::BabeBlockImport<Block, _, _>,
babe_link: &sc_consensus_babe::BabeLink<Block>,
| {
setup_handles = Some((block_import.clone(), babe_link.clone()));
}
)?;
let NewFullBase { task_manager, client, network, transaction_pool, .. } =
new_full_base(
config,
|block_import: &sc_consensus_babe::BabeBlockImport<Block, _, _>,
babe_link: &sc_consensus_babe::BabeLink<Block>| {
setup_handles = Some((block_import.clone(), babe_link.clone()));
},
)?;
let node = sc_service_test::TestNetComponents::new(
task_manager, client, network, transaction_pool
task_manager,
client,
network,
transaction_pool,
);
Ok((node, setup_handles.unwrap()))
},
|config| {
let (keep_alive, _, client, network, transaction_pool) = new_light_base(config)?;
Ok(sc_service_test::TestNetComponents::new(keep_alive, client, network, transaction_pool))
Ok(sc_service_test::TestNetComponents::new(
keep_alive,
client,
network,
transaction_pool,
))
},
|service, &mut (ref mut block_import, ref babe_link)| {
let parent_id = BlockId::number(service.client().chain_info().best_number);
@@ -686,14 +677,9 @@ mod tests {
let parent_hash = parent_header.hash();
let parent_number = *parent_header.number();
futures::executor::block_on(
service.transaction_pool().maintain(
ChainEvent::NewBestBlock {
hash: parent_header.hash(),
tree_route: None,
},
)
);
futures::executor::block_on(service.transaction_pool().maintain(
ChainEvent::NewBestBlock { hash: parent_header.hash(), tree_route: None },
));
let mut proposer_factory = sc_basic_authorship::ProposerFactory::new(
service.spawn_handle(),
@@ -708,23 +694,30 @@ mod tests {
// even though there's only one authority some slots might be empty,
// so we must keep trying the next slots until we can claim one.
let (babe_pre_digest, epoch_descriptor) = loop {
let epoch_descriptor = babe_link.epoch_changes().shared_data().epoch_descriptor_for_child_of(
descendent_query(&*service.client()),
&parent_hash,
parent_number,
slot.into(),
).unwrap().unwrap();
let epoch_descriptor = babe_link
.epoch_changes()
.shared_data()
.epoch_descriptor_for_child_of(
descendent_query(&*service.client()),
&parent_hash,
parent_number,
slot.into(),
)
.unwrap()
.unwrap();
let epoch = babe_link.epoch_changes().shared_data().epoch_data(
&epoch_descriptor,
|slot| sc_consensus_babe::Epoch::genesis(&babe_link.config(), slot),
).unwrap();
let epoch = babe_link
.epoch_changes()
.shared_data()
.epoch_data(&epoch_descriptor, |slot| {
sc_consensus_babe::Epoch::genesis(&babe_link.config(), slot)
})
.unwrap();
if let Some(babe_pre_digest) = sc_consensus_babe::authorship::claim_slot(
slot.into(),
&epoch,
&keystore,
).map(|(digest, _)| digest) {
if let Some(babe_pre_digest) =
sc_consensus_babe::authorship::claim_slot(slot.into(), &epoch, &keystore)
.map(|(digest, _)| digest)
{
break (babe_pre_digest, epoch_descriptor)
}
@@ -736,19 +729,21 @@ mod tests {
std::time::Duration::from_millis(SLOT_DURATION * slot).into(),
),
sp_consensus_babe::inherents::InherentDataProvider::new(slot.into()),
).create_inherent_data().expect("Creates inherent data");
)
.create_inherent_data()
.expect("Creates inherent data");
digest.push(<DigestItem as CompatibleDigestItem>::babe_pre_digest(babe_pre_digest));
let new_block = futures::executor::block_on(async move {
let proposer = proposer_factory.init(&parent_header).await;
proposer.unwrap().propose(
inherent_data,
digest,
std::time::Duration::from_secs(1),
None,
).await
}).expect("Error making test block").block;
proposer
.unwrap()
.propose(inherent_data, digest, std::time::Duration::from_secs(1), None)
.await
})
.expect("Error making test block")
.block;
let (new_header, new_body) = new_block.deconstruct();
let pre_hash = new_header.hash();
@@ -760,10 +755,12 @@ mod tests {
sp_consensus_babe::AuthorityId::ID,
&alice.to_public_crypto_pair(),
&to_sign,
).unwrap().unwrap().try_into().unwrap();
let item = <DigestItem as CompatibleDigestItem>::babe_seal(
signature,
);
)
.unwrap()
.unwrap()
.try_into()
.unwrap();
let item = <DigestItem as CompatibleDigestItem>::babe_seal(signature);
slot += 1;
let mut params = BlockImportParams::new(BlockOrigin::File, new_header);
@@ -811,19 +808,13 @@ mod tests {
let raw_payload = SignedPayload::from_raw(
function,
extra,
(spec_version, transaction_version, genesis_hash, genesis_hash, (), (), ())
(spec_version, transaction_version, genesis_hash, genesis_hash, (), (), ()),
);
let signature = raw_payload.using_encoded(|payload| {
signer.sign(payload)
});
let signature = raw_payload.using_encoded(|payload| signer.sign(payload));
let (function, extra, _) = raw_payload.deconstruct();
index += 1;
UncheckedExtrinsic::new_signed(
function,
from.into(),
signature.into(),
extra,
).into()
UncheckedExtrinsic::new_signed(function, from.into(), signature.into(), extra)
.into()
},
);
}
@@ -834,18 +825,25 @@ mod tests {
sc_service_test::consensus(
crate::chain_spec::tests::integration_test_config_with_two_authorities(),
|config| {
let NewFullBase { task_manager, client, network, transaction_pool, .. }
= new_full_base(config,|_, _| ())?;
Ok(sc_service_test::TestNetComponents::new(task_manager, client, network, transaction_pool))
let NewFullBase { task_manager, client, network, transaction_pool, .. } =
new_full_base(config, |_, _| ())?;
Ok(sc_service_test::TestNetComponents::new(
task_manager,
client,
network,
transaction_pool,
))
},
|config| {
let (keep_alive, _, client, network, transaction_pool) = new_light_base(config)?;
Ok(sc_service_test::TestNetComponents::new(keep_alive, client, network, transaction_pool))
Ok(sc_service_test::TestNetComponents::new(
keep_alive,
client,
network,
transaction_pool,
))
},
vec![
"//Alice".into(),
"//Bob".into(),
],
vec!["//Alice".into(), "//Bob".into()],
)
}
}
+12 -10
View File
@@ -18,11 +18,18 @@
#![cfg(unix)]
use std::{process::{Child, ExitStatus}, thread, time::Duration, path::Path};
use assert_cmd::cargo::cargo_bin;
use std::{convert::TryInto, process::Command};
use nix::sys::signal::{kill, Signal::SIGINT};
use nix::unistd::Pid;
use nix::{
sys::signal::{kill, Signal::SIGINT},
unistd::Pid,
};
use std::{
convert::TryInto,
path::Path,
process::{Child, Command, ExitStatus},
thread,
time::Duration,
};
/// Wait for the given `child` the given number of `secs`.
///
@@ -50,12 +57,7 @@ pub fn wait_for(child: &mut Child, secs: usize) -> Option<ExitStatus> {
pub fn run_dev_node_for_a_while(base_path: &Path) {
let mut cmd = Command::new(cargo_bin("substrate"));
let mut cmd = cmd
.args(&["--dev"])
.arg("-d")
.arg(base_path)
.spawn()
.unwrap();
let mut cmd = cmd.args(&["--dev"]).arg("-d").arg(base_path).spawn().unwrap();
// Let it produce some blocks.
thread::sleep(Duration::from_secs(30));
@@ -19,9 +19,9 @@
#![cfg(unix)]
use assert_cmd::cargo::cargo_bin;
use std::{process::Command, fs, path::PathBuf};
use tempfile::{tempdir, TempDir};
use regex::Regex;
use std::{fs, path::PathBuf, process::Command};
use tempfile::{tempdir, TempDir};
pub mod common;
@@ -63,26 +63,23 @@ impl<'a> ExportImportRevertExecutor<'a> {
fn new(
base_path: &'a TempDir,
exported_blocks_file: &'a PathBuf,
db_path: &'a PathBuf
db_path: &'a PathBuf,
) -> Self {
Self {
base_path,
exported_blocks_file,
db_path,
num_exported_blocks: None,
}
Self { base_path, exported_blocks_file, db_path, num_exported_blocks: None }
}
/// Helper method to run a command. Returns a string corresponding to what has been logged.
fn run_block_command(&self,
fn run_block_command(
&self,
sub_command: SubCommand,
format_opt: FormatOpt,
expected_to_fail: bool
expected_to_fail: bool,
) -> String {
let sub_command_str = sub_command.to_string();
// Adding "--binary" if need be.
let arguments: Vec<&str> = match format_opt {
FormatOpt::Binary => vec![&sub_command_str, "--dev", "--pruning", "archive", "--binary", "-d"],
FormatOpt::Binary =>
vec![&sub_command_str, "--dev", "--pruning", "archive", "--binary", "-d"],
FormatOpt::Json => vec![&sub_command_str, "--dev", "--pruning", "archive", "-d"],
};
@@ -94,7 +91,7 @@ impl<'a> ExportImportRevertExecutor<'a> {
SubCommand::ImportBlocks => {
tmp = tempdir().unwrap();
tmp.path()
}
},
};
// Running the command and capturing the output.
@@ -144,16 +141,13 @@ impl<'a> ExportImportRevertExecutor<'a> {
if !expected_to_fail {
// Using regex to find out how much block we imported,
// and what's the best current block.
let re = Regex::new(r"Imported (?P<imported>\d*) blocks. Best: #(?P<best>\d*)").unwrap();
let re =
Regex::new(r"Imported (?P<imported>\d*) blocks. Best: #(?P<best>\d*)").unwrap();
let caps = re.captures(&log).expect("capture should have succeeded");
let imported = caps["imported"].parse::<u64>().unwrap();
let best = caps["best"].parse::<u64>().unwrap();
assert_eq!(
imported,
best,
"numbers of blocks imported and best number differs"
);
assert_eq!(imported, best, "numbers of blocks imported and best number differs");
assert_eq!(
best,
self.num_exported_blocks.expect("number of exported blocks cannot be None; qed"),
@@ -195,11 +189,7 @@ fn export_import_revert() {
common::run_dev_node_for_a_while(base_path.path());
let mut executor = ExportImportRevertExecutor::new(
&base_path,
&exported_blocks_file,
&db_path,
);
let mut executor = ExportImportRevertExecutor::new(&base_path, &exported_blocks_file, &db_path);
// Binary and binary should work.
executor.run(FormatOpt::Binary, FormatOpt::Binary, false);
@@ -25,8 +25,13 @@ pub mod common;
#[test]
#[cfg(unix)]
fn running_the_node_works_and_can_be_interrupted() {
use nix::sys::signal::{kill, Signal::{self, SIGINT, SIGTERM}};
use nix::unistd::Pid;
use nix::{
sys::signal::{
kill,
Signal::{self, SIGINT, SIGTERM},
},
unistd::Pid,
};
fn run_command_and_kill(signal: Signal) {
let base_path = tempdir().expect("could not create a temp dir");
+13 -22
View File
@@ -17,10 +17,11 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use assert_cmd::cargo::cargo_bin;
use nix::sys::signal::{kill, Signal::SIGINT};
use nix::unistd::Pid;
use std::convert::TryInto;
use std::process;
use nix::{
sys::signal::{kill, Signal::SIGINT},
unistd::Pid,
};
use std::{convert::TryInto, process};
pub mod common;
pub mod websocket_server;
@@ -45,27 +46,22 @@ async fn telemetry_works() {
Event::ConnectionOpen { address } => {
println!("New connection from {:?}", address);
server.accept();
}
},
// Received a message from a connection.
Event::BinaryFrame { message, .. } => {
let json: serde_json::Value = serde_json::from_slice(&message).unwrap();
let object = json
.as_object()
.unwrap()
.get("payload")
.unwrap()
.as_object()
.unwrap();
let object =
json.as_object().unwrap().get("payload").unwrap().as_object().unwrap();
if matches!(object.get("best"), Some(serde_json::Value::String(_))) {
break;
break
}
}
},
Event::TextFrame { .. } => panic!("Got a TextFrame over the socket, this is a bug"),
// Connection has been closed.
Event::ConnectionError { .. } => {}
Event::ConnectionError { .. } => {},
}
}
});
@@ -83,16 +79,11 @@ async fn telemetry_works() {
server_task.await;
assert!(
substrate.try_wait().unwrap().is_none(),
"the process should still be running"
);
assert!(substrate.try_wait().unwrap().is_none(), "the process should still be running");
// Stop the process
kill(Pid::from_raw(substrate.id().try_into().unwrap()), SIGINT).unwrap();
assert!(common::wait_for(&mut substrate, 40)
.map(|x| x.success())
.unwrap_or_default());
assert!(common::wait_for(&mut substrate, 40).map(|x| x.success()).unwrap_or_default());
let output = substrate.wait_with_output().unwrap();
@@ -19,15 +19,19 @@
#![cfg(unix)]
use assert_cmd::cargo::cargo_bin;
use nix::sys::signal::{kill, Signal::SIGINT};
use nix::unistd::Pid;
use nix::{
sys::signal::{kill, Signal::SIGINT},
unistd::Pid,
};
use regex::Regex;
use std::convert::TryInto;
use std::io::Read;
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::thread;
use std::time::Duration;
use std::{
convert::TryInto,
io::Read,
path::PathBuf,
process::{Command, Stdio},
thread,
time::Duration,
};
pub mod common;
@@ -44,29 +48,18 @@ fn temp_base_path_works() {
// Let it produce some blocks.
thread::sleep(Duration::from_secs(30));
assert!(
cmd.try_wait().unwrap().is_none(),
"the process should still be running"
);
assert!(cmd.try_wait().unwrap().is_none(), "the process should still be running");
// Stop the process
kill(Pid::from_raw(cmd.id().try_into().unwrap()), SIGINT).unwrap();
assert!(common::wait_for(&mut cmd, 40)
.map(|x| x.success())
.unwrap_or_default());
assert!(common::wait_for(&mut cmd, 40).map(|x| x.success()).unwrap_or_default());
// Ensure the database has been deleted
let mut stderr = String::new();
cmd.stderr.unwrap().read_to_string(&mut stderr).unwrap();
let re = Regex::new(r"Database: .+ at (\S+)").unwrap();
let db_path = PathBuf::from(
re.captures(stderr.as_str())
.unwrap()
.get(1)
.unwrap()
.as_str()
.to_string(),
);
let db_path =
PathBuf::from(re.captures(stderr.as_str()).unwrap().get(1).unwrap().as_str().to_string());
assert!(!db_path.exists());
}
+9 -25
View File
@@ -22,61 +22,45 @@ use regex::Regex;
use std::process::Command;
fn expected_regex() -> Regex {
Regex::new(r"^substrate (\d+\.\d+\.\d+(?:-.+?)?)-([a-f\d]+|unknown)-(.+?)-(.+?)(?:-(.+))?$").unwrap()
Regex::new(r"^substrate (\d+\.\d+\.\d+(?:-.+?)?)-([a-f\d]+|unknown)-(.+?)-(.+?)(?:-(.+))?$")
.unwrap()
}
#[test]
fn version_is_full() {
let expected = expected_regex();
let output = Command::new(cargo_bin("substrate"))
.args(&["--version"])
.output()
.unwrap();
let output = Command::new(cargo_bin("substrate")).args(&["--version"]).output().unwrap();
assert!(
output.status.success(),
"command returned with non-success exit code"
);
assert!(output.status.success(), "command returned with non-success exit code");
let output = String::from_utf8_lossy(&output.stdout).trim().to_owned();
let captures = expected
.captures(output.as_str())
.expect("could not parse version in output");
let captures = expected.captures(output.as_str()).expect("could not parse version in output");
assert_eq!(&captures[1], env!("CARGO_PKG_VERSION"));
assert_eq!(&captures[3], TARGET_ARCH.as_str());
assert_eq!(&captures[4], TARGET_OS.as_str());
assert_eq!(
captures.get(5).map(|x| x.as_str()),
TARGET_ENV.map(|x| x.as_str())
);
assert_eq!(captures.get(5).map(|x| x.as_str()), TARGET_ENV.map(|x| x.as_str()));
}
#[test]
fn test_regex_matches_properly() {
let expected = expected_regex();
let captures = expected
.captures("substrate 2.0.0-da487d19d-x86_64-linux-gnu")
.unwrap();
let captures = expected.captures("substrate 2.0.0-da487d19d-x86_64-linux-gnu").unwrap();
assert_eq!(&captures[1], "2.0.0");
assert_eq!(&captures[2], "da487d19d");
assert_eq!(&captures[3], "x86_64");
assert_eq!(&captures[4], "linux");
assert_eq!(captures.get(5).map(|x| x.as_str()), Some("gnu"));
let captures = expected
.captures("substrate 2.0.0-alpha.5-da487d19d-x86_64-linux-gnu")
.unwrap();
let captures = expected.captures("substrate 2.0.0-alpha.5-da487d19d-x86_64-linux-gnu").unwrap();
assert_eq!(&captures[1], "2.0.0-alpha.5");
assert_eq!(&captures[2], "da487d19d");
assert_eq!(&captures[3], "x86_64");
assert_eq!(&captures[4], "linux");
assert_eq!(captures.get(5).map(|x| x.as_str()), Some("gnu"));
let captures = expected
.captures("substrate 2.0.0-alpha.5-da487d19d-x86_64-linux")
.unwrap();
let captures = expected.captures("substrate 2.0.0-alpha.5-da487d19d-x86_64-linux").unwrap();
assert_eq!(&captures[1], "2.0.0-alpha.5");
assert_eq!(&captures[2], "da487d19d");
assert_eq!(&captures[3], "x86_64");
@@ -116,7 +116,6 @@ impl WsServer {
/// # Panic
///
/// Panics if no connection is pending.
///
pub fn accept(&mut self) {
let pending_incoming = self.pending_incoming.take().expect("no pending socket");
@@ -129,15 +128,10 @@ impl WsServer {
};
match server
.send_response(&{
Response::Accept {
key: &websocket_key,
protocol: None,
}
})
.send_response(&{ Response::Accept { key: &websocket_key, protocol: None } })
.await
{
Ok(()) => {}
Ok(()) => {},
Err(err) => return Err(Box::new(err) as Box<_>),
};
@@ -153,7 +147,6 @@ impl WsServer {
/// # Panic
///
/// Panics if no connection is pending.
///
pub fn reject(&mut self) {
let _ = self.pending_incoming.take().expect("no pending socket");
}