-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy patheip1186.rs
311 lines (296 loc) · 9.37 KB
/
eip1186.rs
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
use crate::rstd::{result::Result, vec::Vec};
use hash_db::{HashDBRef, Hasher};
use trie_db::{
node::{decode_hash, Node, NodeHandle, Value},
recorder::Recorder,
CError, DBValue, NibbleSlice, NodeCodec, Result as TrieResult, Trie, TrieDBBuilder, TrieHash,
TrieLayout,
};
/// Generate an eip-1186 compatible proof for key-value pairs in a trie given a key.
pub fn generate_proof<L>(
db: &dyn HashDBRef<L::Hash, DBValue>,
root: &TrieHash<L>,
key: &[u8],
) -> TrieResult<(Vec<Vec<u8>>, Option<Vec<u8>>), TrieHash<L>, CError<L>>
where
L: TrieLayout,
{
let mut recorder = Recorder::<L>::new();
let item = {
let trie = TrieDBBuilder::<L>::new(db, root).with_recorder(&mut recorder).build();
trie.get(key)?
};
let proof: Vec<Vec<u8>> = recorder.drain().into_iter().map(|r| r.data).collect();
Ok((proof, item))
}
/// Errors that may occur during proof verification. Most of the errors types simply indicate that
/// the proof is invalid with respect to the statement being verified, and the exact error type can
/// be used for debugging.
#[derive(PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Debug))]
pub enum VerifyError<'a, HO, CE> {
/// The proof does not contain any value for the given key
/// the error carries the nibbles left after traversing the trie
NonExistingValue(NibbleSlice<'a>),
/// The proof contains a value for the given key
/// while we were expecting to find a non-existence proof
ExistingValue(Vec<u8>),
/// The proof indicates that the trie contains a different value.
/// the error carries the value contained in the trie
ValueMismatch(Vec<u8>),
/// The proof is missing trie nodes required to verify.
IncompleteProof,
/// The node hash computed from the proof is not matching.
HashMismatch(HO),
/// One of the proof nodes could not be decoded.
DecodeError(CE),
/// Error in converting a plain hash into a HO
HashDecodeError(&'a [u8]),
}
#[cfg(feature = "std")]
impl<'a, HO: std::fmt::Debug, CE: std::error::Error> std::fmt::Display for VerifyError<'a, HO, CE> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
match self {
VerifyError::NonExistingValue(key) => {
write!(f, "Key does not exist in trie: reaming key={:?}", key)
},
VerifyError::ExistingValue(value) => {
write!(f, "trie contains a value for given key value={:?}", value)
},
VerifyError::ValueMismatch(key) => {
write!(f, "Expected value was not found in the trie: key={:?}", key)
},
VerifyError::IncompleteProof => write!(f, "Proof is incomplete -- expected more nodes"),
VerifyError::HashMismatch(hash) => write!(f, "hash mismatch found: hash={:?}", hash),
VerifyError::DecodeError(err) => write!(f, "Unable to decode proof node: {}", err),
VerifyError::HashDecodeError(plain_hash) => {
write!(f, "Unable to decode hash value plain_hash: {:?}", plain_hash)
},
}
}
}
#[cfg(feature = "std")]
impl<'a, HO: std::fmt::Debug, CE: std::error::Error + 'static> std::error::Error
for VerifyError<'a, HO, CE>
{
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
VerifyError::DecodeError(err) => Some(err),
_ => None,
}
}
}
/// Verify a compact proof for key-value pairs in a trie given a root hash.
pub fn verify_proof<'a, L>(
root: &<L::Hash as Hasher>::Out,
proof: &'a [Vec<u8>],
raw_key: &'a [u8],
expected_value: Option<&[u8]>,
) -> Result<(), VerifyError<'a, TrieHash<L>, CError<L>>>
where
L: TrieLayout,
{
if proof.is_empty() {
return Err(VerifyError::IncompleteProof)
}
let key = NibbleSlice::new(raw_key);
process_node::<L>(Some(root), &proof[0], key, expected_value, &proof[1..])
}
fn process_node<'a, L>(
expected_node_hash: Option<&<L::Hash as Hasher>::Out>,
encoded_node: &'a [u8],
key: NibbleSlice<'a>,
expected_value: Option<&[u8]>,
proof: &'a [Vec<u8>],
) -> Result<(), VerifyError<'a, TrieHash<L>, CError<L>>>
where
L: TrieLayout,
{
if let Some(value) = expected_value {
if encoded_node == value {
return Ok(())
}
}
if let Some(expected) = expected_node_hash {
let calculated_node_hash = <L::Hash as Hasher>::hash(encoded_node);
if calculated_node_hash != *expected {
return Err(VerifyError::HashMismatch(calculated_node_hash))
}
}
let node = <L::Codec as NodeCodec>::decode(encoded_node).map_err(VerifyError::DecodeError)?;
match node {
Node::Empty => process_empty::<L>(key, expected_value, proof),
Node::Leaf(nib, data) => process_leaf::<L>(nib, data, key, expected_value, proof),
Node::Extension(nib, handle) =>
process_extension::<L>(&nib, handle, key, expected_value, proof),
Node::Branch(children, maybe_data) =>
process_branch::<L>(children, maybe_data, key, expected_value, proof),
Node::NibbledBranch(nib, children, maybe_data) =>
process_nibbledbranch::<L>(nib, children, maybe_data, key, expected_value, proof),
}
}
fn process_empty<'a, L>(
key: NibbleSlice<'a>,
expected_value: Option<&[u8]>,
_: &[Vec<u8>],
) -> Result<(), VerifyError<'a, TrieHash<L>, CError<L>>>
where
L: TrieLayout,
{
if expected_value.is_none() {
Ok(())
} else {
Err(VerifyError::NonExistingValue(key))
}
}
fn process_leaf<'a, L>(
nib: NibbleSlice,
data: Value<'a>,
key: NibbleSlice<'a>,
expected_value: Option<&[u8]>,
proof: &'a [Vec<u8>],
) -> Result<(), VerifyError<'a, TrieHash<L>, CError<L>>>
where
L: TrieLayout,
{
if key != nib && expected_value.is_none() {
return Ok(())
} else if key != nib {
return Err(VerifyError::NonExistingValue(key))
}
match_value::<L>(Some(data), key, expected_value, proof)
}
fn process_extension<'a, L>(
nib: &NibbleSlice,
handle: NodeHandle<'a>,
mut key: NibbleSlice<'a>,
expected_value: Option<&[u8]>,
proof: &'a [Vec<u8>],
) -> Result<(), VerifyError<'a, TrieHash<L>, CError<L>>>
where
L: TrieLayout,
{
if !key.starts_with(nib) && expected_value.is_none() {
return Ok(())
} else if !key.starts_with(nib) {
return Err(VerifyError::NonExistingValue(key))
}
key.advance(nib.len());
match handle {
NodeHandle::Inline(encoded_node) =>
process_node::<L>(None, encoded_node, key, expected_value, proof),
NodeHandle::Hash(plain_hash) => {
let new_root = decode_hash::<L::Hash>(plain_hash)
.ok_or(VerifyError::HashDecodeError(plain_hash))?;
process_node::<L>(Some(&new_root), &proof[0], key, expected_value, &proof[1..])
},
}
}
fn process_nibbledbranch<'a, L>(
nib: NibbleSlice,
children: [Option<NodeHandle<'a>>; 16],
maybe_data: Option<Value<'a>>,
mut key: NibbleSlice<'a>,
expected_value: Option<&[u8]>,
proof: &'a [Vec<u8>],
) -> Result<(), VerifyError<'a, TrieHash<L>, CError<L>>>
where
L: TrieLayout,
{
if !key.starts_with(&nib) && expected_value.is_none() {
return Ok(())
} else if !key.starts_with(&nib) && expected_value.is_some() {
return Err(VerifyError::NonExistingValue(key))
}
key.advance(nib.len());
if key.is_empty() {
match_value::<L>(maybe_data, key, expected_value, proof)
} else {
match_children::<L>(children, key, expected_value, proof)
}
}
fn process_branch<'a, L>(
children: [Option<NodeHandle<'a>>; 16],
maybe_data: Option<Value<'a>>,
key: NibbleSlice<'a>,
expected_value: Option<&[u8]>,
proof: &'a [Vec<u8>],
) -> Result<(), VerifyError<'a, TrieHash<L>, CError<L>>>
where
L: TrieLayout,
{
if key.is_empty() {
match_value::<L>(maybe_data, key, expected_value, proof)
} else {
match_children::<L>(children, key, expected_value, proof)
}
}
fn match_children<'a, L>(
children: [Option<NodeHandle<'a>>; 16],
mut key: NibbleSlice<'a>,
expected_value: Option<&[u8]>,
proof: &'a [Vec<u8>],
) -> Result<(), VerifyError<'a, TrieHash<L>, CError<L>>>
where
L: TrieLayout,
{
match children.get(key.at(0) as usize) {
Some(Some(NodeHandle::Hash(hash))) =>
if proof.is_empty() {
Err(VerifyError::IncompleteProof)
} else {
key.advance(1);
let new_root =
decode_hash::<L::Hash>(hash).ok_or(VerifyError::HashDecodeError(hash))?;
process_node::<L>(Some(&new_root), &proof[0], key, expected_value, &proof[1..])
},
Some(Some(NodeHandle::Inline(encoded_node))) => {
key.advance(1);
process_node::<L>(None, encoded_node, key, expected_value, proof)
},
Some(None) =>
if expected_value.is_none() {
Ok(())
} else {
Err(VerifyError::NonExistingValue(key))
},
None => panic!("key index is out of range in children array"),
}
}
fn match_value<'a, L>(
maybe_data: Option<Value<'a>>,
key: NibbleSlice<'a>,
expected_value: Option<&[u8]>,
proof: &'a [Vec<u8>],
) -> Result<(), VerifyError<'a, TrieHash<L>, CError<L>>>
where
L: TrieLayout,
{
match (maybe_data, proof.first(), expected_value) {
(None, _, None) => Ok(()),
(None, _, Some(_)) => Err(VerifyError::NonExistingValue(key)),
(Some(Value::Inline(inline_data)), _, Some(value)) =>
if inline_data == value {
Ok(())
} else {
Err(VerifyError::ValueMismatch(inline_data.to_vec()))
},
(Some(Value::Inline(inline_data)), _, None) =>
Err(VerifyError::ExistingValue(inline_data.to_vec())),
(Some(Value::Node(plain_hash)), Some(next_proof_item), Some(value)) => {
let value_hash = L::Hash::hash(value);
let node_hash = decode_hash::<L::Hash>(plain_hash)
.ok_or(VerifyError::HashDecodeError(plain_hash))?;
if node_hash != value_hash {
Err(VerifyError::HashMismatch(node_hash))
} else if next_proof_item != value {
Err(VerifyError::ValueMismatch(next_proof_item.to_vec()))
} else {
Ok(())
}
},
(Some(Value::Node(_)), None, _) => Err(VerifyError::IncompleteProof),
(Some(Value::Node(_)), Some(proof_item), None) =>
Err(VerifyError::ExistingValue(proof_item.to_vec())),
}
}