Add rustfmt.toml, run `cargo +nightly fmt` (#217)

* add rustfmt to match upstream

* correct rustfmt, run cargo +nightly fmt
main
Dan Shields 2021-07-20 06:44:58 -06:00 committed by GitHub
parent 64f5744e99
commit 3a1acf0a98
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
12 changed files with 226 additions and 213 deletions

View File

@ -1,12 +1,12 @@
use sp_core::{Pair, Public, sr25519};
use node_template_runtime::{ use node_template_runtime::{
AccountId, AuraConfig, BalancesConfig, GenesisConfig, GrandpaConfig, AccountId, AuraConfig, BalancesConfig, GenesisConfig, GrandpaConfig, Signature, SudoConfig,
SudoConfig, SystemConfig, WASM_BINARY, Signature SystemConfig, WASM_BINARY,
}; };
use sp_consensus_aura::sr25519::AuthorityId as AuraId;
use sp_finality_grandpa::AuthorityId as GrandpaId;
use sp_runtime::traits::{Verify, IdentifyAccount};
use sc_service::ChainType; use sc_service::ChainType;
use sp_consensus_aura::sr25519::AuthorityId as AuraId;
use sp_core::{sr25519, Pair, Public};
use sp_finality_grandpa::AuthorityId as GrandpaId;
use sp_runtime::traits::{IdentifyAccount, Verify};
// The URL for the telemetry server. // The URL for the telemetry server.
// const STAGING_TELEMETRY_URL: &str = "wss://telemetry.polkadot.io/submit/"; // const STAGING_TELEMETRY_URL: &str = "wss://telemetry.polkadot.io/submit/";
@ -24,18 +24,16 @@ pub fn get_from_seed<TPublic: Public>(seed: &str) -> <TPublic::Pair as Pair>::Pu
type AccountPublic = <Signature as Verify>::Signer; type AccountPublic = <Signature as Verify>::Signer;
/// Generate an account ID from seed. /// Generate an account ID from seed.
pub fn get_account_id_from_seed<TPublic: Public>(seed: &str) -> AccountId where pub fn get_account_id_from_seed<TPublic: Public>(seed: &str) -> AccountId
AccountPublic: From<<TPublic::Pair as Pair>::Public> where
AccountPublic: From<<TPublic::Pair as Pair>::Public>,
{ {
AccountPublic::from(get_from_seed::<TPublic>(seed)).into_account() AccountPublic::from(get_from_seed::<TPublic>(seed)).into_account()
} }
/// Generate an Aura authority key. /// Generate an Aura authority key.
pub fn authority_keys_from_seed(s: &str) -> (AuraId, GrandpaId) { pub fn authority_keys_from_seed(s: &str) -> (AuraId, GrandpaId) {
( (get_from_seed::<AuraId>(s), get_from_seed::<GrandpaId>(s))
get_from_seed::<AuraId>(s),
get_from_seed::<GrandpaId>(s),
)
} }
pub fn development_config() -> Result<ChainSpec, String> { pub fn development_config() -> Result<ChainSpec, String> {
@ -47,23 +45,23 @@ pub fn development_config() -> Result<ChainSpec, String> {
// ID // ID
"dev", "dev",
ChainType::Development, ChainType::Development,
move || testnet_genesis( move || {
wasm_binary, testnet_genesis(
// Initial PoA authorities wasm_binary,
vec![ // Initial PoA authorities
authority_keys_from_seed("Alice"), vec![authority_keys_from_seed("Alice")],
], // Sudo account
// Sudo account
get_account_id_from_seed::<sr25519::Public>("Alice"),
// Pre-funded accounts
vec![
get_account_id_from_seed::<sr25519::Public>("Alice"), get_account_id_from_seed::<sr25519::Public>("Alice"),
get_account_id_from_seed::<sr25519::Public>("Bob"), // Pre-funded accounts
get_account_id_from_seed::<sr25519::Public>("Alice//stash"), vec![
get_account_id_from_seed::<sr25519::Public>("Bob//stash"), get_account_id_from_seed::<sr25519::Public>("Alice"),
], get_account_id_from_seed::<sr25519::Public>("Bob"),
true, get_account_id_from_seed::<sr25519::Public>("Alice//stash"),
), get_account_id_from_seed::<sr25519::Public>("Bob//stash"),
],
true,
)
},
// Bootnodes // Bootnodes
vec![], vec![],
// Telemetry // Telemetry
@ -86,32 +84,31 @@ pub fn local_testnet_config() -> Result<ChainSpec, String> {
// ID // ID
"local_testnet", "local_testnet",
ChainType::Local, ChainType::Local,
move || testnet_genesis( move || {
wasm_binary, testnet_genesis(
// Initial PoA authorities wasm_binary,
vec![ // Initial PoA authorities
authority_keys_from_seed("Alice"), vec![authority_keys_from_seed("Alice"), authority_keys_from_seed("Bob")],
authority_keys_from_seed("Bob"), // Sudo account
],
// Sudo account
get_account_id_from_seed::<sr25519::Public>("Alice"),
// Pre-funded accounts
vec![
get_account_id_from_seed::<sr25519::Public>("Alice"), get_account_id_from_seed::<sr25519::Public>("Alice"),
get_account_id_from_seed::<sr25519::Public>("Bob"), // Pre-funded accounts
get_account_id_from_seed::<sr25519::Public>("Charlie"), vec![
get_account_id_from_seed::<sr25519::Public>("Dave"), get_account_id_from_seed::<sr25519::Public>("Alice"),
get_account_id_from_seed::<sr25519::Public>("Eve"), get_account_id_from_seed::<sr25519::Public>("Bob"),
get_account_id_from_seed::<sr25519::Public>("Ferdie"), get_account_id_from_seed::<sr25519::Public>("Charlie"),
get_account_id_from_seed::<sr25519::Public>("Alice//stash"), get_account_id_from_seed::<sr25519::Public>("Dave"),
get_account_id_from_seed::<sr25519::Public>("Bob//stash"), get_account_id_from_seed::<sr25519::Public>("Eve"),
get_account_id_from_seed::<sr25519::Public>("Charlie//stash"), get_account_id_from_seed::<sr25519::Public>("Ferdie"),
get_account_id_from_seed::<sr25519::Public>("Dave//stash"), get_account_id_from_seed::<sr25519::Public>("Alice//stash"),
get_account_id_from_seed::<sr25519::Public>("Eve//stash"), get_account_id_from_seed::<sr25519::Public>("Bob//stash"),
get_account_id_from_seed::<sr25519::Public>("Ferdie//stash"), get_account_id_from_seed::<sr25519::Public>("Charlie//stash"),
], get_account_id_from_seed::<sr25519::Public>("Dave//stash"),
true, get_account_id_from_seed::<sr25519::Public>("Eve//stash"),
), get_account_id_from_seed::<sr25519::Public>("Ferdie//stash"),
],
true,
)
},
// Bootnodes // Bootnodes
vec![], vec![],
// Telemetry // Telemetry
@ -141,7 +138,7 @@ fn testnet_genesis(
}, },
balances: BalancesConfig { balances: BalancesConfig {
// Configure endowed accounts with initial balance of 1 << 60. // Configure endowed accounts with initial balance of 1 << 60.
balances: endowed_accounts.iter().cloned().map(|k|(k, 1 << 60)).collect(), balances: endowed_accounts.iter().cloned().map(|k| (k, 1 << 60)).collect(),
}, },
aura: AuraConfig { aura: AuraConfig {
authorities: initial_authorities.iter().map(|x| (x.0.clone())).collect(), authorities: initial_authorities.iter().map(|x| (x.0.clone())).collect(),

View File

@ -1,5 +1,5 @@
use structopt::StructOpt;
use sc_cli::RunCmd; use sc_cli::RunCmd;
use structopt::StructOpt;
#[derive(Debug, StructOpt)] #[derive(Debug, StructOpt)]
pub struct Cli { pub struct Cli {

View File

@ -15,11 +15,14 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
use crate::{chain_spec, service}; use crate::{
use crate::cli::{Cli, Subcommand}; chain_spec,
use sc_cli::{SubstrateCli, RuntimeVersion, Role, ChainSpec}; cli::{Cli, Subcommand},
use sc_service::PartialComponents; service,
};
use node_template_runtime::Block; use node_template_runtime::Block;
use sc_cli::{ChainSpec, Role, RuntimeVersion, SubstrateCli};
use sc_service::PartialComponents;
impl SubstrateCli for Cli { impl SubstrateCli for Cli {
fn impl_name() -> String { fn impl_name() -> String {
@ -50,9 +53,8 @@ impl SubstrateCli for Cli {
Ok(match id { Ok(match id {
"dev" => Box::new(chain_spec::development_config()?), "dev" => Box::new(chain_spec::development_config()?),
"" | "local" => Box::new(chain_spec::local_testnet_config()?), "" | "local" => Box::new(chain_spec::local_testnet_config()?),
path => Box::new(chain_spec::ChainSpec::from_json_file( path =>
std::path::PathBuf::from(path), Box::new(chain_spec::ChainSpec::from_json_file(std::path::PathBuf::from(path))?),
)?),
}) })
} }
@ -74,32 +76,30 @@ pub fn run() -> sc_cli::Result<()> {
Some(Subcommand::CheckBlock(cmd)) => { Some(Subcommand::CheckBlock(cmd)) => {
let runner = cli.create_runner(cmd)?; let runner = cli.create_runner(cmd)?;
runner.async_run(|config| { runner.async_run(|config| {
let PartialComponents { client, task_manager, import_queue, ..} let PartialComponents { client, task_manager, import_queue, .. } =
= service::new_partial(&config)?; service::new_partial(&config)?;
Ok((cmd.run(client, import_queue), task_manager)) Ok((cmd.run(client, import_queue), task_manager))
}) })
}, },
Some(Subcommand::ExportBlocks(cmd)) => { Some(Subcommand::ExportBlocks(cmd)) => {
let runner = cli.create_runner(cmd)?; let runner = cli.create_runner(cmd)?;
runner.async_run(|config| { runner.async_run(|config| {
let PartialComponents { client, task_manager, ..} let PartialComponents { client, task_manager, .. } = service::new_partial(&config)?;
= service::new_partial(&config)?;
Ok((cmd.run(client, config.database), task_manager)) Ok((cmd.run(client, config.database), task_manager))
}) })
}, },
Some(Subcommand::ExportState(cmd)) => { Some(Subcommand::ExportState(cmd)) => {
let runner = cli.create_runner(cmd)?; let runner = cli.create_runner(cmd)?;
runner.async_run(|config| { runner.async_run(|config| {
let PartialComponents { client, task_manager, ..} let PartialComponents { client, task_manager, .. } = service::new_partial(&config)?;
= service::new_partial(&config)?;
Ok((cmd.run(client, config.chain_spec), task_manager)) Ok((cmd.run(client, config.chain_spec), task_manager))
}) })
}, },
Some(Subcommand::ImportBlocks(cmd)) => { Some(Subcommand::ImportBlocks(cmd)) => {
let runner = cli.create_runner(cmd)?; let runner = cli.create_runner(cmd)?;
runner.async_run(|config| { runner.async_run(|config| {
let PartialComponents { client, task_manager, import_queue, ..} let PartialComponents { client, task_manager, import_queue, .. } =
= service::new_partial(&config)?; service::new_partial(&config)?;
Ok((cmd.run(client, import_queue), task_manager)) Ok((cmd.run(client, import_queue), task_manager))
}) })
}, },
@ -110,29 +110,30 @@ pub fn run() -> sc_cli::Result<()> {
Some(Subcommand::Revert(cmd)) => { Some(Subcommand::Revert(cmd)) => {
let runner = cli.create_runner(cmd)?; let runner = cli.create_runner(cmd)?;
runner.async_run(|config| { runner.async_run(|config| {
let PartialComponents { client, task_manager, backend, ..} let PartialComponents { client, task_manager, backend, .. } =
= service::new_partial(&config)?; service::new_partial(&config)?;
Ok((cmd.run(client, backend), task_manager)) Ok((cmd.run(client, backend), task_manager))
}) })
}, },
Some(Subcommand::Benchmark(cmd)) => { Some(Subcommand::Benchmark(cmd)) =>
if cfg!(feature = "runtime-benchmarks") { if cfg!(feature = "runtime-benchmarks") {
let runner = cli.create_runner(cmd)?; let runner = cli.create_runner(cmd)?;
runner.sync_run(|config| cmd.run::<Block, service::Executor>(config)) runner.sync_run(|config| cmd.run::<Block, service::Executor>(config))
} else { } else {
Err("Benchmarking wasn't enabled when building the node. \ 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())
}, },
None => { None => {
let runner = cli.create_runner(&cli.run)?; let runner = cli.create_runner(&cli.run)?;
runner.run_node_until_exit(|config| async move { runner.run_node_until_exit(|config| async move {
match config.role { match config.role {
Role::Light => service::new_light(config), Role::Light => service::new_light(config),
_ => service::new_full(config), _ => service::new_full(config),
}.map_err(sc_cli::Error::Service) }
.map_err(sc_cli::Error::Service)
}) })
} },
} }
} }

View File

@ -1,3 +1,3 @@
pub mod chain_spec; pub mod chain_spec;
pub mod service;
pub mod rpc; pub mod rpc;
pub mod service;

View File

@ -8,13 +8,12 @@
use std::sync::Arc; use std::sync::Arc;
use node_template_runtime::{opaque::Block, AccountId, Balance, Index}; use node_template_runtime::{opaque::Block, AccountId, Balance, Index};
use sp_api::ProvideRuntimeApi;
use sp_blockchain::{Error as BlockChainError, HeaderMetadata, HeaderBackend};
use sp_block_builder::BlockBuilder;
pub use sc_rpc_api::DenyUnsafe; pub use sc_rpc_api::DenyUnsafe;
use sp_api::ProvideRuntimeApi;
use sp_block_builder::BlockBuilder;
use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata};
use sp_transaction_pool::TransactionPool; use sp_transaction_pool::TransactionPool;
/// Full client dependencies. /// Full client dependencies.
pub struct FullDeps<C, P> { pub struct FullDeps<C, P> {
/// The client instance to use. /// The client instance to use.
@ -26,34 +25,25 @@ pub struct FullDeps<C, P> {
} }
/// Instantiate all full RPC extensions. /// Instantiate all full RPC extensions.
pub fn create_full<C, P>( pub fn create_full<C, P>(deps: FullDeps<C, P>) -> jsonrpc_core::IoHandler<sc_rpc::Metadata>
deps: FullDeps<C, P>, where
) -> jsonrpc_core::IoHandler<sc_rpc::Metadata> where
C: ProvideRuntimeApi<Block>, C: ProvideRuntimeApi<Block>,
C: HeaderBackend<Block> + HeaderMetadata<Block, Error=BlockChainError> + 'static, C: HeaderBackend<Block> + HeaderMetadata<Block, Error = BlockChainError> + 'static,
C: Send + Sync + 'static, C: Send + Sync + 'static,
C::Api: substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>, C::Api: substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>,
C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi<Block, Balance>, C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi<Block, Balance>,
C::Api: BlockBuilder<Block>, C::Api: BlockBuilder<Block>,
P: TransactionPool + 'static, P: TransactionPool + 'static,
{ {
use substrate_frame_rpc_system::{FullSystem, SystemApi};
use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApi}; use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApi};
use substrate_frame_rpc_system::{FullSystem, SystemApi};
let mut io = jsonrpc_core::IoHandler::default(); let mut io = jsonrpc_core::IoHandler::default();
let FullDeps { let FullDeps { client, pool, deny_unsafe } = deps;
client,
pool,
deny_unsafe,
} = deps;
io.extend_with( io.extend_with(SystemApi::to_delegate(FullSystem::new(client.clone(), pool, deny_unsafe)));
SystemApi::to_delegate(FullSystem::new(client.clone(), pool, deny_unsafe))
);
io.extend_with( io.extend_with(TransactionPaymentApi::to_delegate(TransactionPayment::new(client.clone())));
TransactionPaymentApi::to_delegate(TransactionPayment::new(client.clone()))
);
// Extend this RPC with a custom API by using the following syntax. // Extend this RPC with a custom API by using the following syntax.
// `YourRpcStruct` should have a reference to a client, which is needed // `YourRpcStruct` should have a reference to a client, which is needed

View File

@ -1,17 +1,17 @@
//! Service and ServiceFactory implementation. Specialized wrapper over substrate service. //! Service and ServiceFactory implementation. Specialized wrapper over substrate service.
use std::{sync::Arc, time::Duration};
use sc_client_api::{ExecutorProvider, RemoteBackend};
use node_template_runtime::{self, opaque::Block, RuntimeApi}; use node_template_runtime::{self, opaque::Block, RuntimeApi};
use sc_service::{error::Error as ServiceError, Configuration, TaskManager}; use sc_client_api::{ExecutorProvider, RemoteBackend};
use sc_consensus_aura::{ImportQueueParams, SlotProportion, StartAuraParams};
use sc_executor::native_executor_instance; use sc_executor::native_executor_instance;
pub use sc_executor::NativeExecutor; pub use sc_executor::NativeExecutor;
use sp_consensus_aura::sr25519::AuthorityPair as AuraPair;
use sc_consensus_aura::{ImportQueueParams, StartAuraParams, SlotProportion};
use sc_finality_grandpa::SharedVoterState; use sc_finality_grandpa::SharedVoterState;
use sc_keystore::LocalKeystore; use sc_keystore::LocalKeystore;
use sc_service::{error::Error as ServiceError, Configuration, TaskManager};
use sc_telemetry::{Telemetry, TelemetryWorker}; use sc_telemetry::{Telemetry, TelemetryWorker};
use sp_consensus::SlotData; use sp_consensus::SlotData;
use sp_consensus_aura::sr25519::AuthorityPair as AuraPair;
use std::{sync::Arc, time::Duration};
// Our native executor instance. // Our native executor instance.
native_executor_instance!( native_executor_instance!(
@ -25,22 +25,35 @@ type FullClient = sc_service::TFullClient<Block, RuntimeApi, Executor>;
type FullBackend = sc_service::TFullBackend<Block>; type FullBackend = sc_service::TFullBackend<Block>;
type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>; type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>;
pub fn new_partial(config: &Configuration) -> Result<sc_service::PartialComponents< pub fn new_partial(
FullClient, FullBackend, FullSelectChain, config: &Configuration,
sp_consensus::DefaultImportQueue<Block, FullClient>, ) -> Result<
sc_transaction_pool::FullPool<Block, FullClient>, sc_service::PartialComponents<
( FullClient,
sc_finality_grandpa::GrandpaBlockImport<FullBackend, Block, FullClient, FullSelectChain>, FullBackend,
sc_finality_grandpa::LinkHalf<Block, FullClient, FullSelectChain>, FullSelectChain,
Option<Telemetry>, sp_consensus::DefaultImportQueue<Block, FullClient>,
) sc_transaction_pool::FullPool<Block, FullClient>,
>, ServiceError> { (
sc_finality_grandpa::GrandpaBlockImport<
FullBackend,
Block,
FullClient,
FullSelectChain,
>,
sc_finality_grandpa::LinkHalf<Block, FullClient, FullSelectChain>,
Option<Telemetry>,
),
>,
ServiceError,
> {
if config.keystore_remote.is_some() { if config.keystore_remote.is_some() {
return Err(ServiceError::Other( return Err(ServiceError::Other(format!("Remote Keystores are not supported.")))
format!("Remote Keystores are not supported.")))
} }
let telemetry = config.telemetry_endpoints.clone() let telemetry = config
.telemetry_endpoints
.clone()
.filter(|x| !x.is_empty()) .filter(|x| !x.is_empty())
.map(|endpoints| -> Result<_, sc_telemetry::Error> { .map(|endpoints| -> Result<_, sc_telemetry::Error> {
let worker = TelemetryWorker::new(16)?; let worker = TelemetryWorker::new(16)?;
@ -56,11 +69,10 @@ pub fn new_partial(config: &Configuration) -> Result<sc_service::PartialComponen
)?; )?;
let client = Arc::new(client); let client = Arc::new(client);
let telemetry = telemetry let telemetry = telemetry.map(|(worker, telemetry)| {
.map(|(worker, telemetry)| { task_manager.spawn_handle().spawn("telemetry", worker.run());
task_manager.spawn_handle().spawn("telemetry", worker.run()); telemetry
telemetry });
});
let select_chain = sc_consensus::LongestChain::new(backend.clone()); let select_chain = sc_consensus::LongestChain::new(backend.clone());
@ -81,8 +93,8 @@ pub fn new_partial(config: &Configuration) -> Result<sc_service::PartialComponen
let slot_duration = sc_consensus_aura::slot_duration(&*client)?.slot_duration(); let slot_duration = sc_consensus_aura::slot_duration(&*client)?.slot_duration();
let import_queue = sc_consensus_aura::import_queue::<AuraPair, _, _, _, _, _, _>( let import_queue =
ImportQueueParams { sc_consensus_aura::import_queue::<AuraPair, _, _, _, _, _, _>(ImportQueueParams {
block_import: grandpa_block_import.clone(), block_import: grandpa_block_import.clone(),
justification_import: Some(Box::new(grandpa_block_import.clone())), justification_import: Some(Box::new(grandpa_block_import.clone())),
client: client.clone(), client: client.clone(),
@ -98,12 +110,13 @@ pub fn new_partial(config: &Configuration) -> Result<sc_service::PartialComponen
Ok((timestamp, slot)) Ok((timestamp, slot))
}, },
spawner: &task_manager.spawn_essential_handle(), spawner: &task_manager.spawn_essential_handle(),
can_author_with: sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()), can_author_with: sp_consensus::CanAuthorWithNativeVersion::new(
client.executor().clone(),
),
registry: config.prometheus_registry(), registry: config.prometheus_registry(),
check_for_equivocation: Default::default(), check_for_equivocation: Default::default(),
telemetry: telemetry.as_ref().map(|x| x.handle()), telemetry: telemetry.as_ref().map(|x| x.handle()),
}, })?;
)?;
Ok(sc_service::PartialComponents { Ok(sc_service::PartialComponents {
client, client,
@ -140,10 +153,11 @@ pub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError>
if let Some(url) = &config.keystore_remote { if let Some(url) = &config.keystore_remote {
match remote_keystore(url) { match remote_keystore(url) {
Ok(k) => keystore_container.set_remote_keystore(k), Ok(k) => keystore_container.set_remote_keystore(k),
Err(e) => { Err(e) =>
return Err(ServiceError::Other( return Err(ServiceError::Other(format!(
format!("Error hooking up remote keystore for {}: {}", url, e))) "Error hooking up remote keystore for {}: {}",
} url, e
))),
}; };
} }
@ -162,7 +176,10 @@ pub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError>
if config.offchain_worker.enabled { if config.offchain_worker.enabled {
sc_service::build_offchain_workers( sc_service::build_offchain_workers(
&config, task_manager.spawn_handle(), client.clone(), network.clone(), &config,
task_manager.spawn_handle(),
client.clone(),
network.clone(),
); );
} }
@ -178,32 +195,27 @@ pub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError>
let pool = transaction_pool.clone(); let pool = transaction_pool.clone();
Box::new(move |deny_unsafe, _| { Box::new(move |deny_unsafe, _| {
let deps = crate::rpc::FullDeps { let deps =
client: client.clone(), crate::rpc::FullDeps { client: client.clone(), pool: pool.clone(), deny_unsafe };
pool: pool.clone(),
deny_unsafe,
};
crate::rpc::create_full(deps) crate::rpc::create_full(deps)
}) })
}; };
let _rpc_handlers = sc_service::spawn_tasks( let _rpc_handlers = sc_service::spawn_tasks(sc_service::SpawnTasksParams {
sc_service::SpawnTasksParams { network: network.clone(),
network: network.clone(), client: client.clone(),
client: client.clone(), keystore: keystore_container.sync_keystore(),
keystore: keystore_container.sync_keystore(), task_manager: &mut task_manager,
task_manager: &mut task_manager, transaction_pool: transaction_pool.clone(),
transaction_pool: transaction_pool.clone(), rpc_extensions_builder,
rpc_extensions_builder, on_demand: None,
on_demand: None, remote_blockchain: None,
remote_blockchain: None, backend,
backend, system_rpc_tx,
system_rpc_tx, config,
config, telemetry: telemetry.as_mut(),
telemetry: telemetry.as_mut(), })?;
},
)?;
if role.is_authority() { if role.is_authority() {
let proposer_factory = sc_basic_authorship::ProposerFactory::new( let proposer_factory = sc_basic_authorship::ProposerFactory::new(
@ -257,11 +269,8 @@ pub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError>
// if the node isn't actively participating in consensus then it doesn't // if the node isn't actively participating in consensus then it doesn't
// need a keystore, regardless of which protocol we use below. // need a keystore, regardless of which protocol we use below.
let keystore = if role.is_authority() { let keystore =
Some(keystore_container.sync_keystore()) if role.is_authority() { Some(keystore_container.sync_keystore()) } else { None };
} else {
None
};
let grandpa_config = sc_finality_grandpa::Config { let grandpa_config = sc_finality_grandpa::Config {
// FIXME #1578 make this available through chainspec // FIXME #1578 make this available through chainspec
@ -295,7 +304,7 @@ pub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError>
// if it fails we take down the service with it. // if it fails we take down the service with it.
task_manager.spawn_essential_handle().spawn_blocking( task_manager.spawn_essential_handle().spawn_blocking(
"grandpa-voter", "grandpa-voter",
sc_finality_grandpa::run_grandpa_voter(grandpa_config)? sc_finality_grandpa::run_grandpa_voter(grandpa_config)?,
); );
} }
@ -305,7 +314,9 @@ pub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError>
/// Builds a new service for a light client. /// Builds a new service for a light client.
pub fn new_light(mut config: Configuration) -> Result<TaskManager, ServiceError> { pub fn new_light(mut config: Configuration) -> Result<TaskManager, ServiceError> {
let telemetry = config.telemetry_endpoints.clone() let telemetry = config
.telemetry_endpoints
.clone()
.filter(|x| !x.is_empty()) .filter(|x| !x.is_empty())
.map(|endpoints| -> Result<_, sc_telemetry::Error> { .map(|endpoints| -> Result<_, sc_telemetry::Error> {
let worker = TelemetryWorker::new(16)?; let worker = TelemetryWorker::new(16)?;
@ -320,11 +331,10 @@ pub fn new_light(mut config: Configuration) -> Result<TaskManager, ServiceError>
telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()), telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),
)?; )?;
let mut telemetry = telemetry let mut telemetry = telemetry.map(|(worker, telemetry)| {
.map(|(worker, telemetry)| { task_manager.spawn_handle().spawn("telemetry", worker.run());
task_manager.spawn_handle().spawn("telemetry", worker.run()); telemetry
telemetry });
});
config.network.extra_sets.push(sc_finality_grandpa::grandpa_peers_set_config()); config.network.extra_sets.push(sc_finality_grandpa::grandpa_peers_set_config());
@ -347,8 +357,8 @@ pub fn new_light(mut config: Configuration) -> Result<TaskManager, ServiceError>
let slot_duration = sc_consensus_aura::slot_duration(&*client)?.slot_duration(); let slot_duration = sc_consensus_aura::slot_duration(&*client)?.slot_duration();
let import_queue = sc_consensus_aura::import_queue::<AuraPair, _, _, _, _, _, _>( let import_queue =
ImportQueueParams { sc_consensus_aura::import_queue::<AuraPair, _, _, _, _, _, _>(ImportQueueParams {
block_import: grandpa_block_import.clone(), block_import: grandpa_block_import.clone(),
justification_import: Some(Box::new(grandpa_block_import.clone())), justification_import: Some(Box::new(grandpa_block_import.clone())),
client: client.clone(), client: client.clone(),
@ -368,8 +378,7 @@ pub fn new_light(mut config: Configuration) -> Result<TaskManager, ServiceError>
registry: config.prometheus_registry(), registry: config.prometheus_registry(),
check_for_equivocation: Default::default(), check_for_equivocation: Default::default(),
telemetry: telemetry.as_ref().map(|x| x.handle()), telemetry: telemetry.as_ref().map(|x| x.handle()),
}, })?;
)?;
let (network, system_rpc_tx, network_starter) = let (network, system_rpc_tx, network_starter) =
sc_service::build_network(sc_service::BuildNetworkParams { sc_service::build_network(sc_service::BuildNetworkParams {
@ -384,7 +393,10 @@ pub fn new_light(mut config: Configuration) -> Result<TaskManager, ServiceError>
if config.offchain_worker.enabled { if config.offchain_worker.enabled {
sc_service::build_offchain_workers( sc_service::build_offchain_workers(
&config, task_manager.spawn_handle(), client.clone(), network.clone(), &config,
task_manager.spawn_handle(),
client.clone(),
network.clone(),
); );
} }

View File

@ -2,10 +2,10 @@
use super::*; use super::*;
use frame_system::RawOrigin;
use frame_benchmarking::{benchmarks, whitelisted_caller, impl_benchmark_test_suite};
#[allow(unused)] #[allow(unused)]
use crate::Pallet as Template; use crate::Pallet as Template;
use frame_benchmarking::{benchmarks, impl_benchmark_test_suite, whitelisted_caller};
use frame_system::RawOrigin;
benchmarks! { benchmarks! {
do_something { do_something {
@ -17,8 +17,4 @@ benchmarks! {
} }
} }
impl_benchmark_test_suite!( impl_benchmark_test_suite!(Template, crate::mock::new_test_ext(), crate::mock::Test,);
Template,
crate::mock::new_test_ext(),
crate::mock::Test,
);

View File

@ -3,7 +3,6 @@
/// Edit this file to define custom logic or remove it if it is not needed. /// Edit this file to define custom logic or remove it if it is not needed.
/// Learn more about FRAME and the core library of Substrate FRAME pallets: /// Learn more about FRAME and the core library of Substrate FRAME pallets:
/// <https://substrate.dev/docs/en/knowledgebase/runtime/frame> /// <https://substrate.dev/docs/en/knowledgebase/runtime/frame>
pub use pallet::*; pub use pallet::*;
#[cfg(test)] #[cfg(test)]
@ -63,7 +62,7 @@ pub mod pallet {
// These functions materialize as "extrinsics", which are often compared to transactions. // These functions materialize as "extrinsics", which are often compared to transactions.
// Dispatchable functions must be annotated with a weight and must return a DispatchResult. // Dispatchable functions must be annotated with a weight and must return a DispatchResult.
#[pallet::call] #[pallet::call]
impl<T:Config> Pallet<T> { impl<T: Config> Pallet<T> {
/// An example dispatchable that takes a singles value as a parameter, writes the value to /// An example dispatchable that takes a singles value as a parameter, writes the value to
/// storage and emits an event. This function must be dispatched by a signed extrinsic. /// storage and emits an event. This function must be dispatched by a signed extrinsic.
#[pallet::weight(10_000 + T::DbWeight::get().writes(1))] #[pallet::weight(10_000 + T::DbWeight::get().writes(1))]

View File

@ -1,10 +1,11 @@
use crate as pallet_template; use crate as pallet_template;
use sp_core::H256;
use frame_support::parameter_types; use frame_support::parameter_types;
use sp_runtime::{
traits::{BlakeTwo256, IdentityLookup}, testing::Header,
};
use frame_system as system; use frame_system as system;
use sp_core::H256;
use sp_runtime::{
testing::Header,
traits::{BlakeTwo256, IdentityLookup},
};
type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
type Block = frame_system::mocking::MockBlock<Test>; type Block = frame_system::mocking::MockBlock<Test>;

View File

@ -1,5 +1,5 @@
use crate::{Error, mock::*}; use crate::{mock::*, Error};
use frame_support::{assert_ok, assert_noop}; use frame_support::{assert_noop, assert_ok};
#[test] #[test]
fn it_works_for_default_value() { fn it_works_for_default_value() {
@ -15,9 +15,6 @@ fn it_works_for_default_value() {
fn correct_error_for_none_value() { fn correct_error_for_none_value() {
new_test_ext().execute_with(|| { new_test_ext().execute_with(|| {
// Ensure the expected error is thrown when no value is present. // Ensure the expected error is thrown when no value is present.
assert_noop!( assert_noop!(TemplateModule::cause_error(Origin::signed(1)), Error::<Test>::NoneValue);
TemplateModule::cause_error(Origin::signed(1)),
Error::<Test>::NoneValue
);
}); });
} }

View File

@ -1,43 +1,44 @@
#![cfg_attr(not(feature = "std"), no_std)] #![cfg_attr(not(feature = "std"), no_std)]
// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256. // `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.
#![recursion_limit="256"] #![recursion_limit = "256"]
// Make the WASM binary available. // Make the WASM binary available.
#[cfg(feature = "std")] #[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
use sp_std::prelude::*; use pallet_grandpa::{
use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; fg_primitives, AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList,
use sp_runtime::{
ApplyExtrinsicResult, generic, create_runtime_str, impl_opaque_keys, MultiSignature,
transaction_validity::{TransactionValidity, TransactionSource},
};
use sp_runtime::traits::{
BlakeTwo256, Block as BlockT, AccountIdLookup, Verify, IdentifyAccount, NumberFor,
}; };
use sp_api::impl_runtime_apis; use sp_api::impl_runtime_apis;
use sp_consensus_aura::sr25519::AuthorityId as AuraId; use sp_consensus_aura::sr25519::AuthorityId as AuraId;
use pallet_grandpa::{AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList}; use sp_core::{crypto::KeyTypeId, OpaqueMetadata};
use pallet_grandpa::fg_primitives; use sp_runtime::{
use sp_version::RuntimeVersion; create_runtime_str, generic, impl_opaque_keys,
traits::{AccountIdLookup, BlakeTwo256, Block as BlockT, IdentifyAccount, NumberFor, Verify},
transaction_validity::{TransactionSource, TransactionValidity},
ApplyExtrinsicResult, MultiSignature,
};
use sp_std::prelude::*;
#[cfg(feature = "std")] #[cfg(feature = "std")]
use sp_version::NativeVersion; use sp_version::NativeVersion;
use sp_version::RuntimeVersion;
// A few exports that help ease life for downstream crates. // A few exports that help ease life for downstream crates.
#[cfg(any(feature = "std", test))]
pub use sp_runtime::BuildStorage;
pub use pallet_timestamp::Call as TimestampCall;
pub use pallet_balances::Call as BalancesCall;
pub use sp_runtime::{Permill, Perbill};
pub use frame_support::{ pub use frame_support::{
construct_runtime, parameter_types, StorageValue, construct_runtime, parameter_types,
traits::{KeyOwnerProofSystem, Randomness}, traits::{KeyOwnerProofSystem, Randomness},
weights::{ weights::{
Weight, IdentityFee,
constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND}, constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},
IdentityFee, Weight,
}, },
StorageValue,
}; };
pub use pallet_balances::Call as BalancesCall;
pub use pallet_timestamp::Call as TimestampCall;
use pallet_transaction_payment::CurrencyAdapter; use pallet_transaction_payment::CurrencyAdapter;
#[cfg(any(feature = "std", test))]
pub use sp_runtime::BuildStorage;
pub use sp_runtime::{Perbill, Permill};
/// Import the template pallet. /// Import the template pallet.
pub use pallet_template; pub use pallet_template;
@ -123,10 +124,7 @@ pub const DAYS: BlockNumber = HOURS * 24;
/// The version information used to identify this runtime when compiled natively. /// The version information used to identify this runtime when compiled natively.
#[cfg(feature = "std")] #[cfg(feature = "std")]
pub fn native_version() -> NativeVersion { pub fn native_version() -> NativeVersion {
NativeVersion { NativeVersion { runtime_version: VERSION, can_author_with: Default::default() }
runtime_version: VERSION,
can_author_with: Default::default(),
}
} }
const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75); const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
@ -306,7 +304,7 @@ pub type SignedExtra = (
frame_system::CheckEra<Runtime>, frame_system::CheckEra<Runtime>,
frame_system::CheckNonce<Runtime>, frame_system::CheckNonce<Runtime>,
frame_system::CheckWeight<Runtime>, frame_system::CheckWeight<Runtime>,
pallet_transaction_payment::ChargeTransactionPayment<Runtime> pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
); );
/// Unchecked extrinsic type as expected by this runtime. /// Unchecked extrinsic type as expected by this runtime.
pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>; pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;

22
rustfmt.toml 100644
View File

@ -0,0 +1,22 @@
# Basic
hard_tabs = true
max_width = 100
use_small_heuristics = "Max"
# Imports
imports_granularity = "Crate"
reorder_imports = true
# Consistency
newline_style = "Unix"
normalize_comments = true
normalize_doc_attributes = true
# Misc
chain_width = 80
spaces_around_ranges = false
binop_separator = "Back"
reorder_impl_items = false
match_arm_leading_pipes = "Preserve"
match_arm_blocks = false
match_block_trailing_comma = true
trailing_comma = "Vertical"
trailing_semicolon = false
use_field_init_shorthand = true