Implement contract_getStorage RPC API (#3944)

This commit is contained in:
Sergei Pepyakin
2019-10-30 13:54:57 +01:00
committed by GitHub
parent 6c49ad4438
commit 5486d7add2
5 changed files with 147 additions and 15 deletions
+15
View File
@@ -664,6 +664,21 @@ impl_runtime_apis! {
Err(_) => ContractExecResult::Error,
}
}
fn get_storage(
address: AccountId,
key: [u8; 32],
) -> contracts_rpc_runtime_api::GetStorageResult {
Contracts::get_storage(address, key).map_err(|rpc_err| {
use contracts::GetStorageError;
use contracts_rpc_runtime_api::{GetStorageError as RpcGetStorageError};
/// Map the contract error into the RPC layer error.
match rpc_err {
GetStorageError::ContractDoesntExist => RpcGetStorageError::ContractDoesntExist,
GetStorageError::IsTombstone => RpcGetStorageError::IsTombstone,
}
})
}
}
impl transaction_payment_rpc_runtime_api::TransactionPaymentApi<
@@ -45,6 +45,20 @@ pub enum ContractExecResult {
Error,
}
/// A result type of the get storage call.
///
/// See [`ContractsApi::get_storage`] for more info.
pub type GetStorageResult = Result<Option<Vec<u8>>, GetStorageError>;
/// The possible errors that can happen querying the storage of a contract.
#[derive(Eq, PartialEq, Encode, Decode, RuntimeDebug)]
pub enum GetStorageError {
/// The given address doesn't point on a contract.
ContractDoesntExist,
/// The specified contract is a tombstone and thus cannot have any storage.
IsTombstone,
}
client::decl_runtime_apis! {
/// The API to interact with contracts without using executive.
pub trait ContractsApi<AccountId, Balance> where
@@ -61,5 +75,16 @@ client::decl_runtime_apis! {
gas_limit: u64,
input_data: Vec<u8>,
) -> ContractExecResult;
/// Query a given storage key in a given contract.
///
/// Returns `Ok(Some(Vec<u8>))` if the storage value exists under the given key in the
/// specified account and `Ok(None)` if it doesn't. If the account specified by the address
/// doesn't exist, or doesn't have a contract or if the contract is a tombstone, then `Err`
/// is returned.
fn get_storage(
address: AccountId,
key: [u8; 32],
) -> GetStorageResult;
}
}
+75 -12
View File
@@ -18,24 +18,50 @@
use std::sync::Arc;
use serde::{Serialize, Deserialize};
use client::blockchain::HeaderBackend;
use codec::Codec;
use jsonrpc_core::{Error, ErrorCode, Result};
use jsonrpc_derive::rpc;
use primitives::Bytes;
use primitives::{H256, Bytes};
use rpc_primitives::number;
use serde::{Deserialize, Serialize};
use sr_primitives::{
generic::BlockId,
traits::{Block as BlockT, ProvideRuntimeApi},
};
use rpc_primitives::number;
pub use srml_contracts_rpc_runtime_api::{ContractExecResult, ContractsApi as ContractsRuntimeApi};
pub use self::gen_client::Client as ContractsClient;
pub use srml_contracts_rpc_runtime_api::{
self as runtime_api, ContractExecResult, ContractsApi as ContractsRuntimeApi, GetStorageResult,
};
const RUNTIME_ERROR: i64 = 1;
const CONTRACT_DOESNT_EXIST: i64 = 2;
const CONTRACT_IS_A_TOMBSTONE: i64 = 3;
// A private newtype for converting `GetStorageError` into an RPC error.
struct GetStorageError(runtime_api::GetStorageError);
impl From<GetStorageError> for Error {
fn from(e: GetStorageError) -> Error {
use runtime_api::GetStorageError::*;
match e.0 {
ContractDoesntExist => Error {
code: ErrorCode::ServerError(CONTRACT_DOESNT_EXIST),
message: "The specified contract doesn't exist.".into(),
data: None,
},
IsTombstone => Error {
code: ErrorCode::ServerError(CONTRACT_IS_A_TOMBSTONE),
message: "The contract is a tombstone and doesn't have any storage.".into(),
data: None,
}
}
}
}
/// A struct that encodes RPC parameters required for a call to a smart-contract.
#[derive(Serialize, Deserialize)]
#[serde(rename_all="camelCase")]
#[serde(rename_all = "camelCase")]
#[serde(deny_unknown_fields)]
pub struct CallRequest<AccountId, Balance> {
origin: AccountId,
@@ -60,6 +86,16 @@ pub trait ContractsApi<BlockHash, AccountId, Balance> {
call_request: CallRequest<AccountId, Balance>,
at: Option<BlockHash>,
) -> Result<ContractExecResult>;
/// Returns the value under a specified storage `key` in a contract given by `address` param,
/// or `None` if it is not set.
#[rpc(name = "contracts_getStorage")]
fn get_storage(
&self,
address: AccountId,
key: H256,
at: Option<BlockHash>,
) -> Result<Option<Bytes>>;
}
/// An implementation of contract specific RPC methods.
@@ -71,13 +107,15 @@ pub struct Contracts<C, B> {
impl<C, B> Contracts<C, B> {
/// Create new `Contracts` with the given reference to the client.
pub fn new(client: Arc<C>) -> Self {
Contracts { client, _marker: Default::default() }
Contracts {
client,
_marker: Default::default(),
}
}
}
const RUNTIME_ERROR: i64 = 1;
impl<C, Block, AccountId, Balance> ContractsApi<<Block as BlockT>::Hash, AccountId, Balance> for Contracts<C, Block>
impl<C, Block, AccountId, Balance> ContractsApi<<Block as BlockT>::Hash, AccountId, Balance>
for Contracts<C, Block>
where
Block: BlockT,
C: Send + Sync + 'static,
@@ -95,15 +133,14 @@ where
let api = self.client.runtime_api();
let at = BlockId::hash(at.unwrap_or_else(||
// If the block hash is not supplied assume the best block.
self.client.info().best_hash
));
self.client.info().best_hash));
let CallRequest {
origin,
dest,
value,
gas_limit,
input_data
input_data,
} = call_request;
let gas_limit = gas_limit.to_number().map_err(|e| Error {
code: ErrorCode::InvalidParams,
@@ -121,4 +158,30 @@ where
Ok(exec_result)
}
fn get_storage(
&self,
address: AccountId,
key: H256,
at: Option<<Block as BlockT>::Hash>,
) -> Result<Option<Bytes>> {
let api = self.client.runtime_api();
let at = BlockId::hash(at.unwrap_or_else(||
// If the block hash is not supplied assume the best block.
self.client.info().best_hash));
let get_storage_result = api
.get_storage(&at, address, key.into())
.map_err(|e|
// Handle general API calling errors.
Error {
code: ErrorCode::ServerError(RUNTIME_ERROR),
message: "Runtime trapped while querying storage.".into(),
data: Some(format!("{:?}", e).into()),
})?
.map_err(GetStorageError)?
.map(Bytes);
Ok(get_storage_result)
}
}
+1 -2
View File
@@ -29,6 +29,7 @@ pub type CallOf<T> = <T as Trait>::Call;
pub type MomentOf<T> = <<T as Trait>::Time as Time>::Moment;
pub type SeedOf<T> = <T as system::Trait>::Hash;
pub type BlockNumberOf<T> = <T as system::Trait>::BlockNumber;
pub type StorageKey = [u8; 32];
/// A type that represents a topic of an event. At the moment a hash is used.
pub type TopicOf<T> = <T as system::Trait>::Hash;
@@ -84,8 +85,6 @@ macro_rules! try_or_exec_error {
}
}
pub type StorageKey = [u8; 32];
/// An interface that provides access to the external environment in which the
/// smart-contract is executed.
///
+31 -1
View File
@@ -650,10 +650,19 @@ decl_module! {
}
}
/// The possible errors that can happen querying the storage of a contract.
pub enum GetStorageError {
/// The given address doesn't point on a contract.
ContractDoesntExist,
/// The specified contract is a tombstone and thus cannot have any storage.
IsTombstone,
}
/// Public APIs provided by the contracts module.
impl<T: Trait> Module<T> {
/// Perform a call to a specified contract.
///
/// This function is similar to `Self::call`, but doesn't perform any lookups and better
/// This function is similar to `Self::call`, but doesn't perform any address lookups and better
/// suitable for calling directly from Rust.
pub fn bare_call(
origin: T::AccountId,
@@ -667,6 +676,27 @@ impl<T: Trait> Module<T> {
})
}
/// Query storage of a specified contract under a specified key.
pub fn get_storage(
address: T::AccountId,
key: [u8; 32],
) -> rstd::result::Result<Option<Vec<u8>>, GetStorageError> {
let contract_info = <ContractInfoOf<T>>::get(&address)
.ok_or(GetStorageError::ContractDoesntExist)?
.get_alive()
.ok_or(GetStorageError::IsTombstone)?;
let maybe_value = AccountDb::<T>::get_storage(
&DirectAccountDb,
&address,
Some(&contract_info.trie_id),
&key,
);
Ok(maybe_value)
}
}
impl<T: Trait> Module<T> {
fn execute_wasm(
origin: T::AccountId,
gas_limit: Gas,