From 0d6a0f66b42fcb5072f240978f1714d104ac2d9f Mon Sep 17 00:00:00 2001 From: Pierre Krieger Date: Wed, 30 Oct 2019 17:10:14 +0100 Subject: [PATCH 01/14] Extract CLI to separate module in node/cli --- core/service/Cargo.toml | 2 +- node/cli/Cargo.toml | 20 ++-- node/cli/bin/main.rs | 6 +- node/cli/build.rs | 2 +- node/cli/src/cli.rs | 212 ++++++++++++++++++++++++++++++++++++++++ node/cli/src/lib.rs | 197 +------------------------------------ 6 files changed, 234 insertions(+), 205 deletions(-) create mode 100644 node/cli/src/cli.rs diff --git a/core/service/Cargo.toml b/core/service/Cargo.toml index 0d6f27936244f..76d68eb45f94f 100644 --- a/core/service/Cargo.toml +++ b/core/service/Cargo.toml @@ -29,7 +29,7 @@ consensus_common = { package = "substrate-consensus-common", path = "../../core/ network = { package = "substrate-network", path = "../../core/network" } chain-spec = { package = "substrate-chain-spec", path = "../chain-spec" } client = { package = "substrate-client", path = "../../core/client" } -client_db = { package = "substrate-client-db", path = "../../core/client/db", features = ["kvdb-rocksdb"] } +client_db = { package = "substrate-client-db", path = "../../core/client/db" } codec = { package = "parity-scale-codec", version = "1.0.0" } substrate-executor = { path = "../../core/executor" } transaction_pool = { package = "substrate-transaction-pool", path = "../../core/transaction-pool" } diff --git a/node/cli/Cargo.toml b/node/cli/Cargo.toml index b85014eeef06a..11a9f098cad71 100644 --- a/node/cli/Cargo.toml +++ b/node/cli/Cargo.toml @@ -16,14 +16,15 @@ is-it-maintained-open-issues = { repository = "paritytech/substrate" } [[bin]] name = "substrate" path = "bin/main.rs" +required-features = ["cli"] [dependencies] log = "0.4.8" -tokio = "0.1.22" +tokio = { version = "0.1.22", optional = true } futures = "0.1.29" -exit-future = "0.1.4" +exit-future = { version = "0.1.4", optional = true } jsonrpc-core = "13.2.0" -cli = { package = "substrate-cli", path = "../../core/cli" } +substrate-cli = { path = "../../core/cli", optional = true } codec = { package = "parity-scale-codec", version = "1.0.0" } sr-io = { path = "../../core/sr-io" } client = { package = "substrate-client", path = "../../core/client" } @@ -47,7 +48,7 @@ sr-primitives = { path = "../../core/sr-primitives" } node-executor = { path = "../executor" } substrate-telemetry = { package = "substrate-telemetry", path = "../../core/telemetry" } structopt = "0.3.3" -transaction-factory = { path = "../../test-utils/transaction-factory" } +transaction-factory = { path = "../../test-utils/transaction-factory", optional = true } keyring = { package = "substrate-keyring", path = "../../core/keyring" } indices = { package = "srml-indices", path = "../../srml/indices" } timestamp = { package = "srml-timestamp", path = "../../srml/timestamp", default-features = false } @@ -60,9 +61,9 @@ transaction-payment = { package = "srml-transaction-payment", path = "../../srml support = { package = "srml-support", path = "../../srml/support", default-features = false } im_online = { package = "srml-im-online", path = "../../srml/im-online", default-features = false } serde = { version = "1.0.101", features = [ "derive" ] } -client_db = { package = "substrate-client-db", path = "../../core/client/db", features = ["kvdb-rocksdb"] } +client_db = { package = "substrate-client-db", path = "../../core/client/db", default-features = false } offchain = { package = "substrate-offchain", path = "../../core/offchain" } -ctrlc = { version = "3.1.3", features = ["termination"] } +ctrlc = { version = "3.1.3", features = ["termination"], optional = true } [dev-dependencies] keystore = { package = "substrate-keystore", path = "../../core/keystore" } @@ -73,6 +74,11 @@ futures03 = { package = "futures-preview", version = "0.3.0-alpha.19" } tempfile = "3.1.0" [build-dependencies] -cli = { package = "substrate-cli", path = "../../core/cli" } +substrate-cli = { package = "substrate-cli", path = "../../core/cli" } structopt = "0.3.3" vergen = "3.0.4" + +[features] +default = ["cli"] +# TODO: docs +cli = ["substrate-cli", "transaction-factory", "tokio", "exit-future", "ctrlc", "client_db/kvdb-rocksdb"] diff --git a/node/cli/bin/main.rs b/node/cli/bin/main.rs index 4b07d8c8a4805..e4415a2a89e66 100644 --- a/node/cli/bin/main.rs +++ b/node/cli/bin/main.rs @@ -18,15 +18,15 @@ #![warn(missing_docs)] -use cli::VersionInfo; use futures::sync::oneshot; use futures::{future, Future}; +use substrate_cli::VersionInfo; use std::cell::RefCell; // handles ctrl-c struct Exit; -impl cli::IntoExit for Exit { +impl substrate_cli::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`. @@ -43,7 +43,7 @@ impl cli::IntoExit for Exit { } } -fn main() -> Result<(), cli::error::Error> { +fn main() -> Result<(), substrate_cli::error::Error> { let version = VersionInfo { name: "Substrate Node", commit: env!("VERGEN_SHA_SHORT"), diff --git a/node/cli/build.rs b/node/cli/build.rs index 48b57c4600e80..8ef644eed5d94 100644 --- a/node/cli/build.rs +++ b/node/cli/build.rs @@ -14,9 +14,9 @@ // You should have received a copy of the GNU General Public License // along with Substrate. If not, see . -use cli::{NoCustom, CoreParams}; use std::{fs, env, path::Path}; use structopt::{StructOpt, clap::Shell}; +use substrate_cli::{NoCustom, CoreParams}; use vergen::{ConstantsFlags, generate_cargo_keys}; fn main() { diff --git a/node/cli/src/cli.rs b/node/cli/src/cli.rs new file mode 100644 index 0000000000000..3f8c9c5657f7a --- /dev/null +++ b/node/cli/src/cli.rs @@ -0,0 +1,212 @@ +// Copyright 2018-2019 Parity Technologies (UK) Ltd. +// This file is part of Substrate. + +// Substrate 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. + +// Substrate 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. If not, see . + +#![cfg(feature = "cli")] + +pub use substrate_cli::error; +use tokio::prelude::Future; +use tokio::runtime::{Builder as RuntimeBuilder, Runtime}; +pub use substrate_cli::{VersionInfo, IntoExit, NoCustom, SharedParams, ExecutionStrategyParam}; +use substrate_service::{AbstractService, Roles as ServiceRoles, Configuration}; +use log::info; +use structopt::{StructOpt, clap::App}; +use substrate_cli::{display_role, parse_and_prepare, AugmentClap, GetLogFilter, ParseAndPrepare}; +use crate::{service, ChainSpec, load_spec}; +use crate::factory_impl::FactoryState; +use transaction_factory::RuntimeAdapter; +use client::ExecutionStrategies; + +/// Custom subcommands. +#[derive(Clone, Debug, StructOpt)] +pub enum CustomSubcommands { + /// The custom factory subcommmand for manufacturing transactions. + #[structopt( + name = "factory", + about = "Manufactures num transactions from Alice to random accounts. \ + Only supported for development or local testnet." + )] + Factory(FactoryCmd), +} + +impl GetLogFilter for CustomSubcommands { + fn get_log_filter(&self) -> Option { + None + } +} + +/// The `factory` command used to generate transactions. +/// Please note: this command currently only works on an empty database! +#[derive(Debug, StructOpt, Clone)] +pub struct FactoryCmd { + /// How often to repeat. This option only has an effect in mode `MasterToNToM`. + #[structopt(long="rounds", default_value = "1")] + pub rounds: u64, + + /// MasterToN: Manufacture `num` transactions from the master account + /// to `num` randomly created accounts, one each. + /// + /// MasterTo1: Manufacture `num` transactions from the master account + /// to exactly one other randomly created account. + /// + /// MasterToNToM: Manufacture `num` transactions from the master account + /// to `num` randomly created accounts. + /// From each of these randomly created accounts manufacture + /// a transaction to another randomly created account. + /// Repeat this `rounds` times. If `rounds` = 1 the behavior + /// is the same as `MasterToN`.{n} + /// A -> B, A -> C, A -> D, ... x `num`{n} + /// B -> E, C -> F, D -> G, ...{n} + /// ... x `rounds` + /// + /// These three modes control manufacturing. + #[structopt(long="mode", default_value = "MasterToN")] + pub mode: transaction_factory::Mode, + + /// Number of transactions to generate. In mode `MasterNToNToM` this is + /// the number of transactions per round. + #[structopt(long="num", default_value = "8")] + pub num: u64, + + #[allow(missing_docs)] + #[structopt(flatten)] + pub shared_params: SharedParams, + + /// The means of execution used when calling into the runtime while importing blocks. + #[structopt( + long = "execution", + value_name = "STRATEGY", + possible_values = &ExecutionStrategyParam::variants(), + case_insensitive = true, + default_value = "NativeElseWasm" + )] + pub execution: ExecutionStrategyParam, +} + +impl AugmentClap for FactoryCmd { + fn augment_clap<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> { + FactoryCmd::augment_clap(app) + } +} + +/// Parse command line arguments into service configuration. +pub fn run(args: I, exit: E, version: substrate_cli::VersionInfo) -> error::Result<()> where + I: IntoIterator, + T: Into + Clone, + E: IntoExit, +{ + type Config = Configuration<(), A, B>; + + match parse_and_prepare::(&version, "substrate-node", args) { + ParseAndPrepare::Run(cmd) => cmd.run(load_spec, exit, + |exit, _cli_args, _custom_args, config: Config<_, _>| { + info!("{}", version.name); + info!(" version {}", config.full_version()); + info!(" by Parity Technologies, 2017-2019"); + info!("Chain specification: {}", config.chain_spec.name()); + info!("Node name: {}", config.name); + info!("Roles: {}", display_role(&config)); + let runtime = RuntimeBuilder::new().name_prefix("main-tokio-").build() + .map_err(|e| format!("{:?}", e))?; + match config.roles { + ServiceRoles::LIGHT => run_until_exit( + runtime, + service::new_light(config)?, + exit + ), + _ => run_until_exit( + runtime, + service::new_full(config)?, + exit + ), + } + }), + ParseAndPrepare::BuildSpec(cmd) => cmd.run(load_spec), + ParseAndPrepare::ExportBlocks(cmd) => cmd.run_with_builder(|config: Config<_, _>| + Ok(new_full_start!(config).0), load_spec, exit), + ParseAndPrepare::ImportBlocks(cmd) => cmd.run_with_builder(|config: 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: Config<_, _>| + Ok(new_full_start!(config).0), load_spec), + ParseAndPrepare::CustomCommand(CustomSubcommands::Factory(cli_args)) => { + let mut config: Config<_, _> = substrate_cli::create_config_with_db_path( + load_spec, + &cli_args.shared_params, + &version, + )?; + config.execution_strategies = ExecutionStrategies { + importing: cli_args.execution.into(), + block_construction: cli_args.execution.into(), + other: cli_args.execution.into(), + ..Default::default() + }; + + match ChainSpec::from(config.chain_spec.id()) { + Some(ref c) if c == &ChainSpec::Development || c == &ChainSpec::LocalTestnet => {}, + _ => panic!("Factory is only supported for development and local testnet."), + } + + let factory_state = FactoryState::new( + cli_args.mode.clone(), + cli_args.num, + cli_args.rounds, + ); + + let service_builder = new_full_start!(config).0; + transaction_factory::factory::, _, _, _, _, _>( + factory_state, + service_builder.client(), + service_builder.select_chain() + .expect("The select_chain is always initialized by new_full_start!; QED") + ).map_err(|e| format!("Error in transaction factory: {}", e))?; + + Ok(()) + } + } +} + +fn run_until_exit( + mut runtime: Runtime, + service: T, + e: E, +) -> error::Result<()> +where + T: AbstractService, + E: IntoExit, +{ + let (exit_send, exit) = exit_future::signal(); + + let informant = substrate_cli::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(); + + 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(); + + // TODO [andre]: timeout this future #1318 + let _ = runtime.shutdown_on_idle().wait(); + + service_res +} diff --git a/node/cli/src/lib.rs b/node/cli/src/lib.rs index 5125ba216a2cc..ad79485209689 100644 --- a/node/cli/src/lib.rs +++ b/node/cli/src/lib.rs @@ -19,22 +19,15 @@ #![warn(missing_docs)] #![warn(unused_extern_crates)] -pub use cli::error; pub mod chain_spec; + #[macro_use] mod service; +mod cli; mod factory_impl; -use tokio::prelude::Future; -use tokio::runtime::{Builder as RuntimeBuilder, Runtime}; -pub use cli::{VersionInfo, IntoExit, NoCustom, SharedParams, ExecutionStrategyParam}; -use substrate_service::{AbstractService, Roles as ServiceRoles, Configuration}; -use log::info; -use structopt::{StructOpt, clap::App}; -use cli::{display_role, parse_and_prepare, AugmentClap, GetLogFilter, ParseAndPrepare}; -use crate::factory_impl::FactoryState; -use transaction_factory::RuntimeAdapter; -use client::ExecutionStrategies; +#[cfg(feature = "cli")] +pub use cli::*; /// The chain specification option. #[derive(Clone, Debug, PartialEq)] @@ -49,78 +42,6 @@ pub enum ChainSpec { StagingTestnet, } -/// Custom subcommands. -#[derive(Clone, Debug, StructOpt)] -pub enum CustomSubcommands { - /// The custom factory subcommmand for manufacturing transactions. - #[structopt( - name = "factory", - about = "Manufactures num transactions from Alice to random accounts. \ - Only supported for development or local testnet." - )] - Factory(FactoryCmd), -} - -impl GetLogFilter for CustomSubcommands { - fn get_log_filter(&self) -> Option { - None - } -} - -/// The `factory` command used to generate transactions. -/// Please note: this command currently only works on an empty database! -#[derive(Debug, StructOpt, Clone)] -pub struct FactoryCmd { - /// How often to repeat. This option only has an effect in mode `MasterToNToM`. - #[structopt(long="rounds", default_value = "1")] - pub rounds: u64, - - /// MasterToN: Manufacture `num` transactions from the master account - /// to `num` randomly created accounts, one each. - /// - /// MasterTo1: Manufacture `num` transactions from the master account - /// to exactly one other randomly created account. - /// - /// MasterToNToM: Manufacture `num` transactions from the master account - /// to `num` randomly created accounts. - /// From each of these randomly created accounts manufacture - /// a transaction to another randomly created account. - /// Repeat this `rounds` times. If `rounds` = 1 the behavior - /// is the same as `MasterToN`.{n} - /// A -> B, A -> C, A -> D, ... x `num`{n} - /// B -> E, C -> F, D -> G, ...{n} - /// ... x `rounds` - /// - /// These three modes control manufacturing. - #[structopt(long="mode", default_value = "MasterToN")] - pub mode: transaction_factory::Mode, - - /// Number of transactions to generate. In mode `MasterNToNToM` this is - /// the number of transactions per round. - #[structopt(long="num", default_value = "8")] - pub num: u64, - - #[allow(missing_docs)] - #[structopt(flatten)] - pub shared_params: SharedParams, - - /// The means of execution used when calling into the runtime while importing blocks. - #[structopt( - long = "execution", - value_name = "STRATEGY", - possible_values = &ExecutionStrategyParam::variants(), - case_insensitive = true, - default_value = "NativeElseWasm" - )] - pub execution: ExecutionStrategyParam, -} - -impl AugmentClap for FactoryCmd { - fn augment_clap<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> { - FactoryCmd::augment_clap(app) - } -} - /// Get a chain config from a spec setting. impl ChainSpec { pub(crate) fn load(self) -> Result { @@ -149,113 +70,3 @@ fn load_spec(id: &str) -> Result, String> { None => None, }) } - -/// Parse command line arguments into service configuration. -pub fn run(args: I, exit: E, version: cli::VersionInfo) -> error::Result<()> where - I: IntoIterator, - T: Into + Clone, - E: IntoExit, -{ - type Config = Configuration<(), A, B>; - - match parse_and_prepare::(&version, "substrate-node", args) { - ParseAndPrepare::Run(cmd) => cmd.run(load_spec, exit, - |exit, _cli_args, _custom_args, config: Config<_, _>| { - info!("{}", version.name); - info!(" version {}", config.full_version()); - info!(" by Parity Technologies, 2017-2019"); - info!("Chain specification: {}", config.chain_spec.name()); - info!("Node name: {}", config.name); - info!("Roles: {}", display_role(&config)); - let runtime = RuntimeBuilder::new().name_prefix("main-tokio-").build() - .map_err(|e| format!("{:?}", e))?; - match config.roles { - ServiceRoles::LIGHT => run_until_exit( - runtime, - service::new_light(config)?, - exit - ), - _ => run_until_exit( - runtime, - service::new_full(config)?, - exit - ), - } - }), - ParseAndPrepare::BuildSpec(cmd) => cmd.run(load_spec), - ParseAndPrepare::ExportBlocks(cmd) => cmd.run_with_builder(|config: Config<_, _>| - Ok(new_full_start!(config).0), load_spec, exit), - ParseAndPrepare::ImportBlocks(cmd) => cmd.run_with_builder(|config: 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: Config<_, _>| - Ok(new_full_start!(config).0), load_spec), - ParseAndPrepare::CustomCommand(CustomSubcommands::Factory(cli_args)) => { - let mut config: Config<_, _> = cli::create_config_with_db_path( - load_spec, - &cli_args.shared_params, - &version, - )?; - config.execution_strategies = ExecutionStrategies { - importing: cli_args.execution.into(), - block_construction: cli_args.execution.into(), - other: cli_args.execution.into(), - ..Default::default() - }; - - match ChainSpec::from(config.chain_spec.id()) { - Some(ref c) if c == &ChainSpec::Development || c == &ChainSpec::LocalTestnet => {}, - _ => panic!("Factory is only supported for development and local testnet."), - } - - let factory_state = FactoryState::new( - cli_args.mode.clone(), - cli_args.num, - cli_args.rounds, - ); - - let service_builder = new_full_start!(config).0; - transaction_factory::factory::, _, _, _, _, _>( - factory_state, - service_builder.client(), - service_builder.select_chain() - .expect("The select_chain is always initialized by new_full_start!; QED") - ).map_err(|e| format!("Error in transaction factory: {}", e))?; - - Ok(()) - } - } -} - -fn run_until_exit( - mut runtime: Runtime, - service: T, - e: E, -) -> error::Result<()> -where - T: AbstractService, - E: IntoExit, -{ - let (exit_send, exit) = exit_future::signal(); - - let informant = cli::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(); - - 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(); - - // TODO [andre]: timeout this future #1318 - let _ = runtime.shutdown_on_idle().wait(); - - service_res -} From 222a6deadc1501d2235243711659684510fa7770 Mon Sep 17 00:00:00 2001 From: Pierre Krieger Date: Wed, 30 Oct 2019 17:32:24 +0100 Subject: [PATCH 02/14] Make node/cli compile for WASM --- core/service/src/lib.rs | 4 ++-- node/cli/src/factory_impl.rs | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/core/service/src/lib.rs b/core/service/src/lib.rs index 3057b8ce4dcd4..bc1a15542de81 100644 --- a/core/service/src/lib.rs +++ b/core/service/src/lib.rs @@ -541,10 +541,10 @@ fn start_rpc_servers rpc_servers::RpcHandler components::RpcHandler>( +fn start_rpc_servers rpc_servers::RpcHandler>( _: &Configuration, _: H -) -> Result, error::Error> { +) -> Result, error::Error> { Ok(Box::new(())) } diff --git a/node/cli/src/factory_impl.rs b/node/cli/src/factory_impl.rs index 48fb7b237f1e6..6578350a5a6dd 100644 --- a/node/cli/src/factory_impl.rs +++ b/node/cli/src/factory_impl.rs @@ -18,6 +18,8 @@ //! using the cli to manufacture transactions and distribute them //! to accounts. +#![cfg(feature = "cli")] + use rand::{Rng, SeedableRng}; use rand::rngs::StdRng; From 2a282e96998e77f7a4a30de4870421182eef6227 Mon Sep 17 00:00:00 2001 From: Pierre Krieger Date: Wed, 30 Oct 2019 18:10:21 +0100 Subject: [PATCH 03/14] More work on node/cli browser --- Cargo.lock | 28 ++++++ core/service/src/lib.rs | 1 + node/cli/Cargo.toml | 14 +++ node/cli/browser-demo/.gitignore | 1 + node/cli/browser-demo/README.md | 10 ++ node/cli/browser-demo/build.sh | 4 + node/cli/browser-demo/favicon.png | Bin 0 -> 10338 bytes node/cli/browser-demo/index.html | 42 +++++++++ node/cli/browser-demo/ws.js | 148 +++++++++++++++++++++++++++++ node/cli/src/browser.rs | 151 ++++++++++++++++++++++++++++++ node/cli/src/lib.rs | 3 + 11 files changed, 402 insertions(+) create mode 100644 node/cli/browser-demo/.gitignore create mode 100644 node/cli/browser-demo/README.md create mode 100755 node/cli/browser-demo/build.sh create mode 100644 node/cli/browser-demo/favicon.png create mode 100644 node/cli/browser-demo/index.html create mode 100644 node/cli/browser-demo/ws.js create mode 100644 node/cli/src/browser.rs diff --git a/Cargo.lock b/Cargo.lock index 75a1b797b07c3..4f3db5032fe53 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -468,6 +468,24 @@ dependencies = [ "cc 1.0.45 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "console_error_panic_hook" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", + "wasm-bindgen 0.2.51 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "console_log" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", + "web-sys 0.3.28 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "const-random" version = "0.1.6" @@ -1153,6 +1171,7 @@ dependencies = [ "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.2.62 (registry+https://github.com/rust-lang/crates.io-index)", "wasi 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", + "wasm-bindgen 0.2.51 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -2377,12 +2396,17 @@ dependencies = [ name = "node-cli" version = "2.0.0" dependencies = [ + "clear_on_drop 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", + "console_error_panic_hook 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", + "console_log 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", "ctrlc 3.1.3 (registry+https://github.com/rust-lang/crates.io-index)", "exit-future 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", "futures 0.1.29 (registry+https://github.com/rust-lang/crates.io-index)", "futures-preview 0.3.0-alpha.19 (registry+https://github.com/rust-lang/crates.io-index)", "hex-literal 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", + "js-sys 0.3.28 (registry+https://github.com/rust-lang/crates.io-index)", "jsonrpc-core 13.2.0 (registry+https://github.com/rust-lang/crates.io-index)", + "libp2p 0.12.0 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", "node-executor 2.0.0", "node-primitives 2.0.0", @@ -2428,6 +2452,8 @@ dependencies = [ "tokio 0.1.22 (registry+https://github.com/rust-lang/crates.io-index)", "transaction-factory 0.0.1", "vergen 3.0.4 (registry+https://github.com/rust-lang/crates.io-index)", + "wasm-bindgen 0.2.51 (registry+https://github.com/rust-lang/crates.io-index)", + "wasm-bindgen-futures 0.3.27 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -6909,6 +6935,8 @@ dependencies = [ "checksum clear_on_drop 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "97276801e127ffb46b66ce23f35cc96bd454fa311294bced4bbace7baa8b1d17" "checksum cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" "checksum cmake 0.1.42 (registry+https://github.com/rust-lang/crates.io-index)" = "81fb25b677f8bf1eb325017cb6bb8452f87969db0fedb4f757b297bee78a7c62" +"checksum console_error_panic_hook 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "b8d976903543e0c48546a91908f21588a680a8c8f984df9a5d69feccb2b2a211" +"checksum console_log 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "1e7871d2947441b0fdd8e2bd1ce2a2f75304f896582c0d572162d48290683c48" "checksum const-random 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "7b641a8c9867e341f3295564203b1c250eb8ce6cb6126e007941f78c4d2ed7fe" "checksum const-random-macro 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c750ec12b83377637110d5a57f5ae08e895b06c4b16e2bdbf1a94ef717428c59" "checksum constant_time_eq 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)" = "995a44c877f9212528ccc74b21a232f66ad69001e40ede5bcee2ac9ef2657120" diff --git a/core/service/src/lib.rs b/core/service/src/lib.rs index bc1a15542de81..c46732d511b3e 100644 --- a/core/service/src/lib.rs +++ b/core/service/src/lib.rs @@ -550,6 +550,7 @@ fn start_rpc_servers rpc_servers::RpcHandler+u2qR5bj(d7VXk&w|jQbIxLPKhB5DS^?QA~Be> zGziGpzKj3wJKu9I=j@F4zQ5;ve)Zn>E>cVL2@Mq+6$uFmjk?-nZ4#18f){_3q`)_D zIm|2x$>n3MXF4jp|8W2QeLg-uetv!d0RcflK_MX_VPRnr5fKOg(F;6y@IXvVOdNoO zxP*j+q@<*jl$1088EF|AnTHP_$^wwPz@tZxgej~>gnm} z128Z!Ff=eUG&BNWY;0^|YyvZZ!CuI668y0eJoTwX?Ici?fT1iz@&(H#c`TcMo?D0G^(nZ{ED| zdgJxh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~3M2gg`)O zN3$d|mW$L20ge~zrvi)yn1~9?K(440E-ixG4nGO=1(=1%MEs=To>gTc-xklF3>>Oq zgB}t{aG>7ijI!&(v|Q)k>myRckXq5Ez!c;6s)l%{Bb1KB5EbJ1LTlEou5<0qe^zW* z2y(S2+u@mxs|;JFiHI!c8{@bn-M_YNmm4owka3EM0Vm4!z`IxFsV}<}tlY`OfmJ-}<4~#C%tg;VaDcg59pyYHfOUbyeuwzW2E zg;`@kNfyAW`lD>(0L{&@pyFn5ZaUdH?UF*U%iPiT+>#CbVtCU(5xM}8kLy>Xw5G?q+ z=hO$LJ~osa53#is%tIu3edF+91j7VN?>*qAOxmKQg(9{Ictd=sJTJjQv@%#~2@L$> za1La6{QAgPc2VKmK*MVX4t$^}Qfp59-LdlIj$clfI{(N(P}{q0G2-=R%^NkAs2Amf zl~#C*TE*=jG~6a$&lk?M9!@0UNjt#QZgC?2d+U~t#*9ADb3~CYbKzcXOM> zkA2Oy&4tvpKWYL7{IsB&eO7?QB#NClnuE^Q+rE>oM^gZnhG&}tH=n_eU>w&F5r|jN z&)S>4Rajd^21HicpWl%WGY?(S-W24olWU%oE}Le>3JaF#^CRUWn17ykjP<}#-(#X5 zZ6CjX!J9rILttow&%CTmd4RsEHE>Gemslzw7k;P;)7p)oVksZ4oj z6yqEBqrS+rd_4c)?~QA-%jKAfUd@KIRhb3jdR@(!=wy_c35+n#+jzHDU#~B@SG8(m zIqHsHlTp=pNh*J=!I4`heW_`Mf#t*|lSZje!&0PfrM^J<22=3Ub9ueM)Z0O2WjVkv PrbyIPG#^(enFsw3U`DIs literal 0 HcmV?d00001 diff --git a/node/cli/browser-demo/index.html b/node/cli/browser-demo/index.html new file mode 100644 index 0000000000000..123f146bf25e0 --- /dev/null +++ b/node/cli/browser-demo/index.html @@ -0,0 +1,42 @@ + + + + + Substrate node + + + + + diff --git a/node/cli/browser-demo/ws.js b/node/cli/browser-demo/ws.js new file mode 100644 index 0000000000000..320f742a12ade --- /dev/null +++ b/node/cli/browser-demo/ws.js @@ -0,0 +1,148 @@ +// Copyright 2018-2019 Parity Technologies (UK) Ltd. +// This file is part of Substrate. + +// Substrate 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. + +// Substrate 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. If not, see . + +export default () => { + return { + dial: dial, + listen_on: (addr) => { + let err = new Error("Listening on WebSockets is not possible from within a browser"); + err.name = "NotSupportedError"; + throw err; + }, + }; +} + +/// Turns a string multiaddress into a WebSockets string URL. +// TODO: support dns addresses as well +const multiaddr_to_ws = (addr) => { + let parsed = addr.match(/^\/(ip4|ip6|dns4|dns6)\/(.*?)\/tcp\/(.*?)\/(ws|wss|x-parity-ws\/(.*)|x-parity-wss\/(.*))$/); + let proto = 'wss'; + if (parsed[4] == 'ws' || parsed[4] == 'x-parity-ws') { + proto = 'ws'; + } + let url = decodeURIComponent(parsed[5] || parsed[6] || ''); + if (parsed != null) { + if (parsed[1] == 'ip6') { + return proto + "://[" + parsed[2] + "]:" + parsed[3] + url; + } else { + return proto + "://" + parsed[2] + ":" + parsed[3] + url; + } + } + + let err = new Error("Address not supported: " + addr); + err.name = "NotSupportedError"; + throw err; +} + +// Attempt to dial a multiaddress. +const dial = (addr) => { + let ws = new WebSocket(multiaddr_to_ws(addr)); + let reader = read_queue(); + + return new Promise((resolve, reject) => { + // TODO: handle ws.onerror properly after dialing has happened + ws.onerror = (ev) => reject(ev); + ws.onmessage = (ev) => reader.inject_blob(ev.data); + ws.onclose = () => reader.inject_eof(); + ws.onopen = () => resolve({ + read: (function*() { while(ws.readyState == 1) { yield reader.next(); } })(), + write: (data) => { + if (ws.readyState == 1) { + ws.send(data); + return promise_when_ws_finished(ws); + } else { + return Promise.reject("WebSocket is closed"); + } + }, + shutdown: () => {}, + close: () => ws.close() + }); + }); +} + +// Takes a WebSocket object and returns a Promise that resolves when bufferedAmount is 0. +const promise_when_ws_finished = (ws) => { + if (ws.bufferedAmount == 0) { + return Promise.resolve(); + } + + return new Promise((resolve, reject) => { + setTimeout(function check() { + if (ws.bufferedAmount == 0) { + resolve(); + } else { + setTimeout(check, 100); + } + }, 2); + }) +} + +// Creates a queue reading system. +const read_queue = () => { + // State of the queue. + let state = { + // Array of promises resolving to `ArrayBuffer`s, that haven't been transmitted back with + // `next` yet. + queue: new Array(), + // If `resolve` isn't null, it is a "resolve" function of a promise that has already been + // returned by `next`. It should be called with some data. + resolve: null, + }; + + return { + // Inserts a new Blob in the queue. + inject_blob: (blob) => { + if (state.resolve != null) { + var resolve = state.resolve; + state.resolve = null; + + var reader = new FileReader(); + reader.addEventListener("loadend", () => resolve(reader.result)); + reader.readAsArrayBuffer(blob); + } else { + state.queue.push(new Promise((resolve, reject) => { + var reader = new FileReader(); + reader.addEventListener("loadend", () => resolve(reader.result)); + reader.readAsArrayBuffer(blob); + })); + } + }, + + // Inserts an EOF message in the queue. + inject_eof: () => { + if (state.resolve != null) { + var resolve = state.resolve; + state.resolve = null; + resolve(null); + } else { + state.queue.push(Promise.resolve(null)); + } + }, + + // Returns a Promise that yields the next entry as an ArrayBuffer. + next: () => { + if (state.queue.length != 0) { + return state.queue.shift(0); + } else { + if (state.resolve !== null) + throw "Internal error: already have a pending promise"; + return new Promise((resolve, reject) => { + state.resolve = resolve; + }); + } + } + }; +}; diff --git a/node/cli/src/browser.rs b/node/cli/src/browser.rs new file mode 100644 index 0000000000000..31db0524b96e1 --- /dev/null +++ b/node/cli/src/browser.rs @@ -0,0 +1,151 @@ +// Copyright 2018-2019 Parity Technologies (UK) Ltd. +// This file is part of Substrate. + +// Substrate 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. + +// Substrate 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. If not, see . + +#![cfg(feature = "browser")] + +use crate::ChainSpec; +use futures::{prelude::*, sync::oneshot, sync::mpsc}; +use libp2p::wasm_ext; +use log::{debug, info}; +use std::sync::Arc; +use substrate_service::{AbstractService, RpcSession, Roles as ServiceRoles, Configuration}; +use wasm_bindgen::prelude::*; + +/// Starts the client. +#[wasm_bindgen] +pub fn start_client(wasm_ext: wasm_ext::ffi::Transport) -> Result { + start_inner(wasm_ext) + .map_err(|err| JsValue::from_str(err.description())) +} + +fn start_inner(wasm_ext: wasm_ext::ffi::Transport) -> Result> { + console_error_panic_hook::set_once(); + console_log::init_with_level(log::Level::Info); + + let wasm_ext = wasm_ext::ExtTransport::new(wasm_ext); + + let chain_spec = ChainSpec::FlamingFir.load().map_err(|e| format!("{:?}", e))?; + let mut config = Configuration::<(), _, _>::default_with_spec(chain_spec); + config.network.transport = network::config::TransportConfig::Normal { + wasm_external_transport: Some(wasm_ext.clone()), + enable_mdns: false, + }; + config.telemetry_external_transport = Some(wasm_ext); + config.roles = ServiceRoles::FULL; + config.name = "Browser node".to_string(); + // TODO: config.database + + //info!("{}", version.name); + info!(" version {}", config.full_version()); + info!(" by Parity Technologies, 2017-2019"); + info!("Chain specification: {}", config.chain_spec.name()); + info!("Node name: {}", config.name); + info!("Roles: {:?}", config.roles); + + let mut service = new_full!(config) + .map_err(|e: String| format!("{:?}", e))?.0; + + /*let informant = substrate_cli::informant::build(&service); + wasm_bindgen_futures::spawn_local(informant);*/ + + let (rpc_send_tx, mut rpc_send_rx) = mpsc::unbounded::(); + wasm_bindgen_futures::spawn_local(futures::future::poll_fn(move || { + loop { + match rpc_send_rx.poll() { + Ok(Async::Ready(Some(message))) => { + let fut = service.rpc_query(&message.session, &message.rpc_json); + let _ = message.send_back.send(Box::new(fut)); + }, + Ok(Async::NotReady) => break, + Err(_) | Ok(Async::Ready(None)) => return Ok(Async::Ready(())), + } + } + + loop { + match service.poll().map_err(|_| ())? { + Async::Ready(()) => return Ok(Async::Ready(())), + Async::NotReady => break + } + } + + Ok(Async::NotReady) + })); + + Ok(Client { + rpc_send_tx, + }) +} + +/// A running client. +#[wasm_bindgen] +pub struct Client { + rpc_send_tx: mpsc::UnboundedSender, +} + +struct RpcMessage { + rpc_json: String, + session: RpcSession, + send_back: oneshot::Sender, Error = ()>>>, +} + +#[wasm_bindgen] +impl Client { + /// Allows starting an RPC request. Returns a `Promise` containing the result of that request. + #[wasm_bindgen(js_name = "rpcSend")] + pub fn rpc_send(&mut self, rpc: &str) -> js_sys::Promise { + let rpc_session = RpcSession::new(mpsc::channel(1).0); + let (tx, rx) = oneshot::channel(); + let _ = self.rpc_send_tx.unbounded_send(RpcMessage { + rpc_json: rpc.to_owned(), + session: rpc_session, + send_back: tx, + }); + let fut = rx + .map_err(|_| ()) + .and_then(|fut| fut) + .map(|s| JsValue::from_str(&s.unwrap_or(String::new()))) + .map_err(|_| JsValue::NULL); + wasm_bindgen_futures::future_to_promise(fut) + } + + /// Subscribes to an RPC pubsub endpoint. + #[wasm_bindgen(js_name = "rpcSubscribe")] + pub fn rpc_subscribe(&mut self, rpc: &str, callback: js_sys::Function) { + let (tx, rx) = mpsc::channel(4); + let rpc_session = RpcSession::new(tx); + let (fut_tx, fut_rx) = oneshot::channel(); + let _ = self.rpc_send_tx.unbounded_send(RpcMessage { + rpc_json: rpc.to_owned(), + session: rpc_session.clone(), + send_back: fut_tx, + }); + let fut_rx = fut_rx + .map_err(|_| ()) + .and_then(|fut| fut); + wasm_bindgen_futures::spawn_local(fut_rx.then(|_| Ok(()))); + wasm_bindgen_futures::spawn_local(rx.for_each(move |s| { + match callback.call1(&callback, &JsValue::from_str(&s)) { + Ok(_) => Ok(()), + Err(_) => Err(()), + } + }).then(move |v| { + // We need to keep `rpc_session` alive. + debug!("RPC subscription has ended"); + drop(rpc_session); + v + })); + } +} diff --git a/node/cli/src/lib.rs b/node/cli/src/lib.rs index ad79485209689..65accabb1f9cb 100644 --- a/node/cli/src/lib.rs +++ b/node/cli/src/lib.rs @@ -23,9 +23,12 @@ pub mod chain_spec; #[macro_use] mod service; +mod browser; mod cli; mod factory_impl; +#[cfg(feature = "browser")] +pub use browser::*; #[cfg(feature = "cli")] pub use cli::*; From 40b0dd11d957b313b79858ebc5fa77d343fbb99f Mon Sep 17 00:00:00 2001 From: Pierre Krieger Date: Wed, 30 Oct 2019 18:14:51 +0100 Subject: [PATCH 04/14] More work on browser node --- node/cli/browser-demo/index.html | 4 ++-- node/cli/src/browser.rs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/node/cli/browser-demo/index.html b/node/cli/browser-demo/index.html index 123f146bf25e0..ba80078c8800f 100644 --- a/node/cli/browser-demo/index.html +++ b/node/cli/browser-demo/index.html @@ -5,7 +5,7 @@ Substrate node