Run cargo fmt on the whole code base (#9394)

* Run cargo fmt on the whole code base

* Second run

* Add CI check

* Fix compilation

* More unnecessary braces

* Handle weights

* Use --all

* Use correct attributes...

* Fix UI tests

* AHHHHHHHHH

* 🤦

* Docs

* Fix compilation

* 🤷

* Please stop

* 🤦 x 2

* More

* make rustfmt.toml consistent with polkadot

Co-authored-by: André Silva <andrerfosilva@gmail.com>
This commit is contained in:
Bastian Köcher
2021-07-21 16:32:32 +02:00
committed by GitHub
parent d451c38c1c
commit 7b56ab15b4
1010 changed files with 53339 additions and 51208 deletions
+285 -292
View File
@@ -17,65 +17,52 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use crate::{
error::Error, MallocSizeOfWasm, RpcHandlers,
start_rpc_servers, build_network_future, TransactionPoolAdapter, TaskManager, SpawnTaskHandle,
metrics::MetricsService,
build_network_future,
client::{light, Client, ClientConfig},
config::{Configuration, KeystoreConfig, PrometheusConfig, TransactionStorageMode},
error::Error,
metrics::MetricsService,
start_rpc_servers, MallocSizeOfWasm, RpcHandlers, SpawnTaskHandle, TaskManager,
TransactionPoolAdapter,
};
use sc_client_api::{
light::RemoteBlockchain, ForkBlocks, BadBlocks, UsageProvider, ExecutorProvider,
};
use sp_utils::mpsc::{tracing_unbounded, TracingUnboundedSender};
use futures::{channel::oneshot, future::ready, FutureExt, StreamExt};
use jsonrpc_pubsub::manager::SubscriptionManager;
use log::info;
use prometheus_endpoint::Registry;
use sc_chain_spec::get_extension;
use sc_client_api::{
execution_extensions::ExecutionExtensions, light::RemoteBlockchain,
proof_provider::ProofProvider, BadBlocks, BlockBackend, BlockchainEvents, ExecutorProvider,
ForkBlocks, StorageProvider, UsageProvider,
};
use sc_client_db::{Backend, DatabaseSettings};
use sc_executor::{NativeExecutionDispatch, NativeExecutor, RuntimeInfo};
use sc_keystore::LocalKeystore;
use sc_network::{
block_request_handler::{self, BlockRequestHandler},
config::{OnDemand, Role, SyncMode},
light_client_requests::{self, handler::LightClientRequestHandler},
state_request_handler::{self, StateRequestHandler},
NetworkService,
};
use sc_telemetry::{telemetry, ConnectionMessage, Telemetry, TelemetryHandle, SUBSTRATE_INFO};
use sc_transaction_pool_api::MaintainedTransactionPool;
use sp_api::{CallApiAt, ProvideRuntimeApi};
use sp_blockchain::{HeaderBackend, HeaderMetadata};
use sp_consensus::{
block_validation::{BlockAnnounceValidator, DefaultBlockAnnounceValidator, Chain},
block_validation::{BlockAnnounceValidator, Chain, DefaultBlockAnnounceValidator},
import_queue::ImportQueue,
};
use jsonrpc_pubsub::manager::SubscriptionManager;
use futures::{
FutureExt, StreamExt,
future::ready,
channel::oneshot,
};
use sc_keystore::LocalKeystore;
use log::info;
use sc_network::config::{Role, OnDemand, SyncMode};
use sc_network::NetworkService;
use sc_network::block_request_handler::{self, BlockRequestHandler};
use sc_network::state_request_handler::{self, StateRequestHandler};
use sc_network::light_client_requests::{self, handler::LightClientRequestHandler};
use sp_runtime::generic::BlockId;
use sp_runtime::traits::{
Block as BlockT, HashFor, Zero, BlockIdTo,
};
use sp_api::{ProvideRuntimeApi, CallApiAt};
use sc_executor::{NativeExecutor, NativeExecutionDispatch, RuntimeInfo};
use std::{sync::Arc, str::FromStr};
use wasm_timer::SystemTime;
use sc_telemetry::{
telemetry,
ConnectionMessage,
Telemetry,
TelemetryHandle,
SUBSTRATE_INFO,
};
use sc_transaction_pool_api::MaintainedTransactionPool;
use prometheus_endpoint::Registry;
use sc_client_db::{Backend, DatabaseSettings};
use sp_core::traits::{
CodeExecutor,
SpawnNamed,
};
use sp_core::traits::{CodeExecutor, SpawnNamed};
use sp_keystore::{CryptoStore, SyncCryptoStore, SyncCryptoStorePtr};
use sp_runtime::BuildStorage;
use sc_client_api::{
BlockBackend, BlockchainEvents,
StorageProvider,
proof_provider::ProofProvider,
execution_extensions::ExecutionExtensions
use sp_runtime::{
generic::BlockId,
traits::{Block as BlockT, BlockIdTo, HashFor, Zero},
BuildStorage,
};
use sp_blockchain::{HeaderMetadata, HeaderBackend};
use sp_utils::mpsc::{tracing_unbounded, TracingUnboundedSender};
use std::{str::FromStr, sync::Arc};
use wasm_timer::SystemTime;
/// A utility trait for building an RPC extension given a `DenyUnsafe` instance.
/// This is useful since at service definition time we don't know whether the
@@ -95,7 +82,8 @@ pub trait RpcExtensionBuilder {
) -> Self::Output;
}
impl<F, R> RpcExtensionBuilder for F where
impl<F, R> RpcExtensionBuilder for F
where
F: Fn(sc_rpc::DenyUnsafe, sc_rpc::SubscriptionTaskExecutor) -> R,
R: sc_rpc::RpcExtension<sc_rpc::Metadata>,
{
@@ -115,7 +103,8 @@ impl<F, R> RpcExtensionBuilder for F where
/// `DenyUnsafe` instance and return a static `RpcExtension` instance.
pub struct NoopRpcExtensionBuilder<R>(pub R);
impl<R> RpcExtensionBuilder for NoopRpcExtensionBuilder<R> where
impl<R> RpcExtensionBuilder for NoopRpcExtensionBuilder<R>
where
R: Clone + sc_rpc::RpcExtension<sc_rpc::Metadata>,
{
type Output = R;
@@ -129,7 +118,8 @@ impl<R> RpcExtensionBuilder for NoopRpcExtensionBuilder<R> where
}
}
impl<R> From<R> for NoopRpcExtensionBuilder<R> where
impl<R> From<R> for NoopRpcExtensionBuilder<R>
where
R: sc_rpc::RpcExtension<sc_rpc::Metadata>,
{
fn from(e: R) -> NoopRpcExtensionBuilder<R> {
@@ -137,58 +127,37 @@ impl<R> From<R> for NoopRpcExtensionBuilder<R> where
}
}
/// Full client type.
pub type TFullClient<TBl, TRtApi, TExecDisp> = Client<
TFullBackend<TBl>,
TFullCallExecutor<TBl, TExecDisp>,
TBl,
TRtApi,
>;
pub type TFullClient<TBl, TRtApi, TExecDisp> =
Client<TFullBackend<TBl>, TFullCallExecutor<TBl, TExecDisp>, TBl, TRtApi>;
/// Full client backend type.
pub type TFullBackend<TBl> = sc_client_db::Backend<TBl>;
/// Full client call executor type.
pub type TFullCallExecutor<TBl, TExecDisp> = crate::client::LocalCallExecutor<
TBl,
sc_client_db::Backend<TBl>,
NativeExecutor<TExecDisp>,
>;
pub type TFullCallExecutor<TBl, TExecDisp> =
crate::client::LocalCallExecutor<TBl, sc_client_db::Backend<TBl>, NativeExecutor<TExecDisp>>;
/// Light client type.
pub type TLightClient<TBl, TRtApi, TExecDisp> = TLightClientWithBackend<
TBl, TRtApi, TExecDisp, TLightBackend<TBl>
>;
pub type TLightClient<TBl, TRtApi, TExecDisp> =
TLightClientWithBackend<TBl, TRtApi, TExecDisp, TLightBackend<TBl>>;
/// Light client backend type.
pub type TLightBackend<TBl> = sc_light::Backend<
sc_client_db::light::LightStorage<TBl>,
HashFor<TBl>,
>;
pub type TLightBackend<TBl> =
sc_light::Backend<sc_client_db::light::LightStorage<TBl>, HashFor<TBl>>;
/// Light call executor type.
pub type TLightCallExecutor<TBl, TExecDisp> = sc_light::GenesisCallExecutor<
sc_light::Backend<
sc_client_db::light::LightStorage<TBl>,
HashFor<TBl>
>,
sc_light::Backend<sc_client_db::light::LightStorage<TBl>, HashFor<TBl>>,
crate::client::LocalCallExecutor<
TBl,
sc_light::Backend<
sc_client_db::light::LightStorage<TBl>,
HashFor<TBl>
>,
NativeExecutor<TExecDisp>
sc_light::Backend<sc_client_db::light::LightStorage<TBl>, HashFor<TBl>>,
NativeExecutor<TExecDisp>,
>,
>;
type TFullParts<TBl, TRtApi, TExecDisp> = (
TFullClient<TBl, TRtApi, TExecDisp>,
Arc<TFullBackend<TBl>>,
KeystoreContainer,
TaskManager,
);
type TFullParts<TBl, TRtApi, TExecDisp> =
(TFullClient<TBl, TRtApi, TExecDisp>, Arc<TFullBackend<TBl>>, KeystoreContainer, TaskManager);
type TLightParts<TBl, TRtApi, TExecDisp> = (
Arc<TLightClient<TBl, TRtApi, TExecDisp>>,
@@ -199,10 +168,8 @@ type TLightParts<TBl, TRtApi, TExecDisp> = (
);
/// Light client backend type with a specific hash type.
pub type TLightBackendWithHash<TBl, THash> = sc_light::Backend<
sc_client_db::light::LightStorage<TBl>,
THash,
>;
pub type TLightBackendWithHash<TBl, THash> =
sc_light::Backend<sc_client_db::light::LightStorage<TBl>, THash>;
/// Light client type with a specific backend.
pub type TLightClientWithBackend<TBl, TRtApi, TExecDisp, TBackend> = Client<
@@ -220,7 +187,10 @@ trait AsCryptoStoreRef {
fn sync_keystore_ref(&self) -> Arc<dyn SyncCryptoStore>;
}
impl<T> AsCryptoStoreRef for Arc<T> where T: CryptoStore + SyncCryptoStore + 'static {
impl<T> AsCryptoStoreRef for Arc<T>
where
T: CryptoStore + SyncCryptoStore + 'static,
{
fn keystore_ref(&self) -> Arc<dyn CryptoStore> {
self.clone()
}
@@ -239,14 +209,12 @@ impl KeystoreContainer {
/// Construct KeystoreContainer
pub fn new(config: &KeystoreConfig) -> Result<Self, Error> {
let keystore = Arc::new(match config {
KeystoreConfig::Path { path, password } => LocalKeystore::open(
path.clone(),
password.clone(),
)?,
KeystoreConfig::Path { path, password } =>
LocalKeystore::open(path.clone(), password.clone())?,
KeystoreConfig::InMemory => LocalKeystore::in_memory(),
});
Ok(Self{remote: Default::default(), local: keystore})
Ok(Self { remote: Default::default(), local: keystore })
}
/// Set the remote keystore.
@@ -255,7 +223,8 @@ impl KeystoreContainer {
/// does not reset any references previously handed out - they will
/// stick around.
pub fn set_remote_keystore<T>(&mut self, remote: Arc<T>)
where T: CryptoStore + SyncCryptoStore + 'static
where
T: CryptoStore + SyncCryptoStore + 'static,
{
self.remote = Some(Box::new(remote))
}
@@ -295,7 +264,8 @@ impl KeystoreContainer {
pub fn new_full_client<TBl, TRtApi, TExecDisp>(
config: &Configuration,
telemetry: Option<TelemetryHandle>,
) -> Result<TFullClient<TBl, TRtApi, TExecDisp>, Error> where
) -> Result<TFullClient<TBl, TRtApi, TExecDisp>, Error>
where
TBl: BlockT,
TExecDisp: NativeExecutionDispatch + 'static,
TBl::Hash: FromStr,
@@ -307,7 +277,8 @@ pub fn new_full_client<TBl, TRtApi, TExecDisp>(
pub fn new_full_parts<TBl, TRtApi, TExecDisp>(
config: &Configuration,
telemetry: Option<TelemetryHandle>,
) -> Result<TFullParts<TBl, TRtApi, TExecDisp>, Error> where
) -> Result<TFullParts<TBl, TRtApi, TExecDisp>, Error>
where
TBl: BlockT,
TExecDisp: NativeExecutionDispatch + 'static,
TBl::Hash: FromStr,
@@ -337,15 +308,13 @@ pub fn new_full_parts<TBl, TRtApi, TExecDisp>(
let (client, backend) = {
let db_config = sc_client_db::DatabaseSettings {
state_cache_size: config.state_cache_size,
state_cache_child_ratio:
config.state_cache_child_ratio.map(|v| (v, 100)),
state_cache_child_ratio: config.state_cache_child_ratio.map(|v| (v, 100)),
state_pruning: config.state_pruning.clone(),
source: config.database.clone(),
keep_blocks: config.keep_blocks.clone(),
transaction_storage: config.transaction_storage.clone(),
};
let backend = new_db_backend(db_config)?;
let extensions = sc_client_api::execution_extensions::ExecutionExtensions::new(
@@ -354,15 +323,20 @@ pub fn new_full_parts<TBl, TRtApi, TExecDisp>(
sc_offchain::OffchainDb::factory_from_backend(&*backend),
);
let wasm_runtime_substitutes = config.chain_spec.code_substitutes().into_iter().map(|(h, c)| {
let hash = TBl::Hash::from_str(&h)
.map_err(|_|
Error::Application(Box::from(
format!("Failed to parse `{}` as block hash for code substitutes.", h)
))
)?;
Ok((hash, c))
}).collect::<Result<std::collections::HashMap<_, _>, Error>>()?;
let wasm_runtime_substitutes = config
.chain_spec
.code_substitutes()
.into_iter()
.map(|(h, c)| {
let hash = TBl::Hash::from_str(&h).map_err(|_| {
Error::Application(Box::from(format!(
"Failed to parse `{}` as block hash for code substitutes.",
h
)))
})?;
Ok((hash, c))
})
.collect::<Result<std::collections::HashMap<_, _>, Error>>()?;
let client = new_client(
backend.clone(),
@@ -375,10 +349,13 @@ pub fn new_full_parts<TBl, TRtApi, TExecDisp>(
config.prometheus_config.as_ref().map(|config| config.registry.clone()),
telemetry,
ClientConfig {
offchain_worker_enabled : config.offchain_worker.enabled,
offchain_worker_enabled: config.offchain_worker.enabled,
offchain_indexing_api: config.offchain_worker.indexing_enabled,
wasm_runtime_overrides: config.wasm_runtime_overrides.clone(),
no_genesis: matches!(config.network.sync_mode, sc_network::config::SyncMode::Fast {..}),
no_genesis: matches!(
config.network.sync_mode,
sc_network::config::SyncMode::Fast { .. }
),
wasm_runtime_substitutes,
},
)?;
@@ -386,19 +363,15 @@ pub fn new_full_parts<TBl, TRtApi, TExecDisp>(
(client, backend)
};
Ok((
client,
backend,
keystore_container,
task_manager,
))
Ok((client, backend, keystore_container, task_manager))
}
/// Create the initial parts of a light node.
pub fn new_light_parts<TBl, TRtApi, TExecDisp>(
config: &Configuration,
telemetry: Option<TelemetryHandle>,
) -> Result<TLightParts<TBl, TRtApi, TExecDisp>, Error> where
) -> Result<TLightParts<TBl, TRtApi, TExecDisp>, Error>
where
TBl: BlockT,
TExecDisp: NativeExecutionDispatch + 'static,
{
@@ -417,8 +390,7 @@ pub fn new_light_parts<TBl, TRtApi, TExecDisp>(
let db_storage = {
let db_settings = sc_client_db::DatabaseSettings {
state_cache_size: config.state_cache_size,
state_cache_child_ratio:
config.state_cache_child_ratio.map(|v| (v, 100)),
state_cache_child_ratio: config.state_cache_child_ratio.map(|v| (v, 100)),
state_pruning: config.state_pruning.clone(),
source: config.database.clone(),
keep_blocks: config.keep_blocks.clone(),
@@ -427,13 +399,11 @@ pub fn new_light_parts<TBl, TRtApi, TExecDisp>(
sc_client_db::light::LightStorage::new(db_settings)?
};
let light_blockchain = sc_light::new_light_blockchain(db_storage);
let fetch_checker = Arc::new(
sc_light::new_fetch_checker::<_, TBl, _>(
light_blockchain.clone(),
executor.clone(),
Box::new(task_manager.spawn_handle()),
),
);
let fetch_checker = Arc::new(sc_light::new_fetch_checker::<_, TBl, _>(
light_blockchain.clone(),
executor.clone(),
Box::new(task_manager.spawn_handle()),
));
let on_demand = Arc::new(sc_network::config::OnDemand::new(fetch_checker));
let backend = sc_light::new_light_backend(light_blockchain);
let client = Arc::new(light::new_light(
@@ -451,7 +421,8 @@ pub fn new_light_parts<TBl, TRtApi, TExecDisp>(
/// Create an instance of default DB-backend backend.
pub fn new_db_backend<Block>(
settings: DatabaseSettings,
) -> Result<Arc<Backend<Block>>, sp_blockchain::Error> where
) -> Result<Arc<Backend<Block>>, sp_blockchain::Error>
where
Block: BlockT,
{
const CANONICALIZATION_DELAY: u64 = 4096;
@@ -480,11 +451,16 @@ pub fn new_client<E, Block, RA>(
>,
sp_blockchain::Error,
>
where
Block: BlockT,
E: CodeExecutor + RuntimeInfo,
where
Block: BlockT,
E: CodeExecutor + RuntimeInfo,
{
let executor = crate::client::LocalCallExecutor::new(backend.clone(), executor, spawn_handle, config.clone())?;
let executor = crate::client::LocalCallExecutor::new(
backend.clone(),
executor,
spawn_handle,
config.clone(),
)?;
Ok(crate::client::Client::new(
backend,
executor,
@@ -534,10 +510,10 @@ pub fn build_offchain_workers<TBl, TCl>(
client: Arc<TCl>,
network: Arc<NetworkService<TBl, <TBl as BlockT>::Hash>>,
) -> Option<Arc<sc_offchain::OffchainWorkers<TCl, TBl>>>
where
TBl: BlockT,
TCl: Send + Sync + ProvideRuntimeApi<TBl> + BlockchainEvents<TBl> + 'static,
<TCl as ProvideRuntimeApi<TBl>>::Api: sc_offchain::OffchainWorkerApi<TBl>,
where
TBl: BlockT,
TCl: Send + Sync + ProvideRuntimeApi<TBl> + BlockchainEvents<TBl> + 'static,
<TCl as ProvideRuntimeApi<TBl>>::Api: sc_offchain::OffchainWorkerApi<TBl>,
{
let offchain_workers = Some(Arc::new(sc_offchain::OffchainWorkers::new(client.clone())));
@@ -551,7 +527,7 @@ pub fn build_offchain_workers<TBl, TCl>(
offchain,
Clone::clone(&spawn_handle),
network.clone(),
)
),
);
}
@@ -562,22 +538,32 @@ pub fn build_offchain_workers<TBl, TCl>(
pub fn spawn_tasks<TBl, TBackend, TExPool, TRpc, TCl>(
params: SpawnTasksParams<TBl, TCl, TExPool, TRpc, TBackend>,
) -> Result<RpcHandlers, Error>
where
TCl: ProvideRuntimeApi<TBl> + HeaderMetadata<TBl, Error=sp_blockchain::Error> + Chain<TBl> +
BlockBackend<TBl> + BlockIdTo<TBl, Error=sp_blockchain::Error> + ProofProvider<TBl> +
HeaderBackend<TBl> + BlockchainEvents<TBl> + ExecutorProvider<TBl> + UsageProvider<TBl> +
StorageProvider<TBl, TBackend> + CallApiAt<TBl> + Send + 'static,
<TCl as ProvideRuntimeApi<TBl>>::Api:
sp_api::Metadata<TBl> +
sc_offchain::OffchainWorkerApi<TBl> +
sp_transaction_pool::runtime_api::TaggedTransactionQueue<TBl> +
sp_session::SessionKeys<TBl> +
sp_api::ApiExt<TBl, StateBackend = TBackend::State>,
TBl: BlockT,
TBackend: 'static + sc_client_api::backend::Backend<TBl> + Send,
TExPool: MaintainedTransactionPool<Block=TBl, Hash = <TBl as BlockT>::Hash> +
MallocSizeOfWasm + 'static,
TRpc: sc_rpc::RpcExtension<sc_rpc::Metadata>
where
TCl: ProvideRuntimeApi<TBl>
+ HeaderMetadata<TBl, Error = sp_blockchain::Error>
+ Chain<TBl>
+ BlockBackend<TBl>
+ BlockIdTo<TBl, Error = sp_blockchain::Error>
+ ProofProvider<TBl>
+ HeaderBackend<TBl>
+ BlockchainEvents<TBl>
+ ExecutorProvider<TBl>
+ UsageProvider<TBl>
+ StorageProvider<TBl, TBackend>
+ CallApiAt<TBl>
+ Send
+ 'static,
<TCl as ProvideRuntimeApi<TBl>>::Api: sp_api::Metadata<TBl>
+ sc_offchain::OffchainWorkerApi<TBl>
+ sp_transaction_pool::runtime_api::TaggedTransactionQueue<TBl>
+ sp_session::SessionKeys<TBl>
+ sp_api::ApiExt<TBl, StateBackend = TBackend::State>,
TBl: BlockT,
TBackend: 'static + sc_client_api::backend::Backend<TBl> + Send,
TExPool: MaintainedTransactionPool<Block = TBl, Hash = <TBl as BlockT>::Hash>
+ MallocSizeOfWasm
+ 'static,
TRpc: sc_rpc::RpcExtension<sc_rpc::Metadata>,
{
let SpawnTasksParams {
mut config,
@@ -600,17 +586,11 @@ pub fn spawn_tasks<TBl, TBackend, TExPool, TRpc, TCl>(
client.clone(),
&BlockId::Hash(chain_info.best_hash),
config.dev_key_seed.clone().map(|s| vec![s]).unwrap_or_default(),
).map_err(|e| Error::Application(Box::new(e)))?;
)
.map_err(|e| Error::Application(Box::new(e)))?;
let telemetry = telemetry
.map(|telemetry| {
init_telemetry(
&mut config,
network.clone(),
client.clone(),
telemetry,
)
})
.map(|telemetry| init_telemetry(&mut config, network.clone(), client.clone(), telemetry))
.transpose()?;
info!("📦 Highest known block at #{}", chain_info.best_number);
@@ -625,63 +605,69 @@ pub fn spawn_tasks<TBl, TBackend, TExPool, TRpc, TCl>(
spawn_handle.spawn(
"on-transaction-imported",
transaction_notifications(
transaction_pool.clone(),
network.clone(),
telemetry.clone(),
),
transaction_notifications(transaction_pool.clone(), network.clone(), telemetry.clone()),
);
// Prometheus metrics.
let metrics_service = if let Some(PrometheusConfig { port, registry }) =
config.prometheus_config.clone()
{
// Set static metrics.
let metrics = MetricsService::with_prometheus(telemetry.clone(), &registry, &config)?;
spawn_handle.spawn(
"prometheus-endpoint",
prometheus_endpoint::init_prometheus(port, registry).map(drop)
);
let metrics_service =
if let Some(PrometheusConfig { port, registry }) = config.prometheus_config.clone() {
// Set static metrics.
let metrics = MetricsService::with_prometheus(telemetry.clone(), &registry, &config)?;
spawn_handle.spawn(
"prometheus-endpoint",
prometheus_endpoint::init_prometheus(port, registry).map(drop),
);
metrics
} else {
MetricsService::new(telemetry.clone())
};
metrics
} else {
MetricsService::new(telemetry.clone())
};
// Periodically updated metrics and telemetry updates.
spawn_handle.spawn("telemetry-periodic-send",
metrics_service.run(
client.clone(),
transaction_pool.clone(),
network.clone(),
)
spawn_handle.spawn(
"telemetry-periodic-send",
metrics_service.run(client.clone(), transaction_pool.clone(), network.clone()),
);
// RPC
let gen_handler = |
deny_unsafe: sc_rpc::DenyUnsafe,
rpc_middleware: sc_rpc_server::RpcMiddleware
| gen_handler(
deny_unsafe, rpc_middleware, &config, task_manager.spawn_handle(),
client.clone(), transaction_pool.clone(), keystore.clone(),
on_demand.clone(), remote_blockchain.clone(), &*rpc_extensions_builder,
backend.offchain_storage(), system_rpc_tx.clone()
);
let gen_handler = |deny_unsafe: sc_rpc::DenyUnsafe,
rpc_middleware: sc_rpc_server::RpcMiddleware| {
gen_handler(
deny_unsafe,
rpc_middleware,
&config,
task_manager.spawn_handle(),
client.clone(),
transaction_pool.clone(),
keystore.clone(),
on_demand.clone(),
remote_blockchain.clone(),
&*rpc_extensions_builder,
backend.offchain_storage(),
system_rpc_tx.clone(),
)
};
let rpc_metrics = sc_rpc_server::RpcMetrics::new(config.prometheus_registry())?;
let rpc = start_rpc_servers(&config, gen_handler, rpc_metrics.clone())?;
// This is used internally, so don't restrict access to unsafe RPC
let rpc_handlers = RpcHandlers(Arc::new(gen_handler(
sc_rpc::DenyUnsafe::No,
sc_rpc_server::RpcMiddleware::new(rpc_metrics, "inbrowser")
).into()));
let rpc_handlers = RpcHandlers(Arc::new(
gen_handler(
sc_rpc::DenyUnsafe::No,
sc_rpc_server::RpcMiddleware::new(rpc_metrics, "inbrowser"),
)
.into(),
));
// Spawn informant task
spawn_handle.spawn("informant", sc_informant::build(
client.clone(),
network.clone(),
transaction_pool.clone(),
config.informant_output_format,
));
spawn_handle.spawn(
"informant",
sc_informant::build(
client.clone(),
network.clone(),
transaction_pool.clone(),
config.informant_output_format,
),
);
task_manager.keep_alive((config.base_path, rpc, rpc_handlers.clone()));
@@ -692,10 +678,9 @@ async fn transaction_notifications<TBl, TExPool>(
transaction_pool: Arc<TExPool>,
network: Arc<NetworkService<TBl, <TBl as BlockT>::Hash>>,
telemetry: Option<TelemetryHandle>,
)
where
TBl: BlockT,
TExPool: MaintainedTransactionPool<Block=TBl, Hash = <TBl as BlockT>::Hash>,
) where
TBl: BlockT,
TExPool: MaintainedTransactionPool<Block = TBl, Hash = <TBl as BlockT>::Hash>,
{
// transaction notifications
transaction_pool
@@ -730,9 +715,11 @@ fn init_telemetry<TBl: BlockT, TCl: BlockBackend<TBl>>(
chain: config.chain_spec.name().to_owned(),
genesis_hash: format!("{:?}", genesis_hash),
authority: config.role.is_authority(),
startup_time: SystemTime::UNIX_EPOCH.elapsed()
startup_time: SystemTime::UNIX_EPOCH
.elapsed()
.map(|dur| dur.as_millis())
.unwrap_or(0).to_string(),
.unwrap_or(0)
.to_string(),
network_id: network.local_peer_id().to_base58(),
};
@@ -753,22 +740,28 @@ fn gen_handler<TBl, TBackend, TExPool, TRpc, TCl>(
remote_blockchain: Option<Arc<dyn RemoteBlockchain<TBl>>>,
rpc_extensions_builder: &(dyn RpcExtensionBuilder<Output = TRpc> + Send),
offchain_storage: Option<<TBackend as sc_client_api::backend::Backend<TBl>>::OffchainStorage>,
system_rpc_tx: TracingUnboundedSender<sc_rpc::system::Request<TBl>>
system_rpc_tx: TracingUnboundedSender<sc_rpc::system::Request<TBl>>,
) -> sc_rpc_server::RpcHandler<sc_rpc::Metadata>
where
TBl: BlockT,
TCl: ProvideRuntimeApi<TBl> + BlockchainEvents<TBl> + HeaderBackend<TBl> +
HeaderMetadata<TBl, Error=sp_blockchain::Error> + ExecutorProvider<TBl> +
CallApiAt<TBl> + ProofProvider<TBl> +
StorageProvider<TBl, TBackend> + BlockBackend<TBl> + Send + Sync + 'static,
TExPool: MaintainedTransactionPool<Block=TBl, Hash = <TBl as BlockT>::Hash> + 'static,
TBackend: sc_client_api::backend::Backend<TBl> + 'static,
TRpc: sc_rpc::RpcExtension<sc_rpc::Metadata>,
<TCl as ProvideRuntimeApi<TBl>>::Api:
sp_session::SessionKeys<TBl> +
sp_api::Metadata<TBl>,
where
TBl: BlockT,
TCl: ProvideRuntimeApi<TBl>
+ BlockchainEvents<TBl>
+ HeaderBackend<TBl>
+ HeaderMetadata<TBl, Error = sp_blockchain::Error>
+ ExecutorProvider<TBl>
+ CallApiAt<TBl>
+ ProofProvider<TBl>
+ StorageProvider<TBl, TBackend>
+ BlockBackend<TBl>
+ Send
+ Sync
+ 'static,
TExPool: MaintainedTransactionPool<Block = TBl, Hash = <TBl as BlockT>::Hash> + 'static,
TBackend: sc_client_api::backend::Backend<TBl> + 'static,
TRpc: sc_rpc::RpcExtension<sc_rpc::Metadata>,
<TCl as ProvideRuntimeApi<TBl>>::Api: sp_session::SessionKeys<TBl> + sp_api::Metadata<TBl>,
{
use sc_rpc::{chain, state, author, system, offchain};
use sc_rpc::{author, chain, offchain, state, system};
let system_info = sc_rpc::system::SystemInfo {
chain_name: config.chain_spec.name().into(),
@@ -781,43 +774,37 @@ fn gen_handler<TBl, TBackend, TExPool, TRpc, TCl>(
let task_executor = sc_rpc::SubscriptionTaskExecutor::new(spawn_handle);
let subscriptions = SubscriptionManager::new(Arc::new(task_executor.clone()));
let (chain, state, child_state) = if let (Some(remote_blockchain), Some(on_demand)) =
(remote_blockchain, on_demand) {
// Light clients
let chain = sc_rpc::chain::new_light(
client.clone(),
subscriptions.clone(),
remote_blockchain.clone(),
on_demand.clone(),
);
let (state, child_state) = sc_rpc::state::new_light(
client.clone(),
subscriptions.clone(),
remote_blockchain.clone(),
on_demand,
deny_unsafe,
);
(chain, state, child_state)
let (chain, state, child_state) =
if let (Some(remote_blockchain), Some(on_demand)) = (remote_blockchain, on_demand) {
// Light clients
let chain = sc_rpc::chain::new_light(
client.clone(),
subscriptions.clone(),
remote_blockchain.clone(),
on_demand.clone(),
);
let (state, child_state) = sc_rpc::state::new_light(
client.clone(),
subscriptions.clone(),
remote_blockchain.clone(),
on_demand,
deny_unsafe,
);
(chain, state, child_state)
} else {
// Full nodes
let chain = sc_rpc::chain::new_full(client.clone(), subscriptions.clone());
let (state, child_state) = sc_rpc::state::new_full(
client.clone(),
subscriptions.clone(),
deny_unsafe,
config.rpc_max_payload,
);
(chain, state, child_state)
};
} else {
// Full nodes
let chain = sc_rpc::chain::new_full(client.clone(), subscriptions.clone());
let (state, child_state) = sc_rpc::state::new_full(
client.clone(),
subscriptions.clone(),
deny_unsafe,
config.rpc_max_payload,
);
(chain, state, child_state)
};
let author = sc_rpc::author::Author::new(
client,
transaction_pool,
subscriptions,
keystore,
deny_unsafe,
);
let author =
sc_rpc::author::Author::new(client, transaction_pool, subscriptions, keystore, deny_unsafe);
let system = system::System::new(system_info, system_rpc_tx, deny_unsafe);
let maybe_offchain_rpc = offchain_storage.map(|storage| {
@@ -835,7 +822,7 @@ fn gen_handler<TBl, TBackend, TExPool, TRpc, TCl>(
system::SystemApi::to_delegate(system),
rpc_extensions_builder.build(deny_unsafe, task_executor),
),
rpc_middleware
rpc_middleware,
)
}
@@ -854,32 +841,42 @@ pub struct BuildNetworkParams<'a, TBl: BlockT, TExPool, TImpQu, TCl> {
/// An optional, shared data fetcher for light clients.
pub on_demand: Option<Arc<OnDemand<TBl>>>,
/// A block announce validator builder.
pub block_announce_validator_builder: Option<Box<
dyn FnOnce(Arc<TCl>) -> Box<dyn BlockAnnounceValidator<TBl> + Send> + Send
>>,
pub block_announce_validator_builder:
Option<Box<dyn FnOnce(Arc<TCl>) -> Box<dyn BlockAnnounceValidator<TBl> + Send> + Send>>,
}
/// Build the network service, the network status sinks and an RPC sender.
pub fn build_network<TBl, TExPool, TImpQu, TCl>(
params: BuildNetworkParams<TBl, TExPool, TImpQu, TCl>
params: BuildNetworkParams<TBl, TExPool, TImpQu, TCl>,
) -> Result<
(
Arc<NetworkService<TBl, <TBl as BlockT>::Hash>>,
TracingUnboundedSender<sc_rpc::system::Request<TBl>>,
NetworkStarter,
),
Error
Error,
>
where
TBl: BlockT,
TCl: ProvideRuntimeApi<TBl> + HeaderMetadata<TBl, Error=sp_blockchain::Error> + Chain<TBl> +
BlockBackend<TBl> + BlockIdTo<TBl, Error=sp_blockchain::Error> + ProofProvider<TBl> +
HeaderBackend<TBl> + BlockchainEvents<TBl> + 'static,
TExPool: MaintainedTransactionPool<Block=TBl, Hash = <TBl as BlockT>::Hash> + 'static,
TImpQu: ImportQueue<TBl> + 'static,
where
TBl: BlockT,
TCl: ProvideRuntimeApi<TBl>
+ HeaderMetadata<TBl, Error = sp_blockchain::Error>
+ Chain<TBl>
+ BlockBackend<TBl>
+ BlockIdTo<TBl, Error = sp_blockchain::Error>
+ ProofProvider<TBl>
+ HeaderBackend<TBl>
+ BlockchainEvents<TBl>
+ 'static,
TExPool: MaintainedTransactionPool<Block = TBl, Hash = <TBl as BlockT>::Hash> + 'static,
TImpQu: ImportQueue<TBl> + 'static,
{
let BuildNetworkParams {
config, client, transaction_pool, spawn_handle, import_queue, on_demand,
config,
client,
transaction_pool,
spawn_handle,
import_queue,
on_demand,
block_announce_validator_builder,
} = params;
@@ -906,8 +903,8 @@ pub fn build_network<TBl, TExPool, TImpQu, TCl>(
let (handler, protocol_config) = BlockRequestHandler::new(
&protocol_id,
client.clone(),
config.network.default_peers_set.in_peers as usize
+ config.network.default_peers_set.out_peers as usize,
config.network.default_peers_set.in_peers as usize +
config.network.default_peers_set.out_peers as usize,
);
spawn_handle.spawn("block_request_handler", handler.run());
protocol_config
@@ -923,8 +920,8 @@ pub fn build_network<TBl, TExPool, TImpQu, TCl>(
let (handler, protocol_config) = StateRequestHandler::new(
&protocol_id,
client.clone(),
config.network.default_peers_set.in_peers as usize
+ config.network.default_peers_set.out_peers as usize,
config.network.default_peers_set.in_peers as usize +
config.network.default_peers_set.out_peers as usize,
);
spawn_handle.spawn("state_request_handler", handler.run());
protocol_config
@@ -937,10 +934,8 @@ pub fn build_network<TBl, TExPool, TImpQu, TCl>(
light_client_requests::generate_protocol_config(&protocol_id)
} else {
// Allow both outgoing and incoming requests.
let (handler, protocol_config) = LightClientRequestHandler::new(
&protocol_id,
client.clone(),
);
let (handler, protocol_config) =
LightClientRequestHandler::new(&protocol_id, client.clone());
spawn_handle.spawn("light_client_request_handler", handler.run());
protocol_config
}
@@ -962,7 +957,7 @@ pub fn build_network<TBl, TExPool, TImpQu, TCl>(
},
network_config: config.network.clone(),
chain: client.clone(),
on_demand: on_demand,
on_demand,
transaction_pool: transaction_pool_adapter as _,
import_queue: Box::new(import_queue),
protocol_id,
@@ -976,10 +971,8 @@ pub fn build_network<TBl, TExPool, TImpQu, TCl>(
// Storage chains don't keep full block history and can't be synced in full mode.
// Force fast sync when storage chain mode is enabled.
if matches!(config.transaction_storage, TransactionStorageMode::StorageChain) {
network_params.network_config.sync_mode = SyncMode::Fast {
storage_chain_mode: true,
skip_proofs: false,
};
network_params.network_config.sync_mode =
SyncMode::Fast { storage_chain_mode: true, skip_proofs: false };
}
let has_bootnodes = !network_params.network_config.boot_nodes.is_empty();
@@ -1028,7 +1021,7 @@ pub fn build_network<TBl, TExPool, TImpQu, TCl>(
);
// This `return` might seem unnecessary, but we don't want to make it look like
// everything is working as normal even though the user is clearly misusing the API.
return;
return
}
future.await