diff --git a/Cargo.toml b/Cargo.toml index 8a619eedf1..2419534d80 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,5 @@ [workspace] -members = [".", "client", "proc-macro", "test-node"] +members = [".", "client", "proc-macro"] [package] name = "substrate-subxt" diff --git a/client/Cargo.toml b/client/Cargo.toml index ef5cd73e6a..a60d376822 100644 --- a/client/Cargo.toml +++ b/client/Cargo.toml @@ -33,4 +33,3 @@ async-std = { version = "1.8.0", features = ["attributes"] } env_logger = "0.8.2" substrate-subxt = { path = "..", features = ["client"] } tempdir = "0.3.7" -test-node = { path = "../test-node" } diff --git a/client/gen-chain-spec.sh b/client/gen-chain-spec.sh deleted file mode 100755 index 14c19000fe..0000000000 --- a/client/gen-chain-spec.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/bin/sh -NODE_TEMPLATE=../target/release/test-node -$NODE_TEMPLATE purge-chain --dev -$NODE_TEMPLATE build-spec --dev > dev-chain.json -rm -rf /tmp/subxt-light-client diff --git a/client/purge-chain.sh b/client/purge-chain.sh deleted file mode 100755 index 4202e349ef..0000000000 --- a/client/purge-chain.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/sh -NODE_TEMPLATE=../target/release/test-node -$NODE_TEMPLATE purge-chain --chain=dev-chain.json -rm -rf /tmp/subxt-light-client diff --git a/client/run.sh b/client/run.sh deleted file mode 100755 index 6f67c6875c..0000000000 --- a/client/run.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/sh -NODE_TEMPLATE=../target/release/test-node -$NODE_TEMPLATE --chain=dev-chain.json --alice diff --git a/test-node/Cargo.toml b/test-node/Cargo.toml deleted file mode 100644 index b80d7c3bea..0000000000 --- a/test-node/Cargo.toml +++ /dev/null @@ -1,42 +0,0 @@ -[package] -name = "test-node" -version = "2.0.0" -authors = ["Anonymous"] -description = "Substrate Node template" -edition = "2018" -license = "Unlicense" -build = "build.rs" -homepage = "https://substrate.dev" -repository = "https://github.com/paritytech/substrate/" - -[package.metadata.docs.rs] -targets = ["x86_64-unknown-linux-gnu"] - -[dependencies] -futures = "0.3.9" -log = "0.4.13" -structopt = "0.3.21" -parking_lot = "0.11.1" - -sc-cli = { version = "0.9.0", features = ["wasmtime"] } -sp-core = "3.0.0" -sc-executor = { version = "0.9.0", features = ["wasmtime"] } -sc-service = { version = "0.9.0", features = ["wasmtime"] } -sp-inherents = "3.0.0" -sc-transaction-pool = "3.0.0" -sp-transaction-pool = "3.0.0" -sc-network = "0.9.0" -sc-consensus-aura = "0.9.0" -sp-consensus-aura = "0.9.0" -sp-consensus = "0.9.0" -sc-consensus = "0.9.0" -sc-finality-grandpa = "0.9.0" -sp-finality-grandpa = "3.0.0" -sc-client-api = "3.0.0" -sp-runtime = "3.0.0" -sc-basic-authorship = "0.9.0" - -test-node-runtime = { path = "runtime" } - -[build-dependencies] -substrate-build-script-utils = "3.0.0" diff --git a/test-node/build.rs b/test-node/build.rs deleted file mode 100644 index 8b089d6124..0000000000 --- a/test-node/build.rs +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2019-2021 Parity Technologies (UK) Ltd. -// This file is part of substrate-subxt. -// -// subxt 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. -// -// subxt 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 substrate-subxt. If not, see . - -use substrate_build_script_utils::{ - generate_cargo_keys, - rerun_if_git_head_changed, -}; - -fn main() { - generate_cargo_keys(); - - rerun_if_git_head_changed(); -} diff --git a/test-node/runtime/Cargo.toml b/test-node/runtime/Cargo.toml deleted file mode 100644 index 595397f705..0000000000 --- a/test-node/runtime/Cargo.toml +++ /dev/null @@ -1,72 +0,0 @@ -[package] -name = "test-node-runtime" -version = "2.0.0" -authors = ["Anonymous"] -edition = "2018" -license = "Unlicense" -homepage = "https://substrate.dev" -repository = "https://github.com/paritytech/substrate/" - -[package.metadata.docs.rs] -targets = ["x86_64-unknown-linux-gnu"] - -[dependencies] -codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] } - -frame-executive = { version = "3.0.0", default-features = false } -frame-support = { version = "3.0.0", default-features = false } -frame-system = { version = "3.0.0", default-features = false } -pallet-aura = { version = "3.0.0", default-features = false } -pallet-balances = { version = "3.0.0", default-features = false } -pallet-grandpa = { version = "3.0.0", default-features = false } -pallet-randomness-collective-flip = { version = "3.0.0", default-features = false } -pallet-staking = { version = "3.0.0", default-features = false } -pallet-sudo = { version = "3.0.0", default-features = false } -pallet-timestamp = { version = "3.0.0", default-features = false } -pallet-transaction-payment = { version = "3.0.0", default-features = false } -serde = { version = "1.0.116", optional = true, features = ["derive"] } -sp-api = { version = "3.0.0", default-features = false } -sp-block-builder = { version = "3.0.0", default-features = false } -sp-consensus-aura = { version = "0.9.0", default-features = false } -sp-core = { version = "3.0.0", default-features = false } -sp-inherents = { version = "3.0.0", default-features = false } -sp-io = { version = "3.0.0", default-features = false } -sp-offchain = { version = "3.0.0", default-features = false } -sp-runtime = { version = "3.0.0", default-features = false } -sp-session = { version = "3.0.0", default-features = false } -sp-std = { version = "3.0.0", default-features = false } -sp-transaction-pool = { version = "3.0.0", default-features = false } -sp-version = { version = "3.0.0", default-features = false } - -[build-dependencies] -substrate-wasm-builder = "3.0.0" - -[features] -default = ["std"] -std = [ - "codec/std", - "frame-executive/std", - "frame-support/std", - "frame-system/std", - "pallet-aura/std", - "pallet-balances/std", - "pallet-grandpa/std", - "pallet-randomness-collective-flip/std", - "pallet-staking/std", - "pallet-sudo/std", - "pallet-timestamp/std", - "pallet-transaction-payment/std", - "serde", - "sp-api/std", - "sp-block-builder/std", - "sp-consensus-aura/std", - "sp-core/std", - "sp-inherents/std", - "sp-io/std", - "sp-offchain/std", - "sp-runtime/std", - "sp-session/std", - "sp-std/std", - "sp-transaction-pool/std", - "sp-version/std", -] diff --git a/test-node/runtime/build.rs b/test-node/runtime/build.rs deleted file mode 100644 index d17020801c..0000000000 --- a/test-node/runtime/build.rs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2019-2021 Parity Technologies (UK) Ltd. -// This file is part of substrate-subxt. -// -// subxt 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. -// -// subxt 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 substrate-subxt. If not, see . - -use substrate_wasm_builder::WasmBuilder; - -fn main() { - WasmBuilder::new() - .with_current_project() - .export_heap_base() - .import_memory() - .build() -} diff --git a/test-node/runtime/src/lib.rs b/test-node/runtime/src/lib.rs deleted file mode 100644 index 5d2d809248..0000000000 --- a/test-node/runtime/src/lib.rs +++ /dev/null @@ -1,458 +0,0 @@ -// Copyright 2019-2021 Parity Technologies (UK) Ltd. -// This file is part of substrate-subxt. -// -// subxt 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. -// -// subxt 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 substrate-subxt. If not, see . - -//! The Substrate Node Template runtime. This can be compiled with `#[no_std]`, ready for Wasm. - -#![cfg_attr(not(feature = "std"), no_std)] -// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256. -#![recursion_limit = "256"] -#![allow(clippy::large_enum_variant)] - -// Make the WASM binary available. -#[cfg(feature = "std")] -include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); - -use pallet_grandpa::{ - fg_primitives, - AuthorityId as GrandpaId, - AuthorityList as GrandpaAuthorityList, -}; -use sp_api::impl_runtime_apis; -use sp_consensus_aura::sr25519::AuthorityId as AuraId; -use sp_core::{ - crypto::KeyTypeId, - OpaqueMetadata, -}; -use sp_runtime::{ - create_runtime_str, - generic, - impl_opaque_keys, - traits::{ - AccountIdLookup, - BlakeTwo256, - Block as BlockT, - IdentifyAccount, - NumberFor, - Verify, - }, - transaction_validity::{ - TransactionSource, - TransactionValidity, - }, - ApplyExtrinsicResult, - MultiSignature, -}; -use sp_std::prelude::*; -#[cfg(feature = "std")] -use sp_version::NativeVersion; -use sp_version::RuntimeVersion; - -// A few exports that help ease life for downstream crates. -pub use frame_support::{ - construct_runtime, - parameter_types, - traits::{ - KeyOwnerProofSystem, - Randomness, - }, - weights::{ - constants::{ - BlockExecutionWeight, - ExtrinsicBaseWeight, - RocksDbWeight, - WEIGHT_PER_SECOND, - }, - IdentityFee, - Weight, - }, - StorageValue, -}; -pub use pallet_balances::Call as BalancesCall; -pub use pallet_timestamp::Call as TimestampCall; -#[cfg(any(feature = "std", test))] -pub use sp_runtime::BuildStorage; -pub use sp_runtime::{ - Perbill, - Permill, -}; - -/// An index to a block. -pub type BlockNumber = u32; - -/// Alias to 512-bit hash when used in the context of a transaction signature on the chain. -pub type Signature = MultiSignature; - -/// Some way of identifying an account on the chain. We intentionally make it equivalent -/// to the public key of our transaction signing scheme. -pub type AccountId = <::Signer as IdentifyAccount>::AccountId; - -/// The type for looking up accounts. We don't expect more than 4 billion of them, but you -/// never know... -pub type AccountIndex = u32; - -/// Balance of an account. -pub type Balance = u128; - -/// Index of a transaction in the chain. -pub type Index = u32; - -/// A hash of some data used by the chain. -pub type Hash = sp_core::H256; - -/// Digest item type. -pub type DigestItem = generic::DigestItem; - -/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know -/// the specifics of the runtime. They can then be made to be agnostic over specific formats -/// of data like extrinsics, allowing for them to continue syncing the network through upgrades -/// to even the core data structures. -pub mod opaque { - use super::*; - - pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic; - - /// Opaque block header type. - pub type Header = generic::Header; - /// Opaque block type. - pub type Block = generic::Block; - /// Opaque block identifier type. - pub type BlockId = generic::BlockId; - - impl_opaque_keys! { - pub struct SessionKeys { - pub aura: Aura, - pub grandpa: Grandpa, - } - } -} - -/// This runtime version. -pub const VERSION: RuntimeVersion = RuntimeVersion { - spec_name: create_runtime_str!("subxt-test-node"), - impl_name: create_runtime_str!("subxt-test-node"), - authoring_version: 1, - spec_version: 1, - impl_version: 1, - apis: RUNTIME_API_VERSIONS, - transaction_version: 1, -}; - -pub const MILLISECS_PER_BLOCK: u64 = 6000; - -pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK; - -// These time units are defined in number of blocks. -pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber); -pub const HOURS: BlockNumber = MINUTES * 60; -pub const DAYS: BlockNumber = HOURS * 24; - -/// The version information used to identify this runtime when compiled natively. -#[cfg(feature = "std")] -pub fn native_version() -> NativeVersion { - NativeVersion { - runtime_version: VERSION, - can_author_with: Default::default(), - } -} - -const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75); - -parameter_types! { - pub const Version: RuntimeVersion = VERSION; - pub const BlockHashCount: BlockNumber = 2400; - /// We allow for 2 seconds of compute with a 6 second average block time. - pub BlockWeights: frame_system::limits::BlockWeights = frame_system::limits::BlockWeights - ::with_sensible_defaults(2 * WEIGHT_PER_SECOND, NORMAL_DISPATCH_RATIO); - pub BlockLength: frame_system::limits::BlockLength = frame_system::limits::BlockLength - ::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO); - pub const SS58Prefix: u8 = 42; -} - -impl frame_system::Config for Runtime { - /// The basic call filter to use in dispatchable. - type BaseCallFilter = (); - /// Block & extrinsics weights: base values and limits. - type BlockWeights = BlockWeights; - /// The maximum length of a block (in bytes). - type BlockLength = BlockLength; - /// The identifier used to distinguish between accounts. - type AccountId = AccountId; - /// The aggregated dispatch type that is available for extrinsics. - type Call = Call; - /// The lookup mechanism to get account ID from whatever is passed in dispatchers. - type Lookup = AccountIdLookup; - /// The index type for storing how many extrinsics an account has signed. - type Index = Index; - /// The index type for blocks. - type BlockNumber = BlockNumber; - /// The type for hashing blocks and tries. - type Hash = Hash; - /// The hashing algorithm used. - type Hashing = BlakeTwo256; - /// The header type. - type Header = generic::Header; - /// The ubiquitous event type. - type Event = Event; - /// The ubiquitous origin type. - type Origin = Origin; - /// Maximum number of block number to block hash mappings to keep (oldest pruned first). - type BlockHashCount = BlockHashCount; - /// The weight of database operations that the runtime can invoke. - type DbWeight = RocksDbWeight; - /// Version of the runtime. - type Version = Version; - /// Converts a module to the index of the module in `construct_runtime!`. - /// - /// This type is being generated by `construct_runtime!`. - type PalletInfo = PalletInfo; - /// What to do if a new account is created. - type OnNewAccount = (); - /// What to do if an account is fully reaped from the system. - type OnKilledAccount = (); - /// The data to be stored in an account. - type AccountData = pallet_balances::AccountData; - /// Weight information for the extrinsics of this pallet. - type SystemWeightInfo = (); - /// This is used as an identifier of the chain. 42 is the generic substrate prefix. - type SS58Prefix = SS58Prefix; -} - -impl pallet_aura::Config for Runtime { - type AuthorityId = AuraId; -} - -impl pallet_grandpa::Config for Runtime { - type Event = Event; - type Call = Call; - - type KeyOwnerProofSystem = (); - - type KeyOwnerProof = - >::Proof; - - type KeyOwnerIdentification = >::IdentificationTuple; - - type HandleEquivocation = (); - type WeightInfo = (); -} - -parameter_types! { - pub const MinimumPeriod: u64 = SLOT_DURATION / 2; -} - -impl pallet_timestamp::Config for Runtime { - /// A timestamp: milliseconds since the unix epoch. - type Moment = u64; - type OnTimestampSet = Aura; - type MinimumPeriod = MinimumPeriod; - type WeightInfo = (); -} - -parameter_types! { - pub const ExistentialDeposit: u128 = 500; -} - -impl pallet_balances::Config for Runtime { - /// The type for recording an account's balance. - type Balance = Balance; - /// The ubiquitous event type. - type Event = Event; - type DustRemoval = (); - type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; - type WeightInfo = (); - type MaxLocks = (); -} - -parameter_types! { - pub const TransactionByteFee: Balance = 1; -} - -impl pallet_transaction_payment::Config for Runtime { - type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter; - type TransactionByteFee = TransactionByteFee; - type WeightToFee = IdentityFee; - type FeeMultiplierUpdate = (); -} - -impl pallet_sudo::Config for Runtime { - type Event = Event; - type Call = Call; -} - -construct_runtime!( - pub enum Runtime where - Block = Block, - NodeBlock = opaque::Block, - UncheckedExtrinsic = UncheckedExtrinsic - { - System: frame_system::{Module, Call, Config, Storage, Event}, - RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Module, Call, Storage}, - Timestamp: pallet_timestamp::{Module, Call, Storage, Inherent}, - Aura: pallet_aura::{Module, Config}, - Grandpa: pallet_grandpa::{Module, Call, Storage, Config, Event}, - Balances: pallet_balances::{Module, Call, Storage, Config, Event}, - TransactionPayment: pallet_transaction_payment::{Module, Storage}, - Sudo: pallet_sudo::{Module, Call, Config, Storage, Event}, - } -); - -/// The address format for describing accounts. -pub type Address = sp_runtime::MultiAddress; -/// Block header type as expected by this runtime. -pub type Header = generic::Header; -/// Block type as expected by this runtime. -pub type Block = generic::Block; -/// A Block signed with a Justification -pub type SignedBlock = generic::SignedBlock; -/// BlockId type as expected by this runtime. -pub type BlockId = generic::BlockId; -/// The SignedExtension to the basic transaction logic. -pub type SignedExtra = ( - frame_system::CheckSpecVersion, - frame_system::CheckTxVersion, - frame_system::CheckGenesis, - frame_system::CheckEra, - frame_system::CheckNonce, - frame_system::CheckWeight, - pallet_transaction_payment::ChargeTransactionPayment, -); -/// Unchecked extrinsic type as expected by this runtime. -pub type UncheckedExtrinsic = - generic::UncheckedExtrinsic; -/// Extrinsic type that has already been checked. -pub type CheckedExtrinsic = generic::CheckedExtrinsic; -/// Executive: handles dispatch to the various modules. -pub type Executive = frame_executive::Executive< - Runtime, - Block, - frame_system::ChainContext, - Runtime, - AllModules, ->; - -impl_runtime_apis! { - impl sp_api::Core for Runtime { - fn version() -> RuntimeVersion { - VERSION - } - - fn execute_block(block: Block) { - Executive::execute_block(block) - } - - fn initialize_block(header: &::Header) { - Executive::initialize_block(header) - } - } - - impl sp_api::Metadata for Runtime { - fn metadata() -> OpaqueMetadata { - Runtime::metadata().into() - } - } - - impl sp_block_builder::BlockBuilder for Runtime { - fn apply_extrinsic(extrinsic: ::Extrinsic) -> ApplyExtrinsicResult { - Executive::apply_extrinsic(extrinsic) - } - - fn finalize_block() -> ::Header { - Executive::finalize_block() - } - - fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<::Extrinsic> { - data.create_extrinsics() - } - - fn check_inherents( - block: Block, - data: sp_inherents::InherentData, - ) -> sp_inherents::CheckInherentsResult { - data.check_extrinsics(&block) - } - - fn random_seed() -> ::Hash { - RandomnessCollectiveFlip::random_seed() - } - } - - impl sp_transaction_pool::runtime_api::TaggedTransactionQueue for Runtime { - fn validate_transaction( - source: TransactionSource, - tx: ::Extrinsic, - ) -> TransactionValidity { - Executive::validate_transaction(source, tx) - } - } - - impl sp_offchain::OffchainWorkerApi for Runtime { - fn offchain_worker(header: &::Header) { - Executive::offchain_worker(header) - } - } - - impl sp_consensus_aura::AuraApi for Runtime { - fn slot_duration() -> u64 { - Aura::slot_duration() - } - - fn authorities() -> Vec { - Aura::authorities() - } - } - - impl sp_session::SessionKeys for Runtime { - fn generate_session_keys(seed: Option>) -> Vec { - opaque::SessionKeys::generate(seed) - } - - fn decode_session_keys( - encoded: Vec, - ) -> Option, KeyTypeId)>> { - opaque::SessionKeys::decode_into_raw_public_keys(&encoded) - } - } - - impl fg_primitives::GrandpaApi for Runtime { - fn grandpa_authorities() -> GrandpaAuthorityList { - Grandpa::grandpa_authorities() - } - - fn submit_report_equivocation_unsigned_extrinsic( - _equivocation_proof: fg_primitives::EquivocationProof< - ::Hash, - NumberFor, - >, - _key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof, - ) -> Option<()> { - None - } - - fn generate_key_ownership_proof( - _set_id: fg_primitives::SetId, - _authority_id: GrandpaId, - ) -> Option { - // NOTE: this is the only implementation possible since we've - // defined our key owner proof type as a bottom type (i.e. a type - // with no values). - None - } - } -} diff --git a/test-node/src/chain_spec.rs b/test-node/src/chain_spec.rs deleted file mode 100644 index 685c044f04..0000000000 --- a/test-node/src/chain_spec.rs +++ /dev/null @@ -1,196 +0,0 @@ -// Copyright 2019-2021 Parity Technologies (UK) Ltd. -// This file is part of substrate-subxt. -// -// subxt 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. -// -// subxt 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 substrate-subxt. If not, see . - -use sc_service::ChainType; -use sp_consensus_aura::sr25519::AuthorityId as AuraId; -use sp_core::{ - sr25519, - Pair, - Public, -}; -use sp_finality_grandpa::AuthorityId as GrandpaId; -use sp_runtime::traits::{ - IdentifyAccount, - Verify, -}; -use test_node_runtime::{ - AccountId, - AuraConfig, - BalancesConfig, - GenesisConfig, - GrandpaConfig, - Signature, - SudoConfig, - SystemConfig, - WASM_BINARY, -}; - -// The URL for the telemetry server. -// const STAGING_TELEMETRY_URL: &str = "wss://telemetry.polkadot.io/submit/"; - -/// Specialized `ChainSpec`. This is a specialization of the general Substrate ChainSpec type. -pub type ChainSpec = sc_service::GenericChainSpec; - -/// Generate a crypto pair from seed. -pub fn get_from_seed(seed: &str) -> ::Public { - TPublic::Pair::from_string(&format!("//{}", seed), None) - .expect("static values are valid; qed") - .public() -} - -type AccountPublic = ::Signer; - -/// Generate an account ID from seed. -pub fn get_account_id_from_seed(seed: &str) -> AccountId -where - AccountPublic: From<::Public>, -{ - AccountPublic::from(get_from_seed::(seed)).into_account() -} - -/// Generate an Aura authority key. -pub fn authority_keys_from_seed(s: &str) -> (AuraId, GrandpaId) { - (get_from_seed::(s), get_from_seed::(s)) -} - -pub fn development_config() -> Result { - let wasm_binary = - WASM_BINARY.ok_or_else(|| "Development wasm not available".to_string())?; - - Ok(ChainSpec::from_genesis( - // Name - "Development", - // ID - "dev", - ChainType::Development, - move || { - testnet_genesis( - wasm_binary, - // Initial PoA authorities - vec![authority_keys_from_seed("Alice")], - // Sudo account - get_account_id_from_seed::("Alice"), - // Pre-funded accounts - vec![ - get_account_id_from_seed::("Alice"), - get_account_id_from_seed::("Bob"), - get_account_id_from_seed::("Alice//stash"), - get_account_id_from_seed::("Bob//stash"), - ], - true, - ) - }, - // Bootnodes - vec![], - // Telemetry - None, - // Protocol ID - None, - // Properties - None, - // Extensions - Default::default(), - )) -} - -pub fn local_testnet_config() -> Result { - let wasm_binary = - WASM_BINARY.ok_or_else(|| "Development wasm not available".to_string())?; - - Ok(ChainSpec::from_genesis( - // Name - "Local Testnet", - // ID - "local_testnet", - ChainType::Local, - move || { - testnet_genesis( - wasm_binary, - // Initial PoA authorities - vec![ - authority_keys_from_seed("Alice"), - authority_keys_from_seed("Bob"), - ], - // Sudo account - get_account_id_from_seed::("Alice"), - // Pre-funded accounts - vec![ - get_account_id_from_seed::("Alice"), - get_account_id_from_seed::("Bob"), - get_account_id_from_seed::("Charlie"), - get_account_id_from_seed::("Dave"), - get_account_id_from_seed::("Eve"), - get_account_id_from_seed::("Ferdie"), - get_account_id_from_seed::("Alice//stash"), - get_account_id_from_seed::("Bob//stash"), - get_account_id_from_seed::("Charlie//stash"), - get_account_id_from_seed::("Dave//stash"), - get_account_id_from_seed::("Eve//stash"), - get_account_id_from_seed::("Ferdie//stash"), - ], - true, - ) - }, - // Bootnodes - vec![], - // Telemetry - None, - // Protocol ID - None, - // Properties - None, - // Extensions - None, - )) -} - -/// Configure initial storage state for FRAME modules. -fn testnet_genesis( - wasm_binary: &[u8], - initial_authorities: Vec<(AuraId, GrandpaId)>, - root_key: AccountId, - endowed_accounts: Vec, - _enable_println: bool, -) -> GenesisConfig { - GenesisConfig { - frame_system: Some(SystemConfig { - // Add Wasm runtime to storage. - code: wasm_binary.to_vec(), - changes_trie_config: Default::default(), - }), - pallet_balances: Some(BalancesConfig { - // Configure endowed accounts with initial balance of 1 << 60. - balances: endowed_accounts - .iter() - .cloned() - .map(|k| (k, 1 << 60)) - .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(), - }), - pallet_sudo: Some(SudoConfig { - // Assign network admin rights. - key: root_key, - }), - } -} diff --git a/test-node/src/cli.rs b/test-node/src/cli.rs deleted file mode 100644 index 3cb95a47c3..0000000000 --- a/test-node/src/cli.rs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2019-2021 Parity Technologies (UK) Ltd. -// This file is part of substrate-subxt. -// -// subxt 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. -// -// subxt 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 substrate-subxt. If not, see . - -use sc_cli::{ - BuildSpecCmd, - PurgeChainCmd, - RunCmd, -}; -use structopt::StructOpt; - -#[derive(Debug, StructOpt)] -pub enum Subcommand { - /// Build a spec.json file, outputs to stdout. - BuildSpec(BuildSpecCmd), - /// Remove the whole chain data. - PurgeChain(PurgeChainCmd), -} - -#[derive(Debug, StructOpt)] -pub struct Cli { - #[structopt(subcommand)] - pub subcommand: Option, - - #[structopt(flatten)] - pub run: RunCmd, -} diff --git a/test-node/src/command.rs b/test-node/src/command.rs deleted file mode 100644 index 1a8a5935e7..0000000000 --- a/test-node/src/command.rs +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright 2019-2021 Parity Technologies (UK) Ltd. -// This file is part of substrate-subxt. -// -// subxt 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. -// -// subxt 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 substrate-subxt. If not, see . - -use crate::{ - chain_spec, - cli::{ - Cli, - Subcommand, - }, - service, -}; -use sc_cli::{ - ChainSpec, - Role, - RuntimeVersion, - SubstrateCli, -}; - -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 native_runtime_version(_: &Box) -> &'static RuntimeVersion { - &test_node_runtime::VERSION - } -} - -/// Parse and run command line arguments -pub fn run() -> sc_cli::Result<()> { - let cli = Cli::from_args(); - - match &cli.subcommand { - Some(Subcommand::BuildSpec(cmd)) => { - let runner = cli.create_runner(cmd)?; - runner.sync_run(|config| cmd.run(config.chain_spec, config.network)) - } - Some(Subcommand::PurgeChain(cmd)) => { - let runner = cli.create_runner(cmd)?; - runner.sync_run(|config| cmd.run(config.database)) - } - None => { - let runner = cli.create_runner(&cli.run)?; - runner.run_node_until_exit(|config| { - async move { - match config.role { - Role::Light => service::new_light(config), - _ => service::new_full(config), - } - .map(|service| service.0) - .map_err(sc_cli::Error::Service) - } - }) - } - } -} diff --git a/test-node/src/lib.rs b/test-node/src/lib.rs deleted file mode 100644 index 89a0782732..0000000000 --- a/test-node/src/lib.rs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2019-2021 Parity Technologies (UK) Ltd. -// This file is part of substrate-subxt. -// -// subxt 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. -// -// subxt 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 substrate-subxt. If not, see . - -pub mod chain_spec; -pub mod service; diff --git a/test-node/src/main.rs b/test-node/src/main.rs deleted file mode 100644 index 7cce1a795d..0000000000 --- a/test-node/src/main.rs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2019-2021 Parity Technologies (UK) Ltd. -// This file is part of substrate-subxt. -// -// subxt 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. -// -// subxt 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 substrate-subxt. If not, see . - -//! Substrate Node Template CLI library. -#![warn(missing_docs)] - -mod chain_spec; -#[macro_use] -mod service; -mod cli; -mod command; - -fn main() -> sc_cli::Result<()> { - command::run() -} diff --git a/test-node/src/service.rs b/test-node/src/service.rs deleted file mode 100644 index 863d775203..0000000000 --- a/test-node/src/service.rs +++ /dev/null @@ -1,368 +0,0 @@ -// Copyright 2019-2021 Parity Technologies (UK) Ltd. -// This file is part of substrate-subxt. -// -// subxt 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. -// -// subxt 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 substrate-subxt. If not, see . - -//! Service and ServiceFactory implementation. Specialized wrapper over substrate service. -#![allow(clippy::type_complexity)] - -use sc_client_api::{ - ExecutorProvider, - RemoteBackend, -}; -use sc_executor::native_executor_instance; -pub use sc_executor::NativeExecutor; -use sc_finality_grandpa::SharedVoterState; -use sc_service::{ - error::Error as ServiceError, - Configuration, - PartialComponents, - RpcHandlers, - TaskManager, -}; -use sp_consensus_aura::sr25519::AuthorityPair as AuraPair; -use sp_inherents::InherentDataProviders; -use std::{ - sync::Arc, - time::Duration, -}; -use test_node_runtime::{ - self, - opaque::Block, - RuntimeApi, -}; - -// Our native executor instance. -native_executor_instance!( - pub Executor, - test_node_runtime::api::dispatch, - test_node_runtime::native_version, -); - -type FullClient = sc_service::TFullClient; -type FullBackend = sc_service::TFullBackend; -type FullSelectChain = sc_consensus::LongestChain; - -pub fn new_partial( - config: &Configuration, -) -> Result< - sc_service::PartialComponents< - FullClient, - FullBackend, - FullSelectChain, - sp_consensus::DefaultImportQueue, - sc_transaction_pool::FullPool, - ( - sc_consensus_aura::AuraBlockImport< - Block, - FullClient, - sc_finality_grandpa::GrandpaBlockImport< - FullBackend, - Block, - FullClient, - FullSelectChain, - >, - AuraPair, - >, - sc_finality_grandpa::LinkHalf, - ), - >, - ServiceError, -> { - if config.keystore_remote.is_some() { - return Err(ServiceError::Other(format!( - "Remote Keystores are not supported." - ))) - } - let inherent_data_providers = sp_inherents::InherentDataProviders::new(); - - let (client, backend, keystore_container, task_manager) = - sc_service::new_full_parts::(&config)?; - let client = Arc::new(client); - - let select_chain = sc_consensus::LongestChain::new(backend.clone()); - - let transaction_pool = sc_transaction_pool::BasicPool::new_full( - config.transaction_pool.clone(), - config.role.is_authority().into(), - config.prometheus_registry(), - task_manager.spawn_handle(), - client.clone(), - ); - - let (grandpa_block_import, grandpa_link) = sc_finality_grandpa::block_import( - client.clone(), - &(client.clone() as Arc<_>), - select_chain.clone(), - )?; - - let aura_block_import = sc_consensus_aura::AuraBlockImport::<_, _, _, AuraPair>::new( - grandpa_block_import.clone(), - client.clone(), - ); - - let import_queue = sc_consensus_aura::import_queue::<_, _, _, AuraPair, _, _>( - sc_consensus_aura::slot_duration(&*client)?, - aura_block_import.clone(), - Some(Box::new(grandpa_block_import.clone())), - client.clone(), - inherent_data_providers.clone(), - &task_manager.spawn_handle(), - config.prometheus_registry(), - sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()), - )?; - - Ok(sc_service::PartialComponents { - client, - backend, - task_manager, - import_queue, - keystore_container, - select_chain, - transaction_pool, - inherent_data_providers, - other: (aura_block_import, grandpa_link), - }) -} - -/// Builds a new service for a full client. -pub fn new_full( - mut config: Configuration, -) -> Result<(TaskManager, RpcHandlers), ServiceError> { - let PartialComponents { - client, - backend, - mut task_manager, - import_queue, - keystore_container, - select_chain, - transaction_pool, - inherent_data_providers, - other: (block_import, grandpa_link), - } = new_partial(&config)?; - - config - .network - .extra_sets - .push(sc_finality_grandpa::grandpa_peers_set_config()); - - let (network, network_status_sinks, system_rpc_tx, network_starter) = - sc_service::build_network(sc_service::BuildNetworkParams { - config: &config, - client: client.clone(), - transaction_pool: transaction_pool.clone(), - spawn_handle: task_manager.spawn_handle(), - import_queue, - on_demand: None, - block_announce_validator_builder: None, - })?; - - if config.offchain_worker.enabled { - sc_service::build_offchain_workers( - &config, - backend.clone(), - task_manager.spawn_handle(), - client.clone(), - network.clone(), - ); - } - - let role = config.role.clone(); - let force_authoring = config.force_authoring; - let backoff_authoring_blocks: Option<()> = None; - let name = config.network.node_name.clone(); - let enable_grandpa = !config.disable_grandpa; - let prometheus_registry = config.prometheus_registry().cloned(); - - let rpc_extensions_builder = Box::new(|_, _| ()); - - let (rpc_handlers, telemetry_connection_notifier) = - sc_service::spawn_tasks(sc_service::SpawnTasksParams { - network: network.clone(), - client: client.clone(), - keystore: keystore_container.sync_keystore(), - task_manager: &mut task_manager, - transaction_pool: transaction_pool.clone(), - rpc_extensions_builder, - on_demand: None, - remote_blockchain: None, - backend, - network_status_sinks, - system_rpc_tx, - config, - })?; - - if role.is_authority() { - let proposer = sc_basic_authorship::ProposerFactory::new( - task_manager.spawn_handle(), - client.clone(), - transaction_pool, - prometheus_registry.as_ref(), - ); - - let can_author_with = - sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()); - - let aura = sc_consensus_aura::start_aura::<_, _, _, _, _, AuraPair, _, _, _, _>( - sc_consensus_aura::slot_duration(&*client)?, - client.clone(), - select_chain, - block_import, - proposer, - network.clone(), - inherent_data_providers.clone(), - force_authoring, - backoff_authoring_blocks, - keystore_container.sync_keystore(), - can_author_with, - )?; - - // the AURA authoring task is considered essential, i.e. if it - // fails we take down the service with it. - task_manager - .spawn_essential_handle() - .spawn_blocking("aura", aura); - } - - // if the node isn't actively participating in consensus then it doesn't - // need a keystore, regardless of which protocol we use below. - let keystore = if role.is_authority() { - Some(keystore_container.sync_keystore()) - } else { - None - }; - - let grandpa_config = sc_finality_grandpa::Config { - gossip_duration: Duration::from_millis(333), - justification_period: 512, - name: Some(name), - observer_enabled: false, - keystore, - is_authority: role.is_network_authority(), - }; - - if enable_grandpa { - // start the full GRANDPA voter - // NOTE: non-authorities could run the GRANDPA observer protocol, but at - // this point the full voter should provide better guarantees of block - // and vote data availability than the observer. The observer has not - // been tested extensively yet and having most nodes in a network run it - // could lead to finality stalls. - let grandpa_config = sc_finality_grandpa::GrandpaParams { - config: grandpa_config, - link: grandpa_link, - network, - telemetry_on_connect: telemetry_connection_notifier - .map(|x| x.on_connect_stream()), - voting_rule: sc_finality_grandpa::VotingRulesBuilder::default().build(), - prometheus_registry, - shared_voter_state: SharedVoterState::empty(), - }; - - // the GRANDPA voter task is considered infallible, i.e. - // if it fails we take down the service with it. - task_manager.spawn_essential_handle().spawn_blocking( - "grandpa-voter", - sc_finality_grandpa::run_grandpa_voter(grandpa_config)?, - ); - } - - network_starter.start_network(); - Ok((task_manager, rpc_handlers)) -} - -/// Builds a new service for a light client. -pub fn new_light( - mut config: Configuration, -) -> Result<(TaskManager, RpcHandlers), ServiceError> { - let (client, backend, keystore_container, mut task_manager, on_demand) = - sc_service::new_light_parts::(&config)?; - - config - .network - .extra_sets - .push(sc_finality_grandpa::grandpa_peers_set_config()); - - let select_chain = sc_consensus::LongestChain::new(backend.clone()); - - let transaction_pool = Arc::new(sc_transaction_pool::BasicPool::new_light( - config.transaction_pool.clone(), - config.prometheus_registry(), - task_manager.spawn_handle(), - client.clone(), - on_demand.clone(), - )); - - let (grandpa_block_import, _) = sc_finality_grandpa::block_import( - client.clone(), - &(client.clone() as Arc<_>), - select_chain.clone(), - )?; - - let aura_block_import = sc_consensus_aura::AuraBlockImport::<_, _, _, AuraPair>::new( - grandpa_block_import.clone(), - client.clone(), - ); - - let import_queue = sc_consensus_aura::import_queue::<_, _, _, AuraPair, _, _>( - sc_consensus_aura::slot_duration(&*client)?, - aura_block_import, - Some(Box::new(grandpa_block_import)), - client.clone(), - InherentDataProviders::new(), - &task_manager.spawn_handle(), - config.prometheus_registry(), - sp_consensus::NeverCanAuthor, - )?; - - let (network, network_status_sinks, system_rpc_tx, network_starter) = - sc_service::build_network(sc_service::BuildNetworkParams { - config: &config, - client: client.clone(), - transaction_pool: transaction_pool.clone(), - spawn_handle: task_manager.spawn_handle(), - import_queue, - on_demand: Some(on_demand.clone()), - block_announce_validator_builder: None, - })?; - - if config.offchain_worker.enabled { - sc_service::build_offchain_workers( - &config, - backend.clone(), - task_manager.spawn_handle(), - client.clone(), - network.clone(), - ); - } - - let rpc_handlers = sc_service::spawn_tasks(sc_service::SpawnTasksParams { - remote_blockchain: Some(backend.remote_blockchain()), - transaction_pool, - task_manager: &mut task_manager, - on_demand: Some(on_demand), - rpc_extensions_builder: Box::new(|_, _| ()), - config, - client, - keystore: keystore_container.sync_keystore(), - backend, - network, - network_status_sinks, - system_rpc_tx, - })?; - - network_starter.start_network(); - - Ok((task_manager, rpc_handlers.0)) -}