-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmerkle_patricia_trie.rs
2013 lines (1827 loc) · 76.4 KB
/
merkle_patricia_trie.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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
extern crate rlp;
extern crate sha3;
use self::rlp::RlpStream;
use self::sha3::{Digest, Sha3_256};
use crate::db::HashValueDb;
use crate::errors::{MerkleTreeError, MerkleTreeErrorKind};
use crate::hasher::Arity2Hasher;
use std::marker::PhantomData;
use std::cmp::min;
// IMPLEMENTATION AS USED BY ETHEREUM. https://github.com/ethereum/wiki/wiki/Patricia-Tree
// Code borrowed from ethereum implementation and this repo https://github.com/lovesh/Merkle-Patricia-Trie
pub trait Key {
fn to_nibbles(&self) -> Vec<u8>;
}
impl Key for Vec<u8> {
fn to_nibbles(&self) -> Vec<u8> {
bytes_to_nibbles(self)
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum NodeType<H, V> {
Empty,
Leaf(Leaf<V>),
Extension(Extension<H, V>),
Branch(Branch<H, V>),
}
impl<H, V> NodeType<H, V> {
fn is_empty(&self) -> bool {
match self {
NodeType::Empty => true,
_ => false,
}
}
fn is_leaf(&self) -> bool {
match self {
NodeType::Leaf(_) => true,
_ => false,
}
}
fn is_extension(&self) -> bool {
match self {
NodeType::Extension(_) => true,
_ => false,
}
}
fn is_branch(&self) -> bool {
match self {
NodeType::Branch(_) => true,
_ => false,
}
}
}
impl<H, V> Default for NodeType<H, V> {
fn default() -> Self {
NodeType::Empty
}
}
pub enum KeyValueNodeType<H, V> {
Leaf(Leaf<V>),
Extension(Extension<H, V>),
}
/// Either a hash (which would be a hash of a serialized branch node) or a branch node
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum HashOrBranch<H, V> {
/// hash of a serialized branch node
Hash(H),
Branch(Branch<H, V>),
}
/// Either hash of a serialized node or a node
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum HashOrNode<H, V> {
Hash(H),
Node(NodeType<H, V>),
}
impl<H, V> Default for HashOrNode<H, V> {
fn default() -> Self {
HashOrNode::Node(NodeType::Empty)
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Leaf<V> {
/// path in nibbles, does not contain nibbles for flag
path: Vec<u8>,
value: V,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Extension<H, V> {
/// path in nibbles, does not contain nibbles for flag
path: Vec<u8>,
key: HashOrBranch<H, V>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Branch<H, V> {
path: [Box<HashOrNode<H, V>>; 16],
value: V,
}
impl<V> Leaf<V> {
pub fn new(path: Vec<u8>, value: V) -> Self {
Leaf { path, value }
}
pub fn has_path(&self, path: &[u8]) -> bool {
self.path == path
}
}
fn nibbles_to_bytes(nibbles: &[u8]) -> Vec<u8> {
assert_eq!(nibbles.len() % 2, 0);
(0..nibbles.len())
.step_by(2)
.map(|i| (nibbles[i] << 4) + nibbles[i + 1])
.collect::<Vec<u8>>()
}
fn bytes_to_nibbles(bytes: &[u8]) -> Vec<u8> {
// XXX: Each iteration results in creation of a heap allocation (Vector). A simple for loop
// might be a better choice
bytes
.into_iter()
.flat_map(|b| vec![b >> 4, b & 15])
.collect::<Vec<u8>>()
}
pub trait KnownLength {
fn len(&self) -> usize;
}
impl KnownLength for Vec<u8> {
fn len(&self) -> usize {
self.len()
}
}
/// Serialize node for creating hash or storing in database
pub trait PatriciaTrieNodeSerializer<H, V, S: KnownLength> {
fn is_empty_root(&self, root: &H) -> bool;
fn serialize(&self, node: NodeType<H, V>) -> Result<S, MerkleTreeError>;
fn deserialize(&self, serz: S) -> Result<NodeType<H, V>, MerkleTreeError>;
/// For leaf and extension nodes. The return type causes heap allocation but avoiding
/// it (like an array with negative number when there is only one flag) pushes the logic
/// of handling 1 or 2 nibbles to serializer.
fn get_flagged_prefix_for_leaf(path_in_nibbles: &[u8]) -> Vec<u8> {
if path_in_nibbles.len() % 2 == 1 {
// path is odd, add only 1 nibble
vec![3]
} else {
// path is even, add 2 nibbles
vec![2, 0]
}
}
fn get_flagged_prefix_for_extension(path_in_nibbles: &[u8]) -> Vec<u8> {
if path_in_nibbles.len() % 2 == 1 {
// path is odd, add only 1 nibble
vec![1]
} else {
// path is even, add 2 nibbles
vec![0, 0]
}
}
/// Takes a path in bytes and retuns the path in nibbles after removing flag nibble(s).
/// Also returns true or false depending on the path being of an extension or not.
fn is_extension_path(path: &[u8]) -> Result<(bool, Vec<u8>), MerkleTreeError> {
let mut nibbles = bytes_to_nibbles(path);
if nibbles.is_empty() {
return Ok((false, vec![]));
}
if nibbles[0] > 3 {
return Err(MerkleTreeError::from_kind(
MerkleTreeErrorKind::IncorrectFlagForRLPNode { flag: nibbles[0] },
));
}
if nibbles[0] < 2 {
// nibbles[0] is 0 or 1, so must be extension
if nibbles[0] == 0 {
nibbles.remove(0);
}
nibbles.remove(0);
Ok((true, nibbles))
} else {
// nibbles[0] is 2 or 3, so must be leaf
if nibbles[0] == 2 {
nibbles.remove(0);
}
nibbles.remove(0);
Ok((false, nibbles))
}
}
}
#[derive(Clone)]
pub struct RLPSerializer {}
impl RLPSerializer {
/// Serialize a node in RLP format
fn bytes_for_node(node: NodeType<Vec<u8>, Vec<u8>>, rlp_stream: &mut RlpStream) {
match node {
NodeType::Empty => {
rlp_stream.append_empty_data();
}
NodeType::Leaf(n) => {
// A leaf has a flag that is prefixed to the leaf path before serialization
let mut prefixed = Self::get_flagged_prefix_for_leaf(&n.path);
prefixed.extend_from_slice(&n.path);
let path = nibbles_to_bytes(&prefixed);
// A leaf is serialized as a list of 2 items
rlp_stream.append_list::<Vec<u8>, Vec<u8>>(&[path, n.value]);
}
NodeType::Extension(n) => {
// An extension has a flag that is prefixed to the extension path before serialization
let mut prefixed = Self::get_flagged_prefix_for_extension(&n.path);
prefixed.extend_from_slice(&n.path);
let path = nibbles_to_bytes(&prefixed);
// A extension is serialized as a list of 2 items
match n.key {
HashOrBranch::Hash(h) => {
rlp_stream.append_list::<Vec<u8>, Vec<u8>>(&[path, h]);
}
HashOrBranch::Branch(b) => {
// The second item in the extension node is a branch which itself will be a list
rlp_stream.begin_unbounded_list();
rlp_stream.append(&path);
Self::bytes_for_node(NodeType::Branch(b), rlp_stream);
rlp_stream.finalize_unbounded_list();
}
}
}
NodeType::Branch(n) => {
// The branch is serialized as a list
rlp_stream.begin_unbounded_list();
for p in n.path.to_vec() {
match *p {
HashOrNode::Hash(h) => {
rlp_stream.append(&h);
}
HashOrNode::Node(i_n) => Self::bytes_for_node(i_n, rlp_stream),
}
}
rlp_stream.append(&n.value);
rlp_stream.finalize_unbounded_list();
}
}
}
fn node_from_bytes(rlp_serz: rlp::Rlp) -> Result<NodeType<Vec<u8>, Vec<u8>>, MerkleTreeError> {
if rlp_serz.is_empty() {
Ok(NodeType::<Vec<u8>, Vec<u8>>::Empty)
} else if rlp_serz.is_list() {
let s = rlp_serz.item_count().unwrap();
if s == 17 {
// a branch
let branch = Self::parse_branch_node(&rlp_serz)?;
Ok(NodeType::<Vec<u8>, Vec<u8>>::Branch(branch))
} else if s == 2 {
// extension or leaf
let kv_node = Self::parse_key_value_node(&rlp_serz)?;
match kv_node {
KeyValueNodeType::Leaf(n) => Ok(NodeType::Leaf(n)),
KeyValueNodeType::Extension(n) => Ok(NodeType::Extension(n)),
}
} else {
let msg = String::from("RLP list length should be of length 2 or 17");
Err(MerkleTreeError::from_kind(
MerkleTreeErrorKind::CannotDeserializeWithRLP { msg },
))
}
} else {
let msg = String::from("RLP not a list nor data");
Err(MerkleTreeError::from_kind(
MerkleTreeErrorKind::CannotDeserializeWithRLP { msg },
))
}
}
fn new_branch() -> Branch<Vec<u8>, Vec<u8>> {
let path: [Box<HashOrNode<Vec<u8>, Vec<u8>>>; 16] = Default::default();
Branch {
path,
value: vec![],
}
}
/// Parse a given RLP slice as a branch
fn parse_branch_node(rlp_serz: &rlp::Rlp) -> Result<Branch<Vec<u8>, Vec<u8>>, MerkleTreeError> {
let mut branch = Self::new_branch();
for i in 0..16 {
let item = rlp_serz.at(i).unwrap();
if item.is_empty() {
// branch has empty node at index `i`
branch.path[i] = Box::new(HashOrNode::Node(NodeType::<Vec<u8>, Vec<u8>>::Empty));
} else if item.is_data() {
// branch has a hash at index `i`
let hash: Vec<u8> = item.as_val().unwrap();
branch.path[i] = Box::new(HashOrNode::Hash(hash));
} else if item.is_list() {
let s = item.item_count().unwrap();
if s == 2 {
// branch has a either a leaf or an extension node at index `i`
let kv_node = Self::parse_key_value_node(&item)?;
match kv_node {
KeyValueNodeType::Leaf(n) => {
branch.path[i] =
Box::new(HashOrNode::Node(NodeType::<Vec<u8>, Vec<u8>>::Leaf(n)));
}
KeyValueNodeType::Extension(n) => {
branch.path[i] = Box::new(HashOrNode::Node(
NodeType::<Vec<u8>, Vec<u8>>::Extension(n),
));
}
}
} else if s == 17 {
// branch has another branch node at index `i`
let inner_branch = Self::parse_branch_node(&item)?;
branch.path[i] = Box::new(HashOrNode::Node(
NodeType::<Vec<u8>, Vec<u8>>::Branch(inner_branch),
));
} else {
let msg = String::from("list inside branch is not of length 2 or 17");
return Err(MerkleTreeError::from_kind(
MerkleTreeErrorKind::CannotDeserializeWithRLP { msg },
));
}
} else {
let msg = String::from("branch's item neither empty, neither data, nor list");
return Err(MerkleTreeError::from_kind(
MerkleTreeErrorKind::CannotDeserializeWithRLP { msg },
));
}
}
let val = rlp_serz.at(16).unwrap();
if val.is_data() {
branch.value = val.as_val().unwrap();
} else if val.is_empty() {
branch.value = vec![];
} else {
let msg = String::from("branch's value neither empty nor data");
return Err(MerkleTreeError::from_kind(
MerkleTreeErrorKind::CannotDeserializeWithRLP { msg },
));
}
Ok(branch)
}
/// Parse a given RLP slice as a key value or an extension node.
fn parse_key_value_node(
rlp_serz: &rlp::Rlp,
) -> Result<KeyValueNodeType<Vec<u8>, Vec<u8>>, MerkleTreeError> {
let item_1 = rlp_serz.at(0).unwrap();
if !item_1.is_data() {
let msg = String::from("first item of key-value RLP is not data");
return Err(MerkleTreeError::from_kind(
MerkleTreeErrorKind::CannotDeserializeWithRLP { msg },
));
}
let item_1: Vec<u8> = item_1.as_val().unwrap();
let (is_extension, path) = Self::is_extension_path(&item_1)?;
if !is_extension {
// Its a leaf node
let item_2 = rlp_serz.at(1).unwrap();
if !item_2.is_data() {
let msg = String::from("second item of leaf is not data");
Err(MerkleTreeError::from_kind(
MerkleTreeErrorKind::CannotDeserializeWithRLP { msg },
))
} else {
let value: Vec<u8> = item_2.as_val().unwrap();
Ok(KeyValueNodeType::<Vec<u8>, Vec<u8>>::Leaf(Leaf {
path,
value,
}))
}
} else {
// Its an extension node, check whether 2nd item is a hash or a branch
let item_2 = rlp_serz.at(1).unwrap();
if item_2.is_data() {
// TODO: Check valid hash length
let key: Vec<u8> = item_2.as_val().unwrap();
Ok(KeyValueNodeType::<Vec<u8>, Vec<u8>>::Extension(Extension {
path,
key: HashOrBranch::Hash(key),
}))
} else if item_2.is_list() {
let s = item_2.item_count().unwrap();
if s == 17 {
let branch = Self::parse_branch_node(&item_2)?;
Ok(KeyValueNodeType::Extension(Extension {
path,
key: HashOrBranch::Branch(branch),
}))
} else {
let msg = String::from("extension's list should be a branch");
Err(MerkleTreeError::from_kind(
MerkleTreeErrorKind::CannotDeserializeWithRLP { msg },
))
}
} else {
let msg = String::from("Extension 2nd items neither data nor list");
Err(MerkleTreeError::from_kind(
MerkleTreeErrorKind::CannotDeserializeWithRLP { msg },
))
}
}
}
}
/// For `RLPSerializer`, `self` is not used for serialization or deserialization but some serializers
/// might have some configuration that needs to be used while (de)serializing which can be accessed
/// with `self`
impl PatriciaTrieNodeSerializer<Vec<u8>, Vec<u8>, Vec<u8>> for RLPSerializer {
fn is_empty_root(&self, root: &Vec<u8>) -> bool {
rlp::Rlp::new(&root).is_empty()
}
fn serialize(&self, node: NodeType<Vec<u8>, Vec<u8>>) -> Result<Vec<u8>, MerkleTreeError> {
let mut stream = RlpStream::new();
RLPSerializer::bytes_for_node(node, &mut stream);
Ok(stream.out())
}
fn deserialize(&self, serz: Vec<u8>) -> Result<NodeType<Vec<u8>, Vec<u8>>, MerkleTreeError> {
let r = rlp::Rlp::new(&serz);
RLPSerializer::node_from_bytes(r)
}
}
pub trait NodeHasher<I, H> {
fn output_size(&self) -> usize;
fn hash(&self, node: I) -> Result<H, MerkleTreeError>;
}
#[derive(Clone)]
pub struct Sha3Hasher {}
impl NodeHasher<Vec<u8>, Vec<u8>> for Sha3Hasher {
fn output_size(&self) -> usize {
32
}
fn hash(&self, node: Vec<u8>) -> Result<Vec<u8>, MerkleTreeError> {
let mut hasher = Sha3_256::new();
hasher.input(&node);
Ok(hasher.result().to_vec())
}
}
/// The type `V` is for the value of the data being stored in the trie.
/// The type `H` is for the hash output
/// The type `S` is for the serialized (node) output
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct MerklePatriciaTrie<V, H, S: Clone + KnownLength, NS, NH>
where
NS: PatriciaTrieNodeSerializer<H, V, S>,
NH: NodeHasher<S, H>,
{
pub root_node: NodeType<H, V>,
hasher: NH,
node_serializer: NS,
pub phantom_1: PhantomData<V>,
pub phantom_2: PhantomData<S>,
}
impl<V: Clone + Default + Eq, H: Clone, S: Clone + KnownLength, NS, NH>
MerklePatriciaTrie<V, H, S, NS, NH>
where
NS: PatriciaTrieNodeSerializer<H, V, S>,
NH: NodeHasher<S, H>,
{
/// Create a new empty trie
pub fn new(hasher: NH, node_serializer: NS) -> Result<Self, MerkleTreeError> {
Ok(Self {
root_node: NodeType::Empty,
hasher,
node_serializer,
phantom_1: PhantomData,
phantom_2: PhantomData,
})
}
/// Initialize a trie with a given root hash and database. The root hash must be
/// present in the database.
pub fn initialize_with_root_hash(
hasher: NH,
node_serializer: NS,
root_hash: &H,
hash_db: &mut dyn HashValueDb<H, S>,
) -> Result<Self, MerkleTreeError> {
let serz_node = hash_db.get(root_hash)?;
let root_node = node_serializer.deserialize(serz_node)?;
Ok(Self {
root_node,
hasher,
node_serializer,
phantom_1: PhantomData,
phantom_2: PhantomData,
})
}
pub fn get_root_hash(&self) -> Result<H, MerkleTreeError> {
self.hash_node(self.root_node.clone()).map(|t| t.0)
}
/// Get value of the given key. If `proof` is not None, it is populated with a proof.
pub fn get(
&self,
key: &dyn Key,
proof: &mut Option<Vec<NodeType<H, V>>>,
hash_db: &dyn HashValueDb<H, S>,
) -> Result<V, MerkleTreeError> {
self.get_from_tree_with_root(&self.root_node, key, proof, hash_db)
}
/// Get value of the given key in a tree with root `tree_root`. If `proof` is not None, it is populated with a proof.
pub fn get_from_tree_with_root(
&self,
tree_root: &NodeType<H, V>,
key: &dyn Key,
proof: &mut Option<Vec<NodeType<H, V>>>,
hash_db: &dyn HashValueDb<H, S>,
) -> Result<V, MerkleTreeError> {
let path = key.to_nibbles();
let need_proof = proof.is_some();
let mut proof_nodes = Vec::<NodeType<H, V>>::new();
let val = self.get_from_subtree(tree_root, path, (need_proof, &mut proof_nodes), hash_db);
if need_proof {
match proof {
Some(v) => {
v.push(tree_root.clone());
v.append(&mut proof_nodes);
}
None => (),
}
}
val
}
/// Insert a key-value into the trie.
pub fn insert(
&mut self,
key: &dyn Key,
value: V,
hash_db: &mut dyn HashValueDb<H, S>,
) -> Result<H, MerkleTreeError> {
let path = key.to_nibbles();
let old_root_node = self.root_node.clone();
// XXX: Maybe i should pass old_root_node and not its reference
let new_root_node = self.insert_into_subtree(&old_root_node, path, value, hash_db)?;
let new_root_hash = self.store_root_node_in_db(new_root_node.clone(), hash_db)?;
self.root_node = new_root_node;
Ok(new_root_hash)
}
/// Verify that a tree with root hash `root_hash` has a key `key` with value `value`
pub fn verify_proof(
key: &dyn Key,
value: &V,
proof: Vec<NodeType<H, V>>,
hasher: NH,
node_serializer: NS,
root_hash: &H,
hash_db: &mut dyn HashValueDb<H, S>,
) -> Result<bool, MerkleTreeError> {
let new_trie = Self::initialize_with_given_nodes_and_root_hash(
hasher,
node_serializer,
root_hash,
proof,
hash_db,
)?;
match new_trie.get(key, &mut None, hash_db) {
Ok(v) => Ok(v == *value),
Err(_) => Ok(false),
}
}
/// Get all key-value pairs in a tree with root `root_node`. If `proof` is not None, it is populated
/// with a proof. The argument `nibbles_to_key` is a function to convert nibbles to keys.
/// Don't want to require `Key` trait to have a nibble_to_key function as this function might not be
/// needed by all implementations.
pub fn get_key_values<K>(
&self,
root_node: &NodeType<H, V>,
proof: &mut Option<Vec<NodeType<H, V>>>,
hash_db: &dyn HashValueDb<H, S>,
nibbles_to_key: &dyn Fn(&[u8]) -> K, // TODO: nibbles_to_key can return an error, return type should be a result
) -> Result<Vec<(K, V)>, MerkleTreeError> {
// TODO: Return value should be a iterator as the tree can contain lots of keys
let need_proof = proof.is_some();
let mut proof_nodes = Vec::<NodeType<H, V>>::new();
let nv =
self.get_key_nibbles_and_values(root_node, (need_proof, &mut proof_nodes), hash_db)?;
if need_proof {
match proof {
Some(v) => {
v.push(root_node.clone());
v.append(&mut proof_nodes);
}
None => (),
}
}
// Since the keys are in nibbles, convert them to a key using the passed function
Ok(nv
.into_iter()
.map(|(n, v)| (nibbles_to_key(&n), v))
.collect::<Vec<(K, V)>>())
}
/// Get all key-value pairs in a tree with root `root_node` and prefix `prefix_key`. If `proof` is
/// not None, it is populated with a proof.
pub fn get_keys_values_with_prefix<K>(
&self,
prefix_key: &dyn Key,
node: &NodeType<H, V>,
proof: &mut Option<Vec<NodeType<H, V>>>,
hash_db: &dyn HashValueDb<H, S>,
nibbles_to_key: &dyn Fn(&[u8]) -> K, // TODO: nibbles_to_key can return an error, return type should be a result
) -> Result<Vec<(K, V)>, MerkleTreeError> {
// TODO: Return value should be a iterator
let path = prefix_key.to_nibbles();
let need_proof = proof.is_some();
let mut proof_nodes = Vec::<NodeType<H, V>>::new();
// Nibbles of the prefix before the prefix_node
let mut seen_prefix_nibbles = vec![];
// Find the node where the prefix ends
let prefix_node = self.get_last_node_for_prefix_key(
node,
path,
&mut seen_prefix_nibbles,
(need_proof, &mut proof_nodes),
hash_db,
)?;
// Get all key-value pairs from the tree rooted at the prefix_node
let nv =
self.get_key_nibbles_and_values(&prefix_node, (need_proof, &mut proof_nodes), hash_db)?;
if need_proof {
match proof {
Some(v) => {
v.push(node.clone());
v.push(prefix_node.clone());
v.append(&mut proof_nodes);
}
None => (),
}
}
// Since the keys are in nibbles, convert them to a key using the passed function after
// adding the prefix
Ok(nv
.into_iter()
.map(|(mut n, v)| {
let mut key = seen_prefix_nibbles.clone();
key.append(&mut n);
(nibbles_to_key(&key), v)
})
.collect::<Vec<(K, V)>>())
}
pub fn verify_proof_multiple_keys(
keys: Vec<&dyn Key>,
values: &[V],
proof: Vec<NodeType<H, V>>,
hasher: NH,
node_serializer: NS,
root_hash: &H,
hash_db: &mut dyn HashValueDb<H, S>,
) -> Result<bool, MerkleTreeError> {
if keys.len() != values.len() {
return Err(MerkleTreeError::from_kind(
MerkleTreeErrorKind::UnequalNoOfKeysAndValues {
num_keys: keys.len(),
num_values: values.len(),
},
));
}
let new_trie = Self::initialize_with_given_nodes_and_root_hash(
hasher,
node_serializer,
root_hash,
proof,
hash_db,
)?;
for i in 0..keys.len() {
let key = keys[i];
let value = &values[i];
match new_trie.get(key, &mut None, hash_db) {
Ok(v) => {
if v != *value {
return Ok(false);
}
}
Err(_) => return Ok(false),
}
}
Ok(true)
}
/// Get the node from which all keys having the prefix `prefix_nibbles` diverge. This node can then
/// be used to traverse all keys with the prefix.
fn get_last_node_for_prefix_key(
&self,
node_to_start_from: &NodeType<H, V>,
mut prefix_nibbles: Vec<u8>,
seen_prefix_nibbles: &mut Vec<u8>,
(need_proof, proof_nodes): (bool, &mut Vec<NodeType<H, V>>),
hash_db: &dyn HashValueDb<H, S>,
) -> Result<NodeType<H, V>, MerkleTreeError> {
match node_to_start_from {
NodeType::Empty => Ok(NodeType::Empty),
NodeType::Leaf(leaf) => {
if leaf.path.starts_with(&prefix_nibbles) {
Ok(node_to_start_from.clone())
} else {
return Err(MerkleTreeError::from_kind(
MerkleTreeErrorKind::NoKeyWithPrefixInTrie,
));
}
}
NodeType::Extension(ext) => {
if prefix_nibbles.is_empty() {
return Err(MerkleTreeError::from_kind(
MerkleTreeErrorKind::NoKeyWithPrefixInTrie,
));
}
if ext.path.starts_with(&prefix_nibbles) {
Ok(node_to_start_from.clone())
} else if prefix_nibbles.starts_with(&ext.path) {
seen_prefix_nibbles.extend_from_slice(&ext.path);
match &ext.key {
HashOrBranch::Hash(h) => {
let inner_node = self.get_node_from_db(h, hash_db)?;
if need_proof {
proof_nodes.push(inner_node.clone());
}
self.get_last_node_for_prefix_key(
&inner_node,
prefix_nibbles[ext.path.len()..].to_vec(),
seen_prefix_nibbles,
(need_proof, proof_nodes),
hash_db,
)
}
HashOrBranch::Branch(branch) => self.get_last_node_for_prefix_key(
&NodeType::Branch(branch.clone()),
prefix_nibbles[ext.path.len()..].to_vec(),
seen_prefix_nibbles,
(need_proof, proof_nodes),
hash_db,
),
}
} else {
return Err(MerkleTreeError::from_kind(
MerkleTreeErrorKind::NoKeyWithPrefixInTrie,
));
}
}
NodeType::Branch(branch) => {
if prefix_nibbles.is_empty() {
Ok(node_to_start_from.clone())
} else {
let node_index = prefix_nibbles.remove(0);
let node = self.get_node_from_branch(node_index as usize, branch, hash_db)?;
seen_prefix_nibbles.push(node_index);
if need_proof {
proof_nodes.push(node.clone());
}
self.get_last_node_for_prefix_key(
&node,
prefix_nibbles,
seen_prefix_nibbles,
(need_proof, proof_nodes),
hash_db,
)
}
}
}
}
/// Insert a value in the subtree at root `subtree_root` at the path `path`
fn insert_into_subtree(
&self,
subtree_root: &NodeType<H, V>,
mut path: Vec<u8>,
value: V,
hash_db: &mut dyn HashValueDb<H, S>,
) -> Result<NodeType<H, V>, MerkleTreeError> {
match subtree_root {
NodeType::Empty => {
let leaf_node = NodeType::Leaf(Leaf::new(path, value));
Ok(leaf_node)
}
NodeType::Leaf(leaf_node) => {
if leaf_node.has_path(&path) {
// Updating value of an existing leaf
let leaf_node = NodeType::Leaf(Leaf::new(path, value));
Ok(leaf_node)
} else {
// Creating a node, will result in creation of more than one new node.
let cur_path = &leaf_node.path;
let common_prefix = Self::get_common_prefix_in_paths(cur_path, &path);
if common_prefix.len() == 0 {
// paths for both nodes (new and existing) have no common prefix, create a branch node with 2 leaf nodes
let branch_path: [Box<HashOrNode<H, V>>; 16] = Default::default();
let mut branch = Branch {
path: branch_path,
value: V::default(),
};
self.store_leaf_in_branch(
&mut branch,
cur_path.to_vec(),
leaf_node.value.clone(),
hash_db,
)?;
self.store_leaf_in_branch(&mut branch, path, value, hash_db)?;
Ok(NodeType::Branch(branch))
} else {
if common_prefix.len() < cur_path.len() && common_prefix.len() < path.len()
{
// Some path prefix is common between both new and existing node, create an extension node
// with common prefix path as key and 2 leaf nodes in a branch node
// this branch will be the key for the extension node
let branch_path: [Box<HashOrNode<H, V>>; 16] = Default::default();
let mut branch = Branch {
path: branch_path,
value: V::default(),
};
// Store both leaves in the branch. The common prefix is not stored in
// the leaf path as its already part of the extension node.
self.store_leaf_in_branch(
&mut branch,
cur_path[common_prefix.len()..].to_vec(),
leaf_node.value.clone(),
hash_db,
)?;
self.store_leaf_in_branch(
&mut branch,
path[common_prefix.len()..].to_vec(),
value,
hash_db,
)?;
Ok(NodeType::Extension(Extension {
path: common_prefix,
key: HashOrBranch::Branch(branch),
}))
} else if common_prefix == *cur_path {
// Existing node and new node will be moved to a new branch node which will be the key of
// a new extension node with path as the common prefix. The value of the existing node will
// be the value of the branch node.
// this branch will be the key for the extension node
let branch_path: [Box<HashOrNode<H, V>>; 16] = Default::default();
let mut branch = Branch {
path: branch_path,
value: leaf_node.value.clone(),
};
// Store new node as a leaf node in the branch. The common prefix is not
// stored in the leaf path as its already part of the extension node.
self.store_leaf_in_branch(
&mut branch,
path[common_prefix.len()..].to_vec(),
value,
hash_db,
)?;
Ok(NodeType::Extension(Extension {
path: common_prefix,
key: HashOrBranch::Branch(branch),
}))
} else {
// common_prefix == path
// Existing node and new node will be moved to a new branch node which will be the key of
// a new extension node with path as the common prefix. The value of the new node will
// be the value of the branch node.
// this branch will be the key for the extension node
let branch_path: [Box<HashOrNode<H, V>>; 16] = Default::default();
let mut branch = Branch {
path: branch_path,
value,
};
// Store existing node as a leaf node in the branch. The common prefix
// is not stored in the leaf path as its already part of the extension node.
self.store_leaf_in_branch(
&mut branch,
cur_path[common_prefix.len()..].to_vec(),
leaf_node.value.clone(),
hash_db,
)?;
Ok(NodeType::Extension(Extension {
path: common_prefix,
key: HashOrBranch::Branch(branch),
}))
}
}
}
}
NodeType::Extension(ext_node) => {
if path == ext_node.path {
// Updating key of an existing extension node to contain the new node as well.
let key = self.update_extension_key(&ext_node.key, vec![], value, hash_db)?;
Ok(NodeType::Extension(Extension { path, key }))
} else {
let cur_path = &ext_node.path;
let common_prefix = Self::get_common_prefix_in_paths(cur_path, &path);
if common_prefix.len() == 0 {
// paths for both nodes (new and existing) have no common prefix, create a
// branch node with 1 leaf node and 1 extension node
let mut branch_path: [Box<HashOrNode<H, V>>; 16] = Default::default();
self.store_extension_in_branch(
&mut branch_path,
cur_path.to_vec(),
ext_node.key.clone(),
hash_db,
)?;
let mut branch = Branch {
path: branch_path,
value: V::default(),
};
self.store_leaf_in_branch(&mut branch, path, value, hash_db)?;
Ok(NodeType::Branch(branch))
} else if common_prefix.len() < cur_path.len()
&& common_prefix.len() < path.len()
{
// Some path prefix is common between both new and existing node, create an extension node
// with common prefix path as key and 1 leaf node and 1 extension node, both
// in a new branch node
// this branch will be the key for the extension node
let mut branch_path: [Box<HashOrNode<H, V>>; 16] = Default::default();
// The common prefix is not stored in the leaf path as its already part of the
// extension node.
self.store_extension_in_branch(
&mut branch_path,
cur_path[common_prefix.len()..].to_vec(),
ext_node.key.clone(),
hash_db,
)?;
let mut branch = Branch {
path: branch_path,
value: V::default(),
};
self.store_leaf_in_branch(
&mut branch,
path[common_prefix.len()..].to_vec(),
value,
hash_db,
)?;
Ok(NodeType::Extension(Extension {
path: common_prefix,
key: HashOrBranch::Branch(branch),
}))
} else if common_prefix == *cur_path {
// Existing node and new node will be moved to a new branch node which will be the key of
// a new extension node with path as the common prefix.
// Update key of the existing extension node to contain the new node as well.
let key = self.update_extension_key(
&ext_node.key,
path[common_prefix.len()..].to_vec(),
value,
hash_db,
)?;
Ok(NodeType::Extension(Extension {