From 8fb6f8ef1090798dffc4906b7796c5faef365d8e Mon Sep 17 00:00:00 2001 From: Bryant Eisenbach Date: Fri, 13 Sep 2019 19:56:42 -0400 Subject: [PATCH] clean: Tabs -> Spaces --- build.rs | 24 +- runtime/build.rs | 14 +- runtime/src/lib.rs | 480 ++++++++++++++++++------------------- runtime/src/plasma_cash.rs | 200 ++++++++-------- scripts/init.sh | 2 +- src/chain_spec.rs | 202 ++++++++-------- src/cli.rs | 150 ++++++------ src/main.rs | 26 +- src/service.rs | 380 ++++++++++++++--------------- 9 files changed, 739 insertions(+), 739 deletions(-) diff --git a/build.rs b/build.rs index bab46f5..5fcfe39 100644 --- a/build.rs +++ b/build.rs @@ -5,20 +5,20 @@ use vergen::{ConstantsFlags, generate_cargo_keys}; const ERROR_MSG: &str = "Failed to generate metadata files"; fn main() { - generate_cargo_keys(ConstantsFlags::SHA_SHORT).expect(ERROR_MSG); + generate_cargo_keys(ConstantsFlags::SHA_SHORT).expect(ERROR_MSG); - let mut manifest_dir = PathBuf::from( - env::var("CARGO_MANIFEST_DIR").expect("`CARGO_MANIFEST_DIR` is always set by cargo.") - ); + let mut manifest_dir = PathBuf::from( + env::var("CARGO_MANIFEST_DIR").expect("`CARGO_MANIFEST_DIR` is always set by cargo.") + ); - while manifest_dir.parent().is_some() { - if manifest_dir.join(".git/HEAD").exists() { - println!("cargo:rerun-if-changed={}", manifest_dir.join(".git/HEAD").display()); - return - } + while manifest_dir.parent().is_some() { + if manifest_dir.join(".git/HEAD").exists() { + println!("cargo:rerun-if-changed={}", manifest_dir.join(".git/HEAD").display()); + return + } - manifest_dir.pop(); - } + manifest_dir.pop(); + } - println!("cargo:warning=Could not find `.git/HEAD` from manifest dir!"); + println!("cargo:warning=Could not find `.git/HEAD` from manifest dir!"); } diff --git a/runtime/build.rs b/runtime/build.rs index 1ed109d..c1ec4fa 100644 --- a/runtime/build.rs +++ b/runtime/build.rs @@ -17,11 +17,11 @@ use wasm_builder_runner::{build_current_project_with_rustflags, WasmBuilderSource}; fn main() { - build_current_project_with_rustflags( - "wasm_binary.rs", - WasmBuilderSource::Crates("1.0.5"), - // This instructs LLD to export __heap_base as a global variable, which is used by the - // external memory allocator. - "-Clink-arg=--export=__heap_base", - ); + build_current_project_with_rustflags( + "wasm_binary.rs", + WasmBuilderSource::Crates("1.0.5"), + // This instructs LLD to export __heap_base as a global variable, which is used by the + // external memory allocator. + "-Clink-arg=--export=__heap_base", + ); } diff --git a/runtime/src/lib.rs b/runtime/src/lib.rs index 0745038..0fa0748 100644 --- a/runtime/src/lib.rs +++ b/runtime/src/lib.rs @@ -11,8 +11,8 @@ include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); use rstd::prelude::*; use primitives::{OpaqueMetadata, crypto::key_types}; use sr_primitives::{ - ApplyResult, transaction_validity::TransactionValidity, generic, create_runtime_str, - impl_opaque_keys, AnySignature + ApplyResult, transaction_validity::TransactionValidity, generic, create_runtime_str, + impl_opaque_keys, AnySignature }; use sr_primitives::traits::{NumberFor, BlakeTwo256, Block as BlockT, DigestFor, StaticLookup, Verify, ConvertInto}; use sr_primitives::weights::Weight; @@ -20,8 +20,8 @@ use babe::{AuthorityId as BabeId}; use grandpa::{AuthorityId as GrandpaId, AuthorityWeight as GrandpaWeight}; use grandpa::fg_primitives::{self, ScheduledChange}; use client::{ - block_builder::api::{CheckInherentsResult, InherentData, self as block_builder_api}, - runtime_api as client_api, impl_runtime_apis + block_builder::api::{CheckInherentsResult, InherentData, self as block_builder_api}, + runtime_api as client_api, impl_runtime_apis }; use version::RuntimeVersion; #[cfg(feature = "std")] @@ -68,37 +68,37 @@ mod plasma_cash; /// of data like extrinsics, allowing for them to continue syncing the network through upgrades /// to even the core datastructures. pub mod opaque { - use super::*; - - pub use sr_primitives::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; - - pub type SessionHandlers = (Grandpa, Babe); - - impl_opaque_keys! { - pub struct SessionKeys { - #[id(key_types::GRANDPA)] - pub grandpa: GrandpaId, - #[id(key_types::BABE)] - pub babe: BabeId, - } - } + use super::*; + + pub use sr_primitives::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; + + pub type SessionHandlers = (Grandpa, Babe); + + impl_opaque_keys! { + pub struct SessionKeys { + #[id(key_types::GRANDPA)] + pub grandpa: GrandpaId, + #[id(key_types::BABE)] + pub babe: BabeId, + } + } } /// This runtime version. pub const VERSION: RuntimeVersion = RuntimeVersion { - spec_name: create_runtime_str!("plasma-cash"), - impl_name: create_runtime_str!("plasma-cash"), - authoring_version: 3, - spec_version: 4, - impl_version: 4, - apis: RUNTIME_API_VERSIONS, + spec_name: create_runtime_str!("plasma-cash"), + impl_name: create_runtime_str!("plasma-cash"), + authoring_version: 3, + spec_version: 4, + impl_version: 4, + apis: RUNTIME_API_VERSIONS, }; /// Constants for Babe. @@ -132,144 +132,144 @@ pub const PRIMARY_PROBABILITY: (u64, u64) = (1, 4); /// The version infromation used to identify this runtime when compiled natively. #[cfg(feature = "std")] pub fn native_version() -> NativeVersion { - NativeVersion { - runtime_version: VERSION, - can_author_with: Default::default(), - } + NativeVersion { + runtime_version: VERSION, + can_author_with: Default::default(), + } } parameter_types! { - pub const BlockHashCount: BlockNumber = 250; - pub const MaximumBlockWeight: Weight = 1_000_000; - pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75); - pub const MaximumBlockLength: u32 = 5 * 1024 * 1024; - pub const Version: RuntimeVersion = VERSION; + pub const BlockHashCount: BlockNumber = 250; + pub const MaximumBlockWeight: Weight = 1_000_000; + pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75); + pub const MaximumBlockLength: u32 = 5 * 1024 * 1024; + pub const Version: RuntimeVersion = VERSION; } impl system::Trait for Runtime { - /// 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 = Indices; - /// 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; - /// Update weight (to fee) multiplier per-block. - type WeightMultiplierUpdate = (); - /// The ubiquitous origin type. - type Origin = Origin; - /// Maximum number of block number to block hash mappings to keep (oldest pruned first). - type BlockHashCount = BlockHashCount; - /// Maximum weight of each block. With a default weight system of 1byte == 1weight, 4mb is ok. - type MaximumBlockWeight = MaximumBlockWeight; - /// Maximum size of all encoded transactions (in bytes) that are allowed in one block. - type MaximumBlockLength = MaximumBlockLength; - /// Portion of the block weight that is available to all normal transactions. - type AvailableBlockRatio = AvailableBlockRatio; - type Version = Version; + /// 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 = Indices; + /// 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; + /// Update weight (to fee) multiplier per-block. + type WeightMultiplierUpdate = (); + /// The ubiquitous origin type. + type Origin = Origin; + /// Maximum number of block number to block hash mappings to keep (oldest pruned first). + type BlockHashCount = BlockHashCount; + /// Maximum weight of each block. With a default weight system of 1byte == 1weight, 4mb is ok. + type MaximumBlockWeight = MaximumBlockWeight; + /// Maximum size of all encoded transactions (in bytes) that are allowed in one block. + type MaximumBlockLength = MaximumBlockLength; + /// Portion of the block weight that is available to all normal transactions. + type AvailableBlockRatio = AvailableBlockRatio; + type Version = Version; } parameter_types! { - pub const EpochDuration: u64 = EPOCH_DURATION_IN_BLOCKS as u64; - pub const ExpectedBlockTime: u64 = MILLISECS_PER_BLOCK; + pub const EpochDuration: u64 = EPOCH_DURATION_IN_BLOCKS as u64; + pub const ExpectedBlockTime: u64 = MILLISECS_PER_BLOCK; } impl babe::Trait for Runtime { - type EpochDuration = EpochDuration; - type ExpectedBlockTime = ExpectedBlockTime; + type EpochDuration = EpochDuration; + type ExpectedBlockTime = ExpectedBlockTime; } impl grandpa::Trait for Runtime { - type Event = Event; + type Event = Event; } impl indices::Trait for Runtime { - /// The type for recording indexing into the account enumeration. If this ever overflows, there - /// will be problems! - type AccountIndex = u32; - /// Use the standard means of resolving an index hint from an id. - type ResolveHint = indices::SimpleResolveHint; - /// Determine whether an account is dead. - type IsDeadAccount = Balances; - /// The ubiquitous event type. - type Event = Event; + /// The type for recording indexing into the account enumeration. If this ever overflows, there + /// will be problems! + type AccountIndex = u32; + /// Use the standard means of resolving an index hint from an id. + type ResolveHint = indices::SimpleResolveHint; + /// Determine whether an account is dead. + type IsDeadAccount = Balances; + /// The ubiquitous event type. + type Event = Event; } parameter_types! { - pub const MinimumPeriod: u64 = 5000; + pub const MinimumPeriod: u64 = 5000; } impl timestamp::Trait for Runtime { - /// A timestamp: milliseconds since the unix epoch. - type Moment = u64; - type OnTimestampSet = Babe; - type MinimumPeriod = MinimumPeriod; + /// A timestamp: milliseconds since the unix epoch. + type Moment = u64; + type OnTimestampSet = Babe; + type MinimumPeriod = MinimumPeriod; } parameter_types! { - pub const ExistentialDeposit: u128 = 500; - pub const TransferFee: u128 = 0; - pub const CreationFee: u128 = 0; - pub const TransactionBaseFee: u128 = 0; - pub const TransactionByteFee: u128 = 1; + pub const ExistentialDeposit: u128 = 500; + pub const TransferFee: u128 = 0; + pub const CreationFee: u128 = 0; + pub const TransactionBaseFee: u128 = 0; + pub const TransactionByteFee: u128 = 1; } impl balances::Trait for Runtime { - /// The type for recording an account's balance. - type Balance = Balance; - /// What to do if an account's free balance gets zeroed. - type OnFreeBalanceZero = (); - /// What to do if a new account is created. - type OnNewAccount = Indices; - /// The ubiquitous event type. - type Event = Event; - - type TransactionPayment = (); - type DustRemoval = (); - type TransferPayment = (); - type ExistentialDeposit = ExistentialDeposit; - type TransferFee = TransferFee; - type CreationFee = CreationFee; - type TransactionBaseFee = TransactionBaseFee; - type TransactionByteFee = TransactionByteFee; - type WeightToFee = ConvertInto; + /// The type for recording an account's balance. + type Balance = Balance; + /// What to do if an account's free balance gets zeroed. + type OnFreeBalanceZero = (); + /// What to do if a new account is created. + type OnNewAccount = Indices; + /// The ubiquitous event type. + type Event = Event; + + type TransactionPayment = (); + type DustRemoval = (); + type TransferPayment = (); + type ExistentialDeposit = ExistentialDeposit; + type TransferFee = TransferFee; + type CreationFee = CreationFee; + type TransactionBaseFee = TransactionBaseFee; + type TransactionByteFee = TransactionByteFee; + type WeightToFee = ConvertInto; } impl sudo::Trait for Runtime { - type Event = Event; - type Proposal = Call; + type Event = Event; + type Proposal = Call; } impl plasma_cash::Trait for Runtime { - type Event = Event; + type Event = Event; } construct_runtime!( - pub enum Runtime where - Block = Block, - NodeBlock = opaque::Block, - UncheckedExtrinsic = UncheckedExtrinsic - { - System: system::{Module, Call, Storage, Config, Event}, - Timestamp: timestamp::{Module, Call, Storage, Inherent}, - Babe: babe::{Module, Call, Storage, Config, Inherent(Timestamp)}, - Grandpa: grandpa::{Module, Call, Storage, Config, Event}, - Indices: indices::{default, Config}, - Balances: balances, - Sudo: sudo, - PlasmaCash: plasma_cash::{Module, Call, Storage, Event}, - } + pub enum Runtime where + Block = Block, + NodeBlock = opaque::Block, + UncheckedExtrinsic = UncheckedExtrinsic + { + System: system::{Module, Call, Storage, Config, Event}, + Timestamp: timestamp::{Module, Call, Storage, Inherent}, + Babe: babe::{Module, Call, Storage, Config, Inherent(Timestamp)}, + Grandpa: grandpa::{Module, Call, Storage, Config, Event}, + Indices: indices::{default, Config}, + Balances: balances, + Sudo: sudo, + PlasmaCash: plasma_cash::{Module, Call, Storage, Event}, + } ); /// The address format for describing accounts. @@ -284,12 +284,12 @@ pub type SignedBlock = generic::SignedBlock; pub type BlockId = generic::BlockId; /// The SignedExtension to the basic transaction logic. pub type SignedExtra = ( - system::CheckVersion, - system::CheckGenesis, - system::CheckEra, - system::CheckNonce, - system::CheckWeight, - balances::TakeFees + system::CheckVersion, + system::CheckGenesis, + system::CheckEra, + system::CheckNonce, + system::CheckWeight, + balances::TakeFees ); /// Unchecked extrinsic type as expected by this runtime. pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; @@ -299,108 +299,108 @@ pub type CheckedExtrinsic = generic::CheckedExtrinsic, Runtime, AllModules>; impl_runtime_apis! { - impl client_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 client_api::Metadata for Runtime { - fn metadata() -> OpaqueMetadata { - Runtime::metadata().into() - } - } - - impl block_builder_api::BlockBuilder for Runtime { - fn apply_extrinsic(extrinsic: ::Extrinsic) -> ApplyResult { - Executive::apply_extrinsic(extrinsic) - } - - fn finalize_block() -> ::Header { - Executive::finalize_block() - } - - fn inherent_extrinsics(data: InherentData) -> Vec<::Extrinsic> { - data.create_extrinsics() - } - - fn check_inherents(block: Block, data: InherentData) -> CheckInherentsResult { - data.check_extrinsics(&block) - } - - fn random_seed() -> ::Hash { - System::random_seed() - } - } - - impl client_api::TaggedTransactionQueue for Runtime { - fn validate_transaction(tx: ::Extrinsic) -> TransactionValidity { - Executive::validate_transaction(tx) - } - } - - impl offchain_primitives::OffchainWorkerApi for Runtime { - fn offchain_worker(number: NumberFor) { - Executive::offchain_worker(number) - } - } - - impl fg_primitives::GrandpaApi for Runtime { - fn grandpa_pending_change(digest: &DigestFor) - -> Option>> - { - Grandpa::pending_change(digest) - } - - fn grandpa_forced_change(digest: &DigestFor) - -> Option<(NumberFor, ScheduledChange>)> - { - Grandpa::forced_change(digest) - } - - fn grandpa_authorities() -> Vec<(GrandpaId, GrandpaWeight)> { - Grandpa::grandpa_authorities() - } - } - - impl babe_primitives::BabeApi for Runtime { - fn startup_data() -> babe_primitives::BabeConfiguration { - // The choice of `c` parameter (where `1 - c` represents the - // probability of a slot being empty), is done in accordance to the - // slot duration and expected target block time, for safely - // resisting network delays of maximum two seconds. - // - babe_primitives::BabeConfiguration { - median_required_blocks: 1000, - slot_duration: Babe::slot_duration(), - c: PRIMARY_PROBABILITY, - } - } - - fn epoch() -> babe_primitives::Epoch { - babe_primitives::Epoch { - start_slot: Babe::epoch_start_slot(), - authorities: Babe::authorities(), - epoch_index: Babe::epoch_index(), - randomness: Babe::randomness(), - duration: EpochDuration::get(), - secondary_slots: Babe::secondary_slots().0, - } - } - } - - impl substrate_session::SessionKeys for Runtime { - fn generate_session_keys(seed: Option>) -> Vec { - let seed = seed.as_ref().map(|s| rstd::str::from_utf8(&s).expect("Seed is an utf8 string")); - opaque::SessionKeys::generate(seed) - } - } + impl client_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 client_api::Metadata for Runtime { + fn metadata() -> OpaqueMetadata { + Runtime::metadata().into() + } + } + + impl block_builder_api::BlockBuilder for Runtime { + fn apply_extrinsic(extrinsic: ::Extrinsic) -> ApplyResult { + Executive::apply_extrinsic(extrinsic) + } + + fn finalize_block() -> ::Header { + Executive::finalize_block() + } + + fn inherent_extrinsics(data: InherentData) -> Vec<::Extrinsic> { + data.create_extrinsics() + } + + fn check_inherents(block: Block, data: InherentData) -> CheckInherentsResult { + data.check_extrinsics(&block) + } + + fn random_seed() -> ::Hash { + System::random_seed() + } + } + + impl client_api::TaggedTransactionQueue for Runtime { + fn validate_transaction(tx: ::Extrinsic) -> TransactionValidity { + Executive::validate_transaction(tx) + } + } + + impl offchain_primitives::OffchainWorkerApi for Runtime { + fn offchain_worker(number: NumberFor) { + Executive::offchain_worker(number) + } + } + + impl fg_primitives::GrandpaApi for Runtime { + fn grandpa_pending_change(digest: &DigestFor) + -> Option>> + { + Grandpa::pending_change(digest) + } + + fn grandpa_forced_change(digest: &DigestFor) + -> Option<(NumberFor, ScheduledChange>)> + { + Grandpa::forced_change(digest) + } + + fn grandpa_authorities() -> Vec<(GrandpaId, GrandpaWeight)> { + Grandpa::grandpa_authorities() + } + } + + impl babe_primitives::BabeApi for Runtime { + fn startup_data() -> babe_primitives::BabeConfiguration { + // The choice of `c` parameter (where `1 - c` represents the + // probability of a slot being empty), is done in accordance to the + // slot duration and expected target block time, for safely + // resisting network delays of maximum two seconds. + // + babe_primitives::BabeConfiguration { + median_required_blocks: 1000, + slot_duration: Babe::slot_duration(), + c: PRIMARY_PROBABILITY, + } + } + + fn epoch() -> babe_primitives::Epoch { + babe_primitives::Epoch { + start_slot: Babe::epoch_start_slot(), + authorities: Babe::authorities(), + epoch_index: Babe::epoch_index(), + randomness: Babe::randomness(), + duration: EpochDuration::get(), + secondary_slots: Babe::secondary_slots().0, + } + } + } + + impl substrate_session::SessionKeys for Runtime { + fn generate_session_keys(seed: Option>) -> Vec { + let seed = seed.as_ref().map(|s| rstd::str::from_utf8(&s).expect("Seed is an utf8 string")); + opaque::SessionKeys::generate(seed) + } + } } diff --git a/runtime/src/plasma_cash.rs b/runtime/src/plasma_cash.rs index 1a78bbe..b27757d 100644 --- a/runtime/src/plasma_cash.rs +++ b/runtime/src/plasma_cash.rs @@ -13,121 +13,121 @@ use system::ensure_signed; /// The module's configuration trait. pub trait Trait: system::Trait { - // TODO: Add other types and constants required configure this module. + // TODO: Add other types and constants required configure this module. - /// The overarching event type. - type Event: From> + Into<::Event>; + /// The overarching event type. + type Event: From> + Into<::Event>; } // This module's storage items. decl_storage! { - trait Store for Module as PlasmaCash { - // Just a dummy storage item. - // Here we are declaring a StorageValue, `Something` as a Option - // `get(something)` is the default getter which returns either the stored `u32` or `None` if nothing stored - Something get(something): Option; - } + trait Store for Module as PlasmaCash { + // Just a dummy storage item. + // Here we are declaring a StorageValue, `Something` as a Option + // `get(something)` is the default getter which returns either the stored `u32` or `None` if nothing stored + Something get(something): Option; + } } // The module's dispatchable functions. decl_module! { - /// The module declaration. - pub struct Module for enum Call where origin: T::Origin { - // Initializing events - // this is needed only if you are using events in your module - fn deposit_event() = default; - - // Just a dummy entry point. - // function that can be called by the external world as an extrinsics call - // takes a parameter of the type `AccountId`, stores it and emits an event - pub fn do_something(origin, something: u32) -> Result { - // TODO: You only need this if you want to check it was signed. - let who = ensure_signed(origin)?; - - // TODO: Code to execute when something calls this. - // For example: the following line stores the passed in u32 in the storage - Something::put(something); - - // here we are raising the Something event - Self::deposit_event(RawEvent::SomethingStored(something, who)); - Ok(()) - } - } + /// The module declaration. + pub struct Module for enum Call where origin: T::Origin { + // Initializing events + // this is needed only if you are using events in your module + fn deposit_event() = default; + + // Just a dummy entry point. + // function that can be called by the external world as an extrinsics call + // takes a parameter of the type `AccountId`, stores it and emits an event + pub fn do_something(origin, something: u32) -> Result { + // TODO: You only need this if you want to check it was signed. + let who = ensure_signed(origin)?; + + // TODO: Code to execute when something calls this. + // For example: the following line stores the passed in u32 in the storage + Something::put(something); + + // here we are raising the Something event + Self::deposit_event(RawEvent::SomethingStored(something, who)); + Ok(()) + } + } } decl_event!( - pub enum Event where AccountId = ::AccountId { - // Just a dummy event. - // Event `Something` is declared with a parameter of the type `u32` and `AccountId` - // To emit this event, we call the deposit funtion, from our runtime funtions - SomethingStored(u32, AccountId), - } + pub enum Event where AccountId = ::AccountId { + // Just a dummy event. + // Event `Something` is declared with a parameter of the type `u32` and `AccountId` + // To emit this event, we call the deposit funtion, from our runtime funtions + SomethingStored(u32, AccountId), + } ); /// tests for this module #[cfg(test)] mod tests { - use super::*; - - use runtime_io::with_externalities; - use primitives::{H256, Blake2Hasher}; - use support::{impl_outer_origin, assert_ok, parameter_types}; - use sr_primitives::{traits::{BlakeTwo256, IdentityLookup}, testing::Header}; - use sr_primitives::weights::Weight; - use sr_primitives::Perbill; - - impl_outer_origin! { - pub enum Origin for Test {} - } - - // For testing the module, we construct most of a mock runtime. This means - // first constructing a configuration type (`Test`) which `impl`s each of the - // configuration traits of modules we want to use. - #[derive(Clone, Eq, PartialEq)] - pub struct Test; - parameter_types! { - pub const BlockHashCount: u64 = 250; - pub const MaximumBlockWeight: Weight = 1024; - pub const MaximumBlockLength: u32 = 2 * 1024; - pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75); - } - impl system::Trait for Test { - type Origin = Origin; - type Call = (); - type Index = u64; - type BlockNumber = u64; - type Hash = H256; - type Hashing = BlakeTwo256; - type AccountId = u64; - type Lookup = IdentityLookup; - type Header = Header; - type WeightMultiplierUpdate = (); - type Event = (); - type BlockHashCount = BlockHashCount; - type MaximumBlockWeight = MaximumBlockWeight; - type MaximumBlockLength = MaximumBlockLength; - type AvailableBlockRatio = AvailableBlockRatio; - type Version = (); - } - impl Trait for Test { - type Event = (); - } - type PlasmaCash = Module; - - // This function basically just builds a genesis storage key/value store according to - // our desired mockup. - fn new_test_ext() -> runtime_io::TestExternalities { - system::GenesisConfig::default().build_storage::().unwrap().into() - } - - #[test] - fn it_works_for_default_value() { - with_externalities(&mut new_test_ext(), || { - // Just a dummy test for the dummy funtion `do_something` - // calling the `do_something` function with a value 42 - assert_ok!(PlasmaCash::do_something(Origin::signed(1), 42)); - // asserting that the stored value is equal to what we stored - assert_eq!(PlasmaCash::something(), Some(42)); - }); - } + use super::*; + + use runtime_io::with_externalities; + use primitives::{H256, Blake2Hasher}; + use support::{impl_outer_origin, assert_ok, parameter_types}; + use sr_primitives::{traits::{BlakeTwo256, IdentityLookup}, testing::Header}; + use sr_primitives::weights::Weight; + use sr_primitives::Perbill; + + impl_outer_origin! { + pub enum Origin for Test {} + } + + // For testing the module, we construct most of a mock runtime. This means + // first constructing a configuration type (`Test`) which `impl`s each of the + // configuration traits of modules we want to use. + #[derive(Clone, Eq, PartialEq)] + pub struct Test; + parameter_types! { + pub const BlockHashCount: u64 = 250; + pub const MaximumBlockWeight: Weight = 1024; + pub const MaximumBlockLength: u32 = 2 * 1024; + pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75); + } + impl system::Trait for Test { + type Origin = Origin; + type Call = (); + type Index = u64; + type BlockNumber = u64; + type Hash = H256; + type Hashing = BlakeTwo256; + type AccountId = u64; + type Lookup = IdentityLookup; + type Header = Header; + type WeightMultiplierUpdate = (); + type Event = (); + type BlockHashCount = BlockHashCount; + type MaximumBlockWeight = MaximumBlockWeight; + type MaximumBlockLength = MaximumBlockLength; + type AvailableBlockRatio = AvailableBlockRatio; + type Version = (); + } + impl Trait for Test { + type Event = (); + } + type PlasmaCash = Module; + + // This function basically just builds a genesis storage key/value store according to + // our desired mockup. + fn new_test_ext() -> runtime_io::TestExternalities { + system::GenesisConfig::default().build_storage::().unwrap().into() + } + + #[test] + fn it_works_for_default_value() { + with_externalities(&mut new_test_ext(), || { + // Just a dummy test for the dummy funtion `do_something` + // calling the `do_something` function with a value 42 + assert_ok!(PlasmaCash::do_something(Origin::signed(1), 42)); + // asserting that the stored value is equal to what we stored + assert_eq!(PlasmaCash::something(), Some(42)); + }); + } } diff --git a/scripts/init.sh b/scripts/init.sh index cf5ecf9..60301cb 100755 --- a/scripts/init.sh +++ b/scripts/init.sh @@ -13,4 +13,4 @@ rustup target add wasm32-unknown-unknown --toolchain nightly # Install wasm-gc. It's useful for stripping slimming down wasm binaries. command -v wasm-gc || \ - cargo +nightly install --git https://github.com/alexcrichton/wasm-gc --force + cargo +nightly install --git https://github.com/alexcrichton/wasm-gc --force diff --git a/src/chain_spec.rs b/src/chain_spec.rs index d4f718c..3c9605c 100644 --- a/src/chain_spec.rs +++ b/src/chain_spec.rs @@ -1,7 +1,7 @@ use primitives::{Pair, Public}; use plasma_cash_runtime::{ - AccountId, BabeConfig, BalancesConfig, GenesisConfig, GrandpaConfig, - SudoConfig, IndicesConfig, SystemConfig, WASM_BINARY, + AccountId, BabeConfig, BalancesConfig, GenesisConfig, GrandpaConfig, + SudoConfig, IndicesConfig, SystemConfig, WASM_BINARY, }; use babe_primitives::{AuthorityId as BabeId}; use grandpa_primitives::{AuthorityId as GrandpaId}; @@ -18,118 +18,118 @@ pub type ChainSpec = substrate_service::ChainSpec; /// from a string (`--chain=...`) into a `ChainSpec`. #[derive(Clone, Debug)] pub enum Alternative { - /// Whatever the current runtime is, with just Alice as an auth. - Development, - /// Whatever the current runtime is, with simple Alice/Bob auths. - LocalTestnet, + /// Whatever the current runtime is, with just Alice as an auth. + Development, + /// Whatever the current runtime is, with simple Alice/Bob auths. + LocalTestnet, } /// Helper function to 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() + TPublic::Pair::from_string(&format!("//{}", seed), None) + .expect("static values are valid; qed") + .public() } /// Helper function to generate stash, controller and session key from seed pub fn get_authority_keys_from_seed(seed: &str) -> (AccountId, AccountId, GrandpaId, BabeId) { - ( - get_from_seed::(&format!("{}//stash", seed)), - get_from_seed::(seed), - get_from_seed::(seed), - get_from_seed::(seed), - ) + ( + get_from_seed::(&format!("{}//stash", seed)), + get_from_seed::(seed), + get_from_seed::(seed), + get_from_seed::(seed), + ) } impl Alternative { - /// Get an actual chain config from one of the alternatives. - pub(crate) fn load(self) -> Result { - Ok(match self { - Alternative::Development => ChainSpec::from_genesis( - "Development", - "dev", - || testnet_genesis(vec![ - get_authority_keys_from_seed("Alice"), - ], - get_from_seed::("Alice"), - vec![ - get_from_seed::("Alice"), - get_from_seed::("Bob"), - get_from_seed::("Alice//stash"), - get_from_seed::("Bob//stash"), - ], - true), - vec![], - None, - None, - None, - None - ), - Alternative::LocalTestnet => ChainSpec::from_genesis( - "Local Testnet", - "local_testnet", - || testnet_genesis(vec![ - get_authority_keys_from_seed("Alice"), - get_authority_keys_from_seed("Bob"), - ], - get_from_seed::("Alice"), - vec![ - get_from_seed::("Alice"), - get_from_seed::("Bob"), - get_from_seed::("Charlie"), - get_from_seed::("Dave"), - get_from_seed::("Eve"), - get_from_seed::("Ferdie"), - get_from_seed::("Alice//stash"), - get_from_seed::("Bob//stash"), - get_from_seed::("Charlie//stash"), - get_from_seed::("Dave//stash"), - get_from_seed::("Eve//stash"), - get_from_seed::("Ferdie//stash"), - ], - true), - vec![], - None, - None, - None, - None - ), - }) - } + /// Get an actual chain config from one of the alternatives. + pub(crate) fn load(self) -> Result { + Ok(match self { + Alternative::Development => ChainSpec::from_genesis( + "Development", + "dev", + || testnet_genesis(vec![ + get_authority_keys_from_seed("Alice"), + ], + get_from_seed::("Alice"), + vec![ + get_from_seed::("Alice"), + get_from_seed::("Bob"), + get_from_seed::("Alice//stash"), + get_from_seed::("Bob//stash"), + ], + true), + vec![], + None, + None, + None, + None + ), + Alternative::LocalTestnet => ChainSpec::from_genesis( + "Local Testnet", + "local_testnet", + || testnet_genesis(vec![ + get_authority_keys_from_seed("Alice"), + get_authority_keys_from_seed("Bob"), + ], + get_from_seed::("Alice"), + vec![ + get_from_seed::("Alice"), + get_from_seed::("Bob"), + get_from_seed::("Charlie"), + get_from_seed::("Dave"), + get_from_seed::("Eve"), + get_from_seed::("Ferdie"), + get_from_seed::("Alice//stash"), + get_from_seed::("Bob//stash"), + get_from_seed::("Charlie//stash"), + get_from_seed::("Dave//stash"), + get_from_seed::("Eve//stash"), + get_from_seed::("Ferdie//stash"), + ], + true), + vec![], + None, + None, + None, + None + ), + }) + } - pub(crate) fn from(s: &str) -> Option { - match s { - "dev" => Some(Alternative::Development), - "" | "local" => Some(Alternative::LocalTestnet), - _ => None, - } - } + pub(crate) fn from(s: &str) -> Option { + match s { + "dev" => Some(Alternative::Development), + "" | "local" => Some(Alternative::LocalTestnet), + _ => None, + } + } } fn testnet_genesis(initial_authorities: Vec<(AccountId, AccountId, GrandpaId, BabeId)>, - root_key: AccountId, - endowed_accounts: Vec, - _enable_println: bool) -> GenesisConfig { - GenesisConfig { - system: Some(SystemConfig { - code: WASM_BINARY.to_vec(), - changes_trie_config: Default::default(), - }), - indices: Some(IndicesConfig { - ids: endowed_accounts.clone(), - }), - balances: Some(BalancesConfig { - balances: endowed_accounts.iter().cloned().map(|k|(k, 1 << 60)).collect(), - vesting: vec![], - }), - sudo: Some(SudoConfig { - key: root_key, - }), - babe: Some(BabeConfig { - authorities: initial_authorities.iter().map(|x| (x.3.clone(), 1)).collect(), - }), - grandpa: Some(GrandpaConfig { - authorities: initial_authorities.iter().map(|x| (x.2.clone(), 1)).collect(), - }), - } + root_key: AccountId, + endowed_accounts: Vec, + _enable_println: bool) -> GenesisConfig { + GenesisConfig { + system: Some(SystemConfig { + code: WASM_BINARY.to_vec(), + changes_trie_config: Default::default(), + }), + indices: Some(IndicesConfig { + ids: endowed_accounts.clone(), + }), + balances: Some(BalancesConfig { + balances: endowed_accounts.iter().cloned().map(|k|(k, 1 << 60)).collect(), + vesting: vec![], + }), + sudo: Some(SudoConfig { + key: root_key, + }), + babe: Some(BabeConfig { + authorities: initial_authorities.iter().map(|x| (x.3.clone(), 1)).collect(), + }), + grandpa: Some(GrandpaConfig { + authorities: initial_authorities.iter().map(|x| (x.2.clone(), 1)).collect(), + }), + } } diff --git a/src/cli.rs b/src/cli.rs index f6edbb2..f74d1f3 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -10,103 +10,103 @@ use log::info; /// Parse command line arguments into service configuration. pub fn run(args: I, exit: E, version: VersionInfo) -> error::Result<()> where - I: IntoIterator, - T: Into + Clone, - E: IntoExit, + I: IntoIterator, + T: Into + Clone, + E: IntoExit, { - match parse_and_prepare::(&version, "substrate-node", args) { - ParseAndPrepare::Run(cmd) => cmd.run::<(), _, _, _, _>(load_spec, exit, - |exit, _cli_args, _custom_args, config| { - info!("{}", version.name); - info!(" version {}", config.full_version()); - info!(" by {}, 2017, 2018", version.author); - info!("Chain specification: {}", config.chain_spec.name()); - info!("Node name: {}", config.name); - info!("Roles: {:?}", config.roles); - let runtime = Runtime::new().map_err(|e| format!("{:?}", e))?; - match config.roles { - ServiceRoles::LIGHT => run_until_exit( - runtime, - service::new_light(config).map_err(|e| format!("{:?}", e))?, - exit - ), - _ => run_until_exit( - runtime, - service::new_full(config).map_err(|e| format!("{:?}", e))?, - exit - ), - }.map_err(|e| format!("{:?}", e)) - }), - ParseAndPrepare::BuildSpec(cmd) => cmd.run(load_spec), - ParseAndPrepare::ExportBlocks(cmd) => cmd.run_with_builder::<(), _, _, _, _, _>(|config| - Ok(new_full_start!(config).0), load_spec, exit), - ParseAndPrepare::ImportBlocks(cmd) => cmd.run_with_builder::<(), _, _, _, _, _>(|config| - Ok(new_full_start!(config).0), load_spec, exit), - ParseAndPrepare::PurgeChain(cmd) => cmd.run(load_spec), - ParseAndPrepare::RevertChain(cmd) => cmd.run_with_builder::<(), _, _, _, _>(|config| - Ok(new_full_start!(config).0), load_spec), - ParseAndPrepare::CustomCommand(_) => Ok(()) - }?; + match parse_and_prepare::(&version, "substrate-node", args) { + ParseAndPrepare::Run(cmd) => cmd.run::<(), _, _, _, _>(load_spec, exit, + |exit, _cli_args, _custom_args, config| { + info!("{}", version.name); + info!(" version {}", config.full_version()); + info!(" by {}, 2017, 2018", version.author); + info!("Chain specification: {}", config.chain_spec.name()); + info!("Node name: {}", config.name); + info!("Roles: {:?}", config.roles); + let runtime = Runtime::new().map_err(|e| format!("{:?}", e))?; + match config.roles { + ServiceRoles::LIGHT => run_until_exit( + runtime, + service::new_light(config).map_err(|e| format!("{:?}", e))?, + exit + ), + _ => run_until_exit( + runtime, + service::new_full(config).map_err(|e| format!("{:?}", e))?, + exit + ), + }.map_err(|e| format!("{:?}", e)) + }), + ParseAndPrepare::BuildSpec(cmd) => cmd.run(load_spec), + ParseAndPrepare::ExportBlocks(cmd) => cmd.run_with_builder::<(), _, _, _, _, _>(|config| + Ok(new_full_start!(config).0), load_spec, exit), + ParseAndPrepare::ImportBlocks(cmd) => cmd.run_with_builder::<(), _, _, _, _, _>(|config| + Ok(new_full_start!(config).0), load_spec, exit), + ParseAndPrepare::PurgeChain(cmd) => cmd.run(load_spec), + ParseAndPrepare::RevertChain(cmd) => cmd.run_with_builder::<(), _, _, _, _>(|config| + Ok(new_full_start!(config).0), load_spec), + ParseAndPrepare::CustomCommand(_) => Ok(()) + }?; - Ok(()) + Ok(()) } fn load_spec(id: &str) -> Result, String> { - Ok(match chain_spec::Alternative::from(id) { - Some(spec) => Some(spec.load()?), - None => None, - }) + Ok(match chain_spec::Alternative::from(id) { + Some(spec) => Some(spec.load()?), + None => None, + }) } fn run_until_exit( - mut runtime: Runtime, - service: T, - e: E, + mut runtime: Runtime, + service: T, + e: E, ) -> error::Result<()> where - T: AbstractService, - E: IntoExit, + T: AbstractService, + E: IntoExit, { - let (exit_send, exit) = exit_future::signal(); + let (exit_send, exit) = exit_future::signal(); - let informant = informant::build(&service); - runtime.executor().spawn(exit.until(informant).map(|_| ())); + let informant = informant::build(&service); + runtime.executor().spawn(exit.until(informant).map(|_| ())); - // we eagerly drop the service so that the internal exit future is fired, - // but we need to keep holding a reference to the global telemetry guard - let _telemetry = service.telemetry(); + // we eagerly drop the service so that the internal exit future is fired, + // but we need to keep holding a reference to the global telemetry guard + let _telemetry = service.telemetry(); - let service_res = { - let exit = e.into_exit().map_err(|_| error::Error::Other("Exit future failed.".into())); - let service = service.map_err(|err| error::Error::Service(err)); - let select = service.select(exit).map(|_| ()).map_err(|(err, _)| err); - runtime.block_on(select) - }; + let service_res = { + let exit = e.into_exit().map_err(|_| error::Error::Other("Exit future failed.".into())); + let service = service.map_err(|err| error::Error::Service(err)); + let select = service.select(exit).map(|_| ()).map_err(|(err, _)| err); + runtime.block_on(select) + }; - exit_send.fire(); + exit_send.fire(); - // TODO [andre]: timeout this future #1318 - let _ = runtime.shutdown_on_idle().wait(); + // TODO [andre]: timeout this future #1318 + let _ = runtime.shutdown_on_idle().wait(); - service_res + service_res } // handles ctrl-c pub struct Exit; impl IntoExit for Exit { - type Exit = future::MapErr, fn(oneshot::Canceled) -> ()>; - fn into_exit(self) -> Self::Exit { - // can't use signal directly here because CtrlC takes only `Fn`. - let (exit_send, exit) = oneshot::channel(); + type Exit = future::MapErr, fn(oneshot::Canceled) -> ()>; + fn into_exit(self) -> Self::Exit { + // can't use signal directly here because CtrlC takes only `Fn`. + let (exit_send, exit) = oneshot::channel(); - let exit_send_cell = RefCell::new(Some(exit_send)); - ctrlc::set_handler(move || { - let exit_send = exit_send_cell.try_borrow_mut().expect("signal handler not reentrant; qed").take(); - if let Some(exit_send) = exit_send { - exit_send.send(()).expect("Error sending exit notification"); - } - }).expect("Error setting Ctrl-C handler"); + let exit_send_cell = RefCell::new(Some(exit_send)); + ctrlc::set_handler(move || { + let exit_send = exit_send_cell.try_borrow_mut().expect("signal handler not reentrant; qed").take(); + if let Some(exit_send) = exit_send { + exit_send.send(()).expect("Error sending exit notification"); + } + }).expect("Error setting Ctrl-C handler"); - exit.map_err(drop) - } + exit.map_err(drop) + } } diff --git a/src/main.rs b/src/main.rs index 39c9449..7e3ce3c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -11,18 +11,18 @@ mod cli; pub use substrate_cli::{VersionInfo, IntoExit, error}; fn main() { - let version = VersionInfo { - name: "Substrate Node", - commit: env!("VERGEN_SHA_SHORT"), - version: env!("CARGO_PKG_VERSION"), - executable_name: "plasma-cash", - author: "Zatoichi Labs", - description: "plasma-cash", - support_url: "support.anonymous.an", - }; + let version = VersionInfo { + name: "Substrate Node", + commit: env!("VERGEN_SHA_SHORT"), + version: env!("CARGO_PKG_VERSION"), + executable_name: "plasma-cash", + author: "Zatoichi Labs", + description: "plasma-cash", + support_url: "support.anonymous.an", + }; - if let Err(e) = cli::run(::std::env::args(), cli::Exit, version) { - eprintln!("Fatal error: {}\n\n{:?}", e, e); - std::process::exit(1) - } + if let Err(e) = cli::run(::std::env::args(), cli::Exit, version) { + eprintln!("Fatal error: {}\n\n{:?}", e, e); + std::process::exit(1) + } } diff --git a/src/service.rs b/src/service.rs index 1f80876..1bbbcfb 100644 --- a/src/service.rs +++ b/src/service.rs @@ -16,14 +16,14 @@ pub use substrate_executor::NativeExecutor; // Our native executor instance. native_executor_instance!( - pub Executor, - plasma_cash_runtime::api::dispatch, - plasma_cash_runtime::native_version + pub Executor, + plasma_cash_runtime::api::dispatch, + plasma_cash_runtime::native_version ); construct_simple_protocol! { - /// Demo protocol attachment for substrate. - pub struct NodeProtocol where Block = Block { } + /// Demo protocol attachment for substrate. + pub struct NodeProtocol where Block = Block { } } /// Starts a `ServiceBuilder` for a full service. @@ -31,200 +31,200 @@ construct_simple_protocol! { /// 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. macro_rules! new_full_start { - ($config:expr) => {{ - let mut import_setup = None; - let inherent_data_providers = inherents::InherentDataProviders::new(); - let mut tasks_to_spawn = None; - - let builder = substrate_service::ServiceBuilder::new_full::< - plasma_cash_runtime::opaque::Block, plasma_cash_runtime::RuntimeApi, crate::service::Executor - >($config)? - .with_select_chain(|_config, client| { - #[allow(deprecated)] - Ok(substrate_client::LongestChain::new(client.backend().clone())) - })? - .with_transaction_pool(|config, client| - Ok(transaction_pool::txpool::Pool::new(config, transaction_pool::ChainApi::new(client))) - )? - .with_import_queue(|_config, client, mut select_chain, transaction_pool| { - let select_chain = select_chain.take() - .ok_or_else(|| substrate_service::Error::SelectChainRequired)?; - let (block_import, link_half) = - grandpa::block_import::<_, _, _, plasma_cash_runtime::RuntimeApi, _, _>( - client.clone(), client.clone(), select_chain - )?; - let justification_import = block_import.clone(); - - let (import_queue, babe_link, babe_block_import, pruning_task) = babe::import_queue( - babe::Config::get_or_compute(&*client)?, - block_import, - Some(Box::new(justification_import)), - None, - client.clone(), - client, - inherent_data_providers.clone(), - Some(transaction_pool) - )?; - - import_setup = Some((babe_block_import.clone(), link_half, babe_link)); - tasks_to_spawn = Some(vec![Box::new(pruning_task)]); - - Ok(import_queue) - })?; - - (builder, import_setup, inherent_data_providers, tasks_to_spawn) - }} + ($config:expr) => {{ + let mut import_setup = None; + let inherent_data_providers = inherents::InherentDataProviders::new(); + let mut tasks_to_spawn = None; + + let builder = substrate_service::ServiceBuilder::new_full::< + plasma_cash_runtime::opaque::Block, plasma_cash_runtime::RuntimeApi, crate::service::Executor + >($config)? + .with_select_chain(|_config, client| { + #[allow(deprecated)] + Ok(substrate_client::LongestChain::new(client.backend().clone())) + })? + .with_transaction_pool(|config, client| + Ok(transaction_pool::txpool::Pool::new(config, transaction_pool::ChainApi::new(client))) + )? + .with_import_queue(|_config, client, mut select_chain, transaction_pool| { + let select_chain = select_chain.take() + .ok_or_else(|| substrate_service::Error::SelectChainRequired)?; + let (block_import, link_half) = + grandpa::block_import::<_, _, _, plasma_cash_runtime::RuntimeApi, _, _>( + client.clone(), client.clone(), select_chain + )?; + let justification_import = block_import.clone(); + + let (import_queue, babe_link, babe_block_import, pruning_task) = babe::import_queue( + babe::Config::get_or_compute(&*client)?, + block_import, + Some(Box::new(justification_import)), + None, + client.clone(), + client, + inherent_data_providers.clone(), + Some(transaction_pool) + )?; + + import_setup = Some((babe_block_import.clone(), link_half, babe_link)); + tasks_to_spawn = Some(vec![Box::new(pruning_task)]); + + Ok(import_queue) + })?; + + (builder, import_setup, inherent_data_providers, tasks_to_spawn) + }} } /// Builds a new service for a full client. pub fn new_full(config: Configuration) - -> Result + -> Result { - let (builder, mut import_setup, inherent_data_providers, mut tasks_to_spawn) = new_full_start!(config); - - let service = builder.with_network_protocol(|_| Ok(NodeProtocol::new()))? - .with_finality_proof_provider(|client| - Ok(Arc::new(GrandpaFinalityProofProvider::new(client.clone(), client)) as _) - )? - .build()?; - - let (block_import, link_half, babe_link) = - import_setup.take() - .expect("Link Half and Block Import are present for Full Services or setup failed before. qed"); - - // spawn any futures that were created in the previous setup steps - if let Some(tasks) = tasks_to_spawn.take() { - for task in tasks { - service.spawn_task( - task.select(service.on_exit()) - .map(|_| ()) - .map_err(|_| ()) - ); - } - } - - if service.config().roles.is_authority() { - let proposer = basic_authorship::ProposerFactory { - client: service.client(), - transaction_pool: service.transaction_pool(), - }; - - let client = service.client(); - let select_chain = service.select_chain() - .ok_or(ServiceError::SelectChainRequired)?; - - let babe_config = babe::BabeParams { - config: Config::get_or_compute(&*client)?, - keystore: service.keystore(), - client, - select_chain, - block_import, - env: proposer, - sync_oracle: service.network(), - inherent_data_providers: inherent_data_providers.clone(), - force_authoring: service.config().force_authoring, - time_source: babe_link, - }; - - let babe = start_babe(babe_config)?; - let select = babe.select(service.on_exit()).then(|_| Ok(())); - - // the BABE authoring task is considered infallible, i.e. if it - // fails we take down the service with it. - service.spawn_essential_task(select); - } - - let config = grandpa::Config { - // FIXME #1578 make this available through chainspec - gossip_duration: Duration::from_millis(333), - justification_period: 4096, - name: Some(service.config().name.clone()), - keystore: Some(service.keystore()), - }; - - match (service.config().roles.is_authority(), service.config().disable_grandpa) { - (false, false) => { - // start the lightweight GRANDPA observer - service.spawn_task(Box::new(grandpa::run_grandpa_observer( - config, - link_half, - service.network(), - service.on_exit(), - )?)); - }, - (true, false) => { - // start the full GRANDPA voter - let grandpa_config = grandpa::GrandpaParams { - config: config, - link: link_half, - network: service.network(), - inherent_data_providers: inherent_data_providers.clone(), - on_exit: service.on_exit(), - telemetry_on_connect: Some(service.telemetry_on_connect_stream()), - }; - - // the GRANDPA voter task is considered infallible, i.e. - // if it fails we take down the service with it. - service.spawn_essential_task(grandpa::run_grandpa_voter(grandpa_config)?); - }, - (_, true) => { - grandpa::setup_disabled_grandpa( - service.client(), - &inherent_data_providers, - service.network(), - )?; - }, - } - - Ok(service) + let (builder, mut import_setup, inherent_data_providers, mut tasks_to_spawn) = new_full_start!(config); + + let service = builder.with_network_protocol(|_| Ok(NodeProtocol::new()))? + .with_finality_proof_provider(|client| + Ok(Arc::new(GrandpaFinalityProofProvider::new(client.clone(), client)) as _) + )? + .build()?; + + let (block_import, link_half, babe_link) = + import_setup.take() + .expect("Link Half and Block Import are present for Full Services or setup failed before. qed"); + + // spawn any futures that were created in the previous setup steps + if let Some(tasks) = tasks_to_spawn.take() { + for task in tasks { + service.spawn_task( + task.select(service.on_exit()) + .map(|_| ()) + .map_err(|_| ()) + ); + } + } + + if service.config().roles.is_authority() { + let proposer = basic_authorship::ProposerFactory { + client: service.client(), + transaction_pool: service.transaction_pool(), + }; + + let client = service.client(); + let select_chain = service.select_chain() + .ok_or(ServiceError::SelectChainRequired)?; + + let babe_config = babe::BabeParams { + config: Config::get_or_compute(&*client)?, + keystore: service.keystore(), + client, + select_chain, + block_import, + env: proposer, + sync_oracle: service.network(), + inherent_data_providers: inherent_data_providers.clone(), + force_authoring: service.config().force_authoring, + time_source: babe_link, + }; + + let babe = start_babe(babe_config)?; + let select = babe.select(service.on_exit()).then(|_| Ok(())); + + // the BABE authoring task is considered infallible, i.e. if it + // fails we take down the service with it. + service.spawn_essential_task(select); + } + + let config = grandpa::Config { + // FIXME #1578 make this available through chainspec + gossip_duration: Duration::from_millis(333), + justification_period: 4096, + name: Some(service.config().name.clone()), + keystore: Some(service.keystore()), + }; + + match (service.config().roles.is_authority(), service.config().disable_grandpa) { + (false, false) => { + // start the lightweight GRANDPA observer + service.spawn_task(Box::new(grandpa::run_grandpa_observer( + config, + link_half, + service.network(), + service.on_exit(), + )?)); + }, + (true, false) => { + // start the full GRANDPA voter + let grandpa_config = grandpa::GrandpaParams { + config: config, + link: link_half, + network: service.network(), + inherent_data_providers: inherent_data_providers.clone(), + on_exit: service.on_exit(), + telemetry_on_connect: Some(service.telemetry_on_connect_stream()), + }; + + // the GRANDPA voter task is considered infallible, i.e. + // if it fails we take down the service with it. + service.spawn_essential_task(grandpa::run_grandpa_voter(grandpa_config)?); + }, + (_, true) => { + grandpa::setup_disabled_grandpa( + service.client(), + &inherent_data_providers, + service.network(), + )?; + }, + } + + Ok(service) } /// Builds a new service for a light client. pub fn new_light(config: Configuration) - -> Result + -> Result { - let inherent_data_providers = InherentDataProviders::new(); - - ServiceBuilder::new_light::(config)? - .with_select_chain(|_config, client| { - #[allow(deprecated)] - Ok(LongestChain::new(client.backend().clone())) - })? - .with_transaction_pool(|config, client| - Ok(TransactionPool::new(config, transaction_pool::ChainApi::new(client))) - )? - .with_import_queue_and_fprb(|_config, client, _select_chain, transaction_pool| { - #[allow(deprecated)] - let fetch_checker = client.backend().blockchain().fetcher() - .upgrade() - .map(|fetcher| fetcher.checker().clone()) - .ok_or_else(|| "Trying to start light import queue without active fetch checker")?; - let block_import = grandpa::light_block_import::<_, _, _, RuntimeApi, _>( - client.clone(), Arc::new(fetch_checker), client.clone() - )?; - - let finality_proof_import = block_import.clone(); - let finality_proof_request_builder = - finality_proof_import.create_finality_proof_request_builder(); - - // FIXME: pruning task isn't started since light client doesn't do `AuthoritySetup`. - let (import_queue, ..) = import_queue( - Config::get_or_compute(&*client)?, - block_import, - None, - Some(Box::new(finality_proof_import)), - client.clone(), - client, - inherent_data_providers.clone(), - Some(transaction_pool) - )?; - - Ok((import_queue, finality_proof_request_builder)) - })? - .with_network_protocol(|_| Ok(NodeProtocol::new()))? - .with_finality_proof_provider(|client| - Ok(Arc::new(GrandpaFinalityProofProvider::new(client.clone(), client)) as _) - )? - .build() + let inherent_data_providers = InherentDataProviders::new(); + + ServiceBuilder::new_light::(config)? + .with_select_chain(|_config, client| { + #[allow(deprecated)] + Ok(LongestChain::new(client.backend().clone())) + })? + .with_transaction_pool(|config, client| + Ok(TransactionPool::new(config, transaction_pool::ChainApi::new(client))) + )? + .with_import_queue_and_fprb(|_config, client, _select_chain, transaction_pool| { + #[allow(deprecated)] + let fetch_checker = client.backend().blockchain().fetcher() + .upgrade() + .map(|fetcher| fetcher.checker().clone()) + .ok_or_else(|| "Trying to start light import queue without active fetch checker")?; + let block_import = grandpa::light_block_import::<_, _, _, RuntimeApi, _>( + client.clone(), Arc::new(fetch_checker), client.clone() + )?; + + let finality_proof_import = block_import.clone(); + let finality_proof_request_builder = + finality_proof_import.create_finality_proof_request_builder(); + + // FIXME: pruning task isn't started since light client doesn't do `AuthoritySetup`. + let (import_queue, ..) = import_queue( + Config::get_or_compute(&*client)?, + block_import, + None, + Some(Box::new(finality_proof_import)), + client.clone(), + client, + inherent_data_providers.clone(), + Some(transaction_pool) + )?; + + Ok((import_queue, finality_proof_request_builder)) + })? + .with_network_protocol(|_| Ok(NodeProtocol::new()))? + .with_finality_proof_provider(|client| + Ok(Arc::new(GrandpaFinalityProofProvider::new(client.clone(), client)) as _) + )? + .build() }