diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..b381f3f --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,44 @@ +name: CI + +on: + push: + branches: [ main ] + pull_request: + branches: [ main ] + +permissions: + contents: read + +concurrency: + group: ci-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Install system deps + run: sudo apt-get update && sudo apt-get install -y protobuf-compiler + - uses: dtolnay/rust-toolchain@v1 + with: + toolchain: 1.75.0 + components: rustfmt, clippy + targets: wasm32-unknown-unknown + - uses: Swatinem/rust-cache@v2 + - run: cargo fmt --all -- --check + - run: cargo clippy --all-targets -- -D warnings + + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Install system deps + run: sudo apt-get update && sudo apt-get install -y protobuf-compiler + - uses: dtolnay/rust-toolchain@v1 + with: + toolchain: 1.75.0 + targets: wasm32-unknown-unknown + - uses: Swatinem/rust-cache@v2 + - run: cargo build --all --all-targets --locked + - run: cargo test --all --all-targets --workspace --locked diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2f7896d --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +target/ diff --git a/bin/node/build.rs b/bin/node/build.rs index 0b10785..f9d839f 100644 --- a/bin/node/build.rs +++ b/bin/node/build.rs @@ -1,7 +1,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(); -} \ No newline at end of file + rerun_if_git_head_changed(); +} diff --git a/bin/node/src/benchmarking.rs b/bin/node/src/benchmarking.rs index be153cd..0af5ebf 100644 --- a/bin/node/src/benchmarking.rs +++ b/bin/node/src/benchmarking.rs @@ -19,143 +19,154 @@ use std::{sync::Arc, time::Duration}; /// /// Note: Should only be used for benchmarking. pub struct RemarkBuilder { - client: Arc, + client: Arc, } impl RemarkBuilder { - /// Creates a new [`Self`] from the given client. - pub fn new(client: Arc) -> Self { - Self { client } - } + /// Creates a new [`Self`] from the given client. + pub fn new(client: Arc) -> Self { + Self { client } + } } impl frame_benchmarking_cli::ExtrinsicBuilder for RemarkBuilder { - fn pallet(&self) -> &str { - "system" - } - - fn extrinsic(&self) -> &str { - "remark" - } - - fn build(&self, nonce: u32) -> std::result::Result { - let acc = Sr25519Keyring::Bob.pair(); - let extrinsic: OpaqueExtrinsic = create_benchmark_extrinsic( - self.client.as_ref(), - acc, - SystemCall::remark { remark: vec![] }.into(), - nonce, - ) - .into(); - - Ok(extrinsic) - } + fn pallet(&self) -> &str { + "system" + } + + fn extrinsic(&self) -> &str { + "remark" + } + + fn build(&self, nonce: u32) -> std::result::Result { + let acc = Sr25519Keyring::Bob.pair(); + let extrinsic: OpaqueExtrinsic = create_benchmark_extrinsic( + self.client.as_ref(), + acc, + SystemCall::remark { remark: vec![] }.into(), + nonce, + ) + .into(); + + Ok(extrinsic) + } } /// Generates `Balances::TransferKeepAlive` extrinsics for the benchmarks. /// /// Note: Should only be used for benchmarking. pub struct TransferKeepAliveBuilder { - client: Arc, - dest: AccountId, - value: Balance, + client: Arc, + dest: AccountId, + value: Balance, } impl TransferKeepAliveBuilder { - /// Creates a new [`Self`] from the given client. - pub fn new(client: Arc, dest: AccountId, value: Balance) -> Self { - Self { client, dest, value } - } + /// Creates a new [`Self`] from the given client. + pub fn new(client: Arc, dest: AccountId, value: Balance) -> Self { + Self { + client, + dest, + value, + } + } } impl frame_benchmarking_cli::ExtrinsicBuilder for TransferKeepAliveBuilder { - fn pallet(&self) -> &str { - "balances" - } - - fn extrinsic(&self) -> &str { - "transfer_keep_alive" - } - - fn build(&self, nonce: u32) -> std::result::Result { - let acc = Sr25519Keyring::Bob.pair(); - let extrinsic: OpaqueExtrinsic = create_benchmark_extrinsic( - self.client.as_ref(), - acc, - BalancesCall::transfer_keep_alive { dest: self.dest.clone().into(), value: self.value } - .into(), - nonce, - ) - .into(); - - Ok(extrinsic) - } + fn pallet(&self) -> &str { + "balances" + } + + fn extrinsic(&self) -> &str { + "transfer_keep_alive" + } + + fn build(&self, nonce: u32) -> std::result::Result { + let acc = Sr25519Keyring::Bob.pair(); + let extrinsic: OpaqueExtrinsic = create_benchmark_extrinsic( + self.client.as_ref(), + acc, + BalancesCall::transfer_keep_alive { + dest: self.dest.clone().into(), + value: self.value, + } + .into(), + nonce, + ) + .into(); + + Ok(extrinsic) + } } /// Create a transaction using the given `call`. /// /// Note: Should only be used for benchmarking. pub fn create_benchmark_extrinsic( - client: &FullClient, - sender: sp_core::sr25519::Pair, - call: runtime::RuntimeCall, - nonce: u32, + client: &FullClient, + sender: sp_core::sr25519::Pair, + call: runtime::RuntimeCall, + nonce: u32, ) -> runtime::UncheckedExtrinsic { - let genesis_hash = client.block_hash(0).ok().flatten().expect("Genesis block exists; qed"); - let best_hash = client.chain_info().best_hash; - let best_block = client.chain_info().best_number; - - let period = runtime::BlockHashCount::get() - .checked_next_power_of_two() - .map(|c| c / 2) - .unwrap_or(2) as u64; - let extra: runtime::SignedExtra = ( - frame_system::CheckNonZeroSender::::new(), - frame_system::CheckSpecVersion::::new(), - frame_system::CheckTxVersion::::new(), - frame_system::CheckGenesis::::new(), - frame_system::CheckEra::::from(sp_runtime::generic::Era::mortal( - period, - best_block.saturated_into(), - )), - frame_system::CheckNonce::::from(nonce), - frame_system::CheckWeight::::new(), - pallet_transaction_payment::ChargeTransactionPayment::::from(0), - ); - - let raw_payload = runtime::SignedPayload::from_raw( - call.clone(), - extra.clone(), - ( - (), - runtime::VERSION.spec_version, - runtime::VERSION.transaction_version, - genesis_hash, - best_hash, - (), - (), - (), - ), - ); - let signature = raw_payload.using_encoded(|e| sender.sign(e)); - - runtime::UncheckedExtrinsic::new_signed( - call, - sp_runtime::AccountId32::from(sender.public()).into(), - runtime::Signature::Sr25519(signature), - extra, - ) + let genesis_hash = client + .block_hash(0) + .ok() + .flatten() + .expect("Genesis block exists; qed"); + let best_hash = client.chain_info().best_hash; + let best_block = client.chain_info().best_number; + + let period = runtime::BlockHashCount::get() + .checked_next_power_of_two() + .map(|c| c / 2) + .unwrap_or(2) as u64; + let extra: runtime::SignedExtra = ( + frame_system::CheckNonZeroSender::::new(), + frame_system::CheckSpecVersion::::new(), + frame_system::CheckTxVersion::::new(), + frame_system::CheckGenesis::::new(), + frame_system::CheckEra::::from(sp_runtime::generic::Era::mortal( + period, + best_block.saturated_into(), + )), + frame_system::CheckNonce::::from(nonce), + frame_system::CheckWeight::::new(), + pallet_transaction_payment::ChargeTransactionPayment::::from(0), + ); + + let raw_payload = runtime::SignedPayload::from_raw( + call.clone(), + extra.clone(), + ( + (), + runtime::VERSION.spec_version, + runtime::VERSION.transaction_version, + genesis_hash, + best_hash, + (), + (), + (), + ), + ); + let signature = raw_payload.using_encoded(|e| sender.sign(e)); + + runtime::UncheckedExtrinsic::new_signed( + call, + sp_runtime::AccountId32::from(sender.public()).into(), + runtime::Signature::Sr25519(signature), + extra, + ) } /// Generates inherent data for the `benchmark overhead` command. /// /// Note: Should only be used for benchmarking. pub fn inherent_benchmark_data() -> Result { - let mut inherent_data = InherentData::new(); - let d = Duration::from_millis(0); - let timestamp = sp_timestamp::InherentDataProvider::new(d.into()); - - futures::executor::block_on(timestamp.provide_inherent_data(&mut inherent_data)) - .map_err(|e| format!("creating inherent data: {:?}", e))?; - Ok(inherent_data) -} \ No newline at end of file + let mut inherent_data = InherentData::new(); + let d = Duration::from_millis(0); + let timestamp = sp_timestamp::InherentDataProvider::new(d.into()); + + futures::executor::block_on(timestamp.provide_inherent_data(&mut inherent_data)) + .map_err(|e| format!("creating inherent data: {:?}", e))?; + Ok(inherent_data) +} diff --git a/bin/node/src/chain_spec.rs b/bin/node/src/chain_spec.rs index a3f004f..ae37af1 100644 --- a/bin/node/src/chain_spec.rs +++ b/bin/node/src/chain_spec.rs @@ -166,4 +166,3 @@ fn testnet_genesis( transaction_payment: Default::default(), } } - diff --git a/bin/node/src/cli.rs b/bin/node/src/cli.rs index 05f040c..80245fe 100644 --- a/bin/node/src/cli.rs +++ b/bin/node/src/cli.rs @@ -2,53 +2,53 @@ use sc_cli::RunCmd; #[derive(Debug, clap::Parser)] pub struct Cli { - #[command(subcommand)] - pub subcommand: Option, + #[command(subcommand)] + pub subcommand: Option, - #[clap(flatten)] - pub run: RunCmd, + #[clap(flatten)] + pub run: RunCmd, } #[derive(Debug, clap::Subcommand)] #[allow(clippy::large_enum_variant)] pub enum Subcommand { - /// Key management cli utilities - #[command(subcommand)] - Key(sc_cli::KeySubcommand), + /// Key management cli utilities + #[command(subcommand)] + Key(sc_cli::KeySubcommand), - /// Build a chain specification. - BuildSpec(sc_cli::BuildSpecCmd), + /// 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), - /// Sub-commands concerned with benchmarking. - #[command(subcommand)] - Benchmark(frame_benchmarking_cli::BenchmarkCmd), + /// Sub-commands concerned with benchmarking. + #[command(subcommand)] + Benchmark(frame_benchmarking_cli::BenchmarkCmd), - /// Try some command against runtime state. - #[cfg(feature = "try-runtime")] - TryRuntime(try_runtime_cli::TryRuntimeCmd), + /// Try some command against runtime state. + #[cfg(feature = "try-runtime")] + TryRuntime(try_runtime_cli::TryRuntimeCmd), - /// Try some command against runtime state. Note: `try-runtime` feature must be enabled. - #[cfg(not(feature = "try-runtime"))] - TryRuntime, + /// Try some command against runtime state. Note: `try-runtime` feature must be enabled. + #[cfg(not(feature = "try-runtime"))] + TryRuntime, - /// Db meta columns information. - ChainInfo(sc_cli::ChainInfoCmd), -} \ No newline at end of file + /// Db meta columns information. + ChainInfo(sc_cli::ChainInfoCmd), +} diff --git a/bin/node/src/command.rs b/bin/node/src/command.rs index 141f6bc..c5757d6 100644 --- a/bin/node/src/command.rs +++ b/bin/node/src/command.rs @@ -1,8 +1,8 @@ use crate::{ - benchmarking::{inherent_benchmark_data, RemarkBuilder, TransferKeepAliveBuilder}, - chain_spec, - cli::{Cli, Subcommand}, - service, + benchmarking::{inherent_benchmark_data, RemarkBuilder, TransferKeepAliveBuilder}, + chain_spec, + cli::{Cli, Subcommand}, + service, }; use frame_benchmarking_cli::{BenchmarkCmd, ExtrinsicFactory, SUBSTRATE_REFERENCE_HARDWARE}; use qsb_runtime::{Block, EXISTENTIAL_DEPOSIT}; @@ -14,199 +14,222 @@ use sp_keyring::Sr25519Keyring; use try_runtime_cli::block_building_info::timestamp_with_aura_info; impl SubstrateCli for Cli { - fn impl_name() -> String { - "Substrate Node".into() - } - - fn impl_version() -> String { - env!("SUBSTRATE_CLI_IMPL_VERSION").into() - } - - fn description() -> String { - env!("CARGO_PKG_DESCRIPTION").into() - } - - fn author() -> String { - env!("CARGO_PKG_AUTHORS").into() - } - - fn support_url() -> String { - "support.anonymous.an".into() - } - - fn copyright_start_year() -> i32 { - 2017 - } - - fn load_spec(&self, id: &str) -> Result, 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 impl_name() -> String { + "Substrate Node".into() + } + + fn impl_version() -> String { + env!("SUBSTRATE_CLI_IMPL_VERSION").into() + } + + fn description() -> String { + env!("CARGO_PKG_DESCRIPTION").into() + } + + fn author() -> String { + env!("CARGO_PKG_AUTHORS").into() + } + + fn support_url() -> String { + "support.anonymous.an".into() + } + + fn copyright_start_year() -> i32 { + 2017 + } + + fn load_spec(&self, id: &str) -> Result, 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), + )?), + }) + } } /// Parse and run command line arguments pub fn run() -> sc_cli::Result<()> { - 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)?; - let aux_revert = Box::new(|client, _, blocks| { - sc_consensus_grandpa::revert(client, blocks)?; - Ok(()) - }); - Ok((cmd.run(client, backend, Some(aux_revert)), task_manager)) - }) - }, - Some(Subcommand::Benchmark(cmd)) => { - let runner = cli.create_runner(cmd)?; - - runner.sync_run(|config| { - // This switch needs to be in the client, since the client decides - // which sub-commands it wants to support. - match cmd { - BenchmarkCmd::Pallet(cmd) => { - if !cfg!(feature = "runtime-benchmarks") { - return Err( - "Runtime benchmarking wasn't enabled when building the node. \ + 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)?; + let aux_revert = Box::new(|client, _, blocks| { + sc_consensus_grandpa::revert(client, blocks)?; + Ok(()) + }); + Ok((cmd.run(client, backend, Some(aux_revert)), task_manager)) + }) + } + Some(Subcommand::Benchmark(cmd)) => { + let runner = cli.create_runner(cmd)?; + + runner.sync_run(|config| { + // This switch needs to be in the client, since the client decides + // which sub-commands it wants to support. + match cmd { + BenchmarkCmd::Pallet(cmd) => { + if !cfg!(feature = "runtime-benchmarks") { + return Err( + "Runtime benchmarking wasn't enabled when building the node. \ You can enable it with `--features runtime-benchmarks`." - .into(), - ) - } - - cmd.run::(config) - }, - BenchmarkCmd::Block(cmd) => { - let PartialComponents { client, .. } = service::new_partial(&config)?; - cmd.run(client) - }, - #[cfg(not(feature = "runtime-benchmarks"))] - BenchmarkCmd::Storage(_) => Err( - "Storage benchmarking can be enabled with `--features runtime-benchmarks`." - .into(), - ), - #[cfg(feature = "runtime-benchmarks")] - BenchmarkCmd::Storage(cmd) => { - let PartialComponents { client, backend, .. } = - service::new_partial(&config)?; - let db = backend.expose_db(); - let storage = backend.expose_storage(); - - cmd.run(config, client, db, storage) - }, - BenchmarkCmd::Overhead(cmd) => { - let PartialComponents { client, .. } = service::new_partial(&config)?; - let ext_builder = RemarkBuilder::new(client.clone()); - - cmd.run( - config, - client, - inherent_benchmark_data()?, - Vec::new(), - &ext_builder, - ) - }, - BenchmarkCmd::Extrinsic(cmd) => { - let PartialComponents { client, .. } = service::new_partial(&config)?; - // Register the *Remark* and *TKA* builders. - let ext_factory = ExtrinsicFactory(vec![ - Box::new(RemarkBuilder::new(client.clone())), - Box::new(TransferKeepAliveBuilder::new( - client.clone(), - Sr25519Keyring::Alice.to_account_id(), - EXISTENTIAL_DEPOSIT, - )), - ]); - - cmd.run(client, inherent_benchmark_data()?, Vec::new(), &ext_factory) - }, - BenchmarkCmd::Machine(cmd) => - cmd.run(&config, SUBSTRATE_REFERENCE_HARDWARE.clone()), - } - }) - }, - #[cfg(feature = "try-runtime")] - Some(Subcommand::TryRuntime(cmd)) => { - use crate::service::ExecutorDispatch; - use sc_executor::{sp_wasm_interface::ExtendedHostFunctions, NativeExecutionDispatch}; - let runner = cli.create_runner(cmd)?; - runner.async_run(|config| { - // we don't need any of the components of new_partial, just a runtime, or a task - // manager to do `async_run`. - let registry = config.prometheus_config.as_ref().map(|cfg| &cfg.registry); - let task_manager = - sc_service::TaskManager::new(config.tokio_handle.clone(), registry) - .map_err(|e| sc_cli::Error::Service(sc_service::Error::Prometheus(e)))?; - let info_provider = timestamp_with_aura_info(6000); - - Ok(( - cmd.run::::ExtendHostFunctions, - >, _>(Some(info_provider)), - task_manager, - )) - }) - }, - #[cfg(not(feature = "try-runtime"))] - Some(Subcommand::TryRuntime) => Err("TryRuntime wasn't enabled when building the node. \ + .into(), + ); + } + + cmd.run::(config) + } + BenchmarkCmd::Block(cmd) => { + let PartialComponents { client, .. } = service::new_partial(&config)?; + cmd.run(client) + } + #[cfg(not(feature = "runtime-benchmarks"))] + BenchmarkCmd::Storage(_) => Err( + "Storage benchmarking can be enabled with `--features runtime-benchmarks`." + .into(), + ), + #[cfg(feature = "runtime-benchmarks")] + BenchmarkCmd::Storage(cmd) => { + let PartialComponents { + client, backend, .. + } = service::new_partial(&config)?; + let db = backend.expose_db(); + let storage = backend.expose_storage(); + + cmd.run(config, client, db, storage) + } + BenchmarkCmd::Overhead(cmd) => { + let PartialComponents { client, .. } = service::new_partial(&config)?; + let ext_builder = RemarkBuilder::new(client.clone()); + + cmd.run( + config, + client, + inherent_benchmark_data()?, + Vec::new(), + &ext_builder, + ) + } + BenchmarkCmd::Extrinsic(cmd) => { + let PartialComponents { client, .. } = service::new_partial(&config)?; + // Register the *Remark* and *TKA* builders. + let ext_factory = ExtrinsicFactory(vec![ + Box::new(RemarkBuilder::new(client.clone())), + Box::new(TransferKeepAliveBuilder::new( + client.clone(), + Sr25519Keyring::Alice.to_account_id(), + EXISTENTIAL_DEPOSIT, + )), + ]); + + cmd.run(client, inherent_benchmark_data()?, Vec::new(), &ext_factory) + } + BenchmarkCmd::Machine(cmd) => { + cmd.run(&config, SUBSTRATE_REFERENCE_HARDWARE.clone()) + } + } + }) + } + #[cfg(feature = "try-runtime")] + Some(Subcommand::TryRuntime(cmd)) => { + use crate::service::ExecutorDispatch; + use sc_executor::{sp_wasm_interface::ExtendedHostFunctions, NativeExecutionDispatch}; + let runner = cli.create_runner(cmd)?; + runner.async_run(|config| { + // we don't need any of the components of new_partial, just a runtime, or a task + // manager to do `async_run`. + let registry = config.prometheus_config.as_ref().map(|cfg| &cfg.registry); + let task_manager = + sc_service::TaskManager::new(config.tokio_handle.clone(), registry) + .map_err(|e| sc_cli::Error::Service(sc_service::Error::Prometheus(e)))?; + let info_provider = timestamp_with_aura_info(6000); + + Ok(( + cmd.run::::ExtendHostFunctions, + >, _>(Some(info_provider)), + task_manager, + )) + }) + } + #[cfg(not(feature = "try-runtime"))] + Some(Subcommand::TryRuntime) => Err("TryRuntime wasn't enabled when building the node. \ You can enable it with `--features try-runtime`." - .into()), - Some(Subcommand::ChainInfo(cmd)) => { - let runner = cli.create_runner(cmd)?; - runner.sync_run(|config| cmd.run::(&config)) - }, - None => { - let runner = cli.create_runner(&cli.run)?; - runner.run_node_until_exit(|config| async move { - service::new_full(config).map_err(sc_cli::Error::Service) - }) - }, - } -} \ No newline at end of file + .into()), + Some(Subcommand::ChainInfo(cmd)) => { + let runner = cli.create_runner(cmd)?; + runner.sync_run(|config| cmd.run::(&config)) + } + None => { + let runner = cli.create_runner(&cli.run)?; + runner.run_node_until_exit(|config| async move { + service::new_full(config).map_err(sc_cli::Error::Service) + }) + } + } +} diff --git a/bin/node/src/main.rs b/bin/node/src/main.rs index eebbfa1..33c3195 100644 --- a/bin/node/src/main.rs +++ b/bin/node/src/main.rs @@ -10,5 +10,5 @@ mod command; mod rpc; fn main() -> sc_cli::Result<()> { - command::run() -} \ No newline at end of file + command::run() +} diff --git a/bin/node/src/rpc.rs b/bin/node/src/rpc.rs index f634a68..014ea7f 100644 --- a/bin/node/src/rpc.rs +++ b/bin/node/src/rpc.rs @@ -7,84 +7,87 @@ use std::sync::Arc; -use jsonrpsee::{core::RpcResult, proc_macros::rpc, RpcModule}; use did_runtime_api::DidRuntimeApi; +use jsonrpsee::{core::RpcResult, proc_macros::rpc, RpcModule}; use qsb_runtime::{opaque::Block, AccountId, Balance, Nonce}; use sc_transaction_pool_api::TransactionPool; use sp_api::ProvideRuntimeApi; use sp_block_builder::BlockBuilder; use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata}; -use sp_runtime::generic::BlockId; pub use sc_rpc_api::DenyUnsafe; #[rpc(server)] pub trait DidApi { - #[method(name = "did_getByString")] - fn did_by_string(&self, did: String) -> RpcResult>; + #[method(name = "did_getByString")] + fn did_by_string(&self, did: String) -> RpcResult>; } pub struct DidRpc { - client: Arc, + client: Arc, } impl DidRpc { - pub fn new(client: Arc) -> Self { - Self { client } - } + pub fn new(client: Arc) -> Self { + Self { client } + } } impl DidApiServer for DidRpc where - C: ProvideRuntimeApi + HeaderBackend + 'static, - C::Api: did_runtime_api::DidRuntimeApi, + C: ProvideRuntimeApi + HeaderBackend + 'static, + C::Api: did_runtime_api::DidRuntimeApi, { - fn did_by_string(&self, did: String) -> RpcResult> { - let api = self.client.runtime_api(); - let at = self.client.info().best_hash; - api.did_by_string(at, did.into_bytes()) - .map_err(|e| jsonrpsee::core::Error::Custom(format!("Runtime API error: {:?}", e))) - } + fn did_by_string(&self, did: String) -> RpcResult> { + let api = self.client.runtime_api(); + let at = self.client.info().best_hash; + api.did_by_string(at, did.into_bytes()) + .map_err(|e| jsonrpsee::core::Error::Custom(format!("Runtime API error: {:?}", e))) + } } /// Full client dependencies. pub struct FullDeps { - /// The client instance to use. - pub client: Arc, - /// Transaction pool instance. - pub pool: Arc

, - /// Whether to deny unsafe calls - pub deny_unsafe: DenyUnsafe, + /// The client instance to use. + pub client: Arc, + /// Transaction pool instance. + pub pool: Arc

, + /// Whether to deny unsafe calls + pub deny_unsafe: DenyUnsafe, } /// Instantiate all full RPC extensions. pub fn create_full( - deps: FullDeps, + deps: FullDeps, ) -> Result, Box> where - C: ProvideRuntimeApi, - C: HeaderBackend + HeaderMetadata + 'static, - C: Send + Sync + 'static, - C::Api: substrate_frame_rpc_system::AccountNonceApi, - C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi, - C::Api: did_runtime_api::DidRuntimeApi, - C::Api: BlockBuilder, - P: TransactionPool + 'static, + C: ProvideRuntimeApi, + C: HeaderBackend + HeaderMetadata + 'static, + C: Send + Sync + 'static, + C::Api: substrate_frame_rpc_system::AccountNonceApi, + C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi, + C::Api: did_runtime_api::DidRuntimeApi, + C::Api: BlockBuilder, + P: TransactionPool + 'static, { - use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer}; - use substrate_frame_rpc_system::{System, SystemApiServer}; + use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer}; + use substrate_frame_rpc_system::{System, SystemApiServer}; - let mut module = RpcModule::new(()); - let FullDeps { client, pool, deny_unsafe } = deps; + let mut module = RpcModule::new(()); + let FullDeps { + client, + pool, + deny_unsafe, + } = deps; - module.merge(System::new(client.clone(), pool, deny_unsafe).into_rpc())?; - module.merge(TransactionPayment::new(client.clone()).into_rpc())?; - module.merge(DidApiServer::into_rpc(DidRpc::new(client)))?; + module.merge(System::new(client.clone(), pool, deny_unsafe).into_rpc())?; + module.merge(TransactionPayment::new(client.clone()).into_rpc())?; + module.merge(DidApiServer::into_rpc(DidRpc::new(client)))?; - // 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. - // `module.merge(YourRpcTrait::into_rpc(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. + // `module.merge(YourRpcTrait::into_rpc(YourRpcStruct::new(ReferenceToClient, ...)))?;` - Ok(module) + Ok(module) } diff --git a/bin/node/src/service.rs b/bin/node/src/service.rs index 03a25c1..2282ae8 100644 --- a/bin/node/src/service.rs +++ b/bin/node/src/service.rs @@ -368,4 +368,3 @@ pub fn new_full(config: Configuration) -> Result { network_starter.start_network(); Ok(task_manager) } - diff --git a/bin/runtime/build.rs b/bin/runtime/build.rs index 80ccb0a..8f021e8 100644 --- a/bin/runtime/build.rs +++ b/bin/runtime/build.rs @@ -1,10 +1,10 @@ fn main() { - #[cfg(feature = "std")] - { - substrate_wasm_builder::WasmBuilder::new() - .with_current_project() - .export_heap_base() - .import_memory() - .build(); - } -} \ No newline at end of file + #[cfg(feature = "std")] + { + substrate_wasm_builder::WasmBuilder::new() + .with_current_project() + .export_heap_base() + .import_memory() + .build(); + } +} diff --git a/pallets/did/src/lib.rs b/pallets/did/src/lib.rs index dc900fc..e56fcc4 100644 --- a/pallets/did/src/lib.rs +++ b/pallets/did/src/lib.rs @@ -70,7 +70,8 @@ pub mod pallet { } #[pallet::storage] - pub(super) type DidRecords = StorageMap<_, Twox64Concat, [u8; 32], DidDetails, OptionQuery>; + pub(super) type DidRecords = + StorageMap<_, Twox64Concat, [u8; 32], DidDetails, OptionQuery>; #[pallet::error] pub enum Error { @@ -89,16 +90,45 @@ pub mod pallet { #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { - DidCreated { did: Vec }, - KeyAdded { did: Vec, public_key: Vec }, - KeyRevoked { did: Vec, public_key: Vec }, - DidDeactivated { did: Vec }, - KeyRotated { did: Vec, old_public_key: Vec, new_public_key: Vec }, - RolesUpdated { did: Vec, public_key: Vec }, - ServiceAdded { did: Vec, service_id: Vec }, - ServiceRemoved { did: Vec, service_id: Vec }, - MetadataSet { did: Vec, key: Vec }, - MetadataRemoved { did: Vec, key: Vec }, + DidCreated { + did: Vec, + }, + KeyAdded { + did: Vec, + public_key: Vec, + }, + KeyRevoked { + did: Vec, + public_key: Vec, + }, + DidDeactivated { + did: Vec, + }, + KeyRotated { + did: Vec, + old_public_key: Vec, + new_public_key: Vec, + }, + RolesUpdated { + did: Vec, + public_key: Vec, + }, + ServiceAdded { + did: Vec, + service_id: Vec, + }, + ServiceRemoved { + did: Vec, + service_id: Vec, + }, + MetadataSet { + did: Vec, + key: Vec, + }, + MetadataRemoved { + did: Vec, + key: Vec, + }, } #[pallet::call] @@ -112,7 +142,10 @@ pub mod pallet { ) -> DispatchResult { let _ = frame_system::ensure_signed(origin)?; let did_id = Self::did_id_from_public_key(&public_key); - ensure!(!DidRecords::::contains_key(did_id), Error::::DidAlreadyExists); + ensure!( + !DidRecords::::contains_key(did_id), + Error::::DidAlreadyExists + ); let details = DidDetails { version: 0, @@ -286,7 +319,11 @@ pub mod pallet { DidRecords::::try_mutate(did_id, |maybe_details| -> DispatchResult { let details = maybe_details.as_mut().ok_or(Error::::DidNotFound)?; ensure!(!details.deactivated, Error::::DidDeactivated); - if let Some(existing) = details.metadata.iter_mut().find(|item| item.key == entry.key) { + if let Some(existing) = details + .metadata + .iter_mut() + .find(|item| item.key == entry.key) + { existing.value = entry.value; } else { details.metadata.push(entry); @@ -344,7 +381,10 @@ pub mod pallet { let details = maybe_details.as_mut().ok_or(Error::::DidNotFound)?; ensure!(!details.deactivated, Error::::DidDeactivated); ensure!( - !details.keys.iter().any(|key| key.public_key == new_public_key), + !details + .keys + .iter() + .any(|key| key.public_key == new_public_key), Error::::KeyAlreadyExists ); diff --git a/pallets/revocation-list/src/lib.rs b/pallets/revocation-list/src/lib.rs index 7f73739..09b7fda 100644 --- a/pallets/revocation-list/src/lib.rs +++ b/pallets/revocation-list/src/lib.rs @@ -53,8 +53,15 @@ pub mod pallet { #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { - StatusListCreated { status_list_id: Vec, issuer_did: Vec }, - StatusUpdated { status_list_id: Vec, status_index: u32, revoked: bool }, + StatusListCreated { + status_list_id: Vec, + issuer_did: Vec, + }, + StatusUpdated { + status_list_id: Vec, + status_index: u32, + revoked: bool, + }, } #[pallet::call] @@ -127,7 +134,10 @@ pub mod pallet { .checked_mul(8) .ok_or(Error::::StatusIndexOutOfBounds)?; let status_index_usize = status_index as usize; - ensure!(status_index_usize < bit_count, Error::::StatusIndexOutOfBounds); + ensure!( + status_index_usize < bit_count, + Error::::StatusIndexOutOfBounds + ); let byte_index = status_index_usize / 8; let bit_index = (status_index_usize % 8) as u8; diff --git a/pallets/schema/src/lib.rs b/pallets/schema/src/lib.rs index ce1f866..bf5d72d 100644 --- a/pallets/schema/src/lib.rs +++ b/pallets/schema/src/lib.rs @@ -49,8 +49,14 @@ pub mod pallet { #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { - SchemaRegistered { schema_id: Vec, issuer_did: Vec }, - SchemaDeprecated { schema_id: Vec, issuer_did: Vec }, + SchemaRegistered { + schema_id: Vec, + issuer_did: Vec, + }, + SchemaDeprecated { + schema_id: Vec, + issuer_did: Vec, + }, } #[pallet::call]