diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 0958f82e2d..1ff2cbb455 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -98,6 +98,36 @@ jobs: - name: Check with Prettier run: npx prettier --check --ignore-path .gitignore '**/*.(yml|js|ts|json)' + check-clippy: + name: "Code checks" + runs-on: ubuntu-latest + steps: + - name: Checkout + if: github.event_name == 'pull_request_target' + uses: actions/checkout@v2 + with: + fetch-depth: 0 + ref: refs/pull/${{ github.event.pull_request.number }}/merge + + - name: Checkout + if: github.event_name != 'pull_request_target' + uses: actions/checkout@v2 + + - name: Install toolchain + uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: nightly-2020-10-03 + components: clippy, rustfmt + target: wasm32-unknown-unknown + default: true + + # - name: Check with Clippy + # run: cargo clippy --workspace --tests -- -D warnings + + - name: Format code with rustfmt + run: cargo fmt -- --check + ####### Building and Testing binaries ####### build: diff --git a/.rustfmt.toml b/.rustfmt.toml index 317959df8c..93cc405cbb 100644 --- a/.rustfmt.toml +++ b/.rustfmt.toml @@ -5,4 +5,6 @@ reorder_imports = true hard_tabs = true max_width = 100 -license_template_path = "FILE_TEMPLATE" +# TODO: add template for license checking. +# this will still fail for some licenses where e.g. Parity's license is used +# license_template_path = "FILE_TEMPLATE" diff --git a/.rusty-hook.toml b/.rusty-hook.toml new file mode 100644 index 0000000000..6bba3d0029 --- /dev/null +++ b/.rusty-hook.toml @@ -0,0 +1,5 @@ +[hooks] +pre-commit = "cargo fmt -- --check && cargo clippy" + +[logging] +verbose = true diff --git a/Cargo.lock b/Cargo.lock index 9fadd4715d..807174e909 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -720,6 +720,15 @@ dependencies = [ "winapi 0.3.9", ] +[[package]] +name = "ci_info" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24f638c70e8c5753795cc9a8c07c44da91554a09e4cf11a7326e8161b0a3c45e" +dependencies = [ + "envmnt", +] + [[package]] name = "clang-sys" version = "0.29.3" @@ -1442,6 +1451,16 @@ version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6576a1755ddffd988788025e75bce9e74b018f7cc226198fe931d077911c6d7e" +[[package]] +name = "envmnt" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2d328fc287c61314c4a61af7cfdcbd7e678e39778488c7cb13ec133ce0f4059" +dependencies = [ + "fsio", + "indexmap", +] + [[package]] name = "erased-serde" version = "0.3.13" @@ -2014,6 +2033,12 @@ dependencies = [ "winapi 0.3.9", ] +[[package]] +name = "fsio" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1fd087255f739f4f1aeea69f11b72f8080e9c2e7645cd06955dad4a178a49e3" + [[package]] name = "fuchsia-cprng" version = "0.1.1" @@ -2251,6 +2276,15 @@ dependencies = [ "version_check", ] +[[package]] +name = "getopts" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14dbbfd5c71d70241ecf9e6f13737f7b5ce823821063188d7e46c41d371eebd5" +dependencies = [ + "unicode-width", +] + [[package]] name = "getrandom" version = "0.1.15" @@ -4095,6 +4129,7 @@ dependencies = [ "parachain-info", "parity-scale-codec", "precompiles", + "rusty-hook", "serde", "sp-api", "sp-block-builder", @@ -4212,6 +4247,12 @@ dependencies = [ "winapi 0.3.9", ] +[[package]] +name = "nias" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab250442c86f1850815b5d268639dff018c0627022bc1940eb2d642ca1ce12f0" + [[package]] name = "nix" version = "0.10.0" @@ -7220,6 +7261,18 @@ dependencies = [ "security-framework", ] +[[package]] +name = "rusty-hook" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96cee9be61be7e1cbadd851e58ed7449c29c620f00b23df937cb9cbc04ac21a3" +dependencies = [ + "ci_info", + "getopts", + "nias", + "toml", +] + [[package]] name = "rw-stream-sink" version = "0.2.1" diff --git a/node/parachain/src/chain_spec.rs b/node/parachain/src/chain_spec.rs index d4f2d71354..ba87792226 100644 --- a/node/parachain/src/chain_spec.rs +++ b/node/parachain/src/chain_spec.rs @@ -16,8 +16,8 @@ use cumulus_primitives::ParaId; use moonbeam_runtime::{ - AccountId, BalancesConfig, GenesisConfig, SudoConfig, SystemConfig, - ParachainInfoConfig, WASM_BINARY, EthereumChainIdConfig, EVMConfig, EthereumConfig + AccountId, BalancesConfig, EVMConfig, EthereumChainIdConfig, EthereumConfig, GenesisConfig, + ParachainInfoConfig, SudoConfig, SystemConfig, WASM_BINARY, }; use sc_chain_spec::{ChainSpecExtension, ChainSpecGroup}; use sc_service::ChainType; @@ -40,7 +40,7 @@ pub struct Extensions { impl Extensions { /// Try to get the extension from the given `ChainSpec`. - pub fn try_get(chain_spec: &Box) -> Option<&Self> { + pub fn try_get(chain_spec: &dyn sc_service::ChainSpec) -> Option<&Self> { sc_chain_spec::get_extension(chain_spec.extensions()) } } @@ -53,9 +53,7 @@ pub fn get_chain_spec(para_id: ParaId) -> ChainSpec { move || { testnet_genesis( AccountId::from_str("6Be02d1d3665660d22FF9624b7BE0551ee1Ac91b").unwrap(), - vec![ - AccountId::from_str("6Be02d1d3665660d22FF9624b7BE0551ee1Ac91b").unwrap(), - ], + vec![AccountId::from_str("6Be02d1d3665660d22FF9624b7BE0551ee1Ac91b").unwrap()], para_id, 1280, //ChainId ) @@ -63,12 +61,7 @@ pub fn get_chain_spec(para_id: ParaId) -> ChainSpec { vec![], None, None, - Some( - serde_json::from_str( - "{\"tokenDecimals\": 18}" - ) - .expect("Provided valid json map") - ), + Some(serde_json::from_str("{\"tokenDecimals\": 18}").expect("Provided valid json map")), Extensions { relay_chain: "local_testnet".into(), para_id: para_id.into(), @@ -97,8 +90,10 @@ fn testnet_genesis( .collect(), }), pallet_sudo: Some(SudoConfig { key: root_key }), - parachain_info: Some(ParachainInfoConfig { parachain_id: para_id }), - pallet_ethereum_chain_id: Some(EthereumChainIdConfig { chain_id: chain_id }), + parachain_info: Some(ParachainInfoConfig { + parachain_id: para_id, + }), + pallet_ethereum_chain_id: Some(EthereumChainIdConfig { chain_id }), pallet_evm: Some(EVMConfig { accounts: BTreeMap::new(), }), diff --git a/node/parachain/src/cli.rs b/node/parachain/src/cli.rs index 6d093d7c0e..0cafcd2ed4 100644 --- a/node/parachain/src/cli.rs +++ b/node/parachain/src/cli.rs @@ -16,7 +16,6 @@ use std::path::PathBuf; -use sc_cli; use structopt::StructOpt; /// Sub-commands supported by the collator. diff --git a/node/parachain/src/command.rs b/node/parachain/src/command.rs index 8d108a5cc1..d98cb01fc9 100644 --- a/node/parachain/src/command.rs +++ b/node/parachain/src/command.rs @@ -24,8 +24,8 @@ use log::info; use moonbeam_runtime::Block; use polkadot_parachain::primitives::AccountIdConversion; use sc_cli::{ - ChainSpec, CliConfiguration, ImportParams, KeystoreParams, NetworkParams, Result, - RuntimeVersion, SharedParams, SubstrateCli, DefaultConfigurationValues, + ChainSpec, CliConfiguration, DefaultConfigurationValues, ImportParams, KeystoreParams, + NetworkParams, Result, RuntimeVersion, SharedParams, SubstrateCli, }; use sc_service::{ config::{BasePath, PrometheusConfig}, @@ -117,8 +117,7 @@ impl SubstrateCli for RelayChainCli { } fn load_spec(&self, id: &str) -> std::result::Result, String> { - polkadot_cli::Cli::from_iter([RelayChainCli::executable_name().to_string()].iter()) - .load_spec(id) + polkadot_cli::Cli::from_iter([RelayChainCli::executable_name()].iter()).load_spec(id) } fn native_runtime_version(chain_spec: &Box) -> &'static RuntimeVersion { @@ -126,6 +125,7 @@ impl SubstrateCli for RelayChainCli { } } +#[allow(clippy::borrowed_box)] fn extract_genesis_wasm(chain_spec: &Box) -> Result> { let mut storage = chain_spec.build_storage()?; @@ -254,14 +254,14 @@ pub fn run() -> Result<()> { // TODO let key = sp_core::Pair::generate().0; - let extension = chain_spec::Extensions::try_get(&config.chain_spec); + let extension = chain_spec::Extensions::try_get(&*config.chain_spec); let relay_chain_id = extension.map(|e| e.relay_chain.clone()); let para_id = extension.map(|e| e.para_id); let polkadot_cli = RelayChainCli::new( config.base_path.as_ref().map(|x| x.path().join("polkadot")), relay_chain_id, - [RelayChainCli::executable_name().to_string()] + [RelayChainCli::executable_name()] .iter() .chain(cli.relaychain_args.iter()), ); diff --git a/node/parachain/src/service.rs b/node/parachain/src/service.rs index 76cd5ac897..783ff99900 100644 --- a/node/parachain/src/service.rs +++ b/node/parachain/src/service.rs @@ -18,6 +18,8 @@ use cumulus_network::build_block_announce_validator; use cumulus_service::{ prepare_node_config, start_collator, start_full_node, StartCollatorParams, StartFullNodeParams, }; +use frontier_consensus::FrontierBlockImport; +use moonbeam_runtime::{opaque::Block, RuntimeApi}; use polkadot_primitives::v0::CollatorPair; use sc_executor::native_executor_instance; pub use sc_executor::NativeExecutor; @@ -26,8 +28,6 @@ use sp_core::Pair; use sp_runtime::traits::BlakeTwo256; use sp_trie::PrefixedMemoryDB; use std::sync::Arc; -use frontier_consensus::FrontierBlockImport; -use moonbeam_runtime::{RuntimeApi, opaque::Block}; // Our native executor instance. native_executor_instance!( pub Executor, @@ -42,6 +42,7 @@ type FullBackend = TFullBackend; /// /// Use this macro if you don't actually need the full service, but just the builder in order to /// be able to perform chain operations. +#[allow(clippy::type_complexity)] pub fn new_partial( config: &Configuration, ) -> Result< @@ -49,19 +50,9 @@ pub fn new_partial( FullClient, FullBackend, (), - sp_consensus::import_queue::BasicQueue< - Block, - PrefixedMemoryDB, - >, - sc_transaction_pool::FullPool< - Block, - FullClient, - >, - FrontierBlockImport< - Block, - Arc, - FullClient, - >, + sp_consensus::import_queue::BasicQueue>, + sc_transaction_pool::FullPool, + FrontierBlockImport, FullClient>, >, sc_service::Error, > { @@ -80,18 +71,14 @@ pub fn new_partial( client.clone(), ); - let frontier_block_import = FrontierBlockImport::new( - client.clone(), - client.clone(), - true - ); + let frontier_block_import = FrontierBlockImport::new(client.clone(), client.clone(), true); let import_queue = cumulus_consensus::import_queue::import_queue( client.clone(), frontier_block_import.clone(), inherent_data_providers.clone(), &task_manager.spawn_handle(), - registry.clone(), + registry, )?; let params = PartialComponents { @@ -119,7 +106,7 @@ async fn start_node_impl( id: polkadot_primitives::v0::Id, validator: bool, _rpc_ext_builder: RB, -) -> sc_service::error::Result<(TaskManager,Arc)> +) -> sc_service::error::Result<(TaskManager, Arc)> where RB: Fn( Arc>, @@ -163,13 +150,13 @@ where let block_import = params.other; let (network, network_status_sinks, system_rpc_tx, start_network) = sc_service::build_network(sc_service::BuildNetworkParams { - config: ¶chain_config, - client: client.clone(), - transaction_pool: transaction_pool.clone(), - spawn_handle: task_manager.spawn_handle(), - import_queue, - on_demand: None, - block_announce_validator_builder: Some(Box::new(|_| block_announce_validator)), + config: ¶chain_config, + client: client.clone(), + transaction_pool: transaction_pool.clone(), + spawn_handle: task_manager.spawn_handle(), + import_queue, + on_demand: None, + block_announce_validator_builder: Some(Box::new(|_| block_announce_validator)), })?; let is_authority = parachain_config.role.is_authority(); @@ -191,17 +178,14 @@ where command_sink: None, }; - moonbeam_rpc::create_full( - deps, - subscription_task_executor.clone() - ) + moonbeam_rpc::create_full(deps, subscription_task_executor.clone()) }) }; sc_service::spawn_tasks(sc_service::SpawnTasksParams { on_demand: None, remote_blockchain: None, - rpc_extensions_builder: rpc_extensions_builder, + rpc_extensions_builder, client: client.clone(), transaction_pool: transaction_pool.clone(), task_manager: &mut task_manager, @@ -232,7 +216,7 @@ where let params = StartCollatorParams { para_id: id, - block_import: block_import, + block_import, proposer_factory, inherent_data_providers: params.inherent_data_providers, block_status: client.clone(), diff --git a/node/rpc/src/lib.rs b/node/rpc/src/lib.rs index 063e1bf8db..0b6f490826 100644 --- a/node/rpc/src/lib.rs +++ b/node/rpc/src/lib.rs @@ -17,27 +17,27 @@ //! A collection of node-specific RPC methods. // Our drop-in replacements for Frontier's RPC servers. -mod server_hotfixes; mod pubsub_hotfixes; +mod server_hotfixes; -use std::{sync::Arc, fmt}; +use std::{fmt, sync::Arc}; -use sc_consensus_manual_seal::rpc::{EngineCommand, ManualSeal, ManualSealApi}; -use moonbeam_runtime::{Hash, AccountId, Index, opaque::Block, Balance}; -use sp_api::ProvideRuntimeApi; -use sp_transaction_pool::TransactionPool; -use sp_blockchain::{Error as BlockChainError, HeaderMetadata, HeaderBackend}; -use sc_rpc_api::DenyUnsafe; +use frontier_rpc::HexEncodedIdProvider; +use jsonrpc_pubsub::manager::SubscriptionManager; +use moonbeam_runtime::{opaque::Block, AccountId, Balance, Hash, Index}; use sc_client_api::{ - backend::{StorageProvider, Backend, StateBackend, AuxStore}, - client::BlockchainEvents + backend::{AuxStore, Backend, StateBackend, StorageProvider}, + client::BlockchainEvents, }; +use sc_consensus_manual_seal::rpc::{EngineCommand, ManualSeal, ManualSealApi}; +use sc_network::NetworkService; use sc_rpc::SubscriptionTaskExecutor; -use sp_runtime::traits::BlakeTwo256; +use sc_rpc_api::DenyUnsafe; +use sp_api::ProvideRuntimeApi; use sp_block_builder::BlockBuilder; -use sc_network::NetworkService; -use jsonrpc_pubsub::manager::SubscriptionManager; -use frontier_rpc::HexEncodedIdProvider; +use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata}; +use sp_runtime::traits::BlakeTwo256; +use sp_transaction_pool::TransactionPool; /// Light client extra dependencies. pub struct LightDeps { @@ -70,28 +70,29 @@ pub struct FullDeps { /// Instantiate all Full RPC extensions. pub fn create_full( deps: FullDeps, - subscription_task_executor: SubscriptionTaskExecutor -) -> jsonrpc_core::IoHandler where + subscription_task_executor: SubscriptionTaskExecutor, +) -> jsonrpc_core::IoHandler +where BE: Backend + 'static, BE::State: StateBackend, C: ProvideRuntimeApi + StorageProvider + AuxStore, C: BlockchainEvents, - C: HeaderBackend + HeaderMetadata + 'static, + C: HeaderBackend + HeaderMetadata + 'static, C: Send + Sync + 'static, C::Api: substrate_frame_rpc_system::AccountNonceApi, C::Api: BlockBuilder, C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi, C::Api: frontier_rpc_primitives::EthereumRuntimeRPCApi, ::Error: fmt::Debug, - P: TransactionPool + 'static, + P: TransactionPool + 'static, { - use substrate_frame_rpc_system::{FullSystem, SystemApi}; - use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApi}; use frontier_rpc::{NetApi, NetApiServer, Web3Api, Web3ApiServer}; + use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApi}; + use substrate_frame_rpc_system::{FullSystem, SystemApi}; // Our drop in replacements for the Eth APIs. These can be removed after // https://github.com/paritytech/frontier/pull/199 lands - use server_hotfixes::{EthApi, EthApiServer}; use pubsub_hotfixes::{EthPubSubApi, EthPubSubApiServer}; + use server_hotfixes::{EthApi, EthApiServer}; let mut io = jsonrpc_core::IoHandler::default(); let FullDeps { @@ -103,67 +104,55 @@ pub fn create_full( command_sink, } = deps; - io.extend_with( - SystemApi::to_delegate(FullSystem::new(client.clone(), pool.clone(), deny_unsafe)) - ); - io.extend_with( - TransactionPaymentApi::to_delegate(TransactionPayment::new(client.clone())) - ); + io.extend_with(SystemApi::to_delegate(FullSystem::new( + client.clone(), + pool.clone(), + deny_unsafe, + ))); + io.extend_with(TransactionPaymentApi::to_delegate(TransactionPayment::new( + client.clone(), + ))); // We currently don't want to support signing in the node. Users should prefer external tools // for transaction signing. So just pass in an empty vector of signers. let signers = Vec::new(); - io.extend_with( - EthApiServer::to_delegate(EthApi::new( - client.clone(), - pool.clone(), - moonbeam_runtime::TransactionConverter, - network.clone(), - signers, - is_authority, - )) - ); - io.extend_with( - NetApiServer::to_delegate(NetApi::new( - client.clone(), - network.clone(), - )) - ); - io.extend_with( - Web3ApiServer::to_delegate(Web3Api::new( - client.clone(), - )) - ); - io.extend_with( - EthPubSubApiServer::to_delegate(EthPubSubApi::new( - pool.clone(), - client.clone(), - network.clone(), - SubscriptionManager::::with_id_provider( - HexEncodedIdProvider::default(), - Arc::new(subscription_task_executor) - ), - )) - ); - - match command_sink { - Some(command_sink) => { - io.extend_with( - // We provide the rpc handler with the sending end of the channel to allow the rpc - // send EngineCommands to the background block authorship task. - ManualSealApi::to_delegate(ManualSeal::new(command_sink)), - ); - } - _ => {} + io.extend_with(EthApiServer::to_delegate(EthApi::new( + client.clone(), + pool.clone(), + moonbeam_runtime::TransactionConverter, + network.clone(), + signers, + is_authority, + ))); + io.extend_with(NetApiServer::to_delegate(NetApi::new( + client.clone(), + network.clone(), + ))); + io.extend_with(Web3ApiServer::to_delegate(Web3Api::new(client.clone()))); + io.extend_with(EthPubSubApiServer::to_delegate(EthPubSubApi::new( + pool, + client, + network, + SubscriptionManager::::with_id_provider( + HexEncodedIdProvider::default(), + Arc::new(subscription_task_executor), + ), + ))); + + if let Some(command_sink) = command_sink { + io.extend_with( + // We provide the rpc handler with the sending end of the channel to allow the rpc + // send EngineCommands to the background block authorship task. + ManualSealApi::to_delegate(ManualSeal::new(command_sink)), + ); } io } /// Instantiate all Light RPC extensions. -pub fn create_light( - deps: LightDeps, -) -> jsonrpc_core::IoHandler where +pub fn create_light(deps: LightDeps) -> jsonrpc_core::IoHandler +where C: sp_blockchain::HeaderBackend, C: Send + Sync + 'static, F: sc_client_api::light::Fetcher + 'static, @@ -176,14 +165,12 @@ pub fn create_light( client, pool, remote_blockchain, - fetcher + fetcher, } = deps; let mut io = jsonrpc_core::IoHandler::default(); - io.extend_with( - SystemApi::::to_delegate( - LightSystem::new(client, remote_blockchain, fetcher, pool) - ) - ); + io.extend_with(SystemApi::::to_delegate( + LightSystem::new(client, remote_blockchain, fetcher, pool), + )); io } diff --git a/node/rpc/src/pubsub_hotfixes.rs b/node/rpc/src/pubsub_hotfixes.rs index f9325f907b..758a64a5fe 100644 --- a/node/rpc/src/pubsub_hotfixes.rs +++ b/node/rpc/src/pubsub_hotfixes.rs @@ -16,45 +16,42 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use std::{marker::PhantomData, sync::Arc}; -use std::collections::BTreeMap; -use sp_runtime::traits::{ - Block as BlockT, BlakeTwo256, - UniqueSaturatedInto -}; -use sp_transaction_pool::TransactionPool; -use sp_api::{ProvideRuntimeApi, BlockId}; -use sp_blockchain::{Error as BlockChainError, HeaderMetadata, HeaderBackend}; -use sp_storage::{StorageKey, StorageData}; -use sp_io::hashing::twox_128; +use log::warn; use sc_client_api::{ - backend::{StorageProvider, Backend, StateBackend, AuxStore}, - client::BlockchainEvents + backend::{AuxStore, Backend, StateBackend, StorageProvider}, + client::BlockchainEvents, }; use sc_rpc::Metadata; -use log::warn; +use sp_api::{BlockId, ProvideRuntimeApi}; +use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata}; +use sp_io::hashing::twox_128; +use sp_runtime::traits::{BlakeTwo256, Block as BlockT, UniqueSaturatedInto}; +use sp_storage::{StorageData, StorageKey}; +use sp_transaction_pool::TransactionPool; +use std::collections::BTreeMap; +use std::{marker::PhantomData, sync::Arc}; -use jsonrpc_pubsub::{ - typed::Subscriber, SubscriptionId, - manager::SubscriptionManager, -}; -use frontier_rpc_core::EthPubSubApi::{self as EthPubSubApiT}; +use codec::Decode; +use ethereum_types::{H256, U256}; use frontier_rpc_core::types::{ - Rich, Header, Bytes, Log, FilteredParams, - pubsub::{Kind, Params, Result as PubSubResult, PubSubSyncStatus} + pubsub::{Kind, Params, PubSubSyncStatus, Result as PubSubResult}, + Bytes, FilteredParams, Header, Log, Rich, }; -use ethereum_types::{H256, U256}; -use codec::Decode; -use sha3::{Keccak256, Digest}; +use frontier_rpc_core::EthPubSubApi::{self as EthPubSubApiT}; +use jsonrpc_pubsub::{manager::SubscriptionManager, typed::Subscriber, SubscriptionId}; +use sha3::{Digest, Keccak256}; pub use frontier_rpc_core::EthPubSubApiServer; use futures::{StreamExt as _, TryStreamExt as _}; -use jsonrpc_core::{Result as JsonRpcResult, futures::{Future, Sink}}; use frontier_rpc_primitives::{EthereumRuntimeRPCApi, TransactionStatus}; +use jsonrpc_core::{ + futures::{Future, Sink}, + Result as JsonRpcResult, +}; -use sc_network::{NetworkService, ExHashT}; use frontier_rpc::HexEncodedIdProvider; +use sc_network::{ExHashT, NetworkService}; pub struct EthPubSubApi { _pool: Arc

, @@ -71,64 +68,63 @@ impl EthPubSubApi { network: Arc>, subscriptions: SubscriptionManager, ) -> Self { - Self { _pool, client, network, subscriptions, _marker: PhantomData } + Self { + _pool, + client, + network, + subscriptions, + _marker: PhantomData, + } } } struct SubscriptionResult {} +#[allow(clippy::all)] impl SubscriptionResult { - pub fn new() -> Self { SubscriptionResult{} } + pub fn new() -> Self { + SubscriptionResult {} + } pub fn new_heads(&self, block: ethereum::Block) -> PubSubResult { - PubSubResult::Header(Box::new( - Rich { - inner: Header { - hash: Some(H256::from_slice(Keccak256::digest( - &rlp::encode(&block.header) - ).as_slice())), - parent_hash: block.header.parent_hash, - uncles_hash: block.header.ommers_hash, - author: block.header.beneficiary, - miner: block.header.beneficiary, - state_root: block.header.state_root, - transactions_root: block.header.transactions_root, - receipts_root: block.header.receipts_root, - number: Some(block.header.number), - gas_used: block.header.gas_used, - gas_limit: block.header.gas_limit, - extra_data: Bytes(block.header.extra_data.clone()), - logs_bloom: block.header.logs_bloom, - timestamp: U256::from(block.header.timestamp), - difficulty: block.header.difficulty, - seal_fields: vec![ - Bytes( - block.header.mix_hash.as_bytes().to_vec() - ), - Bytes( - block.header.nonce.as_bytes().to_vec() - ) - ], - size: Some(U256::from( - rlp::encode(&block).len() as u32 - )), - }, - extra_info: BTreeMap::new() - } - )) + PubSubResult::Header(Box::new(Rich { + inner: Header { + hash: Some(H256::from_slice( + Keccak256::digest(&rlp::encode(&block.header)).as_slice(), + )), + parent_hash: block.header.parent_hash, + uncles_hash: block.header.ommers_hash, + author: block.header.beneficiary, + miner: block.header.beneficiary, + state_root: block.header.state_root, + transactions_root: block.header.transactions_root, + receipts_root: block.header.receipts_root, + number: Some(block.header.number), + gas_used: block.header.gas_used, + gas_limit: block.header.gas_limit, + extra_data: Bytes(block.header.extra_data.clone()), + logs_bloom: block.header.logs_bloom, + timestamp: U256::from(block.header.timestamp), + difficulty: block.header.difficulty, + seal_fields: vec![ + Bytes(block.header.mix_hash.as_bytes().to_vec()), + Bytes(block.header.nonce.as_bytes().to_vec()), + ], + size: Some(U256::from(rlp::encode(&block).len() as u32)), + }, + extra_info: BTreeMap::new(), + })) } pub fn logs( &self, block_input: Option, receipts: Vec, - params: &FilteredParams + params: &FilteredParams, ) -> Vec { if block_input.is_none() { return Vec::new(); } let block = block_input.unwrap(); let block_hash = Some(H256::from_slice( - Keccak256::digest(&rlp::encode( - &block.header - )).as_slice() + Keccak256::digest(&rlp::encode(&block.header)).as_slice(), )); let mut logs: Vec = vec![]; let mut log_index: u32 = 0; @@ -136,18 +132,14 @@ impl SubscriptionResult { let mut transaction_log_index: u32 = 0; let transaction_hash: Option = if receipt.logs.len() > 0 { Some(H256::from_slice( - Keccak256::digest(&rlp::encode( - &block.transactions[receipt_index as usize] - )).as_slice() + Keccak256::digest(&rlp::encode(&block.transactions[receipt_index as usize])) + .as_slice(), )) - } else { None }; + } else { + None + }; for log in receipt.logs { - if self.add_log( - block_hash.unwrap(), - &log, - &block, - params - ) { + if self.add_log(block_hash.unwrap(), &log, &block, params) { logs.push(Log { address: log.address, topics: log.topics, @@ -157,9 +149,7 @@ impl SubscriptionResult { transaction_hash: transaction_hash, transaction_index: Some(U256::from(log_index)), log_index: Some(U256::from(log_index)), - transaction_log_index: Some(U256::from( - transaction_log_index - )), + transaction_log_index: Some(U256::from(transaction_log_index)), removed: false, }); } @@ -174,7 +164,7 @@ impl SubscriptionResult { block_hash: H256, ethereum_log: ðereum::Log, block: ðereum::Block, - params: &FilteredParams + params: &FilteredParams, ) -> bool { let log = Log { address: ethereum_log.address.clone(), @@ -189,12 +179,13 @@ impl SubscriptionResult { removed: false, }; if let Some(_) = params.filter { - let block_number = UniqueSaturatedInto::::unique_saturated_into( - block.header.number - ); - if !params.filter_block_range(block_number) || - !params.filter_block_hash(block_hash) || - !params.filter_address(&log) || !params.filter_topics(&log) { + let block_number = + UniqueSaturatedInto::::unique_saturated_into(block.header.number); + if !params.filter_block_range(block_number) + || !params.filter_block_hash(block_hash) + || !params.filter_address(&log) + || !params.filter_topics(&log) + { return false; } } @@ -208,30 +199,28 @@ fn storage_prefix_build(module: &[u8], storage: &[u8]) -> Vec { macro_rules! stream_build { ($context:expr => $module:expr, $storage:expr) => {{ - let key: StorageKey = StorageKey( - storage_prefix_build($module, $storage) - ); - match $context.client.storage_changes_notification_stream( - Some(&[key]), - None - ) { + let key: StorageKey = StorageKey(storage_prefix_build($module, $storage)); + match $context + .client + .storage_changes_notification_stream(Some(&[key]), None) + { Ok(stream) => Some(stream), Err(_err) => None, - } - }}; + } + }}; } +#[allow(clippy::all)] impl EthPubSubApiT for EthPubSubApi - where - B: BlockT + Send + Sync + 'static, - P: TransactionPool + Send + Sync + 'static, - C: ProvideRuntimeApi + StorageProvider + - BlockchainEvents + AuxStore, - C: HeaderBackend + HeaderMetadata + 'static, - C: Send + Sync + 'static, - C::Api: EthereumRuntimeRPCApi, - BE: Backend + 'static, - BE::State: StateBackend, +where + B: BlockT + Send + Sync + 'static, + P: TransactionPool + Send + Sync + 'static, + C: ProvideRuntimeApi + StorageProvider + BlockchainEvents + AuxStore, + C: HeaderBackend + HeaderMetadata + 'static, + C: Send + Sync + 'static, + C::Api: EthereumRuntimeRPCApi, + BE: Backend + 'static, + BE::State: StateBackend, { type Metadata = Metadata; fn subscribe( @@ -243,7 +232,7 @@ impl EthPubSubApiT for EthPubSubApi FilteredParams::new(Some(filter)), - _ => FilteredParams::default() + _ => FilteredParams::default(), }; let client = self.client.clone(); @@ -255,122 +244,115 @@ impl EthPubSubApiT for EthPubSubApi = - Decode::decode(&mut &data.0[..]).unwrap(); - let block: Option = if let Ok(Some(data)) = client.storage( - &id, - &StorageKey( - storage_prefix_build(b"Ethereum", b"CurrentBlock") - ) - ) { - if let Ok(result) = Decode::decode(&mut &data.0[..]) { - Some(result) - } else { None } - } else { None }; - futures::stream::iter( - SubscriptionResult::new() - .logs(block, receipts, &filtered_params) - ) - }) - .map(|x| { - return Ok::, ()>(Ok( - PubSubResult::Log(Box::new(x)) - )); - }) - .compat(); + .flat_map(move |(block_hash, changes)| { + let id = BlockId::Hash(block_hash); + let data = changes.iter().last().unwrap().2.unwrap(); + let receipts: Vec = + Decode::decode(&mut &data.0[..]).unwrap(); + let block: Option = if let Ok(Some(data)) = client + .storage( + &id, + &StorageKey(storage_prefix_build( + b"Ethereum", + b"CurrentBlock", + )), + ) { + if let Ok(result) = Decode::decode(&mut &data.0[..]) { + Some(result) + } else { + None + } + } else { + None + }; + futures::stream::iter(SubscriptionResult::new().logs( + block, + receipts, + &filtered_params, + )) + }) + .map(|x| { + return Ok::< + Result, + (), + >(Ok(PubSubResult::Log(Box::new(x)))); + }) + .compat(); - sink - .sink_map_err(|e| warn!( - "Error sending notifications: {:?}", e - )) + sink.sink_map_err(|e| warn!("Error sending notifications: {:?}", e)) .send_all(stream) .map(|_| ()) }); } - }, + } Kind::NewHeads => { if let Some(stream) = stream_build!( self => b"Ethereum", b"CurrentBlock" ) { self.subscriptions.add(subscriber, |sink| { let stream = stream - .map(|(_block, changes)| { - let data = changes.iter().last().unwrap().2.unwrap(); - let block: ethereum::Block = - Decode::decode(&mut &data.0[..]).unwrap(); - return Ok::<_, ()>(Ok( - SubscriptionResult::new() - .new_heads(block) - )); - }) - .compat(); + .map(|(_block, changes)| { + let data = changes.iter().last().unwrap().2.unwrap(); + let block: ethereum::Block = + Decode::decode(&mut &data.0[..]).unwrap(); + return Ok::<_, ()>(Ok(SubscriptionResult::new().new_heads(block))); + }) + .compat(); - sink - .sink_map_err(|e| warn!( - "Error sending notifications: {:?}", e - )) + sink.sink_map_err(|e| warn!("Error sending notifications: {:?}", e)) .send_all(stream) .map(|_| ()) }); } - }, + } Kind::NewPendingTransactions => { if let Some(stream) = stream_build!( self => b"Ethereum", b"Pending" ) { self.subscriptions.add(subscriber, |sink| { let stream = stream - .flat_map(|(_block, changes)| { - let mut transactions: Vec = vec![]; - let storage: Vec> = changes.iter() - .filter_map(|(o_sk, _k, v)| { - if o_sk.is_none() { - Some(v.cloned()) - } else { None } - }).collect(); - for change in storage { - if let Some(data) = change { - let storage: Vec<( - ethereum::Transaction, - TransactionStatus, - ethereum::Receipt - )> = Decode::decode(&mut &data.0[..]).unwrap(); - let tmp: Vec = - storage.iter().map(|x| x.0.clone()).collect(); - transactions.extend(tmp); + .flat_map(|(_block, changes)| { + let mut transactions: Vec = vec![]; + let storage: Vec> = changes + .iter() + .filter_map(|(o_sk, _k, v)| { + if o_sk.is_none() { + Some(v.cloned()) + } else { + None + } + }) + .collect(); + for change in storage { + if let Some(data) = change { + let storage: Vec<( + ethereum::Transaction, + TransactionStatus, + ethereum::Receipt, + )> = Decode::decode(&mut &data.0[..]).unwrap(); + let tmp: Vec = + storage.iter().map(|x| x.0.clone()).collect(); + transactions.extend(tmp); + } } - } - futures::stream::iter(transactions) - }) - .map(|transaction| { - return Ok::, ()>(Ok( - PubSubResult::TransactionHash(H256::from_slice( - Keccak256::digest( - &rlp::encode(&transaction) - ).as_slice() - )) - )); - }) - .compat(); + futures::stream::iter(transactions) + }) + .map(|transaction| { + return Ok::< + Result, + (), + >(Ok(PubSubResult::TransactionHash(H256::from_slice( + Keccak256::digest(&rlp::encode(&transaction)).as_slice(), + )))); + }) + .compat(); - sink - .sink_map_err(|e| warn!( - "Error sending notifications: {:?}", e - )) + sink.sink_map_err(|e| warn!("Error sending notifications: {:?}", e)) .send_all(stream) .map(|_| ()) }); } - }, + } Kind::Syncing => { if let Some(stream) = stream_build!( self => b"Ethereum", b"CurrentBlock" @@ -378,43 +360,37 @@ impl EthPubSubApiT for EthPubSubApi, ()>(Ok( - PubSubResult::SyncState(PubSubSyncStatus { - syncing: syncing - }) - )); - }) - .compat(); - sink - .sink_map_err(|e| warn!( - "Error sending notifications: {:?}", e - )) + .filter_map(move |(_, _)| { + let syncing = network.is_major_syncing(); + if previous_syncing != syncing { + previous_syncing = syncing; + futures::future::ready(Some(syncing)) + } else { + futures::future::ready(None) + } + }) + .map(|syncing| { + return Ok::< + Result, + (), + >(Ok(PubSubResult::SyncState(PubSubSyncStatus { + syncing: syncing, + }))); + }) + .compat(); + sink.sink_map_err(|e| warn!("Error sending notifications: {:?}", e)) .send_all(stream) .map(|_| ()) - }); } - }, + } } } fn unsubscribe( &self, _metadata: Option, - subscription_id: SubscriptionId + subscription_id: SubscriptionId, ) -> JsonRpcResult { Ok(self.subscriptions.cancel(subscription_id)) } diff --git a/node/rpc/src/server_hotfixes.rs b/node/rpc/src/server_hotfixes.rs index 4a8b914900..524e6bbb38 100644 --- a/node/rpc/src/server_hotfixes.rs +++ b/node/rpc/src/server_hotfixes.rs @@ -20,39 +20,44 @@ //! replacements will be removed and we will head in the direction of //! https://github.com/paritytech/frontier/pull/199 -use std::{marker::PhantomData, sync::Arc}; -use std::collections::BTreeMap; +use codec::Decode; use ethereum::{ Block as EthereumBlock, Transaction as EthereumTransaction, TransactionMessage as EthereumTransactionMessage, }; -use ethereum_types::{H160, H256, H64, U256, U64, H512}; -use jsonrpc_core::{BoxFuture, Result, futures::future::{self, Future}}; +use ethereum_types::{H160, H256, H512, H64, U256, U64}; +use frontier_rpc::{error_on_execution_failure, internal_err, EthSigner}; +use frontier_rpc_core::types::{ + Block, BlockNumber, BlockTransactions, Bytes, CallRequest, Filter, FilteredParams, Index, Log, + Receipt, Rich, RichBlock, SyncInfo, SyncStatus, Transaction, TransactionRequest, VariadicValue, + Work, +}; +use frontier_rpc_core::EthApi as EthApiT; +use frontier_rpc_primitives::{ConvertTransaction, EthereumRuntimeRPCApi, TransactionStatus}; use futures::future::TryFutureExt; +use jsonrpc_core::{ + futures::future::{self, Future}, + BoxFuture, Result, +}; +use sc_client_api::backend::{AuxStore, Backend, StateBackend, StorageProvider}; +use sc_network::{ExHashT, NetworkService}; +use sha3::{Digest, Keccak256}; +use sp_api::{BlockId, ProvideRuntimeApi}; +use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata}; +use sp_io::hashing::{blake2_128, twox_128}; use sp_runtime::{ - traits::{Block as BlockT, Header as _, UniqueSaturatedInto, Zero, One, Saturating, BlakeTwo256}, - transaction_validity::TransactionSource + traits::{ + BlakeTwo256, Block as BlockT, Header as _, One, Saturating, UniqueSaturatedInto, Zero, + }, + transaction_validity::TransactionSource, }; -use sp_api::{ProvideRuntimeApi, BlockId}; -use sp_transaction_pool::{TransactionPool, InPoolTransaction}; -use sc_client_api::backend::{StorageProvider, Backend, StateBackend, AuxStore}; -use sha3::{Keccak256, Digest}; -use sp_blockchain::{Error as BlockChainError, HeaderMetadata, HeaderBackend}; use sp_storage::StorageKey; -use codec::Decode; -use sp_io::hashing::{twox_128, blake2_128}; -use sc_network::{NetworkService, ExHashT}; -use frontier_rpc_core::EthApi as EthApiT; -use frontier_rpc_core::types::{ - BlockNumber, Bytes, CallRequest, Filter, FilteredParams, Index, Log, Receipt, RichBlock, - SyncStatus, SyncInfo, Transaction, Work, Rich, Block, BlockTransactions, VariadicValue, - TransactionRequest, -}; -use frontier_rpc_primitives::{EthereumRuntimeRPCApi, ConvertTransaction, TransactionStatus}; -use frontier_rpc::{internal_err, error_on_execution_failure, EthSigner}; +use sp_transaction_pool::{InPoolTransaction, TransactionPool}; +use std::collections::BTreeMap; +use std::{marker::PhantomData, sync::Arc}; -pub use frontier_rpc_core::EthApiServer; use codec::{self, Encode}; +pub use frontier_rpc_core::EthApiServer; pub struct EthApi { pool: Arc

, @@ -89,14 +94,12 @@ fn rich_block_build( block: ethereum::Block, statuses: Vec>, hash: Option, - full_transactions: bool + full_transactions: bool, ) -> RichBlock { Rich { inner: Block { hash: Some(hash.unwrap_or_else(|| { - H256::from_slice( - Keccak256::digest(&rlp::encode(&block.header)).as_slice() - ) + H256::from_slice(Keccak256::digest(&rlp::encode(&block.header)).as_slice()) })), parent_hash: block.header.parent_hash, uncles_hash: block.header.ommers_hash, @@ -115,40 +118,50 @@ fn rich_block_build( total_difficulty: None, seal_fields: vec![ Bytes(block.header.mix_hash.as_bytes().to_vec()), - Bytes(block.header.nonce.as_bytes().to_vec()) + Bytes(block.header.nonce.as_bytes().to_vec()), ], uncles: vec![], transactions: { if full_transactions { BlockTransactions::Full( - block.transactions.iter().enumerate().map(|(index, transaction)|{ - transaction_build( - transaction.clone(), - block.clone(), - statuses[index].clone().unwrap_or_default() - ) - }).collect() + block + .transactions + .iter() + .enumerate() + .map(|(index, transaction)| { + transaction_build( + transaction.clone(), + block.clone(), + statuses[index].clone().unwrap_or_default(), + ) + }) + .collect(), ) } else { BlockTransactions::Hashes( - block.transactions.iter().map(|transaction|{ - H256::from_slice( - Keccak256::digest(&rlp::encode(&transaction.clone())).as_slice() - ) - }).collect() + block + .transactions + .iter() + .map(|transaction| { + H256::from_slice( + Keccak256::digest(&rlp::encode(&transaction.clone())) + .as_slice(), + ) + }) + .collect(), ) } }, - size: Some(U256::from(rlp::encode(&block).len() as u32)) + size: Some(U256::from(rlp::encode(&block).len() as u32)), }, - extra_info: BTreeMap::new() + extra_info: BTreeMap::new(), } } fn transaction_build( transaction: EthereumTransaction, block: EthereumBlock, - status: TransactionStatus + status: TransactionStatus, ) -> Transaction { let mut sig = [0u8; 65]; let mut msg = [0u8; 32]; @@ -163,18 +176,14 @@ fn transaction_build( }; Transaction { - hash: H256::from_slice( - Keccak256::digest(&rlp::encode(&transaction)).as_slice() - ), + hash: H256::from_slice(Keccak256::digest(&rlp::encode(&transaction)).as_slice()), nonce: transaction.nonce, block_hash: Some(H256::from_slice( - Keccak256::digest(&rlp::encode(&block.header)).as_slice() + Keccak256::digest(&rlp::encode(&block.header)).as_slice(), )), block_number: Some(block.header.number), transaction_index: Some(U256::from( - UniqueSaturatedInto::::unique_saturated_into( - status.transaction_index - ) + UniqueSaturatedInto::::unique_saturated_into(status.transaction_index), )), from: status.from, to: status.to, @@ -203,115 +212,104 @@ fn blake2_128_extend(bytes: &[u8]) -> Vec { ext } -impl EthApi where +#[allow(clippy::all)] +impl EthApi +where C: ProvideRuntimeApi + StorageProvider + AuxStore, - C: HeaderBackend + HeaderMetadata + 'static, + C: HeaderBackend + HeaderMetadata + 'static, C::Api: EthereumRuntimeRPCApi, BE: Backend + 'static, BE::State: StateBackend, - B: BlockT + Send + Sync + 'static, + B: BlockT + Send + Sync + 'static, C: Send + Sync + 'static, - P: TransactionPool + Send + Sync + 'static, + P: TransactionPool + Send + Sync + 'static, CT: ConvertTransaction<::Extrinsic> + Send + Sync + 'static, { fn native_block_id(&self, number: Option) -> Result>> { Ok(match number.unwrap_or(BlockNumber::Latest) { - BlockNumber::Hash { hash, .. } => { - self.load_hash(hash).unwrap_or(None) - }, - BlockNumber::Num(number) => { - Some(BlockId::Number(number.unique_saturated_into())) - }, - BlockNumber::Latest => { - Some(BlockId::Hash( - self.client.info().best_hash - )) - }, - BlockNumber::Earliest => { - Some(BlockId::Number(Zero::zero())) - }, - BlockNumber::Pending => { - None - } + BlockNumber::Hash { hash, .. } => self.load_hash(hash).unwrap_or(None), + BlockNumber::Num(number) => Some(BlockId::Number(number.unique_saturated_into())), + BlockNumber::Latest => Some(BlockId::Hash(self.client.info().best_hash)), + BlockNumber::Earliest => Some(BlockId::Number(Zero::zero())), + BlockNumber::Pending => None, }) } // Asumes there is only one mapped canonical block in the AuxStore, otherwise something is wrong fn load_hash(&self, hash: H256) -> Result>> { let hashes = match frontier_consensus::load_block_hash::(self.client.as_ref(), hash) - .map_err(|err| internal_err(format!("fetch aux store failed: {:?}", err)))? - { + .map_err(|err| { + internal_err(format!("fetch aux store failed: {:?}", err)) + })? { Some(hashes) => hashes, None => return Ok(None), }; - let out: Vec = hashes.into_iter() + let out: Vec = hashes + .into_iter() .filter_map(|h| { if let Ok(Some(_)) = self.client.header(BlockId::Hash(h)) { Some(h) } else { None } - }).collect(); + }) + .collect(); if out.len() == 1 { - return Ok(Some( - BlockId::Hash(out[0]) - )); + return Ok(Some(BlockId::Hash(out[0]))); } Ok(None) } - fn headers(&self, id: &BlockId) -> Result<(u64,u64)> { - match self.client.header(id.clone()) + fn headers(&self, id: &BlockId) -> Result<(u64, u64)> { + match self + .client + .header(id.clone()) .map_err(|_| internal_err(format!("failed to retrieve header at: {:#?}", id)))? { Some(h) => { let best_number: u64 = UniqueSaturatedInto::::unique_saturated_into( - self.client.info().best_number - ); - let header_number: u64 = UniqueSaturatedInto::::unique_saturated_into( - *h.number() + self.client.info().best_number, ); + let header_number: u64 = + UniqueSaturatedInto::::unique_saturated_into(*h.number()); Ok((best_number, header_number)) } - _ => Err(internal_err(format!("failed to retrieve header at: {:#?}", id))) + _ => Err(internal_err(format!( + "failed to retrieve header at: {:#?}", + id + ))), } } fn current_block(&self, id: &BlockId) -> Option { self.query_storage::( id, - &StorageKey( - storage_prefix_build(b"Ethereum", b"CurrentBlock") - ) + &StorageKey(storage_prefix_build(b"Ethereum", b"CurrentBlock")), ) } fn current_statuses(&self, id: &BlockId) -> Option> { self.query_storage::>( id, - &StorageKey( - storage_prefix_build(b"Ethereum", b"CurrentTransactionStatuses") - ) + &StorageKey(storage_prefix_build( + b"Ethereum", + b"CurrentTransactionStatuses", + )), ) } fn current_receipts(&self, id: &BlockId) -> Option> { self.query_storage::>( id, - &StorageKey( - storage_prefix_build(b"Ethereum", b"CurrentReceipts") - ) + &StorageKey(storage_prefix_build(b"Ethereum", b"CurrentReceipts")), ) } fn account_codes(&self, id: &BlockId, address: H160) -> Option> { let mut key: Vec = storage_prefix_build(b"EVM", b"AccountCodes"); key.extend(blake2_128_extend(address.as_bytes())); - self.query_storage::>( - id, - &StorageKey(key) - ) + self.query_storage::>(id, &StorageKey(key)) } fn account_storages(&self, id: &BlockId, address: H160, index: U256) -> Option { @@ -322,17 +320,11 @@ impl EthApi where key.extend(blake2_128_extend(address.as_bytes())); key.extend(blake2_128_extend(tmp)); - self.query_storage::( - id, - &StorageKey(key) - ) + self.query_storage::(id, &StorageKey(key)) } fn query_storage(&self, id: &BlockId, key: &StorageKey) -> Option { - if let Ok(Some(data)) = self.client.storage( - id, - key - ) { + if let Ok(Some(data)) = self.client.storage(id, key) { if let Ok(result) = Decode::decode(&mut &data.0[..]) { return Some(result); } @@ -341,15 +333,17 @@ impl EthApi where } } -impl EthApiT for EthApi where +#[allow(clippy::all)] +impl EthApiT for EthApi +where C: ProvideRuntimeApi + StorageProvider + AuxStore, - C: HeaderBackend + HeaderMetadata + 'static, + C: HeaderBackend + HeaderMetadata + 'static, C::Api: EthereumRuntimeRPCApi, BE: Backend + 'static, BE::State: StateBackend, - B: BlockT + Send + Sync + 'static, + B: BlockT + Send + Sync + 'static, C: Send + Sync + 'static, - P: TransactionPool + Send + Sync + 'static, + P: TransactionPool + Send + Sync + 'static, CT: ConvertTransaction<::Extrinsic> + Send + Sync + 'static, { fn protocol_version(&self) -> Result { @@ -359,7 +353,11 @@ impl EthApiT for EthApi where fn syncing(&self) -> Result { if self.network.is_major_syncing() { let block_number = U256::from( - self.client.info().best_number.clone().unique_saturated_into() + self.client + .info() + .best_number + .clone() + .unique_saturated_into(), ); Ok(SyncStatus::Info(SyncInfo { starting_block: U256::zero(), @@ -381,14 +379,13 @@ impl EthApiT for EthApi where } fn author(&self) -> Result { - let block: Option = self.current_block(&BlockId::Hash( - self.client.info().best_hash - )); + let block: Option = + self.current_block(&BlockId::Hash(self.client.info().best_hash)); return if let Some(block) = block { Ok(block.header.beneficiary) } else { Err(internal_err("Failed to retrieve block.")) - } + }; } fn is_mining(&self) -> Result { @@ -397,19 +394,23 @@ impl EthApiT for EthApi where fn chain_id(&self) -> Result> { let hash = self.client.info().best_hash; - Ok(Some(self.client.runtime_api().chain_id(&BlockId::Hash(hash)) - .map_err(|err| internal_err(format!("fetch runtime chain id failed: {:?}", err)))?.into())) - } - - fn gas_price(&self) -> Result { - let hash = self.client.info().best_hash; - Ok( + Ok(Some( self.client .runtime_api() - .gas_price(&BlockId::Hash(hash)) + .chain_id(&BlockId::Hash(hash)) .map_err(|err| internal_err(format!("fetch runtime chain id failed: {:?}", err)))? .into(), - ) + )) + } + + fn gas_price(&self) -> Result { + let hash = self.client.info().best_hash; + Ok(self + .client + .runtime_api() + .gas_price(&BlockId::Hash(hash)) + .map_err(|err| internal_err(format!("fetch runtime chain id failed: {:?}", err)))? + .into()) } fn accounts(&self) -> Result> { @@ -421,18 +422,24 @@ impl EthApiT for EthApi where } fn block_number(&self) -> Result { - Ok(U256::from(self.client.info().best_number.clone().unique_saturated_into())) + Ok(U256::from( + self.client + .info() + .best_number + .clone() + .unique_saturated_into(), + )) } fn balance(&self, address: H160, number: Option) -> Result { if let Ok(Some(id)) = self.native_block_id(number) { - return Ok( - self.client - .runtime_api() - .account_basic(&id, address) - .map_err(|err| internal_err(format!("fetch runtime chain id failed: {:?}", err)))? - .balance.into(), - ); + return Ok(self + .client + .runtime_api() + .account_basic(&id, address) + .map_err(|err| internal_err(format!("fetch runtime chain id failed: {:?}", err)))? + .balance + .into()); } Ok(U256::zero()) } @@ -448,7 +455,8 @@ impl EthApiT for EthApi where } fn block_by_hash(&self, hash: H256, full: bool) -> Result> { - let id = match self.load_hash(hash) + let id = match self + .load_hash(hash) .map_err(|err| internal_err(format!("{:?}", err)))? { Some(hash) => hash, @@ -464,17 +472,13 @@ impl EthApiT for EthApi where let statuses: Option> = self.current_statuses(&id); match (block, statuses) { - (Some(block), Some(statuses)) => { - Ok(Some(rich_block_build( - block, - statuses.into_iter().map(|s| Some(s)).collect(), - Some(hash), - full, - ))) - }, - _ => { - Ok(None) - }, + (Some(block), Some(statuses)) => Ok(Some(rich_block_build( + block, + statuses.into_iter().map(|s| Some(s)).collect(), + Some(hash), + full, + ))), + _ => Ok(None), } } @@ -489,9 +493,8 @@ impl EthApiT for EthApi where match (block, statuses) { (Some(block), Some(statuses)) => { - let hash = H256::from_slice( - Keccak256::digest(&rlp::encode(&block.header)).as_slice(), - ); + let hash = + H256::from_slice(Keccak256::digest(&rlp::encode(&block.header)).as_slice()); Ok(Some(rich_block_build( block, @@ -499,10 +502,8 @@ impl EthApiT for EthApi where Some(hash), full, ))) - }, - _ => { - Ok(None) - }, + } + _ => Ok(None), } } @@ -510,9 +511,13 @@ impl EthApiT for EthApi where if let Some(BlockNumber::Pending) = number { // Find future nonce let id = BlockId::hash(self.client.info().best_hash); - let nonce: U256 = self.client.runtime_api() + let nonce: U256 = self + .client + .runtime_api() .account_basic(&id, address) - .map_err(|err| internal_err(format!("fetch runtime account basic failed: {:?}", err)))? + .map_err(|err| { + internal_err(format!("fetch runtime account basic failed: {:?}", err)) + })? .nonce; let mut current_nonce = nonce; @@ -534,16 +539,20 @@ impl EthApiT for EthApi where None => return Ok(U256::zero()), }; - let nonce = self.client.runtime_api() + let nonce = self + .client + .runtime_api() .account_basic(&id, address) .map_err(|err| internal_err(format!("fetch runtime account basic failed: {:?}", err)))? - .nonce.into(); + .nonce + .into(); Ok(nonce) } fn block_transaction_count_by_hash(&self, hash: H256) -> Result> { - let id = match self.load_hash(hash) + let id = match self + .load_hash(hash) .map_err(|err| internal_err(format!("{:?}", err)))? { Some(hash) => hash, @@ -589,7 +598,7 @@ impl EthApiT for EthApi where fn code_at(&self, address: H160, number: Option) -> Result { let mut out: Bytes = Bytes(Vec::new()); if let Ok(Some(id)) = self.native_block_id(number) { - if let Some(account_codes) = self.account_codes(&id,address) { + if let Some(account_codes) = self.account_codes(&id, address) { out = Bytes(account_codes); } } @@ -607,18 +616,18 @@ impl EthApiT for EthApi where match accounts.get(0) { Some(account) => account.clone(), - None => return Box::new(future::result(Err(internal_err("no signer available")))), + None => { + return Box::new(future::result(Err(internal_err("no signer available")))) + } } - }, + } }; let nonce = match request.nonce { Some(nonce) => nonce, - None => { - match self.transaction_count(from, None) { - Ok(nonce) => nonce, - Err(e) => return Box::new(future::result(Err(e))), - } + None => match self.transaction_count(from, None) { + Ok(nonce) => nonce, + Err(e) => return Box::new(future::result(Err(e))), }, }; @@ -648,7 +657,7 @@ impl EthApiT for EthApi where Ok(t) => transaction = Some(t), Err(e) => return Box::new(future::result(Err(e))), } - break + break; } } @@ -656,9 +665,8 @@ impl EthApiT for EthApi where Some(transaction) => transaction, None => return Box::new(future::result(Err(internal_err("no signer available")))), }; - let transaction_hash = H256::from_slice( - Keccak256::digest(&rlp::encode(&transaction)).as_slice() - ); + let transaction_hash = + H256::from_slice(Keccak256::digest(&rlp::encode(&transaction)).as_slice()); let hash = self.client.info().best_hash; Box::new( self.pool @@ -669,20 +677,23 @@ impl EthApiT for EthApi where ) .compat() .map(move |_| transaction_hash) - .map_err(|err| internal_err(format!("submit transaction to pool failed: {:?}", err))) + .map_err(|err| { + internal_err(format!("submit transaction to pool failed: {:?}", err)) + }), ) } fn send_raw_transaction(&self, bytes: Bytes) -> BoxFuture { let transaction = match rlp::decode::(&bytes.0[..]) { Ok(transaction) => transaction, - Err(_) => return Box::new( - future::result(Err(internal_err("decode transaction failed"))) - ), + Err(_) => { + return Box::new(future::result(Err(internal_err( + "decode transaction failed", + )))) + } }; - let transaction_hash = H256::from_slice( - Keccak256::digest(&rlp::encode(&transaction)).as_slice() - ); + let transaction_hash = + H256::from_slice(Keccak256::digest(&rlp::encode(&transaction)).as_slice()); let hash = self.client.info().best_hash; Box::new( self.pool @@ -693,7 +704,9 @@ impl EthApiT for EthApi where ) .compat() .map(move |_| transaction_hash) - .map_err(|err| internal_err(format!("submit transaction to pool failed: {:?}", err))) + .map_err(|err| { + internal_err(format!("submit transaction to pool failed: {:?}", err)) + }), ) } @@ -707,7 +720,7 @@ impl EthApiT for EthApi where gas, value, data, - nonce + nonce, } = request; let gas_limit = gas.unwrap_or(U256::max_value()); // TODO: set a limit @@ -715,7 +728,9 @@ impl EthApiT for EthApi where match to { Some(to) => { - let info = self.client.runtime_api() + let info = self + .client + .runtime_api() .call( &BlockId::Hash(hash), from.unwrap_or_default(), @@ -733,9 +748,11 @@ impl EthApiT for EthApi where error_on_execution_failure(&info.exit_reason, &info.value)?; Ok(Bytes(info.value)) - }, + } None => { - let info = self.client.runtime_api() + let info = self + .client + .runtime_api() .create( &BlockId::Hash(hash), from.unwrap_or_default(), @@ -752,7 +769,7 @@ impl EthApiT for EthApi where error_on_execution_failure(&info.exit_reason, &[])?; Ok(Bytes(info.value[..].to_vec())) - }, + } } } @@ -766,7 +783,7 @@ impl EthApiT for EthApi where gas, value, data, - nonce + nonce, } = request; let gas_limit = gas.unwrap_or(U256::max_value()); // TODO: set a limit @@ -774,7 +791,9 @@ impl EthApiT for EthApi where let used_gas = match to { Some(to) => { - let info = self.client.runtime_api() + let info = self + .client + .runtime_api() .call( &BlockId::Hash(hash), from.unwrap_or_default(), @@ -792,9 +811,11 @@ impl EthApiT for EthApi where error_on_execution_failure(&info.exit_reason, &info.value)?; info.used_gas - }, + } None => { - let info = self.client.runtime_api() + let info = self + .client + .runtime_api() .create( &BlockId::Hash(hash), from.unwrap_or_default(), @@ -811,22 +832,23 @@ impl EthApiT for EthApi where error_on_execution_failure(&info.exit_reason, &[])?; info.used_gas - }, + } }; Ok(used_gas) } fn transaction_by_hash(&self, hash: H256) -> Result> { - let (hash, index) = match frontier_consensus::load_transaction_metadata( - self.client.as_ref(), - hash, - ).map_err(|err| internal_err(format!("fetch aux store failed: {:?})", err)))? { - Some((hash, index)) => (hash, index as usize), - None => return Ok(None), - }; + let (hash, index) = + match frontier_consensus::load_transaction_metadata(self.client.as_ref(), hash) + .map_err(|err| internal_err(format!("fetch aux store failed: {:?})", err)))? + { + Some((hash, index)) => (hash, index as usize), + None => return Ok(None), + }; - let id = match self.load_hash(hash) + let id = match self + .load_hash(hash) .map_err(|err| internal_err(format!("{:?}", err)))? { Some(hash) => hash, @@ -842,14 +864,12 @@ impl EthApiT for EthApi where let statuses: Option> = self.current_statuses(&id); match (block, statuses) { - (Some(block), Some(statuses)) => { - Ok(Some(transaction_build( - block.transactions[index].clone(), - block, - statuses[index].clone(), - ))) - }, - _ => Ok(None) + (Some(block), Some(statuses)) => Ok(Some(transaction_build( + block.transactions[index].clone(), + block, + statuses[index].clone(), + ))), + _ => Ok(None), } } @@ -858,7 +878,8 @@ impl EthApiT for EthApi where hash: H256, index: Index, ) -> Result> { - let id = match self.load_hash(hash) + let id = match self + .load_hash(hash) .map_err(|err| internal_err(format!("{:?}", err)))? { Some(hash) => hash, @@ -875,14 +896,12 @@ impl EthApiT for EthApi where let statuses: Option> = self.current_statuses(&id); match (block, statuses) { - (Some(block), Some(statuses)) => { - Ok(Some(transaction_build( - block.transactions[index].clone(), - block, - statuses[index].clone(), - ))) - }, - _ => Ok(None) + (Some(block), Some(statuses)) => Ok(Some(transaction_build( + block.transactions[index].clone(), + block, + statuses[index].clone(), + ))), + _ => Ok(None), } } @@ -901,27 +920,26 @@ impl EthApiT for EthApi where let statuses: Option> = self.current_statuses(&id); match (block, statuses) { - (Some(block), Some(statuses)) => { - Ok(Some(transaction_build( - block.transactions[index].clone(), - block, - statuses[index].clone(), - ))) - }, - _ => Ok(None) + (Some(block), Some(statuses)) => Ok(Some(transaction_build( + block.transactions[index].clone(), + block, + statuses[index].clone(), + ))), + _ => Ok(None), } } fn transaction_receipt(&self, hash: H256) -> Result> { - let (hash, index) = match frontier_consensus::load_transaction_metadata( - self.client.as_ref(), - hash, - ).map_err(|err| internal_err(format!("fetch aux store failed : {:?}", err)))? { - Some((hash, index)) => (hash, index as usize), - None => return Ok(None), - }; + let (hash, index) = + match frontier_consensus::load_transaction_metadata(self.client.as_ref(), hash) + .map_err(|err| internal_err(format!("fetch aux store failed : {:?}", err)))? + { + Some((hash, index)) => (hash, index as usize), + None => return Ok(None), + }; - let id = match self.load_hash(hash) + let id = match self + .load_hash(hash) .map_err(|err| internal_err(format!("{:?}", err)))? { Some(hash) => hash, @@ -939,9 +957,8 @@ impl EthApiT for EthApi where match (block, statuses, receipts) { (Some(block), Some(statuses), Some(receipts)) => { - let block_hash = H256::from_slice( - Keccak256::digest(&rlp::encode(&block.header)).as_slice() - ); + let block_hash = + H256::from_slice(Keccak256::digest(&rlp::encode(&block.header)).as_slice()); let receipt = receipts[index].clone(); let status = statuses[index].clone(); let mut cumulative_receipts = receipts.clone(); @@ -955,9 +972,10 @@ impl EthApiT for EthApi where to: status.to, block_number: Some(block.header.number), cumulative_gas_used: { - let cumulative_gas: u32 = cumulative_receipts.iter().map(|r| { - r.used_gas.as_u32() - }).sum(); + let cumulative_gas: u32 = cumulative_receipts + .iter() + .map(|r| r.used_gas.as_u32()) + .sum(); U256::from(cumulative_gas) }, gas_used: Some(receipt.used_gas), @@ -966,12 +984,18 @@ impl EthApiT for EthApi where let mut pre_receipts_log_index = None; if cumulative_receipts.len() > 0 { cumulative_receipts.truncate(cumulative_receipts.len() - 1); - pre_receipts_log_index = Some(cumulative_receipts.iter().map(|r| { - r.logs.len() as u32 - }).sum::()); + pre_receipts_log_index = Some( + cumulative_receipts + .iter() + .map(|r| r.logs.len() as u32) + .sum::(), + ); } - receipt.logs.iter().enumerate().map(|(i, log)| { - Log { + receipt + .logs + .iter() + .enumerate() + .map(|(i, log)| Log { address: log.address, topics: log.topics.clone(), data: Bytes(log.data.clone()), @@ -980,17 +1004,17 @@ impl EthApiT for EthApi where transaction_hash: Some(hash), transaction_index: Some(status.transaction_index.into()), log_index: Some(U256::from( - (pre_receipts_log_index.unwrap_or(0)) + i as u32 + (pre_receipts_log_index.unwrap_or(0)) + i as u32, )), transaction_log_index: Some(U256::from(i)), removed: false, - } - }).collect() + }) + .collect() }, status_code: Some(U64::from(receipt.state_root.to_low_u64_be())), logs_bloom: receipt.logs_bloom, state_root: None, - })) + })); } _ => Ok(None), } @@ -1014,7 +1038,8 @@ impl EthApiT for EthApi where let params = FilteredParams::new(Some(filter.clone())); if let Some(hash) = filter.block_hash { - let id = match self.load_hash(hash) + let id = match self + .load_hash(hash) .map_err(|err| internal_err(format!("{:?}", err)))? { Some(hash) => hash, @@ -1033,19 +1058,17 @@ impl EthApiT for EthApi where blocks_and_statuses.push((block, statuses)); } } else { - let mut current_number = filter.to_block + let mut current_number = filter + .to_block .and_then(|v| v.to_min_block_num()) .map(|s| s.unique_saturated_into()) - .unwrap_or( - self.client.info().best_number - ); + .unwrap_or(self.client.info().best_number); - let from_number = filter.from_block + let from_number = filter + .from_block .and_then(|v| v.to_min_block_num()) .map(|s| s.unique_saturated_into()) - .unwrap_or( - self.client.info().best_number - ); + .unwrap_or(self.client.info().best_number); while current_number >= from_number { let id = BlockId::Number(current_number); @@ -1057,7 +1080,7 @@ impl EthApiT for EthApi where } if current_number == Zero::zero() { - break + break; } else { current_number = current_number.saturating_sub(One::one()); } @@ -1066,9 +1089,8 @@ impl EthApiT for EthApi where for (block, statuses) in blocks_and_statuses { let mut block_log_index: u32 = 0; - let block_hash = H256::from_slice( - Keccak256::digest(&rlp::encode(&block.header)).as_slice() - ); + let block_hash = + H256::from_slice(Keccak256::digest(&rlp::encode(&block.header)).as_slice()); for status in statuses.iter() { let logs = status.logs.clone(); let mut transaction_log_index: u32 = 0; @@ -1087,13 +1109,9 @@ impl EthApiT for EthApi where removed: false, }; let mut add: bool = false; - if let ( - Some(VariadicValue::Single(_)), - Some(VariadicValue::Multiple(_)) - ) = ( - filter.address.clone(), - filter.topics.clone(), - ) { + if let (Some(VariadicValue::Single(_)), Some(VariadicValue::Multiple(_))) = + (filter.address.clone(), filter.topics.clone()) + { if !params.filter_address(&log) && params.filter_topics(&log) { add = true; } diff --git a/node/standalone/src/chain_spec.rs b/node/standalone/src/chain_spec.rs index e7207aadaa..ed4b6742a7 100644 --- a/node/standalone/src/chain_spec.rs +++ b/node/standalone/src/chain_spec.rs @@ -14,14 +14,14 @@ // You should have received a copy of the GNU General Public License // along with Moonbeam. If not, see . -use sp_core::{Pair, Public}; use moonbeam_runtime::{ - AccountId, AuraConfig, BalancesConfig, EVMConfig, EthereumConfig, GenesisConfig, GrandpaConfig, - SudoConfig, SystemConfig, WASM_BINARY, EthereumChainIdConfig, + AccountId, AuraConfig, BalancesConfig, EVMConfig, EthereumChainIdConfig, EthereumConfig, + GenesisConfig, GrandpaConfig, SudoConfig, SystemConfig, WASM_BINARY, }; +use sc_service::ChainType; use sp_consensus_aura::sr25519::AuthorityId as AuraId; +use sp_core::{Pair, Public}; use sp_finality_grandpa::AuthorityId as GrandpaId; -use sc_service::ChainType; use std::collections::BTreeMap; use std::str::FromStr; @@ -40,10 +40,7 @@ pub fn get_from_seed(seed: &str) -> ::Pu /// Generate an Aura authority key. pub fn authority_keys_from_seed(s: &str) -> (AuraId, GrandpaId) { - ( - get_from_seed::(s), - get_from_seed::(s), - ) + (get_from_seed::(s), get_from_seed::(s)) } pub fn development_config() -> Result { @@ -55,21 +52,19 @@ pub fn development_config() -> Result { // ID "dev", ChainType::Development, - move || testnet_genesis( - wasm_binary, - // Initial PoA authorities - vec![ - authority_keys_from_seed("Alice"), - ], - // Sudo account - AccountId::from_str("6Be02d1d3665660d22FF9624b7BE0551ee1Ac91b").unwrap(), - // Pre-funded accounts - vec![ + move || { + testnet_genesis( + wasm_binary, + // Initial PoA authorities + vec![authority_keys_from_seed("Alice")], + // Sudo account AccountId::from_str("6Be02d1d3665660d22FF9624b7BE0551ee1Ac91b").unwrap(), - ], - true, - 1281, // ChainId - ), + // Pre-funded accounts + vec![AccountId::from_str("6Be02d1d3665660d22FF9624b7BE0551ee1Ac91b").unwrap()], + true, + 1281, // ChainId + ) + }, // Bootnodes vec![], // Telemetry @@ -77,12 +72,7 @@ pub fn development_config() -> Result { // Protocol ID None, // Properties - Some( - serde_json::from_str( - "{\"tokenDecimals\": 18}" - ) - .expect("Provided valid json map") - ), + Some(serde_json::from_str("{\"tokenDecimals\": 18}").expect("Provided valid json map")), // Extensions None, )) @@ -97,22 +87,22 @@ pub fn local_testnet_config() -> Result { // 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 - AccountId::from_str("6Be02d1d3665660d22FF9624b7BE0551ee1Ac91b").unwrap(), - // Pre-funded accounts - vec![ + move || { + testnet_genesis( + wasm_binary, + // Initial PoA authorities + vec![ + authority_keys_from_seed("Alice"), + authority_keys_from_seed("Bob"), + ], + // Sudo account AccountId::from_str("6Be02d1d3665660d22FF9624b7BE0551ee1Ac91b").unwrap(), - ], - true, - 1281, // ChainId - ), + // Pre-funded accounts + vec![AccountId::from_str("6Be02d1d3665660d22FF9624b7BE0551ee1Ac91b").unwrap()], + true, + 1281, // ChainId + ) + }, // Bootnodes vec![], // Telemetry @@ -120,12 +110,7 @@ pub fn local_testnet_config() -> Result { // Protocol ID None, // Properties - Some( - serde_json::from_str( - "{\"tokenDecimals\": 18}" - ) - .expect("Provided valid json map") - ), + Some(serde_json::from_str("{\"tokenDecimals\": 18}").expect("Provided valid json map")), // Extensions None, )) @@ -148,19 +133,26 @@ fn testnet_genesis( }), pallet_balances: Some(BalancesConfig { // Configure endowed accounts with initial balance of 1 << 80. - balances: endowed_accounts.iter().cloned().map(|k|(k, 1 << 80)).collect(), + balances: endowed_accounts + .iter() + .cloned() + .map(|k| (k, 1 << 80)) + .collect(), }), pallet_aura: Some(AuraConfig { authorities: initial_authorities.iter().map(|x| (x.0.clone())).collect(), }), pallet_grandpa: Some(GrandpaConfig { - authorities: initial_authorities.iter().map(|x| (x.1.clone(), 1)).collect(), + authorities: initial_authorities + .iter() + .map(|x| (x.1.clone(), 1)) + .collect(), }), pallet_sudo: Some(SudoConfig { // Assign network admin rights. key: root_key, }), - pallet_ethereum_chain_id: Some(EthereumChainIdConfig{chain_id}), + pallet_ethereum_chain_id: Some(EthereumChainIdConfig { chain_id }), pallet_evm: Some(EVMConfig { accounts: BTreeMap::new(), }), diff --git a/node/standalone/src/command.rs b/node/standalone/src/command.rs index 60cee67da1..11db052b5d 100644 --- a/node/standalone/src/command.rs +++ b/node/standalone/src/command.rs @@ -17,9 +17,9 @@ use crate::chain_spec; use crate::cli::{Cli, Subcommand}; use crate::service; -use sc_cli::{SubstrateCli, RuntimeVersion, Role, ChainSpec}; -use sc_service::PartialComponents; use crate::service::new_partial; +use sc_cli::{ChainSpec, Role, RuntimeVersion, SubstrateCli}; +use sc_service::PartialComponents; impl SubstrateCli for Cli { fn impl_name() -> String { @@ -69,60 +69,75 @@ pub fn run() -> sc_cli::Result<()> { 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, ..} - = new_partial(&config, cli.run.manual_seal)?; + let PartialComponents { + client, + task_manager, + import_queue, + .. + } = new_partial(&config, cli.run.manual_seal)?; Ok((cmd.run(client, import_queue), task_manager)) }) - }, + } Some(Subcommand::ExportBlocks(cmd)) => { let runner = cli.create_runner(cmd)?; runner.async_run(|config| { - let PartialComponents { client, task_manager, ..} - = new_partial(&config, cli.run.manual_seal)?; + let PartialComponents { + client, + task_manager, + .. + } = new_partial(&config, cli.run.manual_seal)?; Ok((cmd.run(client, config.database), task_manager)) }) - }, + } Some(Subcommand::ExportState(cmd)) => { let runner = cli.create_runner(cmd)?; runner.async_run(|config| { - let PartialComponents { client, task_manager, ..} - = new_partial(&config, cli.run.manual_seal)?; + let PartialComponents { + client, + task_manager, + .. + } = new_partial(&config, cli.run.manual_seal)?; Ok((cmd.run(client, config.chain_spec), task_manager)) }) - }, + } Some(Subcommand::ImportBlocks(cmd)) => { let runner = cli.create_runner(cmd)?; runner.async_run(|config| { - let PartialComponents { client, task_manager, import_queue, ..} - = new_partial(&config, cli.run.manual_seal)?; + let PartialComponents { + client, + task_manager, + import_queue, + .. + } = new_partial(&config, cli.run.manual_seal)?; 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, ..} - = new_partial(&config, cli.run.manual_seal)?; + let PartialComponents { + client, + task_manager, + backend, + .. + } = new_partial(&config, cli.run.manual_seal)?; Ok((cmd.run(client, backend), task_manager)) }) - }, + } None => { let runner = cli.create_runner(&cli.run.base)?; runner.run_node_until_exit(|config| async move { match config.role { Role::Light => service::new_light(config), - _ => service::new_full( - config, - cli.run.manual_seal, - ), + _ => service::new_full(config, cli.run.manual_seal), } }) } diff --git a/node/standalone/src/mock_timestamp.rs b/node/standalone/src/mock_timestamp.rs index 62e7f615a5..7588356295 100644 --- a/node/standalone/src/mock_timestamp.rs +++ b/node/standalone/src/mock_timestamp.rs @@ -24,14 +24,13 @@ // This code was taken from https://github.com/paritytech/frontier/pull/170 // When moonbeam updates to a Frontier version that includes that PR, we should re-evaluate // whether it makes sense to keep this here. - use sp_inherents::{InherentData, InherentIdentifier, ProvideInherentData}; use sp_timestamp::InherentError; use std::cell::RefCell; use moonbeam_runtime::MINIMUM_PERIOD; -const SLOT_DURATION : u64 = MINIMUM_PERIOD * 2; +const SLOT_DURATION: u64 = MINIMUM_PERIOD * 2; /// Provide a mock duration starting at 0 in millisecond for timestamp inherent. /// Each call will increment timestamp by slot_duration making Aura think time has passed. diff --git a/node/standalone/src/service.rs b/node/standalone/src/service.rs index 3883a70a7a..886d033860 100644 --- a/node/standalone/src/service.rs +++ b/node/standalone/src/service.rs @@ -16,21 +16,19 @@ //! Service and ServiceFactory implementation. Specialized wrapper over substrate service. -use std::sync::Arc; -use std::time::Duration; -use sc_client_api::{ExecutorProvider, RemoteBackend}; -use sc_consensus_manual_seal::{self as manual_seal}; +use crate::mock_timestamp::MockTimestampInherentDataProvider; use frontier_consensus::FrontierBlockImport; use moonbeam_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_manual_seal::{self as manual_seal}; use sc_executor::native_executor_instance; pub use sc_executor::NativeExecutor; -use sp_consensus_aura::sr25519::{AuthorityPair as AuraPair}; -use sc_finality_grandpa::{ - GrandpaBlockImport, SharedVoterState, -}; -use crate::mock_timestamp::MockTimestampInherentDataProvider; +use sc_finality_grandpa::{GrandpaBlockImport, SharedVoterState}; +use sc_service::{error::Error as ServiceError, Configuration, TaskManager}; +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!( @@ -53,20 +51,27 @@ pub enum ConsensusResult { GrandpaBlockImport, FullClient, >, - AuraPair + AuraPair, >, - sc_finality_grandpa::LinkHalf + sc_finality_grandpa::LinkHalf, ), - ManualSeal(FrontierBlockImport, FullClient>) + ManualSeal(FrontierBlockImport, FullClient>), } -pub fn new_partial(config: &Configuration, manual_seal: bool) -> Result< +pub fn new_partial( + config: &Configuration, + manual_seal: bool, +) -> Result< sc_service::PartialComponents< - FullClient, FullBackend, FullSelectChain, + FullClient, + FullBackend, + FullSelectChain, sp_consensus::import_queue::BasicQueue>, sc_transaction_pool::FullPool, ConsensusResult, ->, ServiceError> { + >, + ServiceError, +> { let inherent_data_providers = sp_inherents::InherentDataProviders::new(); let (client, backend, keystore_container, task_manager) = @@ -88,11 +93,7 @@ pub fn new_partial(config: &Configuration, manual_seal: bool) -> Result< .map_err(Into::into) .map_err(sp_consensus::error::Error::InherentData)?; - let frontier_block_import = FrontierBlockImport::new( - client.clone(), - client.clone(), - true, - ); + let frontier_block_import = FrontierBlockImport::new(client.clone(), client.clone(), true); let import_queue = sc_consensus_manual_seal::import_queue( Box::new(frontier_block_import.clone()), @@ -101,24 +102,30 @@ pub fn new_partial(config: &Configuration, manual_seal: bool) -> Result< ); return Ok(sc_service::PartialComponents { - client, backend, task_manager, import_queue, keystore_container, select_chain, transaction_pool, + client, + backend, + task_manager, + import_queue, + keystore_container, + select_chain, + transaction_pool, inherent_data_providers, - other: ConsensusResult::ManualSeal(frontier_block_import) - }) + other: ConsensusResult::ManualSeal(frontier_block_import), + }); } let (grandpa_block_import, grandpa_link) = sc_finality_grandpa::block_import( - client.clone(), &(client.clone() as Arc<_>), select_chain.clone(), + client.clone(), + &(client.clone() as Arc<_>), + select_chain.clone(), )?; - let frontier_block_import = FrontierBlockImport::new( - grandpa_block_import.clone(), - client.clone(), - true - ); + let frontier_block_import = + FrontierBlockImport::new(grandpa_block_import.clone(), client.clone(), true); let aura_block_import = sc_consensus_aura::AuraBlockImport::<_, _, _, AuraPair>::new( - frontier_block_import, client.clone(), + frontier_block_import, + client.clone(), ); let import_queue = sc_consensus_aura::import_queue::<_, _, _, AuraPair, _, _>( @@ -133,21 +140,30 @@ pub fn new_partial(config: &Configuration, manual_seal: bool) -> Result< )?; Ok(sc_service::PartialComponents { - client, backend, task_manager, import_queue, keystore_container, select_chain, - transaction_pool, inherent_data_providers, - other: ConsensusResult::Aura(aura_block_import, grandpa_link) + client, + backend, + task_manager, + import_queue, + keystore_container, + select_chain, + transaction_pool, + inherent_data_providers, + other: ConsensusResult::Aura(aura_block_import, grandpa_link), }) } /// Builds a new service for a full client. -pub fn new_full( - config: Configuration, - manual_seal: bool, -) -> Result { +pub fn new_full(config: Configuration, manual_seal: bool) -> Result { let sc_service::PartialComponents { - client, backend, mut task_manager, import_queue, keystore_container, select_chain, - transaction_pool, inherent_data_providers, - other: consensus_result + client, + backend, + mut task_manager, + import_queue, + keystore_container, + select_chain, + transaction_pool, + inherent_data_providers, + other: consensus_result, } = new_partial(&config, manual_seal)?; let (network, network_status_sinks, system_rpc_tx, network_starter) = match consensus_result { @@ -161,27 +177,28 @@ pub fn new_full( on_demand: None, block_announce_validator_builder: None, })? - }, - ConsensusResult::Aura(_, _) => { - 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, - })? } + ConsensusResult::Aura(_, _) => 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, + })?, }; - // Channel for the rpc handler to communicate with the authorship task. let (command_sink, commands_stream) = futures::channel::mpsc::channel(1000); if config.offchain_worker.enabled { sc_service::build_offchain_workers( - &config, backend.clone(), task_manager.spawn_handle(), client.clone(), network.clone(), + &config, + backend.clone(), + task_manager.spawn_handle(), + client.clone(), + network.clone(), ); } @@ -194,9 +211,8 @@ pub fn new_full( let prometheus_registry = config.prometheus_registry().cloned(); let telemetry_connection_sinks = sc_service::TelemetryConnectionSinks::default(); let is_authority = role.is_authority(); - let subscription_task_executor = sc_rpc::SubscriptionTaskExecutor::new( - task_manager.spawn_handle() - ); + let subscription_task_executor = + sc_rpc::SubscriptionTaskExecutor::new(task_manager.spawn_handle()); let rpc_extensions_builder = { let client = client.clone(); @@ -209,12 +225,9 @@ pub fn new_full( deny_unsafe, is_authority, network: network.clone(), - command_sink: Some(command_sink.clone()) + command_sink: Some(command_sink.clone()), }; - moonbeam_rpc::create_full( - deps, - subscription_task_executor.clone() - ) + moonbeam_rpc::create_full(deps, subscription_task_executor.clone()) }) }; @@ -228,7 +241,10 @@ pub fn new_full( rpc_extensions_builder: rpc_extensions_builder, on_demand: None, remote_blockchain: None, - backend, network_status_sinks, system_rpc_tx, config, + backend, + network_status_sinks, + system_rpc_tx, + config, })?; match consensus_result { @@ -242,8 +258,8 @@ pub fn new_full( ); // Background authorship future - let authorship_future = manual_seal::run_manual_seal( - manual_seal::ManualSealParams { + let authorship_future = + manual_seal::run_manual_seal(manual_seal::ManualSealParams { block_import, env, client, @@ -252,17 +268,15 @@ pub fn new_full( select_chain, consensus_data_provider: None, inherent_data_providers, - } - ); + }); // we spawn the future on a background thread managed by service. - task_manager.spawn_essential_handle().spawn_blocking( - "manual-seal", - authorship_future, - ); + task_manager + .spawn_essential_handle() + .spawn_blocking("manual-seal", authorship_future); } log::info!("Manual Seal Ready"); - }, + } ConsensusResult::Aura(aura_block_import, grandpa_link) => { if role.is_authority() { let proposer = sc_basic_authorship::ProposerFactory::new( @@ -290,7 +304,9 @@ pub fn new_full( // 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); + 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. @@ -330,7 +346,7 @@ pub fn new_full( // 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)? + sc_finality_grandpa::run_grandpa_voter(grandpa_config)?, ); } } @@ -395,7 +411,11 @@ pub fn new_light(config: Configuration) -> Result { if config.offchain_worker.enabled { sc_service::build_offchain_workers( - &config, backend.clone(), task_manager.spawn_handle(), client.clone(), network.clone(), + &config, + backend.clone(), + task_manager.spawn_handle(), + client.clone(), + network.clone(), ); } diff --git a/pallets/ethereum-chain-id/src/lib.rs b/pallets/ethereum-chain-id/src/lib.rs index 73fce14cb0..be20787a55 100644 --- a/pallets/ethereum-chain-id/src/lib.rs +++ b/pallets/ethereum-chain-id/src/lib.rs @@ -20,11 +20,10 @@ use frame_support::{decl_module, decl_storage, traits::Get}; - /// Configuration trait of this pallet. pub trait Config: frame_system::Config {} -impl Get for Module { +impl Get for Module { fn get() -> u64 { Self::chain_id() } diff --git a/pallets/parachain-info/src/lib.rs b/pallets/parachain-info/src/lib.rs index 7747d31345..4b540a3df5 100644 --- a/pallets/parachain-info/src/lib.rs +++ b/pallets/parachain-info/src/lib.rs @@ -25,7 +25,7 @@ use cumulus_primitives::ParaId; /// Configuration trait of this pallet. pub trait Config: frame_system::Config {} -impl Get for Module { +impl Get for Module { fn get() -> ParaId { Self::parachain_id() } diff --git a/runtime/Cargo.toml b/runtime/Cargo.toml index 1450df0b5f..8ba542afb1 100644 --- a/runtime/Cargo.toml +++ b/runtime/Cargo.toml @@ -7,6 +7,9 @@ version = '0.1.0' authors = ["PureStake"] edition = '2018' +[dev-dependencies] +rusty-hook = "^0.11.2" + [dependencies] serde = { version = "1.0.101", default-features = false, optional = true, features = ["derive"] } codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false, features = ["derive"] } diff --git a/runtime/account/src/lib.rs b/runtime/account/src/lib.rs index 275a428389..07c9f9d810 100644 --- a/runtime/account/src/lib.rs +++ b/runtime/account/src/lib.rs @@ -20,12 +20,12 @@ #![cfg_attr(not(feature = "std"), no_std)] -use sp_core::{H160, H256, ecdsa}; use codec::{Decode, Encode}; use sha3::{Digest, Keccak256}; +use sp_core::{ecdsa, H160, H256}; #[cfg(feature = "std")] -pub use serde::{Serialize, Deserialize, de::DeserializeOwned}; +pub use serde::{de::DeserializeOwned, Deserialize, Serialize}; #[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] #[derive(Eq, PartialEq, Clone, Encode, Decode, sp_core::RuntimeDebug)] @@ -39,27 +39,22 @@ impl From for EthereumSignature { impl sp_runtime::traits::Verify for EthereumSignature { type Signer = EthereumSigner; - fn verify>( - &self, - mut msg: L, - signer: &H160 - ) -> bool { + fn verify>(&self, mut msg: L, signer: &H160) -> bool { let mut m = [0u8; 32]; m.copy_from_slice(Keccak256::digest(msg.get()).as_slice()); match sp_io::crypto::secp256k1_ecdsa_recover(self.0.as_ref(), &m) { Ok(pubkey) => { // TODO This conversion could use a comment. Why H256 first, then H160? - H160::from(H256::from_slice(Keccak256::digest(&pubkey).as_slice())) == - *signer - }, + H160::from(H256::from_slice(Keccak256::digest(&pubkey).as_slice())) == *signer + } Err(sp_io::EcdsaVerifyError::BadRS) => { log::error!(target: "evm", "Error recovering: Incorrect value of R or S"); false - }, + } Err(sp_io::EcdsaVerifyError::BadV) => { log::error!(target: "evm", "Error recovering: Incorrect value of V"); false - }, + } Err(sp_io::EcdsaVerifyError::BadSignature) => { log::error!(target: "evm", "Error recovering: Invalid signature"); false @@ -68,11 +63,10 @@ impl sp_runtime::traits::Verify for EthereumSignature { } } - /// Public key for an Ethereum / H160 compatible account #[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Encode, Decode, sp_core::RuntimeDebug)] #[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] -pub struct EthereumSigner ([u8; 20]); +pub struct EthereumSigner([u8; 20]); impl sp_runtime::traits::IdentifyAccount for EthereumSigner { type AccountId = H160; @@ -87,7 +81,6 @@ impl From<[u8; 20]> for EthereumSigner { } } - impl From for EthereumSigner { fn from(x: ecdsa::Public) -> Self { let mut m = [0u8; 20]; diff --git a/runtime/account/src/signer.rs b/runtime/account/src/signer.rs new file mode 100644 index 0000000000..5b54dc6cc2 --- /dev/null +++ b/runtime/account/src/signer.rs @@ -0,0 +1,113 @@ +// Copyright 2019-2020 PureStake Inc. +// This file is part of Moonbeam. + +// Moonbeam is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Moonbeam is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Moonbeam. If not, see . + +//! The Ethereum Signature implementation. +//! +//! It includes the Verify and IdentifyAccount traits for the AccountId20 + +use codec::{Decode, Encode}; +use sha3::{Digest, Keccak256}; +use sp_core::{ecdsa, ed25519, sr25519, RuntimeDebug, H160, H256}; + +#[cfg(feature = "std")] +pub use serde::{de::DeserializeOwned, Deserialize, Serialize}; + +#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] +#[derive(Eq, PartialEq, Clone, Encode, Decode, sp_core::RuntimeDebug)] +pub struct EthereumSignature(ecdsa::Signature); + +impl From for EthereumSignature { + fn from(x: ecdsa::Signature) -> Self { + EthereumSignature(x) + } +} + +#[cfg_attr(feature = "std", derive(Serialize, Deserialize))] +#[derive(Eq, PartialEq, Clone, Encode, Decode, RuntimeDebug)] +pub enum MultiSignature { + Ed25519(ed25519::Signature), + Sr25519(sr25519::Signature), + Ecdsa(EthereumSignature), +} + +impl From for MultiSignature { + fn from(x: EthereumSignature) -> Self { + MultiSignature::Ecdsa(x) + } +} + +impl sp_runtime::traits::Verify for MultiSignature { + type Signer = EthereumSigner; + fn verify>(&self, mut msg: L, signer: &H160) -> bool { + match (self, signer) { + (MultiSignature::Ecdsa(ref sig), who) => { + let mut m = [0u8; 32]; + m.copy_from_slice(Keccak256::digest(msg.get()).as_slice()); + match sp_io::crypto::secp256k1_ecdsa_recover(sig.0.as_ref(), &m) { + Ok(pubkey) => { + H160::from(H256::from_slice(Keccak256::digest(&pubkey).as_slice())) == *who + } + Err(sp_io::EcdsaVerifyError::BadRS) => { + log::error!(target: "evm", "Error recovering: Incorrect value of R or S"); + false + } + Err(sp_io::EcdsaVerifyError::BadV) => { + log::error!(target: "evm", "Error recovering: Incorrect value of V"); + false + } + Err(sp_io::EcdsaVerifyError::BadSignature) => { + log::error!(target: "evm", "Error recovering: Invalid signature"); + false + } + } + } + _ => false, + } + } +} + +/// Public key for any known crypto algorithm. +#[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Encode, Decode, sp_core::RuntimeDebug)] +#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] +pub struct EthereumSigner([u8; 20]); + +impl sp_runtime::traits::IdentifyAccount for EthereumSigner { + type AccountId = H160; + fn into_account(self) -> H160 { + self.0.into() + } +} + +impl From<[u8; 20]> for EthereumSigner { + fn from(x: [u8; 20]) -> Self { + EthereumSigner(x) + } +} + +impl From for EthereumSigner { + fn from(x: ecdsa::Public) -> Self { + let mut m = [0u8; 20]; + m.copy_from_slice(&x.as_ref()[13..33]); + EthereumSigner(m) + } +} + +#[cfg(feature = "std")] +impl std::fmt::Display for EthereumSigner { + fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result { + write!(fmt, "ethereum signature: {:?}", H160::from_slice(&self.0)) + } +} diff --git a/runtime/precompiles/src/lib.rs b/runtime/precompiles/src/lib.rs index ab999915f5..f780590930 100644 --- a/runtime/precompiles/src/lib.rs +++ b/runtime/precompiles/src/lib.rs @@ -16,12 +16,12 @@ #![cfg_attr(not(feature = "std"), no_std)] -use sp_std::prelude::*; use pallet_evm::LinearCostPrecompile; -use pallet_evm_precompile_simple::{ECRecover, Sha256, Ripemd160, Identity}; +use pallet_evm_precompile_simple::{ECRecover, Identity, Ripemd160, Sha256}; +use sp_std::prelude::*; // use pallet_evm_precompile_bn128::{Bn128Add, Bn128Mul, Bn128Pairing}; -use pallet_evm_precompile_modexp::Modexp; use pallet_evm_precompile_dispatch::Dispatch; +use pallet_evm_precompile_modexp::Modexp; /// An example of implementing a simple precompile. /// prepends "deadbeef" to any data provided @@ -35,13 +35,13 @@ impl LinearCostPrecompile for DeadbeefPrecompiled { input: &[u8], _: usize, ) -> core::result::Result<(pallet_evm::ExitSucceed, Vec), pallet_evm::ExitError> { - log::info!("Calling deadbeef precompiled contract"); - let mut result_vec: Vec = rustc_hex::FromHex::from_hex("deadbeef") - .map_err(|_| pallet_evm::ExitError::Other( - sp_std::borrow::Cow::Borrowed("unexpected deadbeef conversion") - ))?; + let mut result_vec: Vec = rustc_hex::FromHex::from_hex("deadbeef").map_err(|_| { + pallet_evm::ExitError::Other(sp_std::borrow::Cow::Borrowed( + "unexpected deadbeef conversion", + )) + })?; result_vec.extend(input.to_vec()); Ok((pallet_evm::ExitSucceed::Returned, result_vec)) @@ -55,8 +55,7 @@ impl LinearCostPrecompile for DeadbeefPrecompiled { /// /// TODO I had trouble getting the BN precompiles to compile. /// Also, Why are the BN precompiles in geth called bn256*, but in Frontier they are called Bn128* -pub type MoonbeamPrecompiles = -( +pub type MoonbeamPrecompiles = ( ECRecover, Sha256, Ripemd160, diff --git a/runtime/src/lib.rs b/runtime/src/lib.rs index 55534a665e..38eaea9b29 100644 --- a/runtime/src/lib.rs +++ b/runtime/src/lib.rs @@ -33,10 +33,10 @@ #[cfg(feature = "std")] include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); -#[cfg(feature = "standalone")] -mod standalone; #[cfg(not(feature = "standalone"))] mod parachain; +#[cfg(feature = "standalone")] +mod standalone; #[cfg(feature = "standalone")] use standalone::*; @@ -44,15 +44,15 @@ use standalone::*; // use parachain::*; use codec::{Decode, Encode}; +use frontier_rpc_primitives::TransactionStatus; use sp_api::impl_runtime_apis; -use sp_core::{OpaqueMetadata, H160, U256, H256}; +use sp_core::{OpaqueMetadata, H160, H256, U256}; use sp_runtime::{ create_runtime_str, generic, impl_opaque_keys, - traits::{BlakeTwo256, Block as BlockT, IdentityLookup, Saturating, IdentifyAccount, Verify}, + traits::{BlakeTwo256, Block as BlockT, IdentifyAccount, IdentityLookup, Saturating, Verify}, transaction_validity::{TransactionSource, TransactionValidity}, ApplyExtrinsicResult, }; -use frontier_rpc_primitives::TransactionStatus; use sp_std::{marker::PhantomData, prelude::*}; #[cfg(feature = "std")] use sp_version::NativeVersion; @@ -61,15 +61,12 @@ use sp_version::RuntimeVersion; pub use frame_support::{ construct_runtime, parameter_types, traits::{FindAuthor, Get, Randomness}, - weights::{ - constants::WEIGHT_PER_SECOND, - IdentityFee, Weight - }, + weights::{constants::WEIGHT_PER_SECOND, IdentityFee, Weight}, ConsensusEngineId, StorageValue, }; use pallet_evm::{ - Account as EVMAccount, IdentityAddressMapping, EnsureAddressSame, - EnsureAddressNever, FeeCalculator, Runner + Account as EVMAccount, EnsureAddressNever, EnsureAddressSame, FeeCalculator, + IdentityAddressMapping, Runner, }; use pallet_transaction_payment::CurrencyAdapter; @@ -264,7 +261,7 @@ pub struct TransactionConverter; impl frontier_rpc_primitives::ConvertTransaction for TransactionConverter { fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic { UncheckedExtrinsic::new_unsigned( - pallet_ethereum::Call::::transact(transaction).into() + pallet_ethereum::Call::::transact(transaction).into(), ) } } @@ -470,7 +467,7 @@ impl_runtime_apis! { gas_limit.low_u32(), gas_price, nonce, - config.as_ref().unwrap_or(::config()), + config.as_ref().unwrap_or_else(|| ::config()), ).map_err(|err| err.into()) } @@ -491,6 +488,7 @@ impl_runtime_apis! { None }; + #[allow(clippy::or_fun_call)] // suggestion not helpful here ::Runner::create( from, data, diff --git a/runtime/src/parachain.rs b/runtime/src/parachain.rs index 2dc54d2c03..6c33151f08 100644 --- a/runtime/src/parachain.rs +++ b/runtime/src/parachain.rs @@ -17,7 +17,6 @@ #[macro_export] macro_rules! runtime_parachain { () => { - /// This runtime version. pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("moonbase-alphanet"), diff --git a/runtime/src/standalone.rs b/runtime/src/standalone.rs index 476ddf8098..84866c2dae 100644 --- a/runtime/src/standalone.rs +++ b/runtime/src/standalone.rs @@ -14,15 +14,13 @@ // You should have received a copy of the GNU General Public License // along with Moonbeam. If not, see . +pub use frame_support::traits::KeyOwnerProofSystem; pub use pallet_grandpa::{ - fg_primitives, - AuthorityId as GrandpaId, - AuthorityList as GrandpaAuthorityList + fg_primitives, AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList, }; pub use sp_consensus_aura::sr25519::AuthorityId as AuraId; pub use sp_core::crypto::{KeyTypeId, Public}; pub use sp_runtime::traits::NumberFor; -pub use frame_support::traits::KeyOwnerProofSystem; #[macro_export] macro_rules! runtime_standalone { diff --git a/scripts/init.sh b/scripts/init.sh index 1bfe5a449c..791232afd9 100755 --- a/scripts/init.sh +++ b/scripts/init.sh @@ -5,6 +5,8 @@ source $HOME/.cargo/env echo "*** Initializing WASM build environment" +# TODO: 'rust-toolchain' is allowed to be a TOML file: +# https://github.com/rust-lang/rustup/blob/master/doc/src/overrides.md#the-toolchain-file RUST_NIGHTLY_VERSION=$(cat rust-toolchain) if [ -z ${WASM_BUILD_TOOLCHAIN+x} ]; then @@ -16,4 +18,6 @@ if [ -z $CI_PROJECT_NAME ] ; then rustup update stable fi +rustup component add clippy + rustup target add wasm32-unknown-unknown --toolchain $WASM_BUILD_TOOLCHAIN