difftreelog
fix PoV estimate RPC
in: master
8 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -12843,6 +12843,7 @@
"sp-blockchain",
"sp-core",
"sp-externalities",
+ "sp-keystore",
"sp-rpc",
"sp-runtime",
"sp-state-machine",
Cargo.tomldiffbeforeafterboth--- a/Cargo.toml
+++ b/Cargo.toml
@@ -11,7 +11,7 @@
'runtime/unique',
'runtime/tests',
]
-default-members = ['node/*', 'runtime/opal']
+default-members = ['node/*', 'client/*', 'runtime/opal']
package.version = "0.9.36"
[profile.release]
client/rpc/Cargo.tomldiffbeforeafterboth--- a/client/rpc/Cargo.toml
+++ b/client/rpc/Cargo.toml
@@ -25,6 +25,7 @@
sp-api = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" }
sp-blockchain = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" }
sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" }
+sp-keystore = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" }
sp-rpc = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" }
sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" }
pallet-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.36" }
client/rpc/src/pov_estimate.rsdiffbeforeafterboth--- a/client/rpc/src/pov_estimate.rs
+++ b/client/rpc/src/pov_estimate.rs
@@ -16,7 +16,8 @@
use std::sync::Arc;
-use codec::Encode;
+use codec::{Encode, Decode};
+use sp_externalities::Extensions;
use up_pov_estimate_rpc::{PovEstimateApi as PovEstimateRuntimeApi};
use up_common::types::opaque::RuntimeId;
@@ -24,14 +25,21 @@
use sc_service::{NativeExecutionDispatch, config::ExecutionStrategy};
use sp_state_machine::{StateMachine, TrieBackendBuilder};
-use jsonrpsee::{
- core::RpcResult as Result,
- proc_macros::rpc,
-};
+use jsonrpsee::{core::RpcResult as Result, proc_macros::rpc};
use anyhow::anyhow;
use sc_client_api::backend::Backend;
use sp_blockchain::HeaderBackend;
+use sp_core::{
+ Bytes,
+ offchain::{
+ testing::{TestOffchainExt, TestTransactionPoolExt},
+ OffchainDbExt, OffchainWorkerExt, TransactionPoolExt,
+ },
+ testing::TaskExecutor,
+ traits::TaskExecutorExt,
+};
+use sp_keystore::{testing::KeyStore, KeystoreExt};
use sp_api::{AsTrieBackend, BlockId, BlockT, ProvideRuntimeApi};
use sc_executor::NativeElseWasmExecutor;
@@ -113,93 +121,137 @@
#[rpc(server)]
#[async_trait]
pub trait PovEstimateApi<BlockHash> {
- #[method(name = "unique_povEstimate")]
- fn pov_estimate(&self, encoded_xt: Vec<u8>, at: Option<BlockHash>) -> Result<PovInfo>;
+ #[method(name = "unique_estimateExtrinsicPoV")]
+ fn estimate_extrinsic_pov(&self, encoded_xt: Bytes, at: Option<BlockHash>) -> Result<PovInfo>;
}
#[allow(deprecated)]
#[cfg(feature = "pov-estimate")]
-impl<C, Block>
- PovEstimateApiServer<<Block as BlockT>::Hash> for PovEstimate<C, Block>
+impl<C, Block> PovEstimateApiServer<<Block as BlockT>::Hash> for PovEstimate<C, Block>
where
Block: BlockT,
C: 'static + ProvideRuntimeApi<Block> + HeaderBackend<Block>,
C::Api: PovEstimateRuntimeApi<Block>,
{
- fn pov_estimate(&self, encoded_xt: Vec<u8>, at: Option<<Block as BlockT>::Hash>,) -> Result<PovInfo> {
- self.deny_unsafe.check_if_safe()?;
+ fn estimate_extrinsic_pov(
+ &self,
+ encoded_xt: Bytes,
+ at: Option<<Block as BlockT>::Hash>,
+ ) -> Result<PovInfo> {
+ self.deny_unsafe.check_if_safe()?;
let at = BlockId::<Block>::hash(at.unwrap_or_else(|| self.client.info().best_hash));
- let state = self.backend.state_at(at).map_err(|_| anyhow!("unable to fetch the state at {at:?}"))?;
- match &self.runtime_id {
- #[cfg(feature = "unique-runtime")]
- RuntimeId::Unique => execute_extrinsic_in_sandbox::<Block, UniqueRuntimeExecutor>(state, &self.exec_params, encoded_xt),
+ let state = self
+ .backend
+ .state_at(at)
+ .map_err(|_| anyhow!("unable to fetch the state at {at:?}"))?;
- #[cfg(feature = "quartz-runtime")]
- RuntimeId::Quartz => execute_extrinsic_in_sandbox::<Block, QuartzRuntimeExecutor>(state, &self.exec_params, encoded_xt),
+ match &self.runtime_id {
+ #[cfg(feature = "unique-runtime")]
+ RuntimeId::Unique => execute_extrinsic_in_sandbox::<Block, UniqueRuntimeExecutor>(
+ state,
+ &self.exec_params,
+ encoded_xt,
+ ),
- RuntimeId::Opal => execute_extrinsic_in_sandbox::<Block, OpalRuntimeExecutor>(state, &self.exec_params, encoded_xt),
+ #[cfg(feature = "quartz-runtime")]
+ RuntimeId::Quartz => execute_extrinsic_in_sandbox::<Block, QuartzRuntimeExecutor>(
+ state,
+ &self.exec_params,
+ encoded_xt,
+ ),
+
+ RuntimeId::Opal => execute_extrinsic_in_sandbox::<Block, OpalRuntimeExecutor>(
+ state,
+ &self.exec_params,
+ encoded_xt,
+ ),
- runtime_id => Err(anyhow!("unknown runtime id {:?}", runtime_id).into()),
- }
+ runtime_id => Err(anyhow!("unknown runtime id {:?}", runtime_id).into()),
+ }
}
}
-fn execute_extrinsic_in_sandbox<Block, D>(state: StateOf<Block>, exec_params: &ExecutorParams, encoded_xt: Vec<u8>) -> Result<PovInfo>
+fn full_extensions() -> Extensions {
+ let mut extensions = Extensions::default();
+ extensions.register(TaskExecutorExt::new(TaskExecutor::new()));
+ let (offchain, _offchain_state) = TestOffchainExt::new();
+ let (pool, _pool_state) = TestTransactionPoolExt::new();
+ extensions.register(OffchainDbExt::new(offchain.clone()));
+ extensions.register(OffchainWorkerExt::new(offchain));
+ extensions.register(KeystoreExt(std::sync::Arc::new(KeyStore::new())));
+ extensions.register(TransactionPoolExt::new(pool));
+
+ extensions
+}
+
+fn execute_extrinsic_in_sandbox<Block, D>(
+ state: StateOf<Block>,
+ exec_params: &ExecutorParams,
+ encoded_xt: Bytes,
+) -> Result<PovInfo>
where
- Block: BlockT,
- D: NativeExecutionDispatch + 'static,
+ Block: BlockT,
+ D: NativeExecutionDispatch + 'static,
{
- let backend = state.as_trie_backend().clone();
- let mut changes = Default::default();
- let runtime_code_backend = sp_state_machine::backend::BackendRuntimeCode::new(backend);
+ let backend = state.as_trie_backend().clone();
+ let mut changes = Default::default();
+ let runtime_code_backend = sp_state_machine::backend::BackendRuntimeCode::new(backend);
- let proving_backend =
- TrieBackendBuilder::wrap(&backend).with_recorder(Default::default()).build();
+ let proving_backend = TrieBackendBuilder::wrap(&backend)
+ .with_recorder(Default::default())
+ .build();
- let runtime_code = runtime_code_backend.runtime_code()
- .map_err(|_| anyhow!("runtime code backend creation failed"))?;
+ let runtime_code = runtime_code_backend
+ .runtime_code()
+ .map_err(|_| anyhow!("runtime code backend creation failed"))?;
- let pre_root = *backend.root();
+ let pre_root = *backend.root();
- let executor = NativeElseWasmExecutor::<D>::new(
- exec_params.wasm_method,
- exec_params.default_heap_pages,
- exec_params.max_runtime_instances,
- exec_params.runtime_cache_size,
- );
- let execution = ExecutionStrategy::NativeElseWasm;
+ let executor = NativeElseWasmExecutor::<D>::new(
+ exec_params.wasm_method,
+ exec_params.default_heap_pages,
+ exec_params.max_runtime_instances,
+ exec_params.runtime_cache_size,
+ );
+ let execution = ExecutionStrategy::NativeElseWasm;
- StateMachine::new(
- &proving_backend,
- &mut changes,
- &executor,
- "PovEstimateApi_pov_estimate",
- encoded_xt.as_slice(),
- sp_externalities::Extensions::default(),
- &runtime_code,
- sp_core::testing::TaskExecutor::new(),
- )
- .execute(execution.into())
- .map_err(|e| anyhow!("failed to execute the extrinsic {:?}", e))?;
+ let encoded_bytes = encoded_xt.encode();
- let proof = proving_backend
- .extract_proof()
- .expect("A recorder was set and thus, a storage proof can be extracted; qed");
- let proof_size = proof.encoded_size();
- let compact_proof = proof
- .clone()
- .into_compact_proof::<HasherOf<Block>>(pre_root)
- .map_err(|e| anyhow!("failed to generate compact proof {:?}", e))?;
- let compact_proof_size = compact_proof.encoded_size();
+ let xt_result = StateMachine::new(
+ &proving_backend,
+ &mut changes,
+ &executor,
+ "PovEstimateApi_pov_estimate",
+ encoded_bytes.as_slice(),
+ full_extensions(),
+ &runtime_code,
+ sp_core::testing::TaskExecutor::new(),
+ )
+ .execute(execution.into())
+ .map_err(|e| anyhow!("failed to execute the extrinsic {:?}", e))?;
+
+ let xt_result = Decode::decode(&mut &*xt_result)
+ .map_err(|e| anyhow!("failed to decode the extrinsic result {:?}", e))?;
+
+ let proof = proving_backend
+ .extract_proof()
+ .expect("A recorder was set and thus, a storage proof can be extracted; qed");
+ let proof_size = proof.encoded_size();
+ let compact_proof = proof
+ .clone()
+ .into_compact_proof::<HasherOf<Block>>(pre_root)
+ .map_err(|e| anyhow!("failed to generate compact proof {:?}", e))?;
+ let compact_proof_size = compact_proof.encoded_size();
- let compressed_proof = zstd::stream::encode_all(&compact_proof.encode()[..], 0)
- .map_err(|e| anyhow!("failed to generate compact proof {:?}", e))?;
- let compressed_proof_size = compressed_proof.len();
+ let compressed_proof = zstd::stream::encode_all(&compact_proof.encode()[..], 0)
+ .map_err(|e| anyhow!("failed to generate compact proof {:?}", e))?;
+ let compressed_proof_size = compressed_proof.len();
- Ok(PovInfo {
- proof_size: proof_size as u64,
- compact_proof_size: compact_proof_size as u64,
- compressed_proof_size: compressed_proof_size as u64,
- })
+ Ok(PovInfo {
+ proof_size: proof_size as u64,
+ compact_proof_size: compact_proof_size as u64,
+ compressed_proof_size: compressed_proof_size as u64,
+ result: xt_result,
+ })
}
node/cli/src/service.rsdiffbeforeafterboth--- a/node/cli/src/service.rs
+++ b/node/cli/src/service.rs
@@ -67,6 +67,8 @@
use fc_mapping_sync::{MappingSyncWorker, SyncStrategy};
use up_common::types::opaque::*;
+
+#[cfg(feature = "pov-estimate")]
use crate::chain_spec::RuntimeIdentification;
// RMRK
@@ -517,8 +519,12 @@
.for_each(|()| futures::future::ready(())),
);
+ #[cfg(feature = "pov-estimate")]
let rpc_backend = backend.clone();
+
+ #[cfg(feature = "pov-estimate")]
let runtime_id = parachain_config.chain_spec.runtime_id();
+
let rpc_builder = Box::new(move |deny_unsafe, subscription_task_executor| {
let full_deps = unique_rpc::FullDeps {
#[cfg(feature = "pov-estimate")]
@@ -1058,8 +1064,13 @@
let rpc_pool = transaction_pool.clone();
let rpc_network = network.clone();
let rpc_frontier_backend = frontier_backend.clone();
+
+ #[cfg(feature = "pov-estimate")]
let rpc_backend = backend.clone();
+
+ #[cfg(feature = "pov-estimate")]
let runtime_id = config.chain_spec.runtime_id();
+
let rpc_builder = Box::new(move |deny_unsafe, subscription_executor| {
let full_deps = unique_rpc::FullDeps {
#[cfg(feature = "pov-estimate")]
node/rpc/src/lib.rsdiffbeforeafterboth1// 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 EthBlockDataCacheTask, OverrideHandle, RuntimeApiStorageOverride, SchemaV1Override,20 StorageOverride, SchemaV2Override, SchemaV3Override,21};22use jsonrpsee::RpcModule;23use fc_rpc_core::types::{FilterPool, FeeHistoryCache};24use fp_storage::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, sync::Arc};4243use up_common::types::opaque::*;4445// RMRK46use up_data_structs::{47 RmrkCollectionInfo, RmrkInstanceInfo, RmrkResourceInfo, RmrkPropertyInfo, RmrkBaseInfo,48 RmrkPartType, RmrkTheme,49};5051type FullBackend = sc_service::TFullBackend<Block>;5253/// Extra dependencies for GRANDPA54pub struct GrandpaDeps<B> {55 /// Voting round info.56 pub shared_voter_state: SharedVoterState,57 /// Authority set info.58 pub shared_authority_set: SharedAuthoritySet<Hash, BlockNumber>,59 /// Receives notifications about justification events from Grandpa.60 pub justification_stream: GrandpaJustificationStream<Block>,61 /// Executor to drive the subscription manager in the Grandpa RPC handler.62 pub subscription_executor: SubscriptionTaskExecutor,63 /// Finality proof provider.64 pub finality_provider: Arc<FinalityProofProvider<B, Block>>,65}6667/// Full client dependencies.68pub struct FullDeps<C, P, SC, CA: ChainApi> {69 /// The client instance to use.70 pub client: Arc<C>,71 /// Transaction pool instance.72 pub pool: Arc<P>,73 /// Graph pool instance.74 pub graph: Arc<Pool<CA>>,75 /// The SelectChain Strategy76 pub select_chain: SC,77 /// The Node authority flag78 pub is_authority: bool,79 /// Whether to enable dev signer80 pub enable_dev_signer: bool,81 /// Network service82 pub network: Arc<NetworkService<Block, Hash>>,83 /// Whether to deny unsafe calls84 pub deny_unsafe: DenyUnsafe,85 /// EthFilterApi pool.86 pub filter_pool: Option<FilterPool>,87 88 #[cfg(feature = "pov-estimate")]89 pub runtime_id: RuntimeId,90 /// Executor params for PoV estimating91 #[cfg(feature = "pov-estimate")]92 pub exec_params: uc_rpc::pov_estimate::ExecutorParams,93 /// Substrate Backend.94 #[cfg(feature = "pov-estimate")]95 pub backend: Arc<FullBackend>,9697 /// Ethereum Backend.98 pub eth_backend: Arc<fc_db::Backend<Block>>,99 /// Maximum number of logs in a query.100 pub max_past_logs: u32,101 /// Maximum fee history cache size.102 pub fee_history_limit: u64,103 /// Fee history cache.104 pub fee_history_cache: FeeHistoryCache,105 /// Cache for Ethereum block data.106 pub block_data_cache: Arc<EthBlockDataCacheTask<Block>>,107}108109pub fn overrides_handle<C, BE, R>(client: Arc<C>) -> Arc<OverrideHandle<Block>>110where111 C: ProvideRuntimeApi<Block> + StorageProvider<Block, BE> + AuxStore,112 C: HeaderBackend<Block> + HeaderMetadata<Block, Error = BlockChainError>,113 C: Send + Sync + 'static,114 C::Api: fp_rpc::EthereumRuntimeRPCApi<Block>,115 C::Api: up_rpc::UniqueApi<Block, <R as RuntimeInstance>::CrossAccountId, AccountId>,116 BE: Backend<Block> + 'static,117 BE::State: StateBackend<BlakeTwo256>,118 R: RuntimeInstance + Send + Sync + 'static,119{120 let mut overrides_map = BTreeMap::new();121 overrides_map.insert(122 EthereumStorageSchema::V1,123 Box::new(SchemaV1Override::new(client.clone()))124 as Box<dyn StorageOverride<_> + Send + Sync>,125 );126 overrides_map.insert(127 EthereumStorageSchema::V2,128 Box::new(SchemaV2Override::new(client.clone()))129 as Box<dyn StorageOverride<_> + Send + Sync>,130 );131 overrides_map.insert(132 EthereumStorageSchema::V3,133 Box::new(SchemaV3Override::new(client.clone()))134 as Box<dyn StorageOverride<_> + Send + Sync>,135 );136137 Arc::new(OverrideHandle {138 schemas: overrides_map,139 fallback: Box::new(RuntimeApiStorageOverride::new(client)),140 })141}142143/// Instantiate all Full RPC extensions.144pub fn create_full<C, P, SC, CA, R, A, B>(145 deps: FullDeps<C, P, SC, CA>,146 subscription_task_executor: SubscriptionTaskExecutor,147) -> Result<RpcModule<()>, Box<dyn std::error::Error + Send + Sync>>148where149 C: ProvideRuntimeApi<Block> + StorageProvider<Block, B> + AuxStore,150 C: HeaderBackend<Block> + HeaderMetadata<Block, Error = BlockChainError> + 'static,151 C: Send + Sync + 'static,152 C: BlockchainEvents<Block>,153 C::Api: substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>,154 C::Api: BlockBuilder<Block>,155 // C::Api: pallet_contracts_rpc::ContractsRuntimeApi<Block, AccountId, Balance, BlockNumber, Hash>,156 C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi<Block, Balance>,157 C::Api: fp_rpc::EthereumRuntimeRPCApi<Block>,158 C::Api: fp_rpc::ConvertTransactionRuntimeApi<Block>,159 C::Api: up_rpc::UniqueApi<Block, <R as RuntimeInstance>::CrossAccountId, AccountId>,160 C::Api: app_promotion_rpc::AppPromotionApi<161 Block,162 BlockNumber,163 <R as RuntimeInstance>::CrossAccountId,164 AccountId,165 >,166 C::Api: rmrk_rpc::RmrkApi<167 Block,168 AccountId,169 RmrkCollectionInfo<AccountId>,170 RmrkInstanceInfo<AccountId>,171 RmrkResourceInfo,172 RmrkPropertyInfo,173 RmrkBaseInfo<AccountId>,174 RmrkPartType,175 RmrkTheme,176 >,177 C::Api: up_pov_estimate_rpc::PovEstimateApi<Block>,178 B: sc_client_api::Backend<Block> + Send + Sync + 'static,179 B::State: sc_client_api::backend::StateBackend<sp_runtime::traits::HashFor<Block>>,180 P: TransactionPool<Block = Block> + 'static,181 CA: ChainApi<Block = Block> + 'static,182 R: RuntimeInstance + Send + Sync + 'static,183 <R as RuntimeInstance>::CrossAccountId: serde::Serialize,184 for<'de> <R as RuntimeInstance>::CrossAccountId: serde::Deserialize<'de>,185{186 use fc_rpc::{187 Eth, EthApiServer, EthDevSigner, EthFilter, EthFilterApiServer, EthPubSub,188 EthPubSubApiServer, EthSigner, Net, NetApiServer, Web3, Web3ApiServer,189 };190 use uc_rpc::{UniqueApiServer, Unique};191192 #[cfg(not(feature = "unique-runtime"))]193 use uc_rpc::{AppPromotionApiServer, AppPromotion};194195 #[cfg(not(feature = "unique-runtime"))]196 use uc_rpc::{RmrkApiServer, Rmrk};197198 #[cfg(feature = "pov-estimate")]199 use uc_rpc::pov_estimate::{PovEstimateApiServer, PovEstimate};200201 // use pallet_contracts_rpc::{Contracts, ContractsApi};202 use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer};203 use substrate_frame_rpc_system::{System, SystemApiServer};204205 let mut io = RpcModule::new(());206 let FullDeps {207 client,208 pool,209 graph,210 select_chain: _,211 fee_history_limit,212 fee_history_cache,213 block_data_cache,214 enable_dev_signer,215 is_authority,216 network,217 deny_unsafe,218 filter_pool,219220 #[cfg(feature = "pov-estimate")]221 runtime_id,222223 #[cfg(feature = "pov-estimate")]224 exec_params,225226 #[cfg(feature = "pov-estimate")]227 backend,228229 eth_backend,230 max_past_logs,231 } = deps;232233 io.merge(System::new(Arc::clone(&client), Arc::clone(&pool), deny_unsafe).into_rpc())?;234 io.merge(TransactionPayment::new(Arc::clone(&client)).into_rpc())?;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::<_, _, R>(client.clone());244245 let execute_gas_limit_multiplier = 10;246 io.merge(247 Eth::new(248 client.clone(),249 pool.clone(),250 graph,251 Some(<R as RuntimeInstance>::get_transaction_converter()),252 network.clone(),253 signers,254 overrides.clone(),255 eth_backend.clone(),256 is_authority,257 block_data_cache.clone(),258 fee_history_cache,259 fee_history_limit,260 execute_gas_limit_multiplier,261 )262 .into_rpc(),263 )?;264265 io.merge(Unique::new(client.clone()).into_rpc())?;266267 #[cfg(not(feature = "unique-runtime"))]268 io.merge(AppPromotion::new(client.clone()).into_rpc())?;269270 #[cfg(not(feature = "unique-runtime"))]271 io.merge(Rmrk::new(client.clone()).into_rpc())?;272273 #[cfg(feature = "pov-estimate")]274 io.merge(PovEstimate::new(client.clone(), backend, deny_unsafe, exec_params, runtime_id).into_rpc())?;275276 if let Some(filter_pool) = filter_pool {277 io.merge(278 EthFilter::new(279 client.clone(),280 eth_backend,281 filter_pool,282 500_usize, // max stored filters283 max_past_logs,284 block_data_cache,285 )286 .into_rpc(),287 )?;288 }289290 io.merge(291 Net::new(292 client.clone(),293 network.clone(),294 // Whether to format the `peer_count` response as Hex (default) or not.295 true,296 )297 .into_rpc(),298 )?;299300 io.merge(Web3::new(client.clone()).into_rpc())?;301302 io.merge(303 EthPubSub::new(pool, client, network, subscription_task_executor, overrides).into_rpc(),304 )?;305306 Ok(io)307}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 EthBlockDataCacheTask, OverrideHandle, RuntimeApiStorageOverride, SchemaV1Override,20 StorageOverride, SchemaV2Override, SchemaV3Override,21};22use jsonrpsee::RpcModule;23use fc_rpc_core::types::{FilterPool, FeeHistoryCache};24use fp_storage::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, sync::Arc};4243use up_common::types::opaque::*;4445// RMRK46use up_data_structs::{47 RmrkCollectionInfo, RmrkInstanceInfo, RmrkResourceInfo, RmrkPropertyInfo, RmrkBaseInfo,48 RmrkPartType, RmrkTheme,49};5051#[cfg(feature = "pov-estimate")]52type FullBackend = sc_service::TFullBackend<Block>;5354/// Extra dependencies for GRANDPA55pub struct GrandpaDeps<B> {56 /// Voting round info.57 pub shared_voter_state: SharedVoterState,58 /// Authority set info.59 pub shared_authority_set: SharedAuthoritySet<Hash, BlockNumber>,60 /// Receives notifications about justification events from Grandpa.61 pub justification_stream: GrandpaJustificationStream<Block>,62 /// Executor to drive the subscription manager in the Grandpa RPC handler.63 pub subscription_executor: SubscriptionTaskExecutor,64 /// Finality proof provider.65 pub finality_provider: Arc<FinalityProofProvider<B, Block>>,66}6768/// Full client dependencies.69pub struct FullDeps<C, P, SC, CA: ChainApi> {70 /// The client instance to use.71 pub client: Arc<C>,72 /// Transaction pool instance.73 pub pool: Arc<P>,74 /// Graph pool instance.75 pub graph: Arc<Pool<CA>>,76 /// The SelectChain Strategy77 pub select_chain: SC,78 /// The Node authority flag79 pub is_authority: bool,80 /// Whether to enable dev signer81 pub enable_dev_signer: bool,82 /// Network service83 pub network: Arc<NetworkService<Block, Hash>>,84 /// Whether to deny unsafe calls85 pub deny_unsafe: DenyUnsafe,86 /// EthFilterApi pool.87 pub filter_pool: Option<FilterPool>,8889 #[cfg(feature = "pov-estimate")]90 pub runtime_id: RuntimeId,91 /// Executor params for PoV estimating92 #[cfg(feature = "pov-estimate")]93 pub exec_params: uc_rpc::pov_estimate::ExecutorParams,94 /// Substrate Backend.95 #[cfg(feature = "pov-estimate")]96 pub backend: Arc<FullBackend>,9798 /// Ethereum Backend.99 pub eth_backend: Arc<fc_db::Backend<Block>>,100 /// Maximum number of logs in a query.101 pub max_past_logs: u32,102 /// Maximum fee history cache size.103 pub fee_history_limit: u64,104 /// Fee history cache.105 pub fee_history_cache: FeeHistoryCache,106 /// Cache for Ethereum block data.107 pub block_data_cache: Arc<EthBlockDataCacheTask<Block>>,108}109110pub fn overrides_handle<C, BE, R>(client: Arc<C>) -> Arc<OverrideHandle<Block>>111where112 C: ProvideRuntimeApi<Block> + StorageProvider<Block, BE> + AuxStore,113 C: HeaderBackend<Block> + HeaderMetadata<Block, Error = BlockChainError>,114 C: Send + Sync + 'static,115 C::Api: fp_rpc::EthereumRuntimeRPCApi<Block>,116 C::Api: up_rpc::UniqueApi<Block, <R as RuntimeInstance>::CrossAccountId, AccountId>,117 BE: Backend<Block> + 'static,118 BE::State: StateBackend<BlakeTwo256>,119 R: RuntimeInstance + Send + Sync + 'static,120{121 let mut overrides_map = BTreeMap::new();122 overrides_map.insert(123 EthereumStorageSchema::V1,124 Box::new(SchemaV1Override::new(client.clone()))125 as Box<dyn StorageOverride<_> + Send + Sync>,126 );127 overrides_map.insert(128 EthereumStorageSchema::V2,129 Box::new(SchemaV2Override::new(client.clone()))130 as Box<dyn StorageOverride<_> + Send + Sync>,131 );132 overrides_map.insert(133 EthereumStorageSchema::V3,134 Box::new(SchemaV3Override::new(client.clone()))135 as Box<dyn StorageOverride<_> + Send + Sync>,136 );137138 Arc::new(OverrideHandle {139 schemas: overrides_map,140 fallback: Box::new(RuntimeApiStorageOverride::new(client)),141 })142}143144/// Instantiate all Full RPC extensions.145pub fn create_full<C, P, SC, CA, R, A, B>(146 deps: FullDeps<C, P, SC, CA>,147 subscription_task_executor: SubscriptionTaskExecutor,148) -> Result<RpcModule<()>, Box<dyn std::error::Error + Send + Sync>>149where150 C: ProvideRuntimeApi<Block> + StorageProvider<Block, B> + AuxStore,151 C: HeaderBackend<Block> + HeaderMetadata<Block, Error = BlockChainError> + 'static,152 C: Send + Sync + 'static,153 C: BlockchainEvents<Block>,154 C::Api: substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>,155 C::Api: BlockBuilder<Block>,156 // C::Api: pallet_contracts_rpc::ContractsRuntimeApi<Block, AccountId, Balance, BlockNumber, Hash>,157 C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi<Block, Balance>,158 C::Api: fp_rpc::EthereumRuntimeRPCApi<Block>,159 C::Api: fp_rpc::ConvertTransactionRuntimeApi<Block>,160 C::Api: up_rpc::UniqueApi<Block, <R as RuntimeInstance>::CrossAccountId, AccountId>,161 C::Api: app_promotion_rpc::AppPromotionApi<162 Block,163 BlockNumber,164 <R as RuntimeInstance>::CrossAccountId,165 AccountId,166 >,167 C::Api: rmrk_rpc::RmrkApi<168 Block,169 AccountId,170 RmrkCollectionInfo<AccountId>,171 RmrkInstanceInfo<AccountId>,172 RmrkResourceInfo,173 RmrkPropertyInfo,174 RmrkBaseInfo<AccountId>,175 RmrkPartType,176 RmrkTheme,177 >,178 C::Api: up_pov_estimate_rpc::PovEstimateApi<Block>,179 B: sc_client_api::Backend<Block> + Send + Sync + 'static,180 B::State: sc_client_api::backend::StateBackend<sp_runtime::traits::HashFor<Block>>,181 P: TransactionPool<Block = Block> + 'static,182 CA: ChainApi<Block = Block> + 'static,183 R: RuntimeInstance + Send + Sync + 'static,184 <R as RuntimeInstance>::CrossAccountId: serde::Serialize,185 for<'de> <R as RuntimeInstance>::CrossAccountId: serde::Deserialize<'de>,186{187 use fc_rpc::{188 Eth, EthApiServer, EthDevSigner, EthFilter, EthFilterApiServer, EthPubSub,189 EthPubSubApiServer, EthSigner, Net, NetApiServer, Web3, Web3ApiServer,190 };191 use uc_rpc::{UniqueApiServer, Unique};192193 #[cfg(not(feature = "unique-runtime"))]194 use uc_rpc::{AppPromotionApiServer, AppPromotion};195196 #[cfg(not(feature = "unique-runtime"))]197 use uc_rpc::{RmrkApiServer, Rmrk};198199 #[cfg(feature = "pov-estimate")]200 use uc_rpc::pov_estimate::{PovEstimateApiServer, PovEstimate};201202 // use pallet_contracts_rpc::{Contracts, ContractsApi};203 use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer};204 use substrate_frame_rpc_system::{System, SystemApiServer};205206 let mut io = RpcModule::new(());207 let FullDeps {208 client,209 pool,210 graph,211 select_chain: _,212 fee_history_limit,213 fee_history_cache,214 block_data_cache,215 enable_dev_signer,216 is_authority,217 network,218 deny_unsafe,219 filter_pool,220221 #[cfg(feature = "pov-estimate")]222 runtime_id,223224 #[cfg(feature = "pov-estimate")]225 exec_params,226227 #[cfg(feature = "pov-estimate")]228 backend,229230 eth_backend,231 max_past_logs,232 } = deps;233234 io.merge(System::new(Arc::clone(&client), Arc::clone(&pool), deny_unsafe).into_rpc())?;235 io.merge(TransactionPayment::new(Arc::clone(&client)).into_rpc())?;236237 // io.extend_with(ContractsApi::to_delegate(Contracts::new(client.clone())));238239 let mut signers = Vec::new();240 if enable_dev_signer {241 signers.push(Box::new(EthDevSigner::new()) as Box<dyn EthSigner>);242 }243244 let overrides = overrides_handle::<_, _, R>(client.clone());245246 let execute_gas_limit_multiplier = 10;247 io.merge(248 Eth::new(249 client.clone(),250 pool.clone(),251 graph,252 Some(<R as RuntimeInstance>::get_transaction_converter()),253 network.clone(),254 signers,255 overrides.clone(),256 eth_backend.clone(),257 is_authority,258 block_data_cache.clone(),259 fee_history_cache,260 fee_history_limit,261 execute_gas_limit_multiplier,262 )263 .into_rpc(),264 )?;265266 io.merge(Unique::new(client.clone()).into_rpc())?;267268 #[cfg(not(feature = "unique-runtime"))]269 io.merge(AppPromotion::new(client.clone()).into_rpc())?;270271 #[cfg(not(feature = "unique-runtime"))]272 io.merge(Rmrk::new(client.clone()).into_rpc())?;273274 #[cfg(feature = "pov-estimate")]275 io.merge(276 PovEstimate::new(277 client.clone(),278 backend,279 deny_unsafe,280 exec_params,281 runtime_id,282 )283 .into_rpc(),284 )?;285286 if let Some(filter_pool) = filter_pool {287 io.merge(288 EthFilter::new(289 client.clone(),290 eth_backend,291 filter_pool,292 500_usize, // max stored filters293 max_past_logs,294 block_data_cache,295 )296 .into_rpc(),297 )?;298 }299300 io.merge(301 Net::new(302 client.clone(),303 network.clone(),304 // Whether to format the `peer_count` response as Hex (default) or not.305 true,306 )307 .into_rpc(),308 )?;309310 io.merge(Web3::new(client.clone()).into_rpc())?;311312 io.merge(313 EthPubSub::new(pool, client, network, subscription_task_executor, overrides).into_rpc(),314 )?;315316 Ok(io)317}primitives/pov-estimate-rpc/src/lib.rsdiffbeforeafterboth--- a/primitives/pov-estimate-rpc/src/lib.rs
+++ b/primitives/pov-estimate-rpc/src/lib.rs
@@ -16,24 +16,25 @@
#![cfg_attr(not(feature = "std"), no_std)]
-use codec::{Decode, Encode, MaxEncodedLen};
use scale_info::TypeInfo;
#[cfg(feature = "std")]
use serde::Serialize;
use sp_runtime::ApplyExtrinsicResult;
+use sp_core::Bytes;
#[cfg_attr(feature = "std", derive(Serialize))]
-#[derive(Encode, Decode, Debug, TypeInfo, MaxEncodedLen)]
+#[derive(Debug, TypeInfo)]
pub struct PovInfo {
- pub proof_size: u64,
- pub compact_proof_size: u64,
- pub compressed_proof_size: u64,
+ pub proof_size: u64,
+ pub compact_proof_size: u64,
+ pub compressed_proof_size: u64,
+ pub result: ApplyExtrinsicResult,
}
sp_api::decl_runtime_apis! {
- pub trait PovEstimateApi {
- fn pov_estimate(uxt: Block::Extrinsic) -> ApplyExtrinsicResult;
- }
+ pub trait PovEstimateApi {
+ fn pov_estimate(uxt: Bytes) -> ApplyExtrinsicResult;
+ }
}
runtime/common/runtime_apis.rsdiffbeforeafterboth--- a/runtime/common/runtime_apis.rs
+++ b/runtime/common/runtime_apis.rs
@@ -35,11 +35,11 @@
) => {
use sp_std::prelude::*;
use sp_api::impl_runtime_apis;
- use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H256, U256, H160};
+ use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H256, U256, H160, Bytes};
use sp_runtime::{
Permill,
traits::Block as BlockT,
- transaction_validity::{TransactionSource, TransactionValidity, TransactionValidityError, InvalidTransaction},
+ transaction_validity::{TransactionSource, TransactionValidity},
ApplyExtrinsicResult, DispatchError,
};
use fp_rpc::TransactionStatus;
@@ -780,12 +780,24 @@
impl up_pov_estimate_rpc::PovEstimateApi<Block> for Runtime {
#[allow(unused_variables)]
- fn pov_estimate(uxt: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
+ fn pov_estimate(uxt: Bytes) -> ApplyExtrinsicResult {
#[cfg(feature = "pov-estimate")]
- return Executive::apply_extrinsic(uxt);
+ {
+ use codec::Decode;
+
+ let uxt_decode = <<Block as BlockT>::Extrinsic as Decode>::decode(&mut &*uxt)
+ .map_err(|_| DispatchError::Other("failed to decode the extrinsic"));
+
+ let uxt = match uxt_decode {
+ Ok(uxt) => uxt,
+ Err(err) => return Ok(err.into()),
+ };
+
+ Executive::apply_extrinsic(uxt)
+ }
#[cfg(not(feature = "pov-estimate"))]
- return Err(TransactionValidityError::Invalid(InvalidTransaction::Call))
+ return Ok(unsupported!());
}
}