Skip to content

Commit 6c8eb8a

Browse files
expensesmxindentomaka
authored andcommitted
Companion PR for Substrate#4394 (paritytech#723)
* service/src/lib.rs: Register network event stream for authority disc Previously one would create a sender and receiver channel pair, pass the sender to the build_network_future through the service builder and funnel network events returned from polling the network service into the sender to be consumed by the authority discovery module owning the receiver. With recent changes it is now possible to register an event_stream with the network service directly, thus one does not need to make the detour through the build_network_future. This commit is an adjusted clone of one targeting the Substrate repository. * service/src/lib.rs: Fix futures::stream imports * [TMP] *: Replace polkadot-upstream with feature branch * Switch branch * Small change * Companion PR to substrate#4542 * Revert "Merge remote-tracking branch 'tomaka/companion-4542' into ashley-browser-utils" This reverts commit 17f00afe483ee65cb3cf4a0faca27034e6d6523a, reversing changes made to 928cbb9c55542baff56b53accd9a5a45f12f01f1. * ashley-browser-utils -> ashley-browser-utils-polkadot * Switch branches back Co-authored-by: Max Inden <[email protected]> Co-authored-by: Pierre Krieger <[email protected]>
1 parent 7207d97 commit 6c8eb8a

File tree

4 files changed

+45
-176
lines changed

4 files changed

+45
-176
lines changed

cli/Cargo.toml

Lines changed: 10 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -10,41 +10,27 @@ crate-type = ["cdylib", "rlib"]
1010

1111
[dependencies]
1212
log = "0.4.8"
13-
tokio = "0.1.22"
1413
futures = { version = "0.3.1", features = ["compat"] }
1514
futures01 = { package = "futures", version = "0.1.29" }
1615
structopt = "=0.3.7"
17-
cli = { package = "sc-cli", git = "https://github.com/paritytech/substrate", branch = "polkadot-master" }
16+
sc-cli = { git = "https://github.com/paritytech/substrate", branch = "polkadot-master" }
1817
service = { package = "polkadot-service", path = "../service", default-features = false }
1918

20-
libp2p = { version = "0.13.1", default-features = false, optional = true }
21-
wasm-bindgen = { version = "0.2.55", optional = true }
22-
wasm-bindgen-futures = { version = "0.4.5", optional = true }
23-
console_log = { version = "0.1.2", optional = true }
24-
console_error_panic_hook = { version = "0.1.1", optional = true }
25-
js-sys = { version = "0.3.22", optional = true }
26-
kvdb-web = { version = "0.1.1", optional = true }
27-
substrate-service = { package = "sc-service", git = "https://github.com/paritytech/substrate", branch = "polkadot-master", optional = true, default-features = false }
28-
substrate-network = { package = "sc-network", git = "https://github.com/paritytech/substrate", branch = "polkadot-master", optional = true }
19+
tokio = { version = "0.1.22", optional = true }
2920

30-
# Imported just for the `wasm-bindgen` feature
31-
rand = { version = "0.7", features = ["wasm-bindgen"], optional = true }
32-
rand6 = { package = "rand", version = "0.6.5", features = ["wasm-bindgen"], optional = true }
21+
wasm-bindgen = { version = "0.2.57", optional = true }
22+
wasm-bindgen-futures = { version = "0.4.7", optional = true }
23+
browser-utils = { package = "browser-utils", git = "https://github.com/paritytech/substrate", branch = "polkadot-master", optional = true }
24+
substrate-service = { package = "sc-service", git = "https://github.com/paritytech/substrate", branch = "polkadot-master", optional = true, default-features = false }
3325

3426
[features]
35-
default = [ "wasmtime", "rocksdb" ]
36-
wasmtime = [ "cli/wasmtime" ]
27+
default = [ "wasmtime", "rocksdb", "cli" ]
28+
wasmtime = [ "sc-cli/wasmtime" ]
3729
rocksdb = [ "service/rocksdb" ]
30+
cli = [ "tokio" ]
3831
browser = [
39-
"libp2p",
4032
"wasm-bindgen",
41-
"console_error_panic_hook",
4233
"wasm-bindgen-futures",
43-
"console_log",
44-
"js-sys",
45-
"kvdb-web",
34+
"browser-utils",
4635
"substrate-service",
47-
"substrate-network",
48-
"rand",
49-
"rand6",
5036
]

cli/src/browser.rs

Lines changed: 12 additions & 133 deletions
Original file line numberDiff line numberDiff line change
@@ -15,51 +15,28 @@
1515
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
1616

1717
use crate::ChainSpec;
18-
use futures01::{prelude::*, sync::oneshot, sync::mpsc};
19-
use libp2p::wasm_ext;
20-
use log::{debug, info};
21-
use std::sync::Arc;
22-
use service::{AbstractService, Roles as ServiceRoles};
23-
use substrate_service::{RpcSession, Configuration, config::DatabaseConfig};
18+
use log::info;
19+
use substrate_service::Configuration;
2420
use wasm_bindgen::prelude::*;
25-
use futures::{compat::*, TryFutureExt as _, TryStreamExt as _, FutureExt as _};
21+
use service::CustomConfiguration;
2622

2723
/// Starts the client.
2824
///
2925
/// You must pass a libp2p transport that supports .
3026
#[wasm_bindgen]
31-
pub async fn start_client(wasm_ext: wasm_ext::ffi::Transport) -> Result<Client, JsValue> {
27+
pub async fn start_client(wasm_ext: browser_utils::Transport) -> Result<browser_utils::Client, JsValue> {
3228
start_inner(wasm_ext)
3329
.await
3430
.map_err(|err| JsValue::from_str(&err.to_string()))
3531
}
3632

37-
async fn start_inner(wasm_ext: wasm_ext::ffi::Transport) -> Result<Client, Box<dyn std::error::Error>> {
38-
console_error_panic_hook::set_once();
39-
console_log::init_with_level(log::Level::Info);
33+
async fn start_inner(wasm_ext: browser_utils::Transport) -> Result<browser_utils::Client, Box<dyn std::error::Error>> {
34+
browser_utils::set_console_error_panic_hook();
35+
browser_utils::init_console_log(log::Level::Info)?;
4036

41-
// Build the configuration to pass to the service.
42-
let config = {
43-
let wasm_ext = wasm_ext::ExtTransport::new(wasm_ext);
44-
let chain_spec = ChainSpec::Kusama.load().map_err(|e| format!("{:?}", e))?;
45-
let mut config = Configuration::<service::CustomConfiguration, _, _>::default_with_spec_and_base_path(chain_spec, None);
46-
config.network.transport = substrate_network::config::TransportConfig::Normal {
47-
wasm_external_transport: Some(wasm_ext.clone()),
48-
allow_private_ipv4: true,
49-
enable_mdns: false,
50-
};
51-
config.telemetry_external_transport = Some(wasm_ext);
52-
config.roles = ServiceRoles::LIGHT;
53-
config.name = "Browser node".to_string();
54-
config.database = {
55-
let db = kvdb_web::Database::open("polkadot".into(), 10)
56-
.await
57-
.unwrap();
58-
DatabaseConfig::Custom(Arc::new(db))
59-
};
60-
config.keystore_path = Some(std::path::PathBuf::from("/"));
61-
config
62-
};
37+
let chain_spec = ChainSpec::Kusama.load().map_err(|e| format!("{:?}", e))?;
38+
let config: Configuration<CustomConfiguration, _, _> = browser_utils::browser_configuration(wasm_ext, chain_spec)
39+
.await?;
6340

6441
info!("Polkadot browser node");
6542
info!(" version {}", config.full_version());
@@ -76,105 +53,7 @@ async fn start_inner(wasm_ext: wasm_ext::ffi::Transport) -> Result<Client, Box<d
7653
info!("Roles: {:?}", config.roles);
7754

7855
// Create the service. This is the most heavy initialization step.
79-
let mut service = service::new_light(config).map_err(|e| format!("{:?}", e))?;
56+
let service = service::kusama_new_light(config).map_err(|e| format!("{:?}", e))?;
8057

81-
// We now dispatch a background task responsible for processing the service.
82-
//
83-
// The main action performed by the code below consists in polling the service with
84-
// `service.poll()`.
85-
// The rest consists in handling RPC requests.
86-
let (rpc_send_tx, mut rpc_send_rx) = mpsc::unbounded::<RpcMessage>();
87-
wasm_bindgen_futures::spawn_local(futures01::future::poll_fn(move || {
88-
loop {
89-
match rpc_send_rx.poll() {
90-
Ok(Async::Ready(Some(message))) => {
91-
let fut = service.rpc_query(&message.session, &message.rpc_json);
92-
let _ = message.send_back.send(Box::new(fut));
93-
},
94-
Ok(Async::NotReady) => break,
95-
Err(_) | Ok(Async::Ready(None)) => return Ok(Async::Ready(())),
96-
}
97-
}
98-
99-
loop {
100-
match service.poll().map_err(|_| ())? {
101-
Async::Ready(()) => return Ok(Async::Ready(())),
102-
Async::NotReady => break
103-
}
104-
}
105-
106-
Ok::<_, ()>(Async::NotReady)
107-
}).compat().map(drop));
108-
109-
Ok(Client {
110-
rpc_send_tx,
111-
})
112-
}
113-
114-
/// A running client.
115-
#[wasm_bindgen]
116-
pub struct Client {
117-
rpc_send_tx: mpsc::UnboundedSender<RpcMessage>,
118-
}
119-
120-
struct RpcMessage {
121-
rpc_json: String,
122-
session: RpcSession,
123-
send_back: oneshot::Sender<Box<dyn Future<Item = Option<String>, Error = ()> + Unpin>>,
124-
}
125-
126-
#[wasm_bindgen]
127-
impl Client {
128-
/// Allows starting an RPC request. Returns a `Promise` containing the result of that request.
129-
#[wasm_bindgen(js_name = "rpcSend")]
130-
pub fn rpc_send(&mut self, rpc: &str) -> js_sys::Promise {
131-
let rpc_session = RpcSession::new(mpsc::channel(1).0);
132-
let (tx, rx) = oneshot::channel();
133-
let _ = self.rpc_send_tx.unbounded_send(RpcMessage {
134-
rpc_json: rpc.to_owned(),
135-
session: rpc_session,
136-
send_back: tx,
137-
});
138-
let fut = rx
139-
.compat()
140-
.map_err(|_| ())
141-
.and_then(|fut| fut.compat())
142-
.map_ok(|s| JsValue::from_str(&s.unwrap_or(String::new())))
143-
.map_err(|_| JsValue::NULL);
144-
wasm_bindgen_futures::future_to_promise(fut)
145-
}
146-
147-
/// Subscribes to an RPC pubsub endpoint.
148-
#[wasm_bindgen(js_name = "rpcSubscribe")]
149-
pub fn rpc_subscribe(&mut self, rpc: &str, callback: js_sys::Function) {
150-
let (tx, rx) = mpsc::channel(4);
151-
let rpc_session = RpcSession::new(tx);
152-
let (fut_tx, fut_rx) = oneshot::channel();
153-
let _ = self.rpc_send_tx.unbounded_send(RpcMessage {
154-
rpc_json: rpc.to_owned(),
155-
session: rpc_session.clone(),
156-
send_back: fut_tx,
157-
});
158-
let fut_rx = fut_rx
159-
.compat()
160-
.map_err(|_| ())
161-
.and_then(|fut| fut.compat())
162-
.map(drop);
163-
wasm_bindgen_futures::spawn_local(fut_rx);
164-
wasm_bindgen_futures::spawn_local(rx
165-
.compat()
166-
.try_for_each(move |s| {
167-
match callback.call1(&callback, &JsValue::from_str(&s)) {
168-
Ok(_) => futures::future::ready(Ok(())),
169-
Err(_) => futures::future::ready(Err(())),
170-
}
171-
})
172-
.then(move |_| {
173-
// We need to keep `rpc_session` alive.
174-
debug!("RPC subscription has ended");
175-
drop(rpc_session);
176-
futures::future::ready(())
177-
})
178-
);
179-
}
58+
Ok(browser_utils::start_client(service))
18059
}

cli/src/lib.rs

Lines changed: 22 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ use chain_spec::ChainSpec;
2727
use futures::{
2828
Future, FutureExt, TryFutureExt, future::select, channel::oneshot, compat::Future01CompatExt,
2929
};
30+
#[cfg(feature = "cli")]
3031
use tokio::runtime::Runtime;
3132
use log::info;
3233
use structopt::StructOpt;
@@ -36,8 +37,8 @@ pub use service::{
3637
WrappedExecutor
3738
};
3839

39-
pub use cli::{VersionInfo, IntoExit, NoCustom, SharedParams};
40-
pub use cli::{display_role, error};
40+
pub use sc_cli::{VersionInfo, IntoExit, NoCustom, SharedParams};
41+
pub use sc_cli::{display_role, error};
4142

4243
/// Load the `ChainSpec` for the given `id`.
4344
pub fn load_spec(id: &str) -> Result<Option<service::ChainSpec>, String> {
@@ -53,8 +54,8 @@ enum PolkadotSubCommands {
5354
ValidationWorker(ValidationWorkerCommand),
5455
}
5556

56-
impl cli::GetSharedParams for PolkadotSubCommands {
57-
fn shared_params(&self) -> Option<&cli::SharedParams> { None }
57+
impl sc_cli::GetSharedParams for PolkadotSubCommands {
58+
fn shared_params(&self) -> Option<&sc_cli::SharedParams> { None }
5859
}
5960

6061
#[derive(Debug, StructOpt, Clone)]
@@ -70,16 +71,17 @@ struct PolkadotSubParams {
7071
}
7172

7273
/// Parses polkadot specific CLI arguments and run the service.
73-
pub fn run<E: IntoExit>(exit: E, version: cli::VersionInfo) -> error::Result<()> {
74-
let cmd = cli::parse_and_prepare::<PolkadotSubCommands, PolkadotSubParams, _>(
74+
#[cfg(feature = "cli")]
75+
pub fn run<E: IntoExit>(exit: E, version: sc_cli::VersionInfo) -> error::Result<()> {
76+
let cmd = sc_cli::parse_and_prepare::<PolkadotSubCommands, PolkadotSubParams, _>(
7577
&version,
7678
"parity-polkadot",
7779
std::env::args(),
7880
);
7981

8082
// Preload spec to select native runtime
8183
let spec = match cmd.shared_params() {
82-
Some(params) => Some(cli::load_spec(params, &load_spec)?),
84+
Some(params) => Some(sc_cli::load_spec(params, &load_spec)?),
8385
None => None,
8486
};
8587
if spec.as_ref().map_or(false, |c| c.is_kusama()) {
@@ -100,10 +102,11 @@ pub fn run<E: IntoExit>(exit: E, version: cli::VersionInfo) -> error::Result<()>
100102
}
101103

102104
/// Execute the given `cmd` with the given runtime.
105+
#[cfg(feature = "cli")]
103106
fn execute_cmd_with_runtime<R, D, E, X>(
104107
exit: X,
105-
version: &cli::VersionInfo,
106-
cmd: cli::ParseAndPrepare<PolkadotSubCommands, PolkadotSubParams>,
108+
version: &sc_cli::VersionInfo,
109+
cmd: sc_cli::ParseAndPrepare<PolkadotSubCommands, PolkadotSubParams>,
107110
spec: Option<service::ChainSpec>,
108111
) -> error::Result<()>
109112
where
@@ -120,7 +123,7 @@ where
120123
// Use preloaded spec
121124
let load_spec = |_: &str| Ok(spec);
122125
match cmd {
123-
cli::ParseAndPrepare::Run(cmd) => cmd.run(load_spec, exit,
126+
sc_cli::ParseAndPrepare::Run(cmd) => cmd.run(load_spec, exit,
124127
|exit, _cli_args, custom_args, mut config| {
125128
info!("{}", version.name);
126129
info!(" version {}", config.full_version());
@@ -154,17 +157,17 @@ where
154157
),
155158
}.map_err(|e| format!("{:?}", e))
156159
}),
157-
cli::ParseAndPrepare::BuildSpec(cmd) => cmd.run::<NoCustom, _, _, _>(load_spec),
158-
cli::ParseAndPrepare::ExportBlocks(cmd) => cmd.run_with_builder::<_, _, _, _, _, _, _>(|config|
160+
sc_cli::ParseAndPrepare::BuildSpec(cmd) => cmd.run::<NoCustom, _, _, _>(load_spec),
161+
sc_cli::ParseAndPrepare::ExportBlocks(cmd) => cmd.run_with_builder::<_, _, _, _, _, _, _>(|config|
159162
Ok(service::new_chain_ops::<R, D, E>(config)?), load_spec, exit),
160-
cli::ParseAndPrepare::ImportBlocks(cmd) => cmd.run_with_builder::<_, _, _, _, _, _, _>(|config|
163+
sc_cli::ParseAndPrepare::ImportBlocks(cmd) => cmd.run_with_builder::<_, _, _, _, _, _, _>(|config|
161164
Ok(service::new_chain_ops::<R, D, E>(config)?), load_spec, exit),
162-
cli::ParseAndPrepare::CheckBlock(cmd) => cmd.run_with_builder::<_, _, _, _, _, _, _>(|config|
165+
sc_cli::ParseAndPrepare::CheckBlock(cmd) => cmd.run_with_builder::<_, _, _, _, _, _, _>(|config|
163166
Ok(service::new_chain_ops::<R, D, E>(config)?), load_spec, exit),
164-
cli::ParseAndPrepare::PurgeChain(cmd) => cmd.run(load_spec),
165-
cli::ParseAndPrepare::RevertChain(cmd) => cmd.run_with_builder::<_, _, _, _, _, _>(|config|
167+
sc_cli::ParseAndPrepare::PurgeChain(cmd) => cmd.run(load_spec),
168+
sc_cli::ParseAndPrepare::RevertChain(cmd) => cmd.run_with_builder::<_, _, _, _, _, _>(|config|
166169
Ok(service::new_chain_ops::<R, D, E>(config)?), load_spec),
167-
cli::ParseAndPrepare::CustomCommand(PolkadotSubCommands::ValidationWorker(args)) => {
170+
sc_cli::ParseAndPrepare::CustomCommand(PolkadotSubCommands::ValidationWorker(args)) => {
168171
if cfg!(feature = "browser") {
169172
Err(error::Error::Input("Cannot run validation worker in browser".into()))
170173
} else {
@@ -177,6 +180,7 @@ where
177180
}
178181

179182
/// Run the given `service` using the `runtime` until it exits or `e` fires.
183+
#[cfg(feature = "cli")]
180184
pub fn run_until_exit(
181185
mut runtime: Runtime,
182186
service: impl AbstractService,
@@ -185,7 +189,7 @@ pub fn run_until_exit(
185189
let (exit_send, exit) = oneshot::channel();
186190

187191
let executor = runtime.executor();
188-
let informant = cli::informant::build(&service);
192+
let informant = sc_cli::informant::build(&service);
189193
let future = select(exit, informant)
190194
.map(|_| Ok(()))
191195
.compat();

service/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ consensus_common = { package = "sp-consensus", git = "https://github.com/parityt
3535
grandpa = { package = "sc-finality-grandpa", git = "https://github.com/paritytech/substrate", branch = "polkadot-master" }
3636
grandpa_primitives = { package = "sp-finality-grandpa", git = "https://github.com/paritytech/substrate", branch = "polkadot-master" }
3737
inherents = { package = "sp-inherents", git = "https://github.com/paritytech/substrate", branch = "polkadot-master" }
38-
service = { package = "sc-service", git = "https://github.com/paritytech/substrate", branch = "polkadot-master" }
38+
service = { package = "sc-service", git = "https://github.com/paritytech/substrate", branch = "polkadot-master", default-features = false }
3939
telemetry = { package = "sc-telemetry", git = "https://github.com/paritytech/substrate", branch = "polkadot-master" }
4040
sc-transaction-pool = { git = "https://github.com/paritytech/substrate", branch = "polkadot-master" }
4141
sp-transaction-pool = { git = "https://github.com/paritytech/substrate", branch = "polkadot-master" }

0 commit comments

Comments
 (0)