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};4243#[cfg(feature = "unique-runtime")]44use unique_runtime as runtime;4546#[cfg(feature = "quartz-runtime")]47use quartz_runtime as runtime;4849#[cfg(feature = "opal-runtime")]50use opal_runtime as runtime;5152use runtime::opaque::{Hash, AccountId, CrossAccountId, Index, Block, BlockNumber, Balance};5354/// Public io handler for exporting into other modules55pub type IoHandler = jsonrpc_core::IoHandler<sc_rpc::Metadata>;5657/// Extra dependencies for GRANDPA58pub struct GrandpaDeps<B> {59 /// Voting round info.60 pub shared_voter_state: SharedVoterState,61 /// Authority set info.62 pub shared_authority_set: SharedAuthoritySet<Hash, BlockNumber>,63 /// Receives notifications about justification events from Grandpa.64 pub justification_stream: GrandpaJustificationStream<Block>,65 /// Executor to drive the subscription manager in the Grandpa RPC handler.66 pub subscription_executor: SubscriptionTaskExecutor,67 /// Finality proof provider.68 pub finality_provider: Arc<FinalityProofProvider<B, Block>>,69}7071/// Full client dependencies.72pub struct FullDeps<C, P, SC, CA: ChainApi> {73 /// The client instance to use.74 pub client: Arc<C>,75 /// Transaction pool instance.76 pub pool: Arc<P>,77 /// Graph pool instance.78 pub graph: Arc<Pool<CA>>,79 /// The SelectChain Strategy80 pub select_chain: SC,81 /// The Node authority flag82 pub is_authority: bool,83 /// Whether to enable dev signer84 pub enable_dev_signer: bool,85 /// Network service86 pub network: Arc<NetworkService<Block, Hash>>,87 /// Whether to deny unsafe calls88 pub deny_unsafe: DenyUnsafe,89 /// EthFilterApi pool.90 pub filter_pool: Option<FilterPool>,91 /// Backend.92 pub backend: Arc<fc_db::Backend<Block>>,93 /// Maximum number of logs in a query.94 pub max_past_logs: u32,95 /// Maximum fee history cache size.96 pub fee_history_limit: u64,97 /// Fee history cache.98 pub fee_history_cache: FeeHistoryCache,99 /// Cache for Ethereum block data.100 pub block_data_cache: Arc<EthBlockDataCache<Block>>,101}102103struct AccountCodes<C, B, CAId> {104 client: Arc<C>,105 _blk_marker: PhantomData<B>,106 _caid_marker: PhantomData<CAId>,107}108109impl<C, Block, CAId> AccountCodes<C, Block, CAId>110where111 Block: sp_api::BlockT,112 C: ProvideRuntimeApi<Block>,113{114 fn new(client: Arc<C>) -> Self {115 Self {116 client,117 _blk_marker: PhantomData,118 _caid_marker: PhantomData,119 }120 }121}122123impl<C, Block, CAId> fc_rpc::AccountCodeProvider<Block> for AccountCodes<C, Block, CAId>124where125 Block: sp_api::BlockT,126 C: ProvideRuntimeApi<Block>,127 C::Api: up_rpc::UniqueApi<Block, CAId, AccountId>,128 CAId: pallet_common::account::CrossAccountId<sp_runtime::AccountId32>,129{130 fn code(&self, block: &sp_api::BlockId<Block>, account: sp_core::H160) -> Option<Vec<u8>> {131 use up_rpc::UniqueApi;132 self.client133 .runtime_api()134 .eth_contract_code(block, account)135 .ok()136 .flatten()137 }138}139140pub fn overrides_handle<C, BE, CAId>(client: Arc<C>) -> Arc<OverrideHandle<Block>>141where142 C: ProvideRuntimeApi<Block> + StorageProvider<Block, BE> + AuxStore,143 C: HeaderBackend<Block> + HeaderMetadata<Block, Error = BlockChainError>,144 C: Send + Sync + 'static,145 C::Api: fp_rpc::EthereumRuntimeRPCApi<Block>,146 C::Api: up_rpc::UniqueApi<Block, CAId, AccountId>,147 BE: Backend<Block> + 'static,148 BE::State: StateBackend<BlakeTwo256>,149 CAId: pallet_common::account::CrossAccountId<sp_runtime::AccountId32> + Sync + Send + 'static,150{151 let mut overrides_map = BTreeMap::new();152 overrides_map.insert(153 EthereumStorageSchema::V1,154 Box::new(SchemaV1Override::new_with_code_provider(155 client.clone(),156 Arc::new(AccountCodes::<C, Block, CAId>::new(client.clone())),157 )) as Box<dyn StorageOverride<_> + Send + Sync>,158 );159 overrides_map.insert(160 EthereumStorageSchema::V2,161 Box::new(SchemaV2Override::new(client.clone()))162 as Box<dyn StorageOverride<_> + Send + Sync>,163 );164 overrides_map.insert(165 EthereumStorageSchema::V3,166 Box::new(SchemaV3Override::new(client.clone()))167 as Box<dyn StorageOverride<_> + Send + Sync>,168 );169170 Arc::new(OverrideHandle {171 schemas: overrides_map,172 fallback: Box::new(RuntimeApiStorageOverride::new(client)),173 })174}175176/// Instantiate all Full RPC extensions.177pub fn create_full<C, P, SC, CA, CAId, A, B>(178 deps: FullDeps<C, P, SC, CA>,179 subscription_task_executor: SubscriptionTaskExecutor,180) -> jsonrpc_core::IoHandler<sc_rpc_api::Metadata>181where182 C: ProvideRuntimeApi<Block> + StorageProvider<Block, B> + AuxStore,183 C: HeaderBackend<Block> + HeaderMetadata<Block, Error = BlockChainError> + 'static,184 C: Send + Sync + 'static,185 C: BlockchainEvents<Block>,186 C::Api: substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>,187 C::Api: BlockBuilder<Block>,188 // C::Api: pallet_contracts_rpc::ContractsRuntimeApi<Block, AccountId, Balance, BlockNumber, Hash>,189 C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi<Block, Balance>,190 C::Api: fp_rpc::EthereumRuntimeRPCApi<Block>,191 C::Api: up_rpc::UniqueApi<Block, CAId, AccountId>,192 B: sc_client_api::Backend<Block> + Send + Sync + 'static,193 B::State: sc_client_api::backend::StateBackend<sp_runtime::traits::HashFor<Block>>,194 P: TransactionPool<Block = Block> + 'static,195 CA: ChainApi<Block = Block> + 'static,196 CAId: pallet_common::account::CrossAccountId<sp_runtime::AccountId32> + Sync + Send + 'static,197{198 use fc_rpc::{199 EthApi, EthApiServer, EthDevSigner, EthFilterApi, EthFilterApiServer, EthPubSubApi,200 EthPubSubApiServer, EthSigner, HexEncodedIdProvider, NetApi, NetApiServer, Web3Api,201 Web3ApiServer,202 };203 use uc_rpc::{UniqueApi, Unique};204 // use pallet_contracts_rpc::{Contracts, ContractsApi};205 use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApi};206 use substrate_frame_rpc_system::{FullSystem, SystemApi};207208 let mut io = jsonrpc_core::IoHandler::default();209 let FullDeps {210 client,211 pool,212 graph,213 select_chain: _,214 fee_history_limit,215 fee_history_cache,216 block_data_cache,217 enable_dev_signer,218 is_authority,219 network,220 deny_unsafe,221 filter_pool,222 backend,223 max_past_logs,224 } = deps;225226 io.extend_with(SystemApi::to_delegate(FullSystem::new(227 client.clone(),228 pool.clone(),229 deny_unsafe,230 )));231232 io.extend_with(TransactionPaymentApi::to_delegate(TransactionPayment::new(233 client.clone(),234 )));235236 // io.extend_with(ContractsApi::to_delegate(Contracts::new(client.clone())));237238 let mut signers = Vec::new();239 if enable_dev_signer {240 signers.push(Box::new(EthDevSigner::new()) as Box<dyn EthSigner>);241 }242243 let overrides = overrides_handle::<_, _, CAId>(client.clone());244245 io.extend_with(EthApiServer::to_delegate(EthApi::new(246 client.clone(),247 pool.clone(),248 graph,249 runtime::TransactionConverter,250 network.clone(),251 signers,252 overrides.clone(),253 backend.clone(),254 is_authority,255 max_past_logs,256 block_data_cache.clone(),257 fee_history_limit,258 fee_history_cache,259 )));260 io.extend_with(UniqueApi::to_delegate(Unique::new(client.clone())));261262 if let Some(filter_pool) = filter_pool {263 io.extend_with(EthFilterApiServer::to_delegate(EthFilterApi::new(264 client.clone(),265 backend,266 filter_pool,267 500_usize, // max stored filters268 max_past_logs,269 block_data_cache,270 )));271 }272273 io.extend_with(NetApiServer::to_delegate(NetApi::new(274 client.clone(),275 network.clone(),276 // Whether to format the `peer_count` response as Hex (default) or not.277 true,278 )));279280 io.extend_with(Web3ApiServer::to_delegate(Web3Api::new(client.clone())));281282 io.extend_with(EthPubSubApiServer::to_delegate(EthPubSubApi::new(283 pool,284 client,285 network,286 SubscriptionManager::<HexEncodedIdProvider>::with_id_provider(287 HexEncodedIdProvider::default(),288 Arc::new(subscription_task_executor),289 ),290 overrides,291 )));292293 io294}