git.delta.rocks / unique-network / refs/commits / 9c20d62bf101

difftreelog

source

node/rpc/src/lib.rs9.0 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 sp_runtime::traits::BlakeTwo256;18use fc_rpc::{19	EthBlockDataCache, OverrideHandle, RuntimeApiStorageOverride, SchemaV1Override,20	StorageOverride, SchemaV2Override, SchemaV3Override,21};22use fc_rpc_core::types::{FilterPool, FeeHistoryCache};23use jsonrpc_pubsub::manager::SubscriptionManager;24use pallet_ethereum::EthereumStorageSchema;25use sc_client_api::{26	backend::{AuxStore, StorageProvider},27	client::BlockchainEvents,28	StateBackend, Backend,29};30use sc_finality_grandpa::{31	FinalityProofProvider, GrandpaJustificationStream, SharedAuthoritySet, SharedVoterState,32};33use sc_network::NetworkService;34use sc_rpc::SubscriptionTaskExecutor;35pub use sc_rpc_api::DenyUnsafe;36use sc_transaction_pool::{ChainApi, Pool};37use sp_api::ProvideRuntimeApi;38use sp_block_builder::BlockBuilder;39use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata};40use sc_service::TransactionPool;41use std::{collections::BTreeMap, marker::PhantomData, sync::Arc};4243use unique_runtime_common::types::{44	Hash, AccountId, RuntimeInstance, Index, Block, BlockNumber, Balance,45};4647/// Public io handler for exporting into other modules48pub type IoHandler = jsonrpc_core::IoHandler<sc_rpc::Metadata>;4950/// Extra dependencies for GRANDPA51pub struct GrandpaDeps<B> {52	/// Voting round info.53	pub shared_voter_state: SharedVoterState,54	/// Authority set info.55	pub shared_authority_set: SharedAuthoritySet<Hash, BlockNumber>,56	/// Receives notifications about justification events from Grandpa.57	pub justification_stream: GrandpaJustificationStream<Block>,58	/// Executor to drive the subscription manager in the Grandpa RPC handler.59	pub subscription_executor: SubscriptionTaskExecutor,60	/// Finality proof provider.61	pub finality_provider: Arc<FinalityProofProvider<B, Block>>,62}6364/// Full client dependencies.65pub struct FullDeps<C, P, SC, CA: ChainApi> {66	/// The client instance to use.67	pub client: Arc<C>,68	/// Transaction pool instance.69	pub pool: Arc<P>,70	/// Graph pool instance.71	pub graph: Arc<Pool<CA>>,72	/// The SelectChain Strategy73	pub select_chain: SC,74	/// The Node authority flag75	pub is_authority: bool,76	/// Whether to enable dev signer77	pub enable_dev_signer: bool,78	/// Network service79	pub network: Arc<NetworkService<Block, Hash>>,80	/// Whether to deny unsafe calls81	pub deny_unsafe: DenyUnsafe,82	/// EthFilterApi pool.83	pub filter_pool: Option<FilterPool>,84	/// Backend.85	pub backend: Arc<fc_db::Backend<Block>>,86	/// Maximum number of logs in a query.87	pub max_past_logs: u32,88	/// Maximum fee history cache size.89	pub fee_history_limit: u64,90	/// Fee history cache.91	pub fee_history_cache: FeeHistoryCache,92	/// Cache for Ethereum block data.93	pub block_data_cache: Arc<EthBlockDataCache<Block>>,94}9596struct AccountCodes<C, B, R> {97	client: Arc<C>,98	_blk_marker: PhantomData<B>,99	_runtime_marker: PhantomData<R>,100}101102impl<C, Block, R> AccountCodes<C, Block, R>103where104	Block: sp_api::BlockT,105	C: ProvideRuntimeApi<Block>,106	R: RuntimeInstance,107{108	fn new(client: Arc<C>) -> Self {109		Self {110			client,111			_blk_marker: PhantomData,112			_runtime_marker: PhantomData,113		}114	}115}116117impl<C, Block, Runtime> fc_rpc::AccountCodeProvider<Block> for AccountCodes<C, Block, Runtime>118where119	Block: sp_api::BlockT,120	C: ProvideRuntimeApi<Block>,121	C::Api: up_rpc::UniqueApi<Block, <Runtime as RuntimeInstance>::CrossAccountId, AccountId>,122	Runtime: RuntimeInstance,123{124	fn code(&self, block: &sp_api::BlockId<Block>, account: sp_core::H160) -> Option<Vec<u8>> {125		use up_rpc::UniqueApi;126		self.client127			.runtime_api()128			.eth_contract_code(block, account)129			.ok()130			.flatten()131	}132}133134pub fn overrides_handle<C, BE, R>(client: Arc<C>) -> Arc<OverrideHandle<Block>>135where136	C: ProvideRuntimeApi<Block> + StorageProvider<Block, BE> + AuxStore,137	C: HeaderBackend<Block> + HeaderMetadata<Block, Error = BlockChainError>,138	C: Send + Sync + 'static,139	C::Api: fp_rpc::EthereumRuntimeRPCApi<Block>,140	C::Api: up_rpc::UniqueApi<Block, <R as RuntimeInstance>::CrossAccountId, AccountId>,141	BE: Backend<Block> + 'static,142	BE::State: StateBackend<BlakeTwo256>,143	R: RuntimeInstance + Send + Sync + 'static,144{145	let mut overrides_map = BTreeMap::new();146	overrides_map.insert(147		EthereumStorageSchema::V1,148		Box::new(SchemaV1Override::new_with_code_provider(149			client.clone(),150			Arc::new(AccountCodes::<C, Block, R>::new(client.clone())),151		)) as Box<dyn StorageOverride<_> + Send + Sync>,152	);153	overrides_map.insert(154		EthereumStorageSchema::V2,155		Box::new(SchemaV2Override::new(client.clone()))156			as Box<dyn StorageOverride<_> + Send + Sync>,157	);158	overrides_map.insert(159		EthereumStorageSchema::V3,160		Box::new(SchemaV3Override::new(client.clone()))161			as Box<dyn StorageOverride<_> + Send + Sync>,162	);163164	Arc::new(OverrideHandle {165		schemas: overrides_map,166		fallback: Box::new(RuntimeApiStorageOverride::new(client)),167	})168}169170/// Instantiate all Full RPC extensions.171pub fn create_full<C, P, SC, CA, R, A, B>(172	deps: FullDeps<C, P, SC, CA>,173	subscription_task_executor: SubscriptionTaskExecutor,174) -> jsonrpc_core::IoHandler<sc_rpc_api::Metadata>175where176	C: ProvideRuntimeApi<Block> + StorageProvider<Block, B> + AuxStore,177	C: HeaderBackend<Block> + HeaderMetadata<Block, Error = BlockChainError> + 'static,178	C: Send + Sync + 'static,179	C: BlockchainEvents<Block>,180	C::Api: substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>,181	C::Api: BlockBuilder<Block>,182	// C::Api: pallet_contracts_rpc::ContractsRuntimeApi<Block, AccountId, Balance, BlockNumber, Hash>,183	C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi<Block, Balance>,184	C::Api: fp_rpc::EthereumRuntimeRPCApi<Block>,185	C::Api: up_rpc::UniqueApi<Block, <R as RuntimeInstance>::CrossAccountId, AccountId>,186	B: sc_client_api::Backend<Block> + Send + Sync + 'static,187	B::State: sc_client_api::backend::StateBackend<sp_runtime::traits::HashFor<Block>>,188	P: TransactionPool<Block = Block> + 'static,189	CA: ChainApi<Block = Block> + 'static,190	R: RuntimeInstance + Send + Sync + 'static,191	<R as RuntimeInstance>::CrossAccountId: serde::Serialize,192	for<'de> <R as RuntimeInstance>::CrossAccountId: serde::Deserialize<'de>,193{194	use fc_rpc::{195		EthApi, EthApiServer, EthDevSigner, EthFilterApi, EthFilterApiServer, EthPubSubApi,196		EthPubSubApiServer, EthSigner, HexEncodedIdProvider, NetApi, NetApiServer, Web3Api,197		Web3ApiServer,198	};199	use uc_rpc::{UniqueApi, Unique};200	// use pallet_contracts_rpc::{Contracts, ContractsApi};201	use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApi};202	use substrate_frame_rpc_system::{FullSystem, SystemApi};203204	let mut io = jsonrpc_core::IoHandler::default();205	let FullDeps {206		client,207		pool,208		graph,209		select_chain: _,210		fee_history_limit,211		fee_history_cache,212		block_data_cache,213		enable_dev_signer,214		is_authority,215		network,216		deny_unsafe,217		filter_pool,218		backend,219		max_past_logs,220	} = deps;221222	io.extend_with(SystemApi::to_delegate(FullSystem::new(223		client.clone(),224		pool.clone(),225		deny_unsafe,226	)));227228	io.extend_with(TransactionPaymentApi::to_delegate(TransactionPayment::new(229		client.clone(),230	)));231232	// io.extend_with(ContractsApi::to_delegate(Contracts::new(client.clone())));233234	let mut signers = Vec::new();235	if enable_dev_signer {236		signers.push(Box::new(EthDevSigner::new()) as Box<dyn EthSigner>);237	}238239	let overrides = overrides_handle::<_, _, R>(client.clone());240241	io.extend_with(EthApiServer::to_delegate(EthApi::new(242		client.clone(),243		pool.clone(),244		graph,245		<R as RuntimeInstance>::get_transaction_converter(),246		network.clone(),247		signers,248		overrides.clone(),249		backend.clone(),250		is_authority,251		max_past_logs,252		block_data_cache.clone(),253		fee_history_limit,254		fee_history_cache,255	)));256	io.extend_with(UniqueApi::to_delegate(Unique::new(client.clone())));257258	if let Some(filter_pool) = filter_pool {259		io.extend_with(EthFilterApiServer::to_delegate(EthFilterApi::new(260			client.clone(),261			backend,262			filter_pool,263			500_usize, // max stored filters264			max_past_logs,265			block_data_cache,266		)));267	}268269	io.extend_with(NetApiServer::to_delegate(NetApi::new(270		client.clone(),271		network.clone(),272		// Whether to format the `peer_count` response as Hex (default) or not.273		true,274	)));275276	io.extend_with(Web3ApiServer::to_delegate(Web3Api::new(client.clone())));277278	io.extend_with(EthPubSubApiServer::to_delegate(EthPubSubApi::new(279		pool,280		client,281		network,282		SubscriptionManager::<HexEncodedIdProvider>::with_id_provider(283			HexEncodedIdProvider::default(),284			Arc::new(subscription_task_executor),285		),286		overrides,287	)));288289	io290}