diff --git a/node/build.rs b/node/build.rs index ef1d6b93624374fefa07252fe9d267ec9823c4ce..06701a0aefc406ba854b9b8783966276a3c7db0e 100644 --- a/node/build.rs +++ b/node/build.rs @@ -17,7 +17,7 @@ use substrate_build_script_utils::{generate_cargo_keys, rerun_if_git_head_changed}; fn main() { - generate_cargo_keys(); + generate_cargo_keys(); - rerun_if_git_head_changed(); + rerun_if_git_head_changed(); } diff --git a/node/src/chain_spec.rs b/node/src/chain_spec.rs index a2e4dbf659043e5e198c4595431224b46a654e17..f2572fe9404def9af86383fd770a247b84d8dfd3 100644 --- a/node/src/chain_spec.rs +++ b/node/src/chain_spec.rs @@ -14,15 +14,15 @@ // You should have received a copy of the GNU Affero General Public License // along with Substrate-Libre-Currency. If not, see <https://www.gnu.org/licenses/>. -use sp_core::{Pair, Public, sr25519}; use node_template_runtime::{ - AccountId, AuraConfig, BalancesConfig, GenesisConfig, GrandpaConfig, - SudoConfig, SystemConfig, WASM_BINARY, Signature + AccountId, AuraConfig, BalancesConfig, GenesisConfig, GrandpaConfig, Signature, SudoConfig, + SystemConfig, WASM_BINARY, }; +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::{Verify, IdentifyAccount}; -use sc_service::ChainType; +use sp_runtime::traits::{IdentifyAccount, Verify}; // The URL for the telemetry server. // const STAGING_TELEMETRY_URL: &str = "wss://telemetry.polkadot.io/submit/"; @@ -32,142 +32,149 @@ pub type ChainSpec = sc_service::GenericChainSpec<GenesisConfig>; /// Generate a crypto pair from seed. pub fn get_from_seed<TPublic: Public>(seed: &str) -> <TPublic::Pair as Pair>::Public { - TPublic::Pair::from_string(&format!("//{}", seed), None) - .expect("static values are valid; qed") - .public() + TPublic::Pair::from_string(&format!("//{}", seed), None) + .expect("static values are valid; qed") + .public() } type AccountPublic = <Signature as Verify>::Signer; /// 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() + AccountPublic::from(get_from_seed::<TPublic>(seed)).into_account() } /// Generate an Aura authority key. 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> { - let wasm_binary = WASM_BINARY.ok_or_else(|| "Development wasm not available".to_string())?; + let wasm_binary = WASM_BINARY.ok_or_else(|| "Development wasm not available".to_string())?; - Ok(ChainSpec::from_genesis( - // Name - "Development", - // ID - "dev", - ChainType::Development, - move || testnet_genesis( - wasm_binary, - // Initial PoA authorities - vec![ - authority_keys_from_seed("Alice"), - ], - // 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>("Bob"), - get_account_id_from_seed::<sr25519::Public>("Alice//stash"), - get_account_id_from_seed::<sr25519::Public>("Bob//stash"), - ], - true, - ), - // Bootnodes - vec![], - // Telemetry - None, - // Protocol ID - None, - // Properties - None, - // Extensions - None, - )) + Ok(ChainSpec::from_genesis( + // Name + "Development", + // ID + "dev", + ChainType::Development, + move || { + testnet_genesis( + wasm_binary, + // Initial PoA authorities + vec![authority_keys_from_seed("Alice")], + // 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>("Bob"), + get_account_id_from_seed::<sr25519::Public>("Alice//stash"), + get_account_id_from_seed::<sr25519::Public>("Bob//stash"), + ], + true, + ) + }, + // Bootnodes + vec![], + // Telemetry + None, + // Protocol ID + None, + // Properties + None, + // Extensions + None, + )) } pub fn local_testnet_config() -> Result<ChainSpec, String> { - let wasm_binary = WASM_BINARY.ok_or_else(|| "Development wasm not available".to_string())?; + let wasm_binary = WASM_BINARY.ok_or_else(|| "Development wasm not available".to_string())?; - Ok(ChainSpec::from_genesis( - // Name - "Local Testnet", - // ID - "local_testnet", - ChainType::Local, - move || testnet_genesis( - wasm_binary, - // Initial PoA authorities - vec![ - authority_keys_from_seed("Alice"), - authority_keys_from_seed("Bob"), - ], - // 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>("Bob"), - get_account_id_from_seed::<sr25519::Public>("Charlie"), - get_account_id_from_seed::<sr25519::Public>("Dave"), - get_account_id_from_seed::<sr25519::Public>("Eve"), - get_account_id_from_seed::<sr25519::Public>("Ferdie"), - get_account_id_from_seed::<sr25519::Public>("Alice//stash"), - get_account_id_from_seed::<sr25519::Public>("Bob//stash"), - get_account_id_from_seed::<sr25519::Public>("Charlie//stash"), - get_account_id_from_seed::<sr25519::Public>("Dave//stash"), - get_account_id_from_seed::<sr25519::Public>("Eve//stash"), - get_account_id_from_seed::<sr25519::Public>("Ferdie//stash"), - ], - true, - ), - // Bootnodes - vec![], - // Telemetry - None, - // Protocol ID - None, - // Properties - None, - // Extensions - None, - )) + Ok(ChainSpec::from_genesis( + // Name + "Local Testnet", + // ID + "local_testnet", + ChainType::Local, + move || { + testnet_genesis( + wasm_binary, + // Initial PoA authorities + vec![ + authority_keys_from_seed("Alice"), + authority_keys_from_seed("Bob"), + ], + // 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>("Bob"), + get_account_id_from_seed::<sr25519::Public>("Charlie"), + get_account_id_from_seed::<sr25519::Public>("Dave"), + get_account_id_from_seed::<sr25519::Public>("Eve"), + get_account_id_from_seed::<sr25519::Public>("Ferdie"), + get_account_id_from_seed::<sr25519::Public>("Alice//stash"), + get_account_id_from_seed::<sr25519::Public>("Bob//stash"), + get_account_id_from_seed::<sr25519::Public>("Charlie//stash"), + get_account_id_from_seed::<sr25519::Public>("Dave//stash"), + get_account_id_from_seed::<sr25519::Public>("Eve//stash"), + get_account_id_from_seed::<sr25519::Public>("Ferdie//stash"), + ], + true, + ) + }, + // Bootnodes + vec![], + // Telemetry + None, + // Protocol ID + None, + // Properties + None, + // Extensions + None, + )) } /// Configure initial storage state for FRAME modules. fn testnet_genesis( - wasm_binary: &[u8], - initial_authorities: Vec<(AuraId, GrandpaId)>, - root_key: AccountId, - endowed_accounts: Vec<AccountId>, - _enable_println: bool, + wasm_binary: &[u8], + initial_authorities: Vec<(AuraId, GrandpaId)>, + root_key: AccountId, + endowed_accounts: Vec<AccountId>, + _enable_println: bool, ) -> GenesisConfig { - GenesisConfig { - frame_system: SystemConfig { - // Add Wasm runtime to storage. - code: wasm_binary.to_vec(), - changes_trie_config: Default::default(), - }, - pallet_balances: BalancesConfig { - // Configure endowed accounts with initial balance of 1 << 60. - balances: endowed_accounts.iter().cloned().map(|k|(k, 1 << 60)).collect(), - }, - pallet_aura: AuraConfig { - authorities: initial_authorities.iter().map(|x| (x.0.clone())).collect(), - }, - pallet_grandpa: GrandpaConfig { - authorities: initial_authorities.iter().map(|x| (x.1.clone(), 1)).collect(), - }, - pallet_sudo: SudoConfig { - // Assign network admin rights. - key: root_key, - }, - } + GenesisConfig { + frame_system: SystemConfig { + // Add Wasm runtime to storage. + code: wasm_binary.to_vec(), + changes_trie_config: Default::default(), + }, + pallet_balances: BalancesConfig { + // Configure endowed accounts with initial balance of 1 << 60. + balances: endowed_accounts + .iter() + .cloned() + .map(|k| (k, 1 << 60)) + .collect(), + }, + pallet_aura: AuraConfig { + authorities: initial_authorities.iter().map(|x| (x.0.clone())).collect(), + }, + pallet_grandpa: GrandpaConfig { + authorities: initial_authorities + .iter() + .map(|x| (x.1.clone(), 1)) + .collect(), + }, + pallet_sudo: SudoConfig { + // Assign network admin rights. + key: root_key, + }, + } } diff --git a/node/src/cli.rs b/node/src/cli.rs index 6a4a2924c81a5a2a349145154b60a14c06119d7a..fb2582f6a5f938d99fac31ff9d9d5fca492a9bc3 100644 --- a/node/src/cli.rs +++ b/node/src/cli.rs @@ -14,44 +14,44 @@ // You should have received a copy of the GNU Affero General Public License // along with Substrate-Libre-Currency. If not, see <https://www.gnu.org/licenses/>. -use structopt::StructOpt; use sc_cli::RunCmd; +use structopt::StructOpt; #[derive(Debug, StructOpt)] pub struct Cli { - #[structopt(subcommand)] - pub subcommand: Option<Subcommand>, + #[structopt(subcommand)] + pub subcommand: Option<Subcommand>, - #[structopt(flatten)] - pub run: RunCmd, + #[structopt(flatten)] + pub run: RunCmd, } #[derive(Debug, StructOpt)] pub enum Subcommand { - /// Key management cli utilities - Key(sc_cli::KeySubcommand), - /// Build a chain specification. - BuildSpec(sc_cli::BuildSpecCmd), + /// Key management cli utilities + Key(sc_cli::KeySubcommand), + /// Build a chain specification. + BuildSpec(sc_cli::BuildSpecCmd), - /// Validate blocks. - CheckBlock(sc_cli::CheckBlockCmd), + /// Validate blocks. + CheckBlock(sc_cli::CheckBlockCmd), - /// Export blocks. - ExportBlocks(sc_cli::ExportBlocksCmd), + /// Export blocks. + ExportBlocks(sc_cli::ExportBlocksCmd), - /// Export the state of a given block into a chain spec. - ExportState(sc_cli::ExportStateCmd), + /// Export the state of a given block into a chain spec. + ExportState(sc_cli::ExportStateCmd), - /// Import blocks. - ImportBlocks(sc_cli::ImportBlocksCmd), + /// Import blocks. + ImportBlocks(sc_cli::ImportBlocksCmd), - /// Remove the whole chain. - PurgeChain(sc_cli::PurgeChainCmd), + /// Remove the whole chain. + PurgeChain(sc_cli::PurgeChainCmd), - /// Revert the chain to a previous state. - Revert(sc_cli::RevertCmd), + /// Revert the chain to a previous state. + Revert(sc_cli::RevertCmd), - /// The custom benchmark subcommmand benchmarking runtime pallets. - #[structopt(name = "benchmark", about = "Benchmark runtime pallets.")] - Benchmark(frame_benchmarking_cli::BenchmarkCmd), + /// The custom benchmark subcommmand benchmarking runtime pallets. + #[structopt(name = "benchmark", about = "Benchmark runtime pallets.")] + Benchmark(frame_benchmarking_cli::BenchmarkCmd), } diff --git a/node/src/command.rs b/node/src/command.rs index 573c06d13223c26f88489ce660fd589708620f04..047767c6ab55454b80f955a351ab7b1c027e938e 100644 --- a/node/src/command.rs +++ b/node/src/command.rs @@ -15,124 +15,144 @@ // You should have received a copy of the GNU Affero General Public License // along with Substrate-Libre-Currency. If not, see <https://www.gnu.org/licenses/>. -use crate::{chain_spec, service}; use crate::cli::{Cli, Subcommand}; -use sc_cli::{SubstrateCli, RuntimeVersion, Role, ChainSpec}; -use sc_service::PartialComponents; +use crate::{chain_spec, service}; use node_template_runtime::Block; +use sc_cli::{ChainSpec, Role, RuntimeVersion, SubstrateCli}; +use sc_service::PartialComponents; impl SubstrateCli for Cli { - fn impl_name() -> String { - "Substrate Node".into() - } + fn impl_name() -> String { + "Substrate Node".into() + } - fn impl_version() -> String { - env!("SUBSTRATE_CLI_IMPL_VERSION").into() - } + fn impl_version() -> String { + env!("SUBSTRATE_CLI_IMPL_VERSION").into() + } - fn description() -> String { - env!("CARGO_PKG_DESCRIPTION").into() - } + fn description() -> String { + env!("CARGO_PKG_DESCRIPTION").into() + } - fn author() -> String { - env!("CARGO_PKG_AUTHORS").into() - } + fn author() -> String { + env!("CARGO_PKG_AUTHORS").into() + } - fn support_url() -> String { - "support.anonymous.an".into() - } + fn support_url() -> String { + "support.anonymous.an".into() + } - fn copyright_start_year() -> i32 { - 2017 - } + fn copyright_start_year() -> i32 { + 2017 + } - fn load_spec(&self, id: &str) -> Result<Box<dyn sc_service::ChainSpec>, String> { - Ok(match id { - "dev" => Box::new(chain_spec::development_config()?), - "" | "local" => Box::new(chain_spec::local_testnet_config()?), - path => Box::new(chain_spec::ChainSpec::from_json_file( - std::path::PathBuf::from(path), - )?), - }) - } + fn load_spec(&self, id: &str) -> Result<Box<dyn sc_service::ChainSpec>, String> { + Ok(match id { + "dev" => Box::new(chain_spec::development_config()?), + "" | "local" => Box::new(chain_spec::local_testnet_config()?), + path => Box::new(chain_spec::ChainSpec::from_json_file( + std::path::PathBuf::from(path), + )?), + }) + } - fn native_runtime_version(_: &Box<dyn ChainSpec>) -> &'static RuntimeVersion { - &node_template_runtime::VERSION - } + fn native_runtime_version(_: &Box<dyn ChainSpec>) -> &'static RuntimeVersion { + &node_template_runtime::VERSION + } } /// Parse and run command line arguments pub fn run() -> sc_cli::Result<()> { - let cli = Cli::from_args(); + let cli = Cli::from_args(); - match &cli.subcommand { - Some(Subcommand::Key(cmd)) => cmd.run(&cli), - Some(Subcommand::BuildSpec(cmd)) => { - let runner = cli.create_runner(cmd)?; - runner.sync_run(|config| cmd.run(config.chain_spec, config.network)) - }, - Some(Subcommand::CheckBlock(cmd)) => { - let runner = cli.create_runner(cmd)?; - runner.async_run(|config| { - let PartialComponents { client, task_manager, import_queue, ..} - = service::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, ..} - = service::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, ..} - = service::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, ..} - = service::new_partial(&config)?; - Ok((cmd.run(client, import_queue), task_manager)) - }) - }, - Some(Subcommand::PurgeChain(cmd)) => { - let runner = cli.create_runner(cmd)?; - runner.sync_run(|config| cmd.run(config.database)) - }, - Some(Subcommand::Revert(cmd)) => { - let runner = cli.create_runner(cmd)?; - runner.async_run(|config| { - let PartialComponents { client, task_manager, backend, ..} - = service::new_partial(&config)?; - Ok((cmd.run(client, backend), task_manager)) - }) - }, - Some(Subcommand::Benchmark(cmd)) => { - if cfg!(feature = "runtime-benchmarks") { - let runner = cli.create_runner(cmd)?; + match &cli.subcommand { + Some(Subcommand::Key(cmd)) => cmd.run(&cli), + Some(Subcommand::BuildSpec(cmd)) => { + let runner = cli.create_runner(cmd)?; + runner.sync_run(|config| cmd.run(config.chain_spec, config.network)) + } + Some(Subcommand::CheckBlock(cmd)) => { + let runner = cli.create_runner(cmd)?; + runner.async_run(|config| { + let PartialComponents { + client, + task_manager, + import_queue, + .. + } = service::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, + .. + } = service::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, + .. + } = service::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, + .. + } = service::new_partial(&config)?; + Ok((cmd.run(client, import_queue), task_manager)) + }) + } + Some(Subcommand::PurgeChain(cmd)) => { + let runner = cli.create_runner(cmd)?; + runner.sync_run(|config| cmd.run(config.database)) + } + Some(Subcommand::Revert(cmd)) => { + let runner = cli.create_runner(cmd)?; + runner.async_run(|config| { + let PartialComponents { + client, + task_manager, + backend, + .. + } = service::new_partial(&config)?; + Ok((cmd.run(client, backend), task_manager)) + }) + } + Some(Subcommand::Benchmark(cmd)) => { + if cfg!(feature = "runtime-benchmarks") { + let runner = cli.create_runner(cmd)?; - runner.sync_run(|config| cmd.run::<Block, service::Executor>(config)) - } else { - Err("Benchmarking wasn't enabled when building the node. \ - You can enable it with `--features runtime-benchmarks`.".into()) - } - }, - None => { - let runner = cli.create_runner(&cli.run)?; - runner.run_node_until_exit(|config| async move { - match config.role { - Role::Light => service::new_light(config), - _ => service::new_full(config), - }.map_err(sc_cli::Error::Service) - }) - } - } + runner.sync_run(|config| cmd.run::<Block, service::Executor>(config)) + } else { + Err("Benchmarking wasn't enabled when building the node. \ + You can enable it with `--features runtime-benchmarks`." + .into()) + } + } + None => { + let runner = cli.create_runner(&cli.run)?; + runner.run_node_until_exit(|config| async move { + match config.role { + Role::Light => service::new_light(config), + _ => service::new_full(config), + } + .map_err(sc_cli::Error::Service) + }) + } + } } diff --git a/node/src/lib.rs b/node/src/lib.rs index 97ec6846acdf94084b8cfdaf158fa44c02a3cbe3..decdc601a3cfac4a3fc9b2f024b2e3896ea450f6 100644 --- a/node/src/lib.rs +++ b/node/src/lib.rs @@ -15,5 +15,5 @@ // along with Substrate-Libre-Currency. If not, see <https://www.gnu.org/licenses/>. pub mod chain_spec; -pub mod service; pub mod rpc; +pub mod service; diff --git a/node/src/main.rs b/node/src/main.rs index 41b5a9bec3f584ffad3db58dbd15c45897de4cd6..abe45962afc0d9969a86fc01f0c1f3666f2318d7 100644 --- a/node/src/main.rs +++ b/node/src/main.rs @@ -25,5 +25,5 @@ mod command; mod rpc; fn main() -> sc_cli::Result<()> { - command::run() + command::run() } diff --git a/node/src/rpc.rs b/node/src/rpc.rs index 3714d677ffdc6ee670f292bc68a46d5cf74180d2..0aa8dbb3d4360b9e476878bb3a967a167795ffea 100644 --- a/node/src/rpc.rs +++ b/node/src/rpc.rs @@ -24,57 +24,57 @@ use std::sync::Arc; use node_template_runtime::{opaque::Block, AccountId, Balance, Index}; +pub use sc_rpc_api::DenyUnsafe; use sp_api::ProvideRuntimeApi; -use sp_blockchain::{Error as BlockChainError, HeaderMetadata, HeaderBackend}; use sp_block_builder::BlockBuilder; -pub use sc_rpc_api::DenyUnsafe; +use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata}; use sp_transaction_pool::TransactionPool; - /// Full client dependencies. pub struct FullDeps<C, P> { - /// The client instance to use. - pub client: Arc<C>, - /// Transaction pool instance. - pub pool: Arc<P>, - /// Whether to deny unsafe calls - pub deny_unsafe: DenyUnsafe, + /// The client instance to use. + pub client: Arc<C>, + /// Transaction pool instance. + pub pool: Arc<P>, + /// Whether to deny unsafe calls + pub deny_unsafe: DenyUnsafe, } /// Instantiate all full RPC extensions. -pub fn create_full<C, P>( - deps: FullDeps<C, P>, -) -> jsonrpc_core::IoHandler<sc_rpc::Metadata> where - C: ProvideRuntimeApi<Block>, - C: HeaderBackend<Block> + HeaderMetadata<Block, Error=BlockChainError> + 'static, - C: Send + Sync + 'static, - C::Api: substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>, - C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi<Block, Balance>, - C::Api: BlockBuilder<Block>, - P: TransactionPool + 'static, +pub fn create_full<C, P>(deps: FullDeps<C, P>) -> jsonrpc_core::IoHandler<sc_rpc::Metadata> +where + C: ProvideRuntimeApi<Block>, + C: HeaderBackend<Block> + HeaderMetadata<Block, Error = BlockChainError> + 'static, + C: Send + Sync + 'static, + C::Api: substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>, + C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi<Block, Balance>, + C::Api: BlockBuilder<Block>, + 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 FullDeps { - client, - pool, - deny_unsafe, - } = deps; + let mut io = jsonrpc_core::IoHandler::default(); + let FullDeps { + client, + pool, + deny_unsafe, + } = deps; - io.extend_with( - SystemApi::to_delegate(FullSystem::new(client.clone(), pool, deny_unsafe)) - ); + io.extend_with(SystemApi::to_delegate(FullSystem::new( + client.clone(), + pool, + deny_unsafe, + ))); - io.extend_with( - TransactionPaymentApi::to_delegate(TransactionPayment::new(client.clone())) - ); + io.extend_with(TransactionPaymentApi::to_delegate(TransactionPayment::new( + client.clone(), + ))); - // Extend this RPC with a custom API by using the following syntax. - // `YourRpcStruct` should have a reference to a client, which is needed - // to call into the runtime. - // `io.extend_with(YourRpcTrait::to_delegate(YourRpcStruct::new(ReferenceToClient, ...)));` + // Extend this RPC with a custom API by using the following syntax. + // `YourRpcStruct` should have a reference to a client, which is needed + // to call into the runtime. + // `io.extend_with(YourRpcTrait::to_delegate(YourRpcStruct::new(ReferenceToClient, ...)));` - io + io } diff --git a/node/src/service.rs b/node/src/service.rs index 1a0260e6d8c48c6002fe6a4b9944683ba12a04af..8dca2cd0996f31ce97a0afa2477d8b826a32b264 100644 --- a/node/src/service.rs +++ b/node/src/service.rs @@ -16,393 +16,423 @@ //! Service and ServiceFactory implementation. Specialized wrapper over substrate service. -use std::sync::Arc; -use std::time::Duration; -use sc_client_api::{ExecutorProvider, RemoteBackend}; use node_template_runtime::{self, opaque::Block, RuntimeApi}; -use sc_service::{error::Error as ServiceError, Configuration, TaskManager}; -use sp_inherents::InherentDataProviders; +use sc_client_api::{ExecutorProvider, RemoteBackend}; +use sc_consensus_aura::{ImportQueueParams, SlotProportion, StartAuraParams}; use sc_executor::native_executor_instance; 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_keystore::LocalKeystore; +use sc_service::{error::Error as ServiceError, Configuration, TaskManager}; use sc_telemetry::{Telemetry, TelemetryWorker}; +use sp_consensus_aura::sr25519::AuthorityPair as AuraPair; +use sp_inherents::InherentDataProviders; +use std::sync::Arc; +use std::time::Duration; // Our native executor instance. native_executor_instance!( - pub Executor, - node_template_runtime::api::dispatch, - node_template_runtime::native_version, - frame_benchmarking::benchmarking::HostFunctions, + pub Executor, + node_template_runtime::api::dispatch, + node_template_runtime::native_version, + frame_benchmarking::benchmarking::HostFunctions, ); type FullClient = sc_service::TFullClient<Block, RuntimeApi, Executor>; type FullBackend = sc_service::TFullBackend<Block>; type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>; -pub fn new_partial(config: &Configuration) -> Result<sc_service::PartialComponents< - FullClient, FullBackend, FullSelectChain, - sp_consensus::DefaultImportQueue<Block, FullClient>, - sc_transaction_pool::FullPool<Block, FullClient>, - ( - sc_consensus_aura::AuraBlockImport< - Block, - FullClient, - sc_finality_grandpa::GrandpaBlockImport<FullBackend, Block, FullClient, FullSelectChain>, - AuraPair - >, - sc_finality_grandpa::LinkHalf<Block, FullClient, FullSelectChain>, - Option<Telemetry>, - ) ->, ServiceError> { - if config.keystore_remote.is_some() { - return Err(ServiceError::Other( - format!("Remote Keystores are not supported."))) - } - let inherent_data_providers = InherentDataProviders::new(); - - let telemetry = config.telemetry_endpoints.clone() - .filter(|x| !x.is_empty()) - .map(|endpoints| -> Result<_, sc_telemetry::Error> { - let worker = TelemetryWorker::new(16)?; - let telemetry = worker.handle().new_telemetry(endpoints); - Ok((worker, telemetry)) - }) - .transpose()?; - - let (client, backend, keystore_container, task_manager) = - sc_service::new_full_parts::<Block, RuntimeApi, Executor>( - &config, - telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()), - )?; - let client = Arc::new(client); - - let telemetry = telemetry - .map(|(worker, telemetry)| { - task_manager.spawn_handle().spawn("telemetry", worker.run()); - telemetry - }); - - let select_chain = sc_consensus::LongestChain::new(backend.clone()); - - let transaction_pool = sc_transaction_pool::BasicPool::new_full( - config.transaction_pool.clone(), - config.role.is_authority().into(), - config.prometheus_registry(), - task_manager.spawn_handle(), - client.clone(), - ); - - let (grandpa_block_import, grandpa_link) = sc_finality_grandpa::block_import( - client.clone(), - &(client.clone() as Arc<_>), - select_chain.clone(), - telemetry.as_ref().map(|x| x.handle()), - )?; - - let aura_block_import = sc_consensus_aura::AuraBlockImport::<_, _, _, AuraPair>::new( - grandpa_block_import.clone(), client.clone(), - ); - - let import_queue = sc_consensus_aura::import_queue::<AuraPair, _, _, _, _, _>( - ImportQueueParams { - block_import: aura_block_import.clone(), - justification_import: Some(Box::new(grandpa_block_import.clone())), - client: client.clone(), - inherent_data_providers: inherent_data_providers.clone(), - spawner: &task_manager.spawn_essential_handle(), - can_author_with: sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()), - slot_duration: sc_consensus_aura::slot_duration(&*client)?, - registry: config.prometheus_registry(), - check_for_equivocation: Default::default(), - telemetry: telemetry.as_ref().map(|x| x.handle()), - }, - )?; - - Ok(sc_service::PartialComponents { - client, - backend, - task_manager, - import_queue, - keystore_container, - select_chain, - transaction_pool, - inherent_data_providers, - other: (aura_block_import, grandpa_link, telemetry), - }) +pub fn new_partial( + config: &Configuration, +) -> Result< + sc_service::PartialComponents< + FullClient, + FullBackend, + FullSelectChain, + sp_consensus::DefaultImportQueue<Block, FullClient>, + sc_transaction_pool::FullPool<Block, FullClient>, + ( + sc_consensus_aura::AuraBlockImport< + Block, + FullClient, + sc_finality_grandpa::GrandpaBlockImport< + FullBackend, + Block, + FullClient, + FullSelectChain, + >, + AuraPair, + >, + sc_finality_grandpa::LinkHalf<Block, FullClient, FullSelectChain>, + Option<Telemetry>, + ), + >, + ServiceError, +> { + if config.keystore_remote.is_some() { + return Err(ServiceError::Other(format!( + "Remote Keystores are not supported." + ))); + } + let inherent_data_providers = InherentDataProviders::new(); + + let telemetry = config + .telemetry_endpoints + .clone() + .filter(|x| !x.is_empty()) + .map(|endpoints| -> Result<_, sc_telemetry::Error> { + let worker = TelemetryWorker::new(16)?; + let telemetry = worker.handle().new_telemetry(endpoints); + Ok((worker, telemetry)) + }) + .transpose()?; + + let (client, backend, keystore_container, task_manager) = + sc_service::new_full_parts::<Block, RuntimeApi, Executor>( + &config, + telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()), + )?; + let client = Arc::new(client); + + let telemetry = telemetry.map(|(worker, telemetry)| { + task_manager.spawn_handle().spawn("telemetry", worker.run()); + telemetry + }); + + let select_chain = sc_consensus::LongestChain::new(backend.clone()); + + let transaction_pool = sc_transaction_pool::BasicPool::new_full( + config.transaction_pool.clone(), + config.role.is_authority().into(), + config.prometheus_registry(), + task_manager.spawn_handle(), + client.clone(), + ); + + let (grandpa_block_import, grandpa_link) = sc_finality_grandpa::block_import( + client.clone(), + &(client.clone() as Arc<_>), + select_chain.clone(), + telemetry.as_ref().map(|x| x.handle()), + )?; + + let aura_block_import = sc_consensus_aura::AuraBlockImport::<_, _, _, AuraPair>::new( + grandpa_block_import.clone(), + client.clone(), + ); + + let import_queue = + sc_consensus_aura::import_queue::<AuraPair, _, _, _, _, _>(ImportQueueParams { + block_import: aura_block_import.clone(), + justification_import: Some(Box::new(grandpa_block_import.clone())), + client: client.clone(), + inherent_data_providers: inherent_data_providers.clone(), + spawner: &task_manager.spawn_essential_handle(), + can_author_with: sp_consensus::CanAuthorWithNativeVersion::new( + client.executor().clone(), + ), + slot_duration: sc_consensus_aura::slot_duration(&*client)?, + registry: config.prometheus_registry(), + check_for_equivocation: Default::default(), + telemetry: telemetry.as_ref().map(|x| x.handle()), + })?; + + Ok(sc_service::PartialComponents { + client, + backend, + task_manager, + import_queue, + keystore_container, + select_chain, + transaction_pool, + inherent_data_providers, + other: (aura_block_import, grandpa_link, telemetry), + }) } fn remote_keystore(_url: &String) -> Result<Arc<LocalKeystore>, &'static str> { - // FIXME: here would the concrete keystore be built, - // must return a concrete type (NOT `LocalKeystore`) that - // implements `CryptoStore` and `SyncCryptoStore` - Err("Remote Keystore not supported.") + // FIXME: here would the concrete keystore be built, + // must return a concrete type (NOT `LocalKeystore`) that + // implements `CryptoStore` and `SyncCryptoStore` + Err("Remote Keystore not supported.") } /// Builds a new service for a full client. pub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError> { - let sc_service::PartialComponents { - client, - backend, - mut task_manager, - import_queue, - mut keystore_container, - select_chain, - transaction_pool, - inherent_data_providers, - other: (block_import, grandpa_link, mut telemetry), - } = new_partial(&config)?; - - if let Some(url) = &config.keystore_remote { - match remote_keystore(url) { - Ok(k) => keystore_container.set_remote_keystore(k), - Err(e) => { - return Err(ServiceError::Other( - format!("Error hooking up remote keystore for {}: {}", url, e))) - } - }; - } - - config.network.extra_sets.push(sc_finality_grandpa::grandpa_peers_set_config()); - - let (network, network_status_sinks, system_rpc_tx, network_starter) = - sc_service::build_network(sc_service::BuildNetworkParams { - config: &config, - client: client.clone(), - transaction_pool: transaction_pool.clone(), - spawn_handle: task_manager.spawn_handle(), - import_queue, - on_demand: None, - block_announce_validator_builder: None, - })?; - - if config.offchain_worker.enabled { - sc_service::build_offchain_workers( - &config, task_manager.spawn_handle(), client.clone(), network.clone(), - ); - } - - let role = config.role.clone(); - let force_authoring = config.force_authoring; - let backoff_authoring_blocks: Option<()> = None; - let name = config.network.node_name.clone(); - let enable_grandpa = !config.disable_grandpa; - let prometheus_registry = config.prometheus_registry().cloned(); - - let rpc_extensions_builder = { - let client = client.clone(); - let pool = transaction_pool.clone(); - - Box::new(move |deny_unsafe, _| { - let deps = crate::rpc::FullDeps { - client: client.clone(), - pool: pool.clone(), - deny_unsafe, - }; - - crate::rpc::create_full(deps) - }) - }; - - let _rpc_handlers = sc_service::spawn_tasks( - sc_service::SpawnTasksParams { - network: network.clone(), - client: client.clone(), - keystore: keystore_container.sync_keystore(), - task_manager: &mut task_manager, - transaction_pool: transaction_pool.clone(), - rpc_extensions_builder, - on_demand: None, - remote_blockchain: None, - backend, - network_status_sinks, - system_rpc_tx, - config, - telemetry: telemetry.as_mut(), - }, - )?; - - if role.is_authority() { - let proposer_factory = sc_basic_authorship::ProposerFactory::new( - task_manager.spawn_handle(), - client.clone(), - transaction_pool, - prometheus_registry.as_ref(), - telemetry.as_ref().map(|x| x.handle()), - ); - - let can_author_with = - sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()); - - let aura = sc_consensus_aura::start_aura::<AuraPair, _, _, _, _, _, _, _, _,_>( - StartAuraParams { - slot_duration: sc_consensus_aura::slot_duration(&*client)?, - client: client.clone(), - select_chain, - block_import, - proposer_factory, - inherent_data_providers: inherent_data_providers.clone(), - force_authoring, - backoff_authoring_blocks, - keystore: keystore_container.sync_keystore(), - can_author_with, - sync_oracle: network.clone(), - block_proposal_slot_portion: SlotProportion::new(2f32 / 3f32), - telemetry: telemetry.as_ref().map(|x| x.handle()), - }, - )?; - - // the AURA authoring task is considered essential, i.e. if it - // fails we take down the service with it. - task_manager.spawn_essential_handle().spawn_blocking("aura", aura); - } - - // 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 grandpa_config = sc_finality_grandpa::Config { - // FIXME #1578 make this available through chainspec - gossip_duration: Duration::from_millis(333), - justification_period: 512, - name: Some(name), - observer_enabled: false, - keystore, - is_authority: role.is_authority(), - telemetry: telemetry.as_ref().map(|x| x.handle()), - }; - - if enable_grandpa { - // start the full GRANDPA voter - // NOTE: non-authorities could run the GRANDPA observer protocol, but at - // this point the full voter should provide better guarantees of block - // and vote data availability than the observer. The observer has not - // been tested extensively yet and having most nodes in a network run it - // could lead to finality stalls. - let grandpa_config = sc_finality_grandpa::GrandpaParams { - config: grandpa_config, - link: grandpa_link, - network, - voting_rule: sc_finality_grandpa::VotingRulesBuilder::default().build(), - prometheus_registry, - shared_voter_state: SharedVoterState::empty(), - telemetry: telemetry.as_ref().map(|x| x.handle()), - }; - - // 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", - sc_finality_grandpa::run_grandpa_voter(grandpa_config)? - ); - } - - network_starter.start_network(); - Ok(task_manager) + let sc_service::PartialComponents { + client, + backend, + mut task_manager, + import_queue, + mut keystore_container, + select_chain, + transaction_pool, + inherent_data_providers, + other: (block_import, grandpa_link, mut telemetry), + } = new_partial(&config)?; + + if let Some(url) = &config.keystore_remote { + match remote_keystore(url) { + Ok(k) => keystore_container.set_remote_keystore(k), + Err(e) => { + return Err(ServiceError::Other(format!( + "Error hooking up remote keystore for {}: {}", + url, e + ))) + } + }; + } + + config + .network + .extra_sets + .push(sc_finality_grandpa::grandpa_peers_set_config()); + + let (network, network_status_sinks, system_rpc_tx, network_starter) = + sc_service::build_network(sc_service::BuildNetworkParams { + config: &config, + client: client.clone(), + transaction_pool: transaction_pool.clone(), + spawn_handle: task_manager.spawn_handle(), + import_queue, + on_demand: None, + block_announce_validator_builder: None, + })?; + + if config.offchain_worker.enabled { + sc_service::build_offchain_workers( + &config, + task_manager.spawn_handle(), + client.clone(), + network.clone(), + ); + } + + let role = config.role.clone(); + let force_authoring = config.force_authoring; + let backoff_authoring_blocks: Option<()> = None; + let name = config.network.node_name.clone(); + let enable_grandpa = !config.disable_grandpa; + let prometheus_registry = config.prometheus_registry().cloned(); + + let rpc_extensions_builder = { + let client = client.clone(); + let pool = transaction_pool.clone(); + + Box::new(move |deny_unsafe, _| { + let deps = crate::rpc::FullDeps { + client: client.clone(), + pool: pool.clone(), + deny_unsafe, + }; + + crate::rpc::create_full(deps) + }) + }; + + let _rpc_handlers = sc_service::spawn_tasks(sc_service::SpawnTasksParams { + network: network.clone(), + client: client.clone(), + keystore: keystore_container.sync_keystore(), + task_manager: &mut task_manager, + transaction_pool: transaction_pool.clone(), + rpc_extensions_builder, + on_demand: None, + remote_blockchain: None, + backend, + network_status_sinks, + system_rpc_tx, + config, + telemetry: telemetry.as_mut(), + })?; + + if role.is_authority() { + let proposer_factory = sc_basic_authorship::ProposerFactory::new( + task_manager.spawn_handle(), + client.clone(), + transaction_pool, + prometheus_registry.as_ref(), + telemetry.as_ref().map(|x| x.handle()), + ); + + let can_author_with = + sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()); + + let aura = sc_consensus_aura::start_aura::<AuraPair, _, _, _, _, _, _, _, _, _>( + StartAuraParams { + slot_duration: sc_consensus_aura::slot_duration(&*client)?, + client: client.clone(), + select_chain, + block_import, + proposer_factory, + inherent_data_providers: inherent_data_providers.clone(), + force_authoring, + backoff_authoring_blocks, + keystore: keystore_container.sync_keystore(), + can_author_with, + sync_oracle: network.clone(), + block_proposal_slot_portion: SlotProportion::new(2f32 / 3f32), + telemetry: telemetry.as_ref().map(|x| x.handle()), + }, + )?; + + // the AURA authoring task is considered essential, i.e. if it + // fails we take down the service with it. + task_manager + .spawn_essential_handle() + .spawn_blocking("aura", aura); + } + + // 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 grandpa_config = sc_finality_grandpa::Config { + // FIXME #1578 make this available through chainspec + gossip_duration: Duration::from_millis(333), + justification_period: 512, + name: Some(name), + observer_enabled: false, + keystore, + is_authority: role.is_authority(), + telemetry: telemetry.as_ref().map(|x| x.handle()), + }; + + if enable_grandpa { + // start the full GRANDPA voter + // NOTE: non-authorities could run the GRANDPA observer protocol, but at + // this point the full voter should provide better guarantees of block + // and vote data availability than the observer. The observer has not + // been tested extensively yet and having most nodes in a network run it + // could lead to finality stalls. + let grandpa_config = sc_finality_grandpa::GrandpaParams { + config: grandpa_config, + link: grandpa_link, + network, + voting_rule: sc_finality_grandpa::VotingRulesBuilder::default().build(), + prometheus_registry, + shared_voter_state: SharedVoterState::empty(), + telemetry: telemetry.as_ref().map(|x| x.handle()), + }; + + // 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", + sc_finality_grandpa::run_grandpa_voter(grandpa_config)?, + ); + } + + network_starter.start_network(); + Ok(task_manager) } /// Builds a new service for a light client. pub fn new_light(mut config: Configuration) -> Result<TaskManager, ServiceError> { - let telemetry = config.telemetry_endpoints.clone() - .filter(|x| !x.is_empty()) - .map(|endpoints| -> Result<_, sc_telemetry::Error> { - let worker = TelemetryWorker::new(16)?; - let telemetry = worker.handle().new_telemetry(endpoints); - Ok((worker, telemetry)) - }) - .transpose()?; - - let (client, backend, keystore_container, mut task_manager, on_demand) = - sc_service::new_light_parts::<Block, RuntimeApi, Executor>( - &config, - telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()), - )?; - - let mut telemetry = telemetry - .map(|(worker, telemetry)| { - task_manager.spawn_handle().spawn("telemetry", worker.run()); - telemetry - }); - - config.network.extra_sets.push(sc_finality_grandpa::grandpa_peers_set_config()); - - let select_chain = sc_consensus::LongestChain::new(backend.clone()); - - let transaction_pool = Arc::new(sc_transaction_pool::BasicPool::new_light( - config.transaction_pool.clone(), - config.prometheus_registry(), - task_manager.spawn_handle(), - client.clone(), - on_demand.clone(), - )); - - let (grandpa_block_import, _) = sc_finality_grandpa::block_import( - client.clone(), - &(client.clone() as Arc<_>), - select_chain.clone(), - telemetry.as_ref().map(|x| x.handle()), - )?; - - let aura_block_import = sc_consensus_aura::AuraBlockImport::<_, _, _, AuraPair>::new( - grandpa_block_import.clone(), - client.clone(), - ); - - let import_queue = sc_consensus_aura::import_queue::<AuraPair, _, _, _, _, _>( - ImportQueueParams { - block_import: aura_block_import.clone(), - justification_import: Some(Box::new(grandpa_block_import.clone())), - client: client.clone(), - inherent_data_providers: InherentDataProviders::new(), - spawner: &task_manager.spawn_essential_handle(), - can_author_with: sp_consensus::NeverCanAuthor, - slot_duration: sc_consensus_aura::slot_duration(&*client)?, - registry: config.prometheus_registry(), - check_for_equivocation: Default::default(), - telemetry: telemetry.as_ref().map(|x| x.handle()), - }, - )?; - - let (network, network_status_sinks, system_rpc_tx, network_starter) = - sc_service::build_network(sc_service::BuildNetworkParams { - config: &config, - client: client.clone(), - transaction_pool: transaction_pool.clone(), - spawn_handle: task_manager.spawn_handle(), - import_queue, - on_demand: Some(on_demand.clone()), - block_announce_validator_builder: None, - })?; - - if config.offchain_worker.enabled { - sc_service::build_offchain_workers( - &config, task_manager.spawn_handle(), client.clone(), network.clone(), - ); - } - - sc_service::spawn_tasks(sc_service::SpawnTasksParams { - remote_blockchain: Some(backend.remote_blockchain()), - transaction_pool, - task_manager: &mut task_manager, - on_demand: Some(on_demand), - rpc_extensions_builder: Box::new(|_, _| ()), - config, - client, - keystore: keystore_container.sync_keystore(), - backend, - network, - network_status_sinks, - system_rpc_tx, - telemetry: telemetry.as_mut(), - })?; - - network_starter.start_network(); - - Ok(task_manager) + let telemetry = config + .telemetry_endpoints + .clone() + .filter(|x| !x.is_empty()) + .map(|endpoints| -> Result<_, sc_telemetry::Error> { + let worker = TelemetryWorker::new(16)?; + let telemetry = worker.handle().new_telemetry(endpoints); + Ok((worker, telemetry)) + }) + .transpose()?; + + let (client, backend, keystore_container, mut task_manager, on_demand) = + sc_service::new_light_parts::<Block, RuntimeApi, Executor>( + &config, + telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()), + )?; + + let mut telemetry = telemetry.map(|(worker, telemetry)| { + task_manager.spawn_handle().spawn("telemetry", worker.run()); + telemetry + }); + + config + .network + .extra_sets + .push(sc_finality_grandpa::grandpa_peers_set_config()); + + let select_chain = sc_consensus::LongestChain::new(backend.clone()); + + let transaction_pool = Arc::new(sc_transaction_pool::BasicPool::new_light( + config.transaction_pool.clone(), + config.prometheus_registry(), + task_manager.spawn_handle(), + client.clone(), + on_demand.clone(), + )); + + let (grandpa_block_import, _) = sc_finality_grandpa::block_import( + client.clone(), + &(client.clone() as Arc<_>), + select_chain.clone(), + telemetry.as_ref().map(|x| x.handle()), + )?; + + let aura_block_import = sc_consensus_aura::AuraBlockImport::<_, _, _, AuraPair>::new( + grandpa_block_import.clone(), + client.clone(), + ); + + let import_queue = + sc_consensus_aura::import_queue::<AuraPair, _, _, _, _, _>(ImportQueueParams { + block_import: aura_block_import.clone(), + justification_import: Some(Box::new(grandpa_block_import.clone())), + client: client.clone(), + inherent_data_providers: InherentDataProviders::new(), + spawner: &task_manager.spawn_essential_handle(), + can_author_with: sp_consensus::NeverCanAuthor, + slot_duration: sc_consensus_aura::slot_duration(&*client)?, + registry: config.prometheus_registry(), + check_for_equivocation: Default::default(), + telemetry: telemetry.as_ref().map(|x| x.handle()), + })?; + + let (network, network_status_sinks, system_rpc_tx, network_starter) = + sc_service::build_network(sc_service::BuildNetworkParams { + config: &config, + client: client.clone(), + transaction_pool: transaction_pool.clone(), + spawn_handle: task_manager.spawn_handle(), + import_queue, + on_demand: Some(on_demand.clone()), + block_announce_validator_builder: None, + })?; + + if config.offchain_worker.enabled { + sc_service::build_offchain_workers( + &config, + task_manager.spawn_handle(), + client.clone(), + network.clone(), + ); + } + + sc_service::spawn_tasks(sc_service::SpawnTasksParams { + remote_blockchain: Some(backend.remote_blockchain()), + transaction_pool, + task_manager: &mut task_manager, + on_demand: Some(on_demand), + rpc_extensions_builder: Box::new(|_, _| ()), + config, + client, + keystore: keystore_container.sync_keystore(), + backend, + network, + network_status_sinks, + system_rpc_tx, + telemetry: telemetry.as_mut(), + })?; + + network_starter.start_network(); + + Ok(task_manager) } diff --git a/pallets/template/src/benchmarking.rs b/pallets/template/src/benchmarking.rs index 9af31ba86968c01f9376b2f6723348cff162b3e6..3936d6d5a3a65b00247986177c4a5cc724ea04af 100644 --- a/pallets/template/src/benchmarking.rs +++ b/pallets/template/src/benchmarking.rs @@ -18,23 +18,19 @@ use super::*; -use frame_system::RawOrigin; -use frame_benchmarking::{benchmarks, whitelisted_caller, impl_benchmark_test_suite}; #[allow(unused)] use crate::Pallet as Template; +use frame_benchmarking::{benchmarks, impl_benchmark_test_suite, whitelisted_caller}; +use frame_system::RawOrigin; benchmarks! { - do_something { - let s in 0 .. 100; - let caller: T::AccountId = whitelisted_caller(); - }: _(RawOrigin::Signed(caller), s) - verify { - assert_eq!(Something::<T>::get(), Some(s)); - } + do_something { + let s in 0 .. 100; + let caller: T::AccountId = whitelisted_caller(); + }: _(RawOrigin::Signed(caller), s) + verify { + assert_eq!(Something::<T>::get(), Some(s)); + } } -impl_benchmark_test_suite!( - Template, - crate::mock::new_test_ext(), - crate::mock::Test, -); +impl_benchmark_test_suite!(Template, crate::mock::new_test_ext(), crate::mock::Test,); diff --git a/pallets/template/src/lib.rs b/pallets/template/src/lib.rs index 84d0659dd537f1afa16b99c44e675ba3164b31f1..c6e4001c04cc3f394105fdd5245728c0bc936bef 100644 --- a/pallets/template/src/lib.rs +++ b/pallets/template/src/lib.rs @@ -19,7 +19,6 @@ /// 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: /// <https://substrate.dev/docs/en/knowledgebase/runtime/frame> - pub use pallet::*; #[cfg(test)] @@ -33,91 +32,91 @@ mod benchmarking; #[frame_support::pallet] pub mod pallet { - use frame_support::{dispatch::DispatchResult, pallet_prelude::*}; - use frame_system::pallet_prelude::*; - - /// Configure the pallet by specifying the parameters and types on which it depends. - #[pallet::config] - pub trait Config: frame_system::Config { - /// Because this pallet emits events, it depends on the runtime's definition of an event. - type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>; - } - - #[pallet::pallet] - #[pallet::generate_store(pub(super) trait Store)] - pub struct Pallet<T>(_); - - // The pallet's runtime storage items. - // https://substrate.dev/docs/en/knowledgebase/runtime/storage - #[pallet::storage] - #[pallet::getter(fn something)] - // Learn more about declaring storage items: - // https://substrate.dev/docs/en/knowledgebase/runtime/storage#declaring-storage-items - pub type Something<T> = StorageValue<_, u32>; - - // Pallets use events to inform users when important changes are made. - // https://substrate.dev/docs/en/knowledgebase/runtime/events - #[pallet::event] - #[pallet::metadata(T::AccountId = "AccountId")] - #[pallet::generate_deposit(pub(super) fn deposit_event)] - pub enum Event<T: Config> { - /// Event documentation should end with an array that provides descriptive names for event - /// parameters. [something, who] - SomethingStored(u32, T::AccountId), - } - - // Errors inform users that something went wrong. - #[pallet::error] - pub enum Error<T> { - /// Error names should be descriptive. - NoneValue, - /// Errors should have helpful documentation associated with them. - StorageOverflow, - } - - #[pallet::hooks] - impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {} - - // Dispatchable functions allows users to interact with the pallet and invoke state changes. - // These functions materialize as "extrinsics", which are often compared to transactions. - // Dispatchable functions must be annotated with a weight and must return a DispatchResult. - #[pallet::call] - impl<T:Config> Pallet<T> { - /// 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. - #[pallet::weight(10_000 + T::DbWeight::get().writes(1))] - pub fn do_something(origin: OriginFor<T>, something: u32) -> DispatchResult { - // Check that the extrinsic was signed and get the signer. - // This function will return an error if the extrinsic is not signed. - // https://substrate.dev/docs/en/knowledgebase/runtime/origin - let who = ensure_signed(origin)?; - - // Update storage. - <Something<T>>::put(something); - - // Emit an event. - Self::deposit_event(Event::SomethingStored(something, who)); - // Return a successful DispatchResultWithPostInfo - Ok(()) - } - - /// An example dispatchable that may throw a custom error. - #[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))] - pub fn cause_error(origin: OriginFor<T>) -> DispatchResult { - let _who = ensure_signed(origin)?; - - // Read a value from storage. - match <Something<T>>::get() { - // Return an error if the value has not been set. - None => Err(Error::<T>::NoneValue)?, - Some(old) => { - // Increment the value read from storage; will error in the event of overflow. - let new = old.checked_add(1).ok_or(Error::<T>::StorageOverflow)?; - // Update the value in storage with the incremented result. - <Something<T>>::put(new); - Ok(()) - }, - } - } - } + use frame_support::{dispatch::DispatchResult, pallet_prelude::*}; + use frame_system::pallet_prelude::*; + + /// Configure the pallet by specifying the parameters and types on which it depends. + #[pallet::config] + pub trait Config: frame_system::Config { + /// Because this pallet emits events, it depends on the runtime's definition of an event. + type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>; + } + + #[pallet::pallet] + #[pallet::generate_store(pub(super) trait Store)] + pub struct Pallet<T>(_); + + // The pallet's runtime storage items. + // https://substrate.dev/docs/en/knowledgebase/runtime/storage + #[pallet::storage] + #[pallet::getter(fn something)] + // Learn more about declaring storage items: + // https://substrate.dev/docs/en/knowledgebase/runtime/storage#declaring-storage-items + pub type Something<T> = StorageValue<_, u32>; + + // Pallets use events to inform users when important changes are made. + // https://substrate.dev/docs/en/knowledgebase/runtime/events + #[pallet::event] + #[pallet::metadata(T::AccountId = "AccountId")] + #[pallet::generate_deposit(pub(super) fn deposit_event)] + pub enum Event<T: Config> { + /// Event documentation should end with an array that provides descriptive names for event + /// parameters. [something, who] + SomethingStored(u32, T::AccountId), + } + + // Errors inform users that something went wrong. + #[pallet::error] + pub enum Error<T> { + /// Error names should be descriptive. + NoneValue, + /// Errors should have helpful documentation associated with them. + StorageOverflow, + } + + #[pallet::hooks] + impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {} + + // Dispatchable functions allows users to interact with the pallet and invoke state changes. + // These functions materialize as "extrinsics", which are often compared to transactions. + // Dispatchable functions must be annotated with a weight and must return a DispatchResult. + #[pallet::call] + impl<T: Config> Pallet<T> { + /// 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. + #[pallet::weight(10_000 + T::DbWeight::get().writes(1))] + pub fn do_something(origin: OriginFor<T>, something: u32) -> DispatchResult { + // Check that the extrinsic was signed and get the signer. + // This function will return an error if the extrinsic is not signed. + // https://substrate.dev/docs/en/knowledgebase/runtime/origin + let who = ensure_signed(origin)?; + + // Update storage. + <Something<T>>::put(something); + + // Emit an event. + Self::deposit_event(Event::SomethingStored(something, who)); + // Return a successful DispatchResultWithPostInfo + Ok(()) + } + + /// An example dispatchable that may throw a custom error. + #[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))] + pub fn cause_error(origin: OriginFor<T>) -> DispatchResult { + let _who = ensure_signed(origin)?; + + // Read a value from storage. + match <Something<T>>::get() { + // Return an error if the value has not been set. + None => Err(Error::<T>::NoneValue)?, + Some(old) => { + // Increment the value read from storage; will error in the event of overflow. + let new = old.checked_add(1).ok_or(Error::<T>::StorageOverflow)?; + // Update the value in storage with the incremented result. + <Something<T>>::put(new); + Ok(()) + } + } + } + } } diff --git a/pallets/template/src/mock.rs b/pallets/template/src/mock.rs index 1b069f6ce2c9cf30f8ce80777c16716015acf3a7..e0f21ee12e3340dd0a8f21d8ba53e5331a3683e2 100644 --- a/pallets/template/src/mock.rs +++ b/pallets/template/src/mock.rs @@ -15,64 +15,68 @@ // along with Substrate-Libre-Currency. If not, see <https://www.gnu.org/licenses/>. use crate as pallet_template; -use sp_core::H256; use frame_support::parameter_types; +use frame_system as system; +use sp_core::H256; use sp_runtime::{ - traits::{BlakeTwo256, IdentityLookup}, testing::Header, + testing::Header, + traits::{BlakeTwo256, IdentityLookup}, }; -use frame_system as system; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>; type Block = frame_system::mocking::MockBlock<Test>; // Configure a mock runtime to test the pallet. frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { - System: frame_system::{Pallet, Call, Config, Storage, Event<T>}, - TemplateModule: pallet_template::{Pallet, Call, Storage, Event<T>}, - } + pub enum Test where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { + System: frame_system::{Pallet, Call, Config, Storage, Event<T>}, + TemplateModule: pallet_template::{Pallet, Call, Storage, Event<T>}, + } ); parameter_types! { - pub const BlockHashCount: u64 = 250; - pub const SS58Prefix: u8 = 42; + pub const BlockHashCount: u64 = 250; + pub const SS58Prefix: u8 = 42; } impl system::Config for Test { - type BaseCallFilter = (); - type BlockWeights = (); - type BlockLength = (); - type DbWeight = (); - type Origin = Origin; - type Call = Call; - type Index = u64; - type BlockNumber = u64; - type Hash = H256; - type Hashing = BlakeTwo256; - type AccountId = u64; - type Lookup = IdentityLookup<Self::AccountId>; - type Header = Header; - type Event = Event; - type BlockHashCount = BlockHashCount; - type Version = (); - type PalletInfo = PalletInfo; - type AccountData = (); - type OnNewAccount = (); - type OnKilledAccount = (); - type SystemWeightInfo = (); - type SS58Prefix = SS58Prefix; - type OnSetCode = (); + type BaseCallFilter = (); + type BlockWeights = (); + type BlockLength = (); + type DbWeight = (); + type Origin = Origin; + type Call = Call; + type Index = u64; + type BlockNumber = u64; + type Hash = H256; + type Hashing = BlakeTwo256; + type AccountId = u64; + type Lookup = IdentityLookup<Self::AccountId>; + type Header = Header; + type Event = Event; + type BlockHashCount = BlockHashCount; + type Version = (); + type PalletInfo = PalletInfo; + type AccountData = (); + type OnNewAccount = (); + type OnKilledAccount = (); + type SystemWeightInfo = (); + type SS58Prefix = SS58Prefix; + type OnSetCode = (); } impl pallet_template::Config for Test { - type Event = Event; + type Event = Event; } // Build genesis storage according to the mock runtime. pub fn new_test_ext() -> sp_io::TestExternalities { - system::GenesisConfig::default().build_storage::<Test>().unwrap().into() + system::GenesisConfig::default() + .build_storage::<Test>() + .unwrap() + .into() } diff --git a/pallets/template/src/tests.rs b/pallets/template/src/tests.rs index c4c8292d68c6585865f42d8323a4197bf8754f2a..de01cafec1b4f9797db7b6692237d04c8995538d 100644 --- a/pallets/template/src/tests.rs +++ b/pallets/template/src/tests.rs @@ -14,26 +14,26 @@ // You should have received a copy of the GNU Affero General Public License // along with Substrate-Libre-Currency. If not, see <https://www.gnu.org/licenses/>. -use crate::{Error, mock::*}; -use frame_support::{assert_ok, assert_noop}; +use crate::{mock::*, Error}; +use frame_support::{assert_noop, assert_ok}; #[test] fn it_works_for_default_value() { - new_test_ext().execute_with(|| { - // Dispatch a signed extrinsic. - assert_ok!(TemplateModule::do_something(Origin::signed(1), 42)); - // Read pallet storage and assert an expected result. - assert_eq!(TemplateModule::something(), Some(42)); - }); + new_test_ext().execute_with(|| { + // Dispatch a signed extrinsic. + assert_ok!(TemplateModule::do_something(Origin::signed(1), 42)); + // Read pallet storage and assert an expected result. + assert_eq!(TemplateModule::something(), Some(42)); + }); } #[test] fn correct_error_for_none_value() { - new_test_ext().execute_with(|| { - // Ensure the expected error is thrown when no value is present. - assert_noop!( - TemplateModule::cause_error(Origin::signed(1)), - Error::<Test>::NoneValue - ); - }); + new_test_ext().execute_with(|| { + // Ensure the expected error is thrown when no value is present. + assert_noop!( + TemplateModule::cause_error(Origin::signed(1)), + Error::<Test>::NoneValue + ); + }); } diff --git a/runtime/build.rs b/runtime/build.rs index 2de3e7b623a9a66bad27e13f67ad19a7f68b6814..e1a9234c5811d46427b41f3e7c1e6b85fcf4c904 100644 --- a/runtime/build.rs +++ b/runtime/build.rs @@ -17,9 +17,9 @@ use substrate_wasm_builder::WasmBuilder; fn main() { - WasmBuilder::new() - .with_current_project() - .export_heap_base() - .import_memory() - .build() + WasmBuilder::new() + .with_current_project() + .export_heap_base() + .import_memory() + .build() } diff --git a/runtime/src/lib.rs b/runtime/src/lib.rs index ba4fee0dd2f5920537bc2e65a0f8bcb1a0c917b1..285ff487e9cb4e1fa1f1295f14e74f4bb1931a17 100644 --- a/runtime/src/lib.rs +++ b/runtime/src/lib.rs @@ -16,44 +16,46 @@ #![cfg_attr(not(feature = "std"), no_std)] // `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. #[cfg(feature = "std")] include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); -use sp_std::prelude::*; +use pallet_grandpa::fg_primitives; +use pallet_grandpa::{AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList}; +use sp_api::impl_runtime_apis; +use sp_consensus_aura::sr25519::AuthorityId as AuraId; use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; -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, + AccountIdLookup, BlakeTwo256, Block as BlockT, IdentifyAccount, NumberFor, Verify, }; -use sp_api::impl_runtime_apis; -use sp_consensus_aura::sr25519::AuthorityId as AuraId; -use pallet_grandpa::{AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList}; -use pallet_grandpa::fg_primitives; -use sp_version::RuntimeVersion; +use sp_runtime::{ + create_runtime_str, generic, impl_opaque_keys, + transaction_validity::{TransactionSource, TransactionValidity}, + ApplyExtrinsicResult, MultiSignature, +}; +use sp_std::prelude::*; #[cfg(feature = "std")] use sp_version::NativeVersion; +use sp_version::RuntimeVersion; // 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::{ - construct_runtime, parameter_types, StorageValue, - traits::{KeyOwnerProofSystem, Randomness}, - weights::{ - Weight, IdentityFee, - constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND}, - }, + construct_runtime, parameter_types, + traits::{KeyOwnerProofSystem, Randomness}, + weights::{ + 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; +#[cfg(any(feature = "std", test))] +pub use sp_runtime::BuildStorage; +pub use sp_runtime::{Perbill, Permill}; /// Import the template pallet. pub use pallet_template; @@ -89,40 +91,40 @@ pub type DigestItem = generic::DigestItem<Hash>; /// of data like extrinsics, allowing for them to continue syncing the network through upgrades /// to even the core data structures. pub mod opaque { - use super::*; - - pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic; - - /// Opaque block header type. - pub type Header = generic::Header<BlockNumber, BlakeTwo256>; - /// Opaque block type. - pub type Block = generic::Block<Header, UncheckedExtrinsic>; - /// Opaque block identifier type. - pub type BlockId = generic::BlockId<Block>; - - impl_opaque_keys! { - pub struct SessionKeys { - pub aura: Aura, - pub grandpa: Grandpa, - } - } + use super::*; + + pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic; + + /// Opaque block header type. + pub type Header = generic::Header<BlockNumber, BlakeTwo256>; + /// Opaque block type. + pub type Block = generic::Block<Header, UncheckedExtrinsic>; + /// Opaque block identifier type. + pub type BlockId = generic::BlockId<Block>; + + impl_opaque_keys! { + pub struct SessionKeys { + pub aura: Aura, + pub grandpa: Grandpa, + } + } } // To learn more about runtime versioning and what each of the following value means: // https://substrate.dev/docs/en/knowledgebase/runtime/upgrades#runtime-versioning pub const VERSION: RuntimeVersion = RuntimeVersion { - spec_name: create_runtime_str!("node-template"), - impl_name: create_runtime_str!("node-template"), - authoring_version: 1, - // The version of the runtime specification. A full node will not attempt to use its native - // runtime in substitute for the on-chain Wasm runtime unless all of `spec_name`, - // `spec_version`, and `authoring_version` are the same between Wasm and native. - // This value is set to 100 to notify Polkadot-JS App (https://polkadot.js.org/apps) to use - // the compatible custom types. - spec_version: 100, - impl_version: 1, - apis: RUNTIME_API_VERSIONS, - transaction_version: 1, + spec_name: create_runtime_str!("node-template"), + impl_name: create_runtime_str!("node-template"), + authoring_version: 1, + // The version of the runtime specification. A full node will not attempt to use its native + // runtime in substitute for the on-chain Wasm runtime unless all of `spec_name`, + // `spec_version`, and `authoring_version` are the same between Wasm and native. + // This value is set to 100 to notify Polkadot-JS App (https://polkadot.js.org/apps) to use + // the compatible custom types. + spec_version: 100, + impl_version: 1, + apis: RUNTIME_API_VERSIONS, + transaction_version: 1, }; /// This determines the average expected block time that we are targeting. @@ -145,169 +147,169 @@ pub const DAYS: BlockNumber = HOURS * 24; /// The version information used to identify this runtime when compiled natively. #[cfg(feature = "std")] pub fn native_version() -> NativeVersion { - NativeVersion { - runtime_version: VERSION, - can_author_with: Default::default(), - } + NativeVersion { + runtime_version: VERSION, + can_author_with: Default::default(), + } } const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75); parameter_types! { - pub const Version: RuntimeVersion = VERSION; - pub const BlockHashCount: BlockNumber = 2400; - /// We allow for 2 seconds of compute with a 6 second average block time. - pub BlockWeights: frame_system::limits::BlockWeights = frame_system::limits::BlockWeights - ::with_sensible_defaults(2 * WEIGHT_PER_SECOND, NORMAL_DISPATCH_RATIO); - pub BlockLength: frame_system::limits::BlockLength = frame_system::limits::BlockLength - ::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO); - pub const SS58Prefix: u8 = 42; + pub const Version: RuntimeVersion = VERSION; + pub const BlockHashCount: BlockNumber = 2400; + /// We allow for 2 seconds of compute with a 6 second average block time. + pub BlockWeights: frame_system::limits::BlockWeights = frame_system::limits::BlockWeights + ::with_sensible_defaults(2 * WEIGHT_PER_SECOND, NORMAL_DISPATCH_RATIO); + pub BlockLength: frame_system::limits::BlockLength = frame_system::limits::BlockLength + ::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO); + pub const SS58Prefix: u8 = 42; } // Configure FRAME pallets to include in runtime. impl frame_system::Config for Runtime { - /// The basic call filter to use in dispatchable. - type BaseCallFilter = (); - /// Block & extrinsics weights: base values and limits. - type BlockWeights = BlockWeights; - /// The maximum length of a block (in bytes). - type BlockLength = BlockLength; - /// The identifier used to distinguish between accounts. - type AccountId = AccountId; - /// The aggregated dispatch type that is available for extrinsics. - type Call = Call; - /// The lookup mechanism to get account ID from whatever is passed in dispatchers. - type Lookup = AccountIdLookup<AccountId, ()>; - /// The index type for storing how many extrinsics an account has signed. - type Index = Index; - /// The index type for blocks. - type BlockNumber = BlockNumber; - /// The type for hashing blocks and tries. - type Hash = Hash; - /// The hashing algorithm used. - type Hashing = BlakeTwo256; - /// The header type. - type Header = generic::Header<BlockNumber, BlakeTwo256>; - /// The ubiquitous event type. - type Event = Event; - /// The ubiquitous origin type. - type Origin = Origin; - /// Maximum number of block number to block hash mappings to keep (oldest pruned first). - type BlockHashCount = BlockHashCount; - /// The weight of database operations that the runtime can invoke. - type DbWeight = RocksDbWeight; - /// Version of the runtime. - type Version = Version; - /// Converts a module to the index of the module in `construct_runtime!`. - /// - /// This type is being generated by `construct_runtime!`. - type PalletInfo = PalletInfo; - /// What to do if a new account is created. - type OnNewAccount = (); - /// What to do if an account is fully reaped from the system. - type OnKilledAccount = (); - /// The data to be stored in an account. - type AccountData = pallet_balances::AccountData<Balance>; - /// Weight information for the extrinsics of this pallet. - type SystemWeightInfo = (); - /// This is used as an identifier of the chain. 42 is the generic substrate prefix. - type SS58Prefix = SS58Prefix; - /// The set code logic, just the default since we're not a parachain. - type OnSetCode = (); + /// The basic call filter to use in dispatchable. + type BaseCallFilter = (); + /// Block & extrinsics weights: base values and limits. + type BlockWeights = BlockWeights; + /// The maximum length of a block (in bytes). + type BlockLength = BlockLength; + /// The identifier used to distinguish between accounts. + type AccountId = AccountId; + /// The aggregated dispatch type that is available for extrinsics. + type Call = Call; + /// The lookup mechanism to get account ID from whatever is passed in dispatchers. + type Lookup = AccountIdLookup<AccountId, ()>; + /// The index type for storing how many extrinsics an account has signed. + type Index = Index; + /// The index type for blocks. + type BlockNumber = BlockNumber; + /// The type for hashing blocks and tries. + type Hash = Hash; + /// The hashing algorithm used. + type Hashing = BlakeTwo256; + /// The header type. + type Header = generic::Header<BlockNumber, BlakeTwo256>; + /// The ubiquitous event type. + type Event = Event; + /// The ubiquitous origin type. + type Origin = Origin; + /// Maximum number of block number to block hash mappings to keep (oldest pruned first). + type BlockHashCount = BlockHashCount; + /// The weight of database operations that the runtime can invoke. + type DbWeight = RocksDbWeight; + /// Version of the runtime. + type Version = Version; + /// Converts a module to the index of the module in `construct_runtime!`. + /// + /// This type is being generated by `construct_runtime!`. + type PalletInfo = PalletInfo; + /// What to do if a new account is created. + type OnNewAccount = (); + /// What to do if an account is fully reaped from the system. + type OnKilledAccount = (); + /// The data to be stored in an account. + type AccountData = pallet_balances::AccountData<Balance>; + /// Weight information for the extrinsics of this pallet. + type SystemWeightInfo = (); + /// This is used as an identifier of the chain. 42 is the generic substrate prefix. + type SS58Prefix = SS58Prefix; + /// The set code logic, just the default since we're not a parachain. + type OnSetCode = (); } impl pallet_aura::Config for Runtime { - type AuthorityId = AuraId; + type AuthorityId = AuraId; } impl pallet_grandpa::Config for Runtime { - type Event = Event; - type Call = Call; + type Event = Event; + type Call = Call; - type KeyOwnerProofSystem = (); + type KeyOwnerProofSystem = (); - type KeyOwnerProof = - <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof; + type KeyOwnerProof = + <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof; - type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<( - KeyTypeId, - GrandpaId, - )>>::IdentificationTuple; + type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<( + KeyTypeId, + GrandpaId, + )>>::IdentificationTuple; - type HandleEquivocation = (); + type HandleEquivocation = (); - type WeightInfo = (); + type WeightInfo = (); } parameter_types! { - pub const MinimumPeriod: u64 = SLOT_DURATION / 2; + pub const MinimumPeriod: u64 = SLOT_DURATION / 2; } impl pallet_timestamp::Config for Runtime { - /// A timestamp: milliseconds since the unix epoch. - type Moment = u64; - type OnTimestampSet = Aura; - type MinimumPeriod = MinimumPeriod; - type WeightInfo = (); + /// A timestamp: milliseconds since the unix epoch. + type Moment = u64; + type OnTimestampSet = Aura; + type MinimumPeriod = MinimumPeriod; + type WeightInfo = (); } parameter_types! { - pub const ExistentialDeposit: u128 = 500; - pub const MaxLocks: u32 = 50; + pub const ExistentialDeposit: u128 = 500; + pub const MaxLocks: u32 = 50; } impl pallet_balances::Config for Runtime { - type MaxLocks = MaxLocks; - /// The type for recording an account's balance. - type Balance = Balance; - /// The ubiquitous event type. - type Event = Event; - type DustRemoval = (); - type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; - type WeightInfo = pallet_balances::weights::SubstrateWeight<Runtime>; + type MaxLocks = MaxLocks; + /// The type for recording an account's balance. + type Balance = Balance; + /// The ubiquitous event type. + type Event = Event; + type DustRemoval = (); + type ExistentialDeposit = ExistentialDeposit; + type AccountStore = System; + type WeightInfo = pallet_balances::weights::SubstrateWeight<Runtime>; } parameter_types! { - pub const TransactionByteFee: Balance = 1; + pub const TransactionByteFee: Balance = 1; } impl pallet_transaction_payment::Config for Runtime { - type OnChargeTransaction = CurrencyAdapter<Balances, ()>; - type TransactionByteFee = TransactionByteFee; - type WeightToFee = IdentityFee<Balance>; - type FeeMultiplierUpdate = (); + type OnChargeTransaction = CurrencyAdapter<Balances, ()>; + type TransactionByteFee = TransactionByteFee; + type WeightToFee = IdentityFee<Balance>; + type FeeMultiplierUpdate = (); } impl pallet_sudo::Config for Runtime { - type Event = Event; - type Call = Call; + type Event = Event; + type Call = Call; } /// Configure the pallet-template in pallets/template. impl pallet_template::Config for Runtime { - type Event = Event; + type Event = Event; } // Create the runtime by composing the FRAME pallets that were previously configured. construct_runtime!( - pub enum Runtime where - Block = Block, - NodeBlock = opaque::Block, - UncheckedExtrinsic = UncheckedExtrinsic - { - System: frame_system::{Pallet, Call, Config, Storage, Event<T>}, - RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Call, Storage}, - Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, - Aura: pallet_aura::{Pallet, Config<T>}, - Grandpa: pallet_grandpa::{Pallet, Call, Storage, Config, Event}, - Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>}, - TransactionPayment: pallet_transaction_payment::{Pallet, Storage}, - Sudo: pallet_sudo::{Pallet, Call, Config<T>, Storage, Event<T>}, - // Include the custom logic from the pallet-template in the runtime. - TemplateModule: pallet_template::{Pallet, Call, Storage, Event<T>}, - } + pub enum Runtime where + Block = Block, + NodeBlock = opaque::Block, + UncheckedExtrinsic = UncheckedExtrinsic + { + System: frame_system::{Pallet, Call, Config, Storage, Event<T>}, + RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Call, Storage}, + Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, + Aura: pallet_aura::{Pallet, Config<T>}, + Grandpa: pallet_grandpa::{Pallet, Call, Storage, Config, Event}, + Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>}, + TransactionPayment: pallet_transaction_payment::{Pallet, Storage}, + Sudo: pallet_sudo::{Pallet, Call, Config<T>, Storage, Event<T>}, + // Include the custom logic from the pallet-template in the runtime. + TemplateModule: pallet_template::{Pallet, Call, Storage, Event<T>}, + } ); /// The address format for describing accounts. @@ -322,13 +324,13 @@ pub type SignedBlock = generic::SignedBlock<Block>; pub type BlockId = generic::BlockId<Block>; /// The SignedExtension to the basic transaction logic. pub type SignedExtra = ( - frame_system::CheckSpecVersion<Runtime>, - frame_system::CheckTxVersion<Runtime>, - frame_system::CheckGenesis<Runtime>, - frame_system::CheckEra<Runtime>, - frame_system::CheckNonce<Runtime>, - frame_system::CheckWeight<Runtime>, - pallet_transaction_payment::ChargeTransactionPayment<Runtime> + frame_system::CheckSpecVersion<Runtime>, + frame_system::CheckTxVersion<Runtime>, + frame_system::CheckGenesis<Runtime>, + frame_system::CheckEra<Runtime>, + frame_system::CheckNonce<Runtime>, + frame_system::CheckWeight<Runtime>, + pallet_transaction_payment::ChargeTransactionPayment<Runtime>, ); /// Unchecked extrinsic type as expected by this runtime. pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>; @@ -336,176 +338,176 @@ pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signatu pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Call, SignedExtra>; /// Executive: handles dispatch to the various modules. pub type Executive = frame_executive::Executive< - Runtime, - Block, - frame_system::ChainContext<Runtime>, - Runtime, - AllPallets, + Runtime, + Block, + frame_system::ChainContext<Runtime>, + Runtime, + AllPallets, >; impl_runtime_apis! { - impl sp_api::Core<Block> for Runtime { - fn version() -> RuntimeVersion { - VERSION - } - - fn execute_block(block: Block) { - Executive::execute_block(block); - } - - fn initialize_block(header: &<Block as BlockT>::Header) { - Executive::initialize_block(header) - } - } - - impl sp_api::Metadata<Block> for Runtime { - fn metadata() -> OpaqueMetadata { - Runtime::metadata().into() - } - } - - impl sp_block_builder::BlockBuilder<Block> for Runtime { - fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult { - Executive::apply_extrinsic(extrinsic) - } - - fn finalize_block() -> <Block as BlockT>::Header { - Executive::finalize_block() - } - - fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> { - data.create_extrinsics() - } - - fn check_inherents( - block: Block, - data: sp_inherents::InherentData, - ) -> sp_inherents::CheckInherentsResult { - data.check_extrinsics(&block) - } - - fn random_seed() -> <Block as BlockT>::Hash { - RandomnessCollectiveFlip::random_seed().0 - } - } - - impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime { - fn validate_transaction( - source: TransactionSource, - tx: <Block as BlockT>::Extrinsic, - ) -> TransactionValidity { - Executive::validate_transaction(source, tx) - } - } - - impl sp_offchain::OffchainWorkerApi<Block> for Runtime { - fn offchain_worker(header: &<Block as BlockT>::Header) { - Executive::offchain_worker(header) - } - } - - impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime { - fn slot_duration() -> sp_consensus_aura::SlotDuration { - sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration()) - } - - fn authorities() -> Vec<AuraId> { - Aura::authorities() - } - } - - impl sp_session::SessionKeys<Block> for Runtime { - fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> { - opaque::SessionKeys::generate(seed) - } - - fn decode_session_keys( - encoded: Vec<u8>, - ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> { - opaque::SessionKeys::decode_into_raw_public_keys(&encoded) - } - } - - impl fg_primitives::GrandpaApi<Block> for Runtime { - fn grandpa_authorities() -> GrandpaAuthorityList { - Grandpa::grandpa_authorities() - } - - fn submit_report_equivocation_unsigned_extrinsic( - _equivocation_proof: fg_primitives::EquivocationProof< - <Block as BlockT>::Hash, - NumberFor<Block>, - >, - _key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof, - ) -> Option<()> { - None - } - - fn generate_key_ownership_proof( - _set_id: fg_primitives::SetId, - _authority_id: GrandpaId, - ) -> Option<fg_primitives::OpaqueKeyOwnershipProof> { - // NOTE: this is the only implementation possible since we've - // defined our key owner proof type as a bottom type (i.e. a type - // with no values). - None - } - } - - impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime { - fn account_nonce(account: AccountId) -> Index { - System::account_nonce(account) - } - } - - impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime { - fn query_info( - uxt: <Block as BlockT>::Extrinsic, - len: u32, - ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> { - TransactionPayment::query_info(uxt, len) - } - fn query_fee_details( - uxt: <Block as BlockT>::Extrinsic, - len: u32, - ) -> pallet_transaction_payment::FeeDetails<Balance> { - TransactionPayment::query_fee_details(uxt, len) - } - } - - #[cfg(feature = "runtime-benchmarks")] - impl frame_benchmarking::Benchmark<Block> for Runtime { - fn dispatch_benchmark( - config: frame_benchmarking::BenchmarkConfig - ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> { - use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey}; - - use frame_system_benchmarking::Pallet as SystemBench; - impl frame_system_benchmarking::Config for Runtime {} - - let whitelist: Vec<TrackedStorageKey> = vec![ - // Block Number - hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(), - // Total Issuance - hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(), - // Execution Phase - hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(), - // Event Count - hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(), - // System Events - hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(), - ]; - - let mut batches = Vec::<BenchmarkBatch>::new(); - let params = (&config, &whitelist); - - add_benchmark!(params, batches, frame_system, SystemBench::<Runtime>); - add_benchmark!(params, batches, pallet_balances, Balances); - add_benchmark!(params, batches, pallet_timestamp, Timestamp); - add_benchmark!(params, batches, pallet_template, TemplateModule); - - if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) } - Ok(batches) - } - } + impl sp_api::Core<Block> for Runtime { + fn version() -> RuntimeVersion { + VERSION + } + + fn execute_block(block: Block) { + Executive::execute_block(block); + } + + fn initialize_block(header: &<Block as BlockT>::Header) { + Executive::initialize_block(header) + } + } + + impl sp_api::Metadata<Block> for Runtime { + fn metadata() -> OpaqueMetadata { + Runtime::metadata().into() + } + } + + impl sp_block_builder::BlockBuilder<Block> for Runtime { + fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult { + Executive::apply_extrinsic(extrinsic) + } + + fn finalize_block() -> <Block as BlockT>::Header { + Executive::finalize_block() + } + + fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> { + data.create_extrinsics() + } + + fn check_inherents( + block: Block, + data: sp_inherents::InherentData, + ) -> sp_inherents::CheckInherentsResult { + data.check_extrinsics(&block) + } + + fn random_seed() -> <Block as BlockT>::Hash { + RandomnessCollectiveFlip::random_seed().0 + } + } + + impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime { + fn validate_transaction( + source: TransactionSource, + tx: <Block as BlockT>::Extrinsic, + ) -> TransactionValidity { + Executive::validate_transaction(source, tx) + } + } + + impl sp_offchain::OffchainWorkerApi<Block> for Runtime { + fn offchain_worker(header: &<Block as BlockT>::Header) { + Executive::offchain_worker(header) + } + } + + impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime { + fn slot_duration() -> sp_consensus_aura::SlotDuration { + sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration()) + } + + fn authorities() -> Vec<AuraId> { + Aura::authorities() + } + } + + impl sp_session::SessionKeys<Block> for Runtime { + fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> { + opaque::SessionKeys::generate(seed) + } + + fn decode_session_keys( + encoded: Vec<u8>, + ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> { + opaque::SessionKeys::decode_into_raw_public_keys(&encoded) + } + } + + impl fg_primitives::GrandpaApi<Block> for Runtime { + fn grandpa_authorities() -> GrandpaAuthorityList { + Grandpa::grandpa_authorities() + } + + fn submit_report_equivocation_unsigned_extrinsic( + _equivocation_proof: fg_primitives::EquivocationProof< + <Block as BlockT>::Hash, + NumberFor<Block>, + >, + _key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof, + ) -> Option<()> { + None + } + + fn generate_key_ownership_proof( + _set_id: fg_primitives::SetId, + _authority_id: GrandpaId, + ) -> Option<fg_primitives::OpaqueKeyOwnershipProof> { + // NOTE: this is the only implementation possible since we've + // defined our key owner proof type as a bottom type (i.e. a type + // with no values). + None + } + } + + impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime { + fn account_nonce(account: AccountId) -> Index { + System::account_nonce(account) + } + } + + impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime { + fn query_info( + uxt: <Block as BlockT>::Extrinsic, + len: u32, + ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> { + TransactionPayment::query_info(uxt, len) + } + fn query_fee_details( + uxt: <Block as BlockT>::Extrinsic, + len: u32, + ) -> pallet_transaction_payment::FeeDetails<Balance> { + TransactionPayment::query_fee_details(uxt, len) + } + } + + #[cfg(feature = "runtime-benchmarks")] + impl frame_benchmarking::Benchmark<Block> for Runtime { + fn dispatch_benchmark( + config: frame_benchmarking::BenchmarkConfig + ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> { + use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey}; + + use frame_system_benchmarking::Pallet as SystemBench; + impl frame_system_benchmarking::Config for Runtime {} + + let whitelist: Vec<TrackedStorageKey> = vec![ + // Block Number + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(), + // Total Issuance + hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(), + // Execution Phase + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(), + // Event Count + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(), + // System Events + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(), + ]; + + let mut batches = Vec::<BenchmarkBatch>::new(); + let params = (&config, &whitelist); + + add_benchmark!(params, batches, frame_system, SystemBench::<Runtime>); + add_benchmark!(params, batches, pallet_balances, Balances); + add_benchmark!(params, batches, pallet_timestamp, Timestamp); + add_benchmark!(params, batches, pallet_template, TemplateModule); + + if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) } + Ok(batches) + } + } }