1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
#![warn(missing_docs)]
use std::sync::Arc;
use codec::{Codec, Encode};
use jsonrpc_core::{Error, ErrorCode, Result};
use jsonrpc_derive::rpc;
use serde::{Deserialize, Serialize};
use pallet_mmr_primitives::{Error as MmrError, Proof};
use sp_api::ProvideRuntimeApi;
use sp_blockchain::HeaderBackend;
use sp_core::Bytes;
use sp_runtime::{generic::BlockId, traits::Block as BlockT};
pub use pallet_mmr_primitives::MmrApi as MmrRuntimeApi;
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct LeafProof<BlockHash> {
pub block_hash: BlockHash,
pub leaf: Bytes,
pub proof: Bytes,
}
impl<BlockHash> LeafProof<BlockHash> {
pub fn new<Leaf, MmrHash>(block_hash: BlockHash, leaf: Leaf, proof: Proof<MmrHash>) -> Self
where
Leaf: Encode,
MmrHash: Encode,
{
Self { block_hash, leaf: Bytes(leaf.encode()), proof: Bytes(proof.encode()) }
}
}
#[rpc]
pub trait MmrApi<BlockHash> {
#[rpc(name = "mmr_generateProof")]
fn generate_proof(
&self,
leaf_index: u64,
at: Option<BlockHash>,
) -> Result<LeafProof<BlockHash>>;
}
pub struct Mmr<C, B> {
client: Arc<C>,
_marker: std::marker::PhantomData<B>,
}
impl<C, B> Mmr<C, B> {
pub fn new(client: Arc<C>) -> Self {
Self { client, _marker: Default::default() }
}
}
impl<C, Block, MmrHash> MmrApi<<Block as BlockT>::Hash> for Mmr<C, (Block, MmrHash)>
where
Block: BlockT,
C: Send + Sync + 'static + ProvideRuntimeApi<Block> + HeaderBackend<Block>,
C::Api: MmrRuntimeApi<Block, MmrHash>,
MmrHash: Codec + Send + Sync + 'static,
{
fn generate_proof(
&self,
leaf_index: u64,
at: Option<<Block as BlockT>::Hash>,
) -> Result<LeafProof<<Block as BlockT>::Hash>> {
let api = self.client.runtime_api();
let block_hash = at.unwrap_or_else(||
self.client.info().best_hash);
let (leaf, proof) = api
.generate_proof_with_context(
&BlockId::hash(block_hash),
sp_core::ExecutionContext::OffchainCall(None),
leaf_index,
)
.map_err(runtime_error_into_rpc_error)?
.map_err(mmr_error_into_rpc_error)?;
Ok(LeafProof::new(block_hash, leaf, proof))
}
}
const RUNTIME_ERROR: i64 = 8000;
const MMR_ERROR: i64 = 8010;
fn mmr_error_into_rpc_error(err: MmrError) -> Error {
match err {
MmrError::LeafNotFound => Error {
code: ErrorCode::ServerError(MMR_ERROR + 1),
message: "Leaf was not found".into(),
data: Some(format!("{:?}", err).into()),
},
MmrError::GenerateProof => Error {
code: ErrorCode::ServerError(MMR_ERROR + 2),
message: "Error while generating the proof".into(),
data: Some(format!("{:?}", err).into()),
},
_ => Error {
code: ErrorCode::ServerError(MMR_ERROR),
message: "Unexpected MMR error".into(),
data: Some(format!("{:?}", err).into()),
},
}
}
fn runtime_error_into_rpc_error(err: impl std::fmt::Debug) -> Error {
Error {
code: ErrorCode::ServerError(RUNTIME_ERROR),
message: "Runtime trapped".into(),
data: Some(format!("{:?}", err).into()),
}
}
#[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 = Proof {
leaf_index: 1,
leaf_count: 9,
items: vec![H256::repeat_byte(1), H256::repeat_byte(2)],
};
let leaf_proof = LeafProof::new(H256::repeat_byte(0), leaf, proof);
let actual = serde_json::to_string(&leaf_proof).unwrap();
assert_eq!(
actual,
r#"{"blockHash":"0x0000000000000000000000000000000000000000000000000000000000000000","leaf":"0x1001020304","proof":"0x010000000000000009000000000000000801010101010101010101010101010101010101010101010101010101010101010202020202020202020202020202020202020202020202020202020202020202"}"#
);
}
#[test]
fn should_deserialize_leaf_proof() {
let expected = LeafProof {
block_hash: H256::repeat_byte(0),
leaf: Bytes(vec![1_u8, 2, 3, 4].encode()),
proof: Bytes(
Proof {
leaf_index: 1,
leaf_count: 9,
items: vec![H256::repeat_byte(1), H256::repeat_byte(2)],
}
.encode(),
),
};
let actual: LeafProof<H256> = serde_json::from_str(r#"{
"blockHash":"0x0000000000000000000000000000000000000000000000000000000000000000",
"leaf":"0x1001020304",
"proof":"0x010000000000000009000000000000000801010101010101010101010101010101010101010101010101010101010101010202020202020202020202020202020202020202020202020202020202020202"
}"#).unwrap();
assert_eq!(actual, expected);
}
}