git.delta.rocks / unique-network / refs/commits / ec57cb9db90d

difftreelog

source

node/rpc/src/lib.rs9.8 KiBsourcehistory
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617use fc_mapping_sync::{EthereumBlockNotificationSinks, EthereumBlockNotification};18use sp_runtime::traits::BlakeTwo256;19use fc_rpc::{20	EthBlockDataCacheTask, OverrideHandle, RuntimeApiStorageOverride, SchemaV1Override,21	StorageOverride, SchemaV2Override, SchemaV3Override,22};23use jsonrpsee::RpcModule;24use fc_rpc_core::types::{FilterPool, FeeHistoryCache};25use fp_storage::EthereumStorageSchema;26use sc_client_api::{27	backend::{AuxStore, StorageProvider},28	client::BlockchainEvents,29	StateBackend, Backend,30};31use sc_network::NetworkService;32use sc_network_sync::SyncingService;33use sc_rpc::SubscriptionTaskExecutor;34pub use sc_rpc_api::DenyUnsafe;35use sc_transaction_pool::{ChainApi, Pool};36use sp_api::ProvideRuntimeApi;37use sp_block_builder::BlockBuilder;38use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata};39use sc_service::TransactionPool;40use std::{collections::BTreeMap, sync::Arc};4142use up_common::types::opaque::*;4344#[cfg(feature = "pov-estimate")]45type FullBackend = sc_service::TFullBackend<Block>;4647/// Full client dependencies.48pub struct FullDeps<C, P, SC> {49	/// The client instance to use.50	pub client: Arc<C>,51	/// Transaction pool instance.52	pub pool: Arc<P>,53	/// The SelectChain Strategy54	pub select_chain: SC,55	/// Whether to deny unsafe calls56	pub deny_unsafe: DenyUnsafe,5758	/// Runtime identification (read from the chain spec)59	pub runtime_id: RuntimeId,60	/// Executor params for PoV estimating61	#[cfg(feature = "pov-estimate")]62	pub exec_params: uc_rpc::pov_estimate::ExecutorParams,63	/// Substrate Backend.64	#[cfg(feature = "pov-estimate")]65	pub backend: Arc<FullBackend>,66}6768pub fn overrides_handle<C, BE, R>(client: Arc<C>) -> Arc<OverrideHandle<Block>>69where70	C: ProvideRuntimeApi<Block> + StorageProvider<Block, BE> + AuxStore,71	C: HeaderBackend<Block> + HeaderMetadata<Block, Error = BlockChainError>,72	C: Send + Sync + 'static,73	C::Api: fp_rpc::EthereumRuntimeRPCApi<Block>,74	C::Api: up_rpc::UniqueApi<Block, <R as RuntimeInstance>::CrossAccountId, AccountId>,75	BE: Backend<Block> + 'static,76	BE::State: StateBackend<BlakeTwo256>,77	R: RuntimeInstance + Send + Sync + 'static,78{79	let mut overrides_map = BTreeMap::new();80	overrides_map.insert(81		EthereumStorageSchema::V1,82		Box::new(SchemaV1Override::new(client.clone())) as Box<dyn StorageOverride<_> + 'static>,83	);84	overrides_map.insert(85		EthereumStorageSchema::V2,86		Box::new(SchemaV2Override::new(client.clone())) as Box<dyn StorageOverride<_> + 'static>,87	);88	overrides_map.insert(89		EthereumStorageSchema::V3,90		Box::new(SchemaV3Override::new(client.clone())) as Box<dyn StorageOverride<_> + 'static>,91	);9293	Arc::new(OverrideHandle {94		schemas: overrides_map,95		fallback: Box::new(RuntimeApiStorageOverride::new(client)),96	})97}9899/// Instantiate all Full RPC extensions.100pub fn create_full<C, P, SC, R, A, B>(101	io: &mut RpcModule<()>,102	deps: FullDeps<C, P, SC>,103) -> Result<(), Box<dyn std::error::Error + Send + Sync>>104where105	C: ProvideRuntimeApi<Block> + StorageProvider<Block, B> + AuxStore,106	C: HeaderBackend<Block> + HeaderMetadata<Block, Error = BlockChainError> + 'static,107	C: Send + Sync + 'static,108	C: BlockchainEvents<Block>,109	C::Api: substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>,110	C::Api: BlockBuilder<Block>,111	// C::Api: pallet_contracts_rpc::ContractsRuntimeApi<Block, AccountId, Balance, BlockNumber, Hash>,112	C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi<Block, Balance>,113	C::Api: up_rpc::UniqueApi<Block, <R as RuntimeInstance>::CrossAccountId, AccountId>,114	C::Api: app_promotion_rpc::AppPromotionApi<115		Block,116		BlockNumber,117		<R as RuntimeInstance>::CrossAccountId,118		AccountId,119	>,120	C::Api: up_pov_estimate_rpc::PovEstimateApi<Block>,121	B: sc_client_api::Backend<Block> + Send + Sync + 'static,122	B::State: sc_client_api::backend::StateBackend<sp_runtime::traits::HashFor<Block>>,123	P: TransactionPool<Block = Block> + 'static,124	R: RuntimeInstance + Send + Sync + 'static,125	<R as RuntimeInstance>::CrossAccountId: serde::Serialize,126	C: sp_api::CallApiAt<127		sp_runtime::generic::Block<128			sp_runtime::generic::Header<u32, BlakeTwo256>,129			sp_runtime::OpaqueExtrinsic,130		>,131	>,132	for<'de> <R as RuntimeInstance>::CrossAccountId: serde::Deserialize<'de>,133{134	use uc_rpc::{UniqueApiServer, Unique};135136	use uc_rpc::{AppPromotionApiServer, AppPromotion};137138	#[cfg(feature = "pov-estimate")]139	use uc_rpc::pov_estimate::{PovEstimateApiServer, PovEstimate};140141	// use pallet_contracts_rpc::{Contracts, ContractsApi};142	use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer};143	use substrate_frame_rpc_system::{System, SystemApiServer};144145	let FullDeps {146		client,147		pool,148		select_chain: _,149		deny_unsafe,150151		runtime_id: _,152153		#[cfg(feature = "pov-estimate")]154		exec_params,155156		#[cfg(feature = "pov-estimate")]157		backend,158	} = deps;159160	io.merge(System::new(Arc::clone(&client), Arc::clone(&pool), deny_unsafe).into_rpc())?;161	io.merge(TransactionPayment::new(Arc::clone(&client)).into_rpc())?;162163	io.merge(Unique::new(client.clone()).into_rpc())?;164165	io.merge(AppPromotion::new(client.clone()).into_rpc())?;166167	#[cfg(feature = "pov-estimate")]168	io.merge(169		PovEstimate::new(170			client.clone(),171			backend,172			deny_unsafe,173			exec_params,174			runtime_id,175		)176		.into_rpc(),177	)?;178179	Ok(())180}181182pub struct EthDeps<C, P, CA: ChainApi> {183	/// The client instance to use.184	pub client: Arc<C>,185	/// Transaction pool instance.186	pub pool: Arc<P>,187	/// Graph pool instance.188	pub graph: Arc<Pool<CA>>,189	/// Syncing service190	pub sync: Arc<SyncingService<Block>>,191	/// The Node authority flag192	pub is_authority: bool,193	/// Network service194	pub network: Arc<NetworkService<Block, Hash>>,195196	/// Ethereum Backend.197	pub eth_backend: Arc<dyn fc_db::BackendReader<Block> + Send + Sync>,198	/// Maximum number of logs in a query.199	pub max_past_logs: u32,200	/// Maximum fee history cache size.201	pub fee_history_limit: u64,202	/// Fee history cache.203	pub fee_history_cache: FeeHistoryCache,204	pub eth_block_data_cache: Arc<EthBlockDataCacheTask<Block>>,205	/// EthFilterApi pool.206	pub eth_filter_pool: Option<FilterPool>,207	pub eth_pubsub_notification_sinks: Arc<EthereumBlockNotificationSinks<EthereumBlockNotification<Block>>>,208	/// Whether to enable eth dev signer209	pub enable_dev_signer: bool,210211	pub overrides: Arc<OverrideHandle<Block>>,212}213214/// This converter is never used, but we have a generic215/// Option<T>, where T should implement ConvertTransaction216///217/// TODO: remove after never-type (`!`) stabilization218enum NeverConvert {}219impl<T> fp_rpc::ConvertTransaction<T> for NeverConvert {220	fn convert_transaction(&self, _transaction: pallet_ethereum::Transaction) -> T {221		unreachable!()222	}223}224225pub fn create_eth<C, P, CA, B>(226	io: &mut RpcModule<()>,227	deps: EthDeps<C, P, CA>,228	subscription_task_executor: SubscriptionTaskExecutor,229) -> Result<(), Box<dyn std::error::Error + Send + Sync>>230where231	C: ProvideRuntimeApi<Block> + StorageProvider<Block, B> + AuxStore,232	C: HeaderBackend<Block> + HeaderMetadata<Block, Error = BlockChainError> + 'static,233	C: Send + Sync + 'static,234	C: BlockchainEvents<Block>,235	C::Api: BlockBuilder<Block>,236	C::Api: fp_rpc::EthereumRuntimeRPCApi<Block>,237	C::Api: fp_rpc::ConvertTransactionRuntimeApi<Block>,238	P: TransactionPool<Block = Block> + 'static,239	CA: ChainApi<Block = Block> + 'static,240	B: sc_client_api::Backend<Block> + Send + Sync + 'static,241	C: sp_api::CallApiAt<242		sp_runtime::generic::Block<243			sp_runtime::generic::Header<u32, BlakeTwo256>,244			sp_runtime::OpaqueExtrinsic,245		>,246	>,247{248	use fc_rpc::{249		Eth, EthApiServer, EthDevSigner, EthFilter, EthFilterApiServer, EthPubSub,250		EthPubSubApiServer, EthSigner, Net, NetApiServer, Web3, Web3ApiServer, TxPool, TxPoolApiServer,251	};252253	let EthDeps {254		client,255		pool,256		graph,257		eth_backend,258		max_past_logs,259		fee_history_limit,260		fee_history_cache,261		eth_block_data_cache,262		eth_filter_pool,263		eth_pubsub_notification_sinks,264		enable_dev_signer,265		sync,266		is_authority,267		network,268		overrides,269	} = deps;270271	let mut signers = Vec::new();272	if enable_dev_signer {273		signers.push(Box::new(EthDevSigner::new()) as Box<dyn EthSigner>);274	}275	let execute_gas_limit_multiplier = 10;276	io.merge(277		Eth::new(278			client.clone(),279			pool.clone(),280			graph.clone(),281			// We have no runtimes old enough to only accept converted transactions282			None::<NeverConvert>,283			sync.clone(),284			signers,285			overrides.clone(),286			eth_backend.clone(),287			is_authority,288			eth_block_data_cache.clone(),289			fee_history_cache,290			fee_history_limit,291			execute_gas_limit_multiplier,292			None,293		)294		.into_rpc(),295	)?;296297	let tx_pool = TxPool::new(298		client.clone(),299		graph,300		);301302	if let Some(filter_pool) = eth_filter_pool {303		io.merge(304			EthFilter::new(305				client.clone(),306				eth_backend,307				tx_pool.clone(),308				filter_pool,309				500_usize, // max stored filters310				max_past_logs,311				eth_block_data_cache,312			)313			.into_rpc(),314		)?;315	}316	io.merge(317		Net::new(318			client.clone(),319			network,320			// Whether to format the `peer_count` response as Hex (default) or not.321			true,322		)323		.into_rpc(),324	)?;325	io.merge(Web3::new(client.clone()).into_rpc())?;326	io.merge(327		EthPubSub::new(328			pool,329			client,330			sync,331			subscription_task_executor,332			overrides,333			eth_pubsub_notification_sinks,334		)335		.into_rpc(),336	)?;337	io.merge(tx_pool.into_rpc())?;338339	Ok(())340}