Skip to content

Commit 84d5d45

Browse files
authored
Various improvements (#48)
* Introduce RpcParams into run cmd * No need to clone params in Run * Use proper subcoin is_major_syncing signal * Clean up TODOs * Rename to subcoin_params.rs * Add book.toml * Docs
1 parent 35eebfb commit 84d5d45

File tree

16 files changed

+317
-40
lines changed

16 files changed

+317
-40
lines changed

crates/sc-consensus-nakamoto/src/block_executor.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -503,12 +503,14 @@ where
503503
}
504504
}
505505

506+
/// Executor for benchmarking the runtime execution with different backends.
506507
pub struct BenchmarkRuntimeBlockExecutor<Block: BlockT> {
507508
disk_runtime_block_executor: Box<dyn BlockExecutor<Block>>,
508509
in_memory_runtime_block_executor: Box<dyn BlockExecutor<Block>>,
509510
}
510511

511512
impl<Block: BlockT> BenchmarkRuntimeBlockExecutor<Block> {
513+
/// Constructs a new instance of [`BenchmarkRuntimeBlockExecutor`].
512514
pub fn new(
513515
disk_runtime_block_executor: Box<dyn BlockExecutor<Block>>,
514516
in_memory_runtime_block_executor: Box<dyn BlockExecutor<Block>>,
@@ -581,6 +583,7 @@ impl<Block: BlockT> BlockExecutor<Block> for BenchmarkRuntimeBlockExecutor<Block
581583
}
582584
}
583585

586+
/// This is responsible for benchmarking all kinds of block executors.
584587
pub struct BenchmarkAllExecutor<
585588
Block,
586589
DiskRuntime,
@@ -598,6 +601,7 @@ pub struct BenchmarkAllExecutor<
598601
impl<Block, DiskRuntime, InMemoryRuntime, DiskOffRuntime, InMemoryOffRuntime>
599602
BenchmarkAllExecutor<Block, DiskRuntime, InMemoryRuntime, DiskOffRuntime, InMemoryOffRuntime>
600603
{
604+
/// Constructs a new instance of [`BenchmarkAllExecutor`].
601605
pub fn new(
602606
disk_runtime_block_executor: DiskRuntime,
603607
in_memory_runtime_block_executor: InMemoryRuntime,

crates/sc-consensus-nakamoto/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ pub use import_queue::{
1919
};
2020
pub use verification::{BlockVerification, BlockVerifier, HeaderVerifier};
2121

22+
/// Consensus error type.
2223
#[derive(Debug, thiserror::Error)]
2324
pub enum Error {
2425
#[error("Header uses the wrong engine {0:?}")]

crates/subcoin-informant/src/lib.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -84,8 +84,7 @@ where
8484
}
8585
});
8686

87-
// TODO: proper status
88-
let is_major_syncing = Arc::new(true.into());
87+
let is_major_syncing = network.is_major_syncing();
8988

9089
futures::select! {
9190
() = display_notifications.fuse() => (),

crates/subcoin-network/src/lib.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,7 @@ impl Clone for Bandwidth {
199199
}
200200
}
201201

202+
/// Represents the result of sending a transaction to the network.
202203
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
203204
#[serde(rename_all = "camelCase")]
204205
pub enum SendTransactionResult {
@@ -270,6 +271,7 @@ impl NetworkHandle {
270271
receiver.await.unwrap_or_default()
271272
}
272273

274+
/// Fetches the transaction for given txid.
273275
pub async fn get_transaction(&self, txid: Txid) -> Option<Transaction> {
274276
let (sender, receiver) = oneshot::channel();
275277

@@ -284,6 +286,7 @@ impl NetworkHandle {
284286
receiver.await.ok().flatten()
285287
}
286288

289+
/// Sends an transaction to the network.
287290
pub async fn send_transaction(&self, transaction: Transaction) -> SendTransactionResult {
288291
let (sender, receiver) = oneshot::channel();
289292

@@ -308,6 +311,7 @@ impl NetworkHandle {
308311
.unwrap_or(SendTransactionResult::Failure("Internal error".to_string()))
309312
}
310313

314+
/// Starts the block sync in chain sync component.
311315
pub fn start_block_sync(&self) -> bool {
312316
self.worker_msg_sender
313317
.unbounded_send(NetworkWorkerMessage::StartBlockSync)

crates/subcoin-node/src/cli.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
pub mod params;
1+
pub mod rpc_params;
2+
pub mod subcoin_params;
23

34
use crate::commands::blockchain::{Blockchain, BlockchainCmd};
45
use crate::commands::import_blocks::{ImportBlocks, ImportBlocksCmd};
@@ -86,11 +87,11 @@ pub fn run() -> sc_cli::Result<()> {
8687

8788
match command {
8889
Command::Run(run) => {
89-
let run_cmd = RunCmd::new(&run);
90+
let run_cmd = RunCmd::new(*run);
9091
let runner = SubstrateCli.create_runner(&run_cmd)?;
9192
runner.run_node_until_exit(|config| async move {
9293
run_cmd
93-
.start(config, *run, no_hardware_benchmarks, storage_monitor)
94+
.start(config, no_hardware_benchmarks, storage_monitor)
9495
.await
9596
})
9697
}
Lines changed: 180 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,180 @@
1+
use clap::Parser;
2+
use sc_cli::{
3+
Cors, RpcMethods, RPC_DEFAULT_MAX_CONNECTIONS, RPC_DEFAULT_MAX_REQUEST_SIZE_MB,
4+
RPC_DEFAULT_MAX_RESPONSE_SIZE_MB, RPC_DEFAULT_MAX_SUBS_PER_CONN,
5+
RPC_DEFAULT_MESSAGE_CAPACITY_PER_CONN,
6+
};
7+
use sc_service::config::IpNetwork;
8+
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
9+
use std::num::NonZeroU32;
10+
11+
/// RPC parameters extracted from the upstream RunCmd.
12+
#[derive(Debug, Clone, Parser)]
13+
pub struct RpcParams {
14+
/// Listen to all RPC interfaces (default: local).
15+
///
16+
/// Not all RPC methods are safe to be exposed publicly.
17+
///
18+
/// Use an RPC proxy server to filter out dangerous methods. More details:
19+
/// <https://docs.substrate.io/build/remote-procedure-calls/#public-rpc-interfaces>.
20+
///
21+
/// Use `--unsafe-rpc-external` to suppress the warning if you understand the risks.
22+
#[arg(long)]
23+
pub rpc_external: bool,
24+
25+
/// Listen to all RPC interfaces.
26+
///
27+
/// Same as `--rpc-external`.
28+
#[arg(long)]
29+
pub unsafe_rpc_external: bool,
30+
31+
/// RPC methods to expose.
32+
#[arg(
33+
long,
34+
value_name = "METHOD SET",
35+
value_enum,
36+
ignore_case = true,
37+
default_value_t = RpcMethods::Auto,
38+
verbatim_doc_comment
39+
)]
40+
pub rpc_methods: RpcMethods,
41+
42+
/// RPC rate limiting (calls/minute) for each connection.
43+
///
44+
/// This is disabled by default.
45+
///
46+
/// For example `--rpc-rate-limit 10` will maximum allow
47+
/// 10 calls per minute per connection.
48+
#[arg(long)]
49+
pub rpc_rate_limit: Option<NonZeroU32>,
50+
51+
/// Disable RPC rate limiting for certain ip addresses.
52+
///
53+
/// Each IP address must be in CIDR notation such as `1.2.3.4/24`.
54+
#[arg(long, num_args = 1..)]
55+
pub rpc_rate_limit_whitelisted_ips: Vec<IpNetwork>,
56+
57+
/// Trust proxy headers for disable rate limiting.
58+
///
59+
/// By default the rpc server will not trust headers such `X-Real-IP`, `X-Forwarded-For` and
60+
/// `Forwarded` and this option will make the rpc server to trust these headers.
61+
///
62+
/// For instance this may be secure if the rpc server is behind a reverse proxy and that the
63+
/// proxy always sets these headers.
64+
#[arg(long)]
65+
pub rpc_rate_limit_trust_proxy_headers: bool,
66+
67+
/// Set the maximum RPC request payload size for both HTTP and WS in megabytes.
68+
#[arg(long, default_value_t = RPC_DEFAULT_MAX_REQUEST_SIZE_MB)]
69+
pub rpc_max_request_size: u32,
70+
71+
/// Set the maximum RPC response payload size for both HTTP and WS in megabytes.
72+
#[arg(long, default_value_t = RPC_DEFAULT_MAX_RESPONSE_SIZE_MB)]
73+
pub rpc_max_response_size: u32,
74+
75+
/// Set the maximum concurrent subscriptions per connection.
76+
#[arg(long, default_value_t = RPC_DEFAULT_MAX_SUBS_PER_CONN)]
77+
pub rpc_max_subscriptions_per_connection: u32,
78+
79+
/// Specify JSON-RPC server TCP port.
80+
#[arg(long, value_name = "PORT")]
81+
pub rpc_port: Option<u16>,
82+
83+
/// Maximum number of RPC server connections.
84+
#[arg(long, value_name = "COUNT", default_value_t = RPC_DEFAULT_MAX_CONNECTIONS)]
85+
pub rpc_max_connections: u32,
86+
87+
/// The number of messages the RPC server is allowed to keep in memory.
88+
///
89+
/// If the buffer becomes full then the server will not process
90+
/// new messages until the connected client start reading the
91+
/// underlying messages.
92+
///
93+
/// This applies per connection which includes both
94+
/// JSON-RPC methods calls and subscriptions.
95+
#[arg(long, default_value_t = RPC_DEFAULT_MESSAGE_CAPACITY_PER_CONN)]
96+
pub rpc_message_buffer_capacity_per_connection: u32,
97+
98+
/// Disable RPC batch requests
99+
#[arg(long, alias = "rpc_no_batch_requests", conflicts_with_all = &["rpc_max_batch_request_len"])]
100+
pub rpc_disable_batch_requests: bool,
101+
102+
/// Limit the max length per RPC batch request
103+
#[arg(long, conflicts_with_all = &["rpc_disable_batch_requests"], value_name = "LEN")]
104+
pub rpc_max_batch_request_len: Option<u32>,
105+
106+
/// Specify browser *origins* allowed to access the HTTP & WS RPC servers.
107+
///
108+
/// A comma-separated list of origins (protocol://domain or special `null`
109+
/// value). Value of `all` will disable origin validation. Default is to
110+
/// allow localhost and <https://polkadot.js.org> origins. When running in
111+
/// `--dev` mode the default is to allow all origins.
112+
#[arg(long, value_name = "ORIGINS")]
113+
pub rpc_cors: Option<Cors>,
114+
}
115+
116+
impl RpcParams {
117+
pub(crate) fn rpc_cors(&self, is_dev: bool) -> sc_cli::Result<Option<Vec<String>>> {
118+
Ok(self
119+
.rpc_cors
120+
.clone()
121+
.unwrap_or_else(|| {
122+
if is_dev {
123+
tracing::warn!("Running in --dev mode, RPC CORS has been disabled.");
124+
Cors::All
125+
} else {
126+
Cors::List(vec![
127+
"http://localhost:*".into(),
128+
"http://127.0.0.1:*".into(),
129+
"https://localhost:*".into(),
130+
"https://127.0.0.1:*".into(),
131+
"https://polkadot.js.org".into(),
132+
])
133+
}
134+
})
135+
.into())
136+
}
137+
138+
pub(crate) fn rpc_addr(&self, default_listen_port: u16) -> sc_cli::Result<Option<SocketAddr>> {
139+
let interface = rpc_interface(
140+
self.rpc_external,
141+
self.unsafe_rpc_external,
142+
self.rpc_methods,
143+
false, // TODO: miner
144+
)?;
145+
146+
Ok(Some(SocketAddr::new(
147+
interface,
148+
self.rpc_port.unwrap_or(default_listen_port),
149+
)))
150+
}
151+
}
152+
153+
fn rpc_interface(
154+
is_external: bool,
155+
is_unsafe_external: bool,
156+
rpc_methods: RpcMethods,
157+
is_validator: bool,
158+
) -> sc_cli::Result<IpAddr> {
159+
if is_external && is_validator && rpc_methods != RpcMethods::Unsafe {
160+
return Err(sc_cli::Error::Input(
161+
"--rpc-external option shouldn't be used if the node is running as \
162+
a validator. Use `--unsafe-rpc-external` or `--rpc-methods=unsafe` if you understand \
163+
the risks. See the options description for more information."
164+
.to_owned(),
165+
));
166+
}
167+
168+
if is_external || is_unsafe_external {
169+
if rpc_methods == RpcMethods::Unsafe {
170+
tracing::warn!(
171+
"It isn't safe to expose RPC publicly without a proxy server that filters \
172+
available set of RPC methods."
173+
);
174+
}
175+
176+
Ok(Ipv4Addr::UNSPECIFIED.into())
177+
} else {
178+
Ok(Ipv4Addr::LOCALHOST.into())
179+
}
180+
}
File renamed without changes.

crates/subcoin-node/src/commands/blockchain.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use crate::cli::params::CommonParams;
1+
use crate::cli::subcoin_params::CommonParams;
22
use crate::utils::Yield;
33
use sc_cli::{ImportParams, NodeKeyParams, SharedParams};
44
use sc_client_api::{HeaderBackend, StorageProvider};

crates/subcoin-node/src/commands/import_blocks.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use crate::cli::params::CommonParams;
1+
use crate::cli::subcoin_params::CommonParams;
22
use crate::utils::Yield;
33
use bitcoin_explorer::BitcoinDB;
44
use futures::FutureExt;

0 commit comments

Comments
 (0)