mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-04-26 15:47:58 +00:00
add system_dryRun (#6300)
* add system_dryRun * fix build error * delete unneeded code * return ApplyExtrinsicResult directly * line width * mark dry run unsafe * line width * fix test * add test * update comment
This commit is contained in:
@@ -26,6 +26,8 @@ frame-system-rpc-runtime-api = { version = "2.0.0-rc3", path = "../../../../fram
|
||||
sp-core = { version = "2.0.0-rc3", path = "../../../../primitives/core" }
|
||||
sp-blockchain = { version = "2.0.0-rc3", path = "../../../../primitives/blockchain" }
|
||||
sp-transaction-pool = { version = "2.0.0-rc3", path = "../../../../primitives/transaction-pool" }
|
||||
sp-block-builder = { version = "2.0.0-rc3", path = "../../../../primitives/block-builder" }
|
||||
sc-rpc-api = { version = "0.8.0-rc3", path = "../../../../client/rpc-api" }
|
||||
|
||||
[dev-dependencies]
|
||||
substrate-test-runtime-client = { version = "2.0.0-rc3", path = "../../../../test-utils/runtime/client" }
|
||||
|
||||
@@ -22,8 +22,8 @@ use std::sync::Arc;
|
||||
use codec::{self, Codec, Decode, Encode};
|
||||
use sc_client_api::light::{future_header, RemoteBlockchain, Fetcher, RemoteCallRequest};
|
||||
use jsonrpc_core::{
|
||||
Error, ErrorCode,
|
||||
futures::future::{result, Future},
|
||||
Error as RpcError, ErrorCode,
|
||||
futures::future::{self as rpc_future,result, Future},
|
||||
};
|
||||
use jsonrpc_derive::rpc;
|
||||
use futures::future::{ready, TryFutureExt};
|
||||
@@ -35,18 +35,20 @@ use sp_runtime::{
|
||||
generic::BlockId,
|
||||
traits,
|
||||
};
|
||||
use sp_core::hexdisplay::HexDisplay;
|
||||
use sp_core::{hexdisplay::HexDisplay, Bytes};
|
||||
use sp_transaction_pool::{TransactionPool, InPoolTransaction};
|
||||
use sp_block_builder::BlockBuilder;
|
||||
use sc_rpc_api::DenyUnsafe;
|
||||
|
||||
pub use frame_system_rpc_runtime_api::AccountNonceApi;
|
||||
pub use self::gen_client::Client as SystemClient;
|
||||
|
||||
/// Future that resolves to account nonce.
|
||||
pub type FutureResult<T> = Box<dyn Future<Item = T, Error = Error> + Send>;
|
||||
pub type FutureResult<T> = Box<dyn Future<Item = T, Error = RpcError> + Send>;
|
||||
|
||||
/// System RPC methods.
|
||||
#[rpc]
|
||||
pub trait SystemApi<AccountId, Index> {
|
||||
pub trait SystemApi<BlockHash, AccountId, Index> {
|
||||
/// Returns the next valid index (aka nonce) for given account.
|
||||
///
|
||||
/// This method takes into consideration all pending transactions
|
||||
@@ -54,34 +56,57 @@ pub trait SystemApi<AccountId, Index> {
|
||||
/// it fallbacks to query the index from the runtime (aka. state nonce).
|
||||
#[rpc(name = "system_accountNextIndex", alias("account_nextIndex"))]
|
||||
fn nonce(&self, account: AccountId) -> FutureResult<Index>;
|
||||
|
||||
/// Dry run an extrinsic at a given block. Return SCALE encoded ApplyExtrinsicResult.
|
||||
#[rpc(name = "system_dryRun", alias("system_dryRunAt"))]
|
||||
fn dry_run(&self, extrinsic: Bytes, at: Option<BlockHash>) -> FutureResult<Bytes>;
|
||||
}
|
||||
|
||||
const RUNTIME_ERROR: i64 = 1;
|
||||
/// Error type of this RPC api.
|
||||
pub enum Error {
|
||||
/// The transaction was not decodable.
|
||||
DecodeError,
|
||||
/// The call to runtime failed.
|
||||
RuntimeError,
|
||||
}
|
||||
|
||||
impl From<Error> for i64 {
|
||||
fn from(e: Error) -> i64 {
|
||||
match e {
|
||||
Error::RuntimeError => 1,
|
||||
Error::DecodeError => 2,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An implementation of System-specific RPC methods on full client.
|
||||
pub struct FullSystem<P: TransactionPool, C, B> {
|
||||
client: Arc<C>,
|
||||
pool: Arc<P>,
|
||||
deny_unsafe: DenyUnsafe,
|
||||
_marker: std::marker::PhantomData<B>,
|
||||
}
|
||||
|
||||
impl<P: TransactionPool, C, B> FullSystem<P, C, B> {
|
||||
/// Create new `FullSystem` given client and transaction pool.
|
||||
pub fn new(client: Arc<C>, pool: Arc<P>) -> Self {
|
||||
pub fn new(client: Arc<C>, pool: Arc<P>, deny_unsafe: DenyUnsafe,) -> Self {
|
||||
FullSystem {
|
||||
client,
|
||||
pool,
|
||||
deny_unsafe,
|
||||
_marker: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<P, C, Block, AccountId, Index> SystemApi<AccountId, Index> for FullSystem<P, C, Block>
|
||||
impl<P, C, Block, AccountId, Index> SystemApi<<Block as traits::Block>::Hash, AccountId, Index>
|
||||
for FullSystem<P, C, Block>
|
||||
where
|
||||
C: sp_api::ProvideRuntimeApi<Block>,
|
||||
C: HeaderBackend<Block>,
|
||||
C: Send + Sync + 'static,
|
||||
C::Api: AccountNonceApi<Block, AccountId, Index>,
|
||||
C::Api: BlockBuilder<Block>,
|
||||
P: TransactionPool + 'static,
|
||||
Block: traits::Block,
|
||||
AccountId: Clone + std::fmt::Display + Codec,
|
||||
@@ -93,8 +118,8 @@ where
|
||||
let best = self.client.info().best_hash;
|
||||
let at = BlockId::hash(best);
|
||||
|
||||
let nonce = api.account_nonce(&at, account.clone()).map_err(|e| Error {
|
||||
code: ErrorCode::ServerError(RUNTIME_ERROR),
|
||||
let nonce = api.account_nonce(&at, account.clone()).map_err(|e| RpcError {
|
||||
code: ErrorCode::ServerError(Error::RuntimeError.into()),
|
||||
message: "Unable to query nonce.".into(),
|
||||
data: Some(format!("{:?}", e).into()),
|
||||
})?;
|
||||
@@ -104,6 +129,38 @@ where
|
||||
|
||||
Box::new(result(get_nonce()))
|
||||
}
|
||||
|
||||
fn dry_run(&self, extrinsic: Bytes, at: Option<<Block as traits::Block>::Hash>) -> FutureResult<Bytes> {
|
||||
if let Err(err) = self.deny_unsafe.check_if_safe() {
|
||||
return Box::new(rpc_future::err(err.into()));
|
||||
}
|
||||
|
||||
let dry_run = || {
|
||||
let api = self.client.runtime_api();
|
||||
let at = BlockId::<Block>::hash(at.unwrap_or_else(||
|
||||
// If the block hash is not supplied assume the best block.
|
||||
self.client.info().best_hash
|
||||
));
|
||||
|
||||
let uxt: <Block as traits::Block>::Extrinsic = Decode::decode(&mut &*extrinsic).map_err(|e| RpcError {
|
||||
code: ErrorCode::ServerError(Error::DecodeError.into()),
|
||||
message: "Unable to dry run extrinsic.".into(),
|
||||
data: Some(format!("{:?}", e).into()),
|
||||
})?;
|
||||
|
||||
let result = api.apply_extrinsic(&at, uxt)
|
||||
.map_err(|e| RpcError {
|
||||
code: ErrorCode::ServerError(Error::RuntimeError.into()),
|
||||
message: "Unable to dry run extrinsic.".into(),
|
||||
data: Some(format!("{:?}", e).into()),
|
||||
})?;
|
||||
|
||||
Ok(Encode::encode(&result).into())
|
||||
};
|
||||
|
||||
|
||||
Box::new(result(dry_run()))
|
||||
}
|
||||
}
|
||||
|
||||
/// An implementation of System-specific RPC methods on light client.
|
||||
@@ -131,7 +188,8 @@ impl<P: TransactionPool, C, F, Block> LightSystem<P, C, F, Block> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<P, C, F, Block, AccountId, Index> SystemApi<AccountId, Index> for LightSystem<P, C, F, Block>
|
||||
impl<P, C, F, Block, AccountId, Index> SystemApi<<Block as traits::Block>::Hash, AccountId, Index>
|
||||
for LightSystem<P, C, F, Block>
|
||||
where
|
||||
P: TransactionPool + 'static,
|
||||
C: HeaderBackend<Block>,
|
||||
@@ -165,8 +223,8 @@ where
|
||||
).compat();
|
||||
let future_nonce = future_nonce.and_then(|nonce| Decode::decode(&mut &nonce[..])
|
||||
.map_err(|e| ClientError::CallResultDecode("Cannot decode account nonce", e)));
|
||||
let future_nonce = future_nonce.map_err(|e| Error {
|
||||
code: ErrorCode::ServerError(RUNTIME_ERROR),
|
||||
let future_nonce = future_nonce.map_err(|e| RpcError {
|
||||
code: ErrorCode::ServerError(Error::RuntimeError.into()),
|
||||
message: "Unable to query nonce.".into(),
|
||||
data: Some(format!("{:?}", e).into()),
|
||||
});
|
||||
@@ -176,6 +234,14 @@ where
|
||||
|
||||
Box::new(future_nonce)
|
||||
}
|
||||
|
||||
fn dry_run(&self, _extrinsic: Bytes, _at: Option<<Block as traits::Block>::Hash>) -> FutureResult<Bytes> {
|
||||
Box::new(result(Err(RpcError {
|
||||
code: ErrorCode::MethodNotFound,
|
||||
message: "Unable to dry run extrinsic.".into(),
|
||||
data: None,
|
||||
})))
|
||||
}
|
||||
}
|
||||
|
||||
/// Adjust account nonce from state, so that tx with the nonce will be
|
||||
@@ -224,6 +290,7 @@ mod tests {
|
||||
use futures::executor::block_on;
|
||||
use substrate_test_runtime_client::{runtime::Transfer, AccountKeyring};
|
||||
use sc_transaction_pool::{BasicPool, FullChainApi};
|
||||
use sp_runtime::{ApplyExtrinsicResult, transaction_validity::{TransactionValidityError, InvalidTransaction}};
|
||||
|
||||
#[test]
|
||||
fn should_return_next_nonce_for_some_account() {
|
||||
@@ -255,7 +322,7 @@ mod tests {
|
||||
let ext1 = new_transaction(1);
|
||||
block_on(pool.submit_one(&BlockId::number(0), source, ext1)).unwrap();
|
||||
|
||||
let accounts = FullSystem::new(client, pool);
|
||||
let accounts = FullSystem::new(client, pool, DenyUnsafe::Yes);
|
||||
|
||||
// when
|
||||
let nonce = accounts.nonce(AccountKeyring::Alice.into());
|
||||
@@ -263,4 +330,91 @@ mod tests {
|
||||
// then
|
||||
assert_eq!(nonce.wait().unwrap(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dry_run_should_deny_unsafe() {
|
||||
let _ = env_logger::try_init();
|
||||
|
||||
// given
|
||||
let client = Arc::new(substrate_test_runtime_client::new());
|
||||
let pool = Arc::new(
|
||||
BasicPool::new(
|
||||
Default::default(),
|
||||
Arc::new(FullChainApi::new(client.clone())),
|
||||
None,
|
||||
).0
|
||||
);
|
||||
|
||||
let accounts = FullSystem::new(client, pool, DenyUnsafe::Yes);
|
||||
|
||||
// when
|
||||
let res = accounts.dry_run(vec![].into(), None);
|
||||
|
||||
// then
|
||||
assert_eq!(res.wait(), Err(RpcError::method_not_found()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dry_run_should_work() {
|
||||
let _ = env_logger::try_init();
|
||||
|
||||
// given
|
||||
let client = Arc::new(substrate_test_runtime_client::new());
|
||||
let pool = Arc::new(
|
||||
BasicPool::new(
|
||||
Default::default(),
|
||||
Arc::new(FullChainApi::new(client.clone())),
|
||||
None,
|
||||
).0
|
||||
);
|
||||
|
||||
let accounts = FullSystem::new(client, pool, DenyUnsafe::No);
|
||||
|
||||
let tx = Transfer {
|
||||
from: AccountKeyring::Alice.into(),
|
||||
to: AccountKeyring::Bob.into(),
|
||||
amount: 5,
|
||||
nonce: 0,
|
||||
}.into_signed_tx();
|
||||
|
||||
// when
|
||||
let res = accounts.dry_run(tx.encode().into(), None);
|
||||
|
||||
// then
|
||||
let bytes = res.wait().unwrap().0;
|
||||
let apply_res: ApplyExtrinsicResult = Decode::decode(&mut bytes.as_slice()).unwrap();
|
||||
assert_eq!(apply_res, Ok(Ok(())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dry_run_should_indicate_error() {
|
||||
let _ = env_logger::try_init();
|
||||
|
||||
// given
|
||||
let client = Arc::new(substrate_test_runtime_client::new());
|
||||
let pool = Arc::new(
|
||||
BasicPool::new(
|
||||
Default::default(),
|
||||
Arc::new(FullChainApi::new(client.clone())),
|
||||
None,
|
||||
).0
|
||||
);
|
||||
|
||||
let accounts = FullSystem::new(client, pool, DenyUnsafe::No);
|
||||
|
||||
let tx = Transfer {
|
||||
from: AccountKeyring::Alice.into(),
|
||||
to: AccountKeyring::Bob.into(),
|
||||
amount: 5,
|
||||
nonce: 100,
|
||||
}.into_signed_tx();
|
||||
|
||||
// when
|
||||
let res = accounts.dry_run(tx.encode().into(), None);
|
||||
|
||||
// then
|
||||
let bytes = res.wait().unwrap().0;
|
||||
let apply_res: ApplyExtrinsicResult = Decode::decode(&mut bytes.as_slice()).unwrap();
|
||||
assert_eq!(apply_res, Err(TransactionValidityError::Invalid(InvalidTransaction::Stale)));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user