#![warn(missing_docs)]
#![warn(unused_crate_dependencies)]
use std::{marker::PhantomData, sync::Arc};
use codec::{Codec, Decode, Encode};
use jsonrpsee::{
core::{async_trait, RpcResult},
proc_macros::rpc,
types::{error::ErrorObject, ErrorObjectOwned},
};
use serde::{Deserialize, Serialize};
use sp_api::{ApiExt, ProvideRuntimeApi};
use sp_blockchain::HeaderBackend;
use sp_core::{
offchain::{storage::OffchainDb, OffchainDbExt, OffchainStorage},
Bytes,
};
use sp_mmr_primitives::{Error as MmrError, LeafProof};
use sp_runtime::traits::{Block as BlockT, NumberFor};
pub use sp_mmr_primitives::MmrApi as MmrRuntimeApi;
const RUNTIME_ERROR: i32 = 8000;
const MMR_ERROR: i32 = 8010;
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct LeavesProof<BlockHash> {
pub block_hash: BlockHash,
pub leaves: Bytes,
pub proof: Bytes,
}
impl<BlockHash> LeavesProof<BlockHash> {
pub fn new<Leaf, MmrHash>(
block_hash: BlockHash,
leaves: Vec<Leaf>,
proof: LeafProof<MmrHash>,
) -> Self
where
Leaf: Encode,
MmrHash: Encode,
{
Self { block_hash, leaves: Bytes(leaves.encode()), proof: Bytes(proof.encode()) }
}
}
#[rpc(client, server)]
pub trait MmrApi<BlockHash, BlockNumber, MmrHash> {
#[method(name = "mmr_root")]
fn mmr_root(&self, at: Option<BlockHash>) -> RpcResult<MmrHash>;
#[method(name = "mmr_generateProof")]
fn generate_proof(
&self,
block_numbers: Vec<BlockNumber>,
best_known_block_number: Option<BlockNumber>,
at: Option<BlockHash>,
) -> RpcResult<LeavesProof<BlockHash>>;
#[method(name = "mmr_verifyProof")]
fn verify_proof(&self, proof: LeavesProof<BlockHash>) -> RpcResult<bool>;
#[method(name = "mmr_verifyProofStateless")]
fn verify_proof_stateless(
&self,
mmr_root: MmrHash,
proof: LeavesProof<BlockHash>,
) -> RpcResult<bool>;
}
pub struct Mmr<Client, Block, S> {
client: Arc<Client>,
offchain_db: OffchainDb<S>,
_marker: PhantomData<Block>,
}
impl<C, B, S> Mmr<C, B, S> {
pub fn new(client: Arc<C>, offchain_storage: S) -> Self {
Self { client, _marker: Default::default(), offchain_db: OffchainDb::new(offchain_storage) }
}
}
#[async_trait]
impl<Client, Block, MmrHash, S> MmrApiServer<<Block as BlockT>::Hash, NumberFor<Block>, MmrHash>
for Mmr<Client, (Block, MmrHash), S>
where
Block: BlockT,
Client: Send + Sync + 'static + ProvideRuntimeApi<Block> + HeaderBackend<Block>,
Client::Api: MmrRuntimeApi<Block, MmrHash, NumberFor<Block>>,
MmrHash: Codec + Send + Sync + 'static,
S: OffchainStorage + 'static,
{
fn mmr_root(&self, at: Option<<Block as BlockT>::Hash>) -> RpcResult<MmrHash> {
let block_hash = at.unwrap_or_else(||
self.client.info().best_hash);
let api = self.client.runtime_api();
let mmr_root = api
.mmr_root(block_hash)
.map_err(runtime_error_into_rpc_error)?
.map_err(mmr_error_into_rpc_error)?;
Ok(mmr_root)
}
fn generate_proof(
&self,
block_numbers: Vec<NumberFor<Block>>,
best_known_block_number: Option<NumberFor<Block>>,
at: Option<<Block as BlockT>::Hash>,
) -> RpcResult<LeavesProof<<Block as BlockT>::Hash>> {
let mut api = self.client.runtime_api();
let block_hash = at.unwrap_or_else(||
self.client.info().best_hash);
api.register_extension(OffchainDbExt::new(self.offchain_db.clone()));
let (leaves, proof) = api
.generate_proof(block_hash, block_numbers, best_known_block_number)
.map_err(runtime_error_into_rpc_error)?
.map_err(mmr_error_into_rpc_error)?;
Ok(LeavesProof::new(block_hash, leaves, proof))
}
fn verify_proof(&self, proof: LeavesProof<<Block as BlockT>::Hash>) -> RpcResult<bool> {
let mut api = self.client.runtime_api();
let leaves = Decode::decode(&mut &proof.leaves.0[..]).map_err(invalid_params)?;
let decoded_proof = Decode::decode(&mut &proof.proof.0[..]).map_err(invalid_params)?;
api.register_extension(OffchainDbExt::new(self.offchain_db.clone()));
api.verify_proof(proof.block_hash, leaves, decoded_proof)
.map_err(runtime_error_into_rpc_error)?
.map_err(mmr_error_into_rpc_error)?;
Ok(true)
}
fn verify_proof_stateless(
&self,
mmr_root: MmrHash,
proof: LeavesProof<<Block as BlockT>::Hash>,
) -> RpcResult<bool> {
let api = self.client.runtime_api();
let leaves = Decode::decode(&mut &proof.leaves.0[..]).map_err(invalid_params)?;
let decoded_proof = Decode::decode(&mut &proof.proof.0[..]).map_err(invalid_params)?;
api.verify_proof_stateless(proof.block_hash, mmr_root, leaves, decoded_proof)
.map_err(runtime_error_into_rpc_error)?
.map_err(mmr_error_into_rpc_error)?;
Ok(true)
}
}
fn mmr_error_into_rpc_error(err: MmrError) -> ErrorObjectOwned {
let error_code = MMR_ERROR +
match err {
MmrError::LeafNotFound => 1,
MmrError::GenerateProof => 2,
MmrError::Verify => 3,
MmrError::InvalidNumericOp => 4,
MmrError::InvalidBestKnownBlock => 5,
_ => 0,
};
ErrorObject::owned(error_code, err.to_string(), Some(format!("{:?}", err)))
}
fn runtime_error_into_rpc_error(err: impl std::fmt::Debug) -> ErrorObjectOwned {
ErrorObject::owned(RUNTIME_ERROR, "Runtime trapped", Some(format!("{:?}", err)))
}
fn invalid_params(e: impl std::error::Error) -> ErrorObjectOwned {
ErrorObject::owned(
jsonrpsee::types::error::ErrorCode::InvalidParams.code(),
e.to_string(),
None::<()>,
)
}
#[cfg(test)]
mod tests {
use super::*;
use sp_core::H256;
#[test]
fn should_serialize_leaf_proof() {
let leaf = vec![1_u8, 2, 3, 4];
let proof = LeafProof {
leaf_indices: vec![1],
leaf_count: 9,
items: vec![H256::repeat_byte(1), H256::repeat_byte(2)],
};
let leaf_proof = LeavesProof::new(H256::repeat_byte(0), vec![leaf], proof);
let actual = serde_json::to_string(&leaf_proof).unwrap();
assert_eq!(
actual,
r#"{"blockHash":"0x0000000000000000000000000000000000000000000000000000000000000000","leaves":"0x041001020304","proof":"0x04010000000000000009000000000000000801010101010101010101010101010101010101010101010101010101010101010202020202020202020202020202020202020202020202020202020202020202"}"#
);
}
#[test]
fn should_serialize_leaves_proof() {
let leaf_a = vec![1_u8, 2, 3, 4];
let leaf_b = vec![2_u8, 2, 3, 4];
let proof = LeafProof {
leaf_indices: vec![1, 2],
leaf_count: 9,
items: vec![H256::repeat_byte(1), H256::repeat_byte(2)],
};
let leaf_proof = LeavesProof::new(H256::repeat_byte(0), vec![leaf_a, leaf_b], proof);
let actual = serde_json::to_string(&leaf_proof).unwrap();
assert_eq!(
actual,
r#"{"blockHash":"0x0000000000000000000000000000000000000000000000000000000000000000","leaves":"0x0810010203041002020304","proof":"0x080100000000000000020000000000000009000000000000000801010101010101010101010101010101010101010101010101010101010101010202020202020202020202020202020202020202020202020202020202020202"}"#
);
}
#[test]
fn should_deserialize_leaf_proof() {
let expected = LeavesProof {
block_hash: H256::repeat_byte(0),
leaves: Bytes(vec![vec![1_u8, 2, 3, 4]].encode()),
proof: Bytes(
LeafProof {
leaf_indices: vec![1],
leaf_count: 9,
items: vec![H256::repeat_byte(1), H256::repeat_byte(2)],
}
.encode(),
),
};
let actual: LeavesProof<H256> = serde_json::from_str(r#"{
"blockHash":"0x0000000000000000000000000000000000000000000000000000000000000000",
"leaves":"0x041001020304",
"proof":"0x04010000000000000009000000000000000801010101010101010101010101010101010101010101010101010101010101010202020202020202020202020202020202020202020202020202020202020202"
}"#).unwrap();
assert_eq!(actual, expected);
}
#[test]
fn should_deserialize_leaves_proof() {
let expected = LeavesProof {
block_hash: H256::repeat_byte(0),
leaves: Bytes(vec![vec![1_u8, 2, 3, 4], vec![2_u8, 2, 3, 4]].encode()),
proof: Bytes(
LeafProof {
leaf_indices: vec![1, 2],
leaf_count: 9,
items: vec![H256::repeat_byte(1), H256::repeat_byte(2)],
}
.encode(),
),
};
let actual: LeavesProof<H256> = serde_json::from_str(r#"{
"blockHash":"0x0000000000000000000000000000000000000000000000000000000000000000",
"leaves":"0x0810010203041002020304",
"proof":"0x080100000000000000020000000000000009000000000000000801010101010101010101010101010101010101010101010101010101010101010202020202020202020202020202020202020202020202020202020202020202"
}"#).unwrap();
assert_eq!(actual, expected);
}
}