Skip to content

Commit

Permalink
Fix system rpc (#34)
Browse files Browse the repository at this point in the history
* Remove dummy build_system_rpc_future()

* Add protocol id to chain spec

* Fix clippy
  • Loading branch information
liuchengxu authored Aug 6, 2024
1 parent 033aeaa commit 9ab54e1
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 150 deletions.
4 changes: 2 additions & 2 deletions crates/subcoin-node/res/chain-spec-raw-bitcoin-mainnet.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"chainType": "Live",
"bootNodes": [],
"telemetryEndpoints": null,
"protocolId": null,
"protocolId": "subcoin-cc1",
"properties": {
"tokenDecimals": 8,
"tokenSymbol": "BTC"
Expand All @@ -27,4 +27,4 @@
"childrenDefault": {}
}
}
}
}
59 changes: 29 additions & 30 deletions crates/subcoin-node/src/commands/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ impl RunCmd {
/// Start subcoin node.
pub async fn start(
self,
config: Configuration,
mut config: Configuration,
run: Run,
no_hardware_benchmarks: bool,
storage_monitor: sc_storage_monitor::StorageMonitorParams,
Expand All @@ -111,7 +111,6 @@ impl RunCmd {
backend,
mut task_manager,
block_executor,
system_rpc_tx,
keystore_container,
telemetry,
..
Expand Down Expand Up @@ -170,6 +169,34 @@ impl RunCmd {
task_manager.keep_alive(bitcoin_network);
}

let system_rpc_tx = match config.network.network_backend {
sc_network::config::NetworkBackendType::Libp2p => {
subcoin_service::start_substrate_network::<
sc_network::NetworkWorker<
subcoin_runtime::interface::OpaqueBlock,
<subcoin_runtime::interface::OpaqueBlock as sp_runtime::traits::Block>::Hash,
>,
>(
&mut config,
client.clone(),
backend,
&mut task_manager,
keystore_container.keystore(),
telemetry,
)?
}
sc_network::config::NetworkBackendType::Litep2p => {
subcoin_service::start_substrate_network::<sc_network::Litep2pNetworkBackend>(
&mut config,
client.clone(),
backend,
&mut task_manager,
keystore_container.keystore(),
telemetry,
)?
}
};

// TODO: Bitcoin-compatible RPC
// Start JSON-RPC server.
let gen_rpc_module = |deny_unsafe: sc_rpc::DenyUnsafe| {
Expand All @@ -195,34 +222,6 @@ impl RunCmd {
let rpc = sc_service::start_rpc_servers(&config, gen_rpc_module, None)?;
task_manager.keep_alive((config.base_path.clone(), rpc));

match config.network.network_backend {
sc_network::config::NetworkBackendType::Libp2p => {
subcoin_service::start_substrate_network::<
sc_network::NetworkWorker<
subcoin_runtime::interface::OpaqueBlock,
<subcoin_runtime::interface::OpaqueBlock as sp_runtime::traits::Block>::Hash,
>,
>(
config,
client.clone(),
backend,
&mut task_manager,
keystore_container.keystore(),
telemetry,
)?;
}
sc_network::config::NetworkBackendType::Litep2p => {
subcoin_service::start_substrate_network::<sc_network::Litep2pNetworkBackend>(
config,
client.clone(),
backend,
&mut task_manager,
keystore_container.keystore(),
telemetry,
)?;
}
}

if !no_finalizer {
spawn_handle.spawn("finalizer", None, {
subcoin_service::finalize_confirmed_blocks(
Expand Down
8 changes: 4 additions & 4 deletions crates/subcoin-service/src/chain_spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ fn props() -> Properties {

pub fn config(network: bitcoin::Network) -> Result<ChainSpec, String> {
let (name, id) = match network {
bitcoin::Network::Bitcoin => ("Bitcoin", "mainnet"),
bitcoin::Network::Testnet => ("Bitcoin Testnet", "testnet"),
bitcoin::Network::Signet => ("Bitcoin Signet", "signet"),
bitcoin::Network::Regtest => ("Bitcoin Regtest", "regtest"),
bitcoin::Network::Bitcoin => ("Bitcoin Mainnet", "bitcoin-mainnet"),
bitcoin::Network::Testnet => ("Bitcoin Testnet", "bitcoin-testnet"),
bitcoin::Network::Signet => ("Bitcoin Signet", "bitcoin-signet"),
bitcoin::Network::Regtest => ("Bitcoin Regtest", "bitcoin-regtest"),
unknown_network => unreachable!("Unknown Bitcoin network: {unknown_network:?}"),
};
Ok(ChainSpec::builder(
Expand Down
123 changes: 9 additions & 114 deletions crates/subcoin-service/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,13 @@ use sc_consensus::import_queue::BasicQueue;
use sc_consensus::{BlockImportParams, Verifier};
use sc_consensus_nakamoto::{BlockExecutionStrategy, BlockExecutor};
use sc_executor::NativeElseWasmExecutor;
use sc_network::PeerId;
use sc_service::config::PrometheusConfig;
use sc_service::error::Error as ServiceError;
use sc_service::{
Configuration, KeystoreContainer, MetricsService, NativeExecutionDispatch, Role, TaskManager,
Configuration, KeystoreContainer, MetricsService, NativeExecutionDispatch, TaskManager,
};
use sc_telemetry::{Telemetry, TelemetryWorker};
use sc_utils::mpsc::{tracing_unbounded, TracingUnboundedReceiver, TracingUnboundedSender};
use sc_utils::mpsc::TracingUnboundedSender;
use sp_core::traits::SpawnNamed;
use sp_core::Encode;
use sp_keystore::KeystorePtr;
Expand Down Expand Up @@ -74,90 +73,6 @@ impl NativeExecutionDispatch for BitcoinExecutorDispatch {
}
}

/// Builds a future that processes system RPC requests.
///
/// This is adapted from the upstream `build_system_rpc_future`.
async fn build_system_rpc_future<Block, Client>(
role: Role,
client: Arc<Client>,
mut rpc_rx: TracingUnboundedReceiver<sc_rpc::system::Request<Block>>,
should_have_peers: bool,
) where
Block: BlockT,
Client: HeaderBackend<Block> + Send + Sync + 'static,
{
// Current best block at initialization, to report to the RPC layer.
let starting_block = client.info().best_number;

loop {
// Answer incoming RPC requests.
let Some(req) = rpc_rx.next().await else {
tracing::debug!(
"RPC requests stream has terminated, shutting down the system RPC future."
);
return;
};

match req {
sc_rpc::system::Request::Health(sender) => {
// TODO: Proper is_major_syncing
let _ = sender.send(sc_rpc::system::Health {
peers: 0,
is_syncing: false,
should_have_peers,
});
}
sc_rpc::system::Request::LocalPeerId(sender) => {
// TODO: Proper local peer id.
let _ = sender.send(PeerId::random().to_base58());
}
sc_rpc::system::Request::LocalListenAddresses(sender) => {
// TODO: Proper addresses
let _ = sender.send(Vec::new());
}
sc_rpc::system::Request::Peers(sender) => {
// TODO: Proper peers
let _ = sender.send(Vec::new());
}
sc_rpc::system::Request::NetworkState(sender) => {
// TODO: Proper network state.
let _ = sender.send(serde_json::Value::Null);
}
sc_rpc::system::Request::NetworkAddReservedPeer(_peer_addr, _sender) => {
unreachable!("NetworkAddReservedPeer");
}
sc_rpc::system::Request::NetworkRemoveReservedPeer(_peer_id, _sender) => {
unreachable!("NetworkRemoveReservedPeer");
}
sc_rpc::system::Request::NetworkReservedPeers(sender) => {
let _ = sender.send(Vec::new());
}
sc_rpc::system::Request::NodeRoles(sender) => {
use sc_rpc::system::NodeRole;

let node_role = match role {
Role::Authority { .. } => NodeRole::Authority,
Role::Full => NodeRole::Full,
};

let _ = sender.send(vec![node_role]);
}
sc_rpc::system::Request::SyncState(sender) => {
use sc_rpc::system::SyncState;

let best_number = client.info().best_number;

// TODO: Proper highest_block
let _ = sender.send(SyncState {
starting_block,
current_block: best_number,
highest_block: best_number,
});
}
}
}
}

pub struct CoinStorageKey;

impl subcoin_primitives::CoinStorageKey for CoinStorageKey {
Expand All @@ -182,8 +97,6 @@ pub struct NodeComponents {
pub task_manager: TaskManager,
/// Block processor used in the block import pipeline.
pub block_executor: Box<dyn BlockExecutor<Block>>,
/// TODO: useless, remove later?
pub system_rpc_tx: TracingUnboundedSender<sc_rpc::system::Request<Block>>,
pub keystore_container: KeystoreContainer,
pub telemetry: Option<Telemetry>,
}
Expand Down Expand Up @@ -297,21 +210,6 @@ pub fn new_node(config: SubcoinConfiguration) -> Result<NodeComponents, ServiceE
telemetry
});

let has_bootnodes = false;

let spawner = task_manager.spawn_handle();
let (system_rpc_tx, system_rpc_rx) = tracing_unbounded("mpsc_system_rpc", 10_000);
spawner.spawn(
"system-rpc-handler",
Some("networking"),
build_system_rpc_future(
config.role.clone(),
client.clone(),
system_rpc_rx,
has_bootnodes,
),
);

let database_path = config.database.path().map(Path::to_path_buf);
let maybe_hwbench = (!no_hardware_benchmarks)
.then_some(database_path.as_ref().map(|db_path| {
Expand Down Expand Up @@ -356,21 +254,20 @@ pub fn new_node(config: SubcoinConfiguration) -> Result<NodeComponents, ServiceE
executor,
task_manager,
block_executor,
system_rpc_tx,
keystore_container,
telemetry,
})
}

/// Runs the Substrate networking.
pub fn start_substrate_network<N>(
mut config: Configuration,
config: &mut Configuration,
client: Arc<FullClient>,
_backend: Arc<FullBackend>,
task_manager: &mut TaskManager,
_keystore: KeystorePtr,
mut telemetry: Option<Telemetry>,
) -> Result<(), ServiceError>
) -> Result<TracingUnboundedSender<sc_rpc::system::Request<Block>>, ServiceError>
where
N: sc_network::NetworkBackend<Block, <Block as BlockT>::Hash>,
{
Expand Down Expand Up @@ -398,7 +295,7 @@ where

let (network, system_rpc_tx, _tx_handler_controller, network_starter, sync_service) =
sc_service::build_network(sc_service::BuildNetworkParams {
config: &config,
config,
net_config,
client: client.clone(),
transaction_pool: transaction_pool.clone(),
Expand All @@ -420,7 +317,7 @@ where
.as_mut()
.map(|telemetry| {
sc_service::init_telemetry(
&mut config,
config,
network.clone(),
client.clone(),
telemetry,
Expand All @@ -433,7 +330,7 @@ where
let metrics_service =
if let Some(PrometheusConfig { port, registry }) = config.prometheus_config.clone() {
// Set static metrics.
let metrics = MetricsService::with_prometheus(telemetry, &registry, &config)?;
let metrics = MetricsService::with_prometheus(telemetry, &registry, config)?;
spawn_handle.spawn(
"prometheus-endpoint",
None,
Expand Down Expand Up @@ -464,15 +361,13 @@ where
client.clone(),
Arc::new(network),
sync_service.clone(),
config.informant_output_format,
config.informant_output_format.clone(),
),
);

task_manager.keep_alive(system_rpc_tx);

network_starter.start_network();

Ok(())
Ok(system_rpc_tx)
}

/// Creates a future to finalize blocks with enough confirmations.
Expand Down

0 comments on commit 9ab54e1

Please sign in to comment.