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
@@ -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)
}
}