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
#[cfg(test)]
mod restore_test;
use crate::{
node_type::{
get_child_and_sibling_half_start, Child, Children, InternalNode, LeafNode, Node, NodeKey,
},
NibbleExt, NodeBatch, TreeReader, TreeWriter, ROOT_NIBBLE_HEIGHT,
};
use anyhow::{bail, ensure, format_err, Result};
use diem_crypto::{
hash::{CryptoHash, SPARSE_MERKLE_PLACEHOLDER_HASH},
HashValue,
};
use diem_types::{
nibble::{
nibble_path::{NibbleIterator, NibblePath},
Nibble,
},
proof::{SparseMerkleInternalNode, SparseMerkleRangeProof},
transaction::Version,
};
use mirai_annotations::*;
use std::sync::Arc;
#[derive(Clone, Debug, Eq, PartialEq)]
enum ChildInfo<V> {
Internal { hash: Option<HashValue> },
Leaf { node: LeafNode<V> },
}
impl<V> ChildInfo<V>
where
V: crate::Value,
{
fn into_child(self, version: Version) -> Child {
match self {
Self::Internal { hash } => {
Child::new(
hash.expect("Must have been initialized."),
version,
false, )
}
Self::Leaf { node } => {
Child::new(node.hash(), version, true )
}
}
}
}
#[derive(Clone, Debug)]
struct InternalInfo<V> {
node_key: NodeKey,
children: [Option<ChildInfo<V>>; 16],
}
impl<V> InternalInfo<V>
where
V: crate::Value,
{
fn new_empty(node_key: NodeKey) -> Self {
Self {
node_key,
children: Default::default(),
}
}
fn set_child(&mut self, index: usize, child_info: ChildInfo<V>) {
precondition!(index < 16);
self.children[index] = Some(child_info);
}
fn into_internal_node(mut self, version: Version) -> (NodeKey, InternalNode) {
let mut children = Children::new();
for (index, child_info_option) in self.children.iter_mut().enumerate() {
if let Some(child_info) = child_info_option.take() {
children.insert((index as u8).into(), child_info.into_child(version));
}
}
(self.node_key, InternalNode::new(children))
}
}
pub struct JellyfishMerkleRestore<V> {
store: Arc<dyn TreeWriter<V>>,
version: Version,
partial_nodes: Vec<InternalInfo<V>>,
frozen_nodes: NodeBatch<V>,
previous_leaf: Option<LeafNode<V>>,
num_keys_received: u64,
expected_root_hash: HashValue,
}
impl<V> JellyfishMerkleRestore<V>
where
V: crate::Value,
{
pub fn new<D: 'static + TreeReader<V> + TreeWriter<V>>(
store: Arc<D>,
version: Version,
expected_root_hash: HashValue,
) -> Result<Self> {
let tree_reader = Arc::clone(&store);
let (partial_nodes, previous_leaf) =
if let Some((node_key, leaf_node)) = tree_reader.get_rightmost_leaf()? {
(
Self::recover_partial_nodes(tree_reader.as_ref(), version, node_key)?,
Some(leaf_node),
)
} else {
(
vec![InternalInfo::new_empty(NodeKey::new_empty_path(version))],
None,
)
};
Ok(Self {
store,
version,
partial_nodes,
frozen_nodes: NodeBatch::new(),
previous_leaf,
num_keys_received: 0,
expected_root_hash,
})
}
pub fn new_overwrite<D: 'static + TreeWriter<V>>(
store: Arc<D>,
version: Version,
expected_root_hash: HashValue,
) -> Result<Self> {
Ok(Self {
store,
version,
partial_nodes: vec![InternalInfo::new_empty(NodeKey::new_empty_path(version))],
frozen_nodes: NodeBatch::new(),
previous_leaf: None,
num_keys_received: 0,
expected_root_hash,
})
}
fn recover_partial_nodes(
store: &dyn TreeReader<V>,
version: Version,
rightmost_leaf_node_key: NodeKey,
) -> Result<Vec<InternalInfo<V>>> {
ensure!(
!rightmost_leaf_node_key.nibble_path().is_empty(),
"Root node would not be written until entire restoration process has completed \
successfully.",
);
let mut node_key = rightmost_leaf_node_key.gen_parent_node_key();
while store.get_node_option(&node_key)?.is_some() {
node_key = node_key.gen_parent_node_key();
}
let mut partial_nodes = vec![];
let mut previous_child_index = None;
loop {
let mut internal_info = InternalInfo::new_empty(node_key.clone());
for i in 0..previous_child_index.unwrap_or(16) {
let child_node_key = node_key.gen_child_node_key(version, (i as u8).into());
if let Some(node) = store.get_node_option(&child_node_key)? {
let child_info = match node {
Node::Internal(internal_node) => ChildInfo::Internal {
hash: Some(internal_node.hash()),
},
Node::Leaf(leaf_node) => ChildInfo::Leaf { node: leaf_node },
Node::Null => bail!("Null node should not appear in storage."),
};
internal_info.set_child(i, child_info);
}
}
if let Some(index) = previous_child_index {
internal_info.set_child(index, ChildInfo::Internal { hash: None });
}
partial_nodes.push(internal_info);
if node_key.nibble_path().is_empty() {
break;
}
previous_child_index = node_key.nibble_path().last().map(|x| u8::from(x) as usize);
node_key = node_key.gen_parent_node_key();
}
partial_nodes.reverse();
Ok(partial_nodes)
}
pub fn add_chunk(
&mut self,
chunk: Vec<(HashValue, V)>,
proof: SparseMerkleRangeProof,
) -> Result<()> {
ensure!(!chunk.is_empty(), "Should not add empty chunks.");
for (key, value) in chunk {
if let Some(ref prev_leaf) = self.previous_leaf {
ensure!(
key > prev_leaf.account_key(),
"Account keys must come in increasing order.",
)
}
self.add_one(key, value.clone());
self.previous_leaf.replace(LeafNode::new(key, value));
self.num_keys_received += 1;
}
self.verify(proof)?;
self.store.write_node_batch(&self.frozen_nodes)?;
self.frozen_nodes.clear();
Ok(())
}
fn add_one(&mut self, new_key: HashValue, new_value: V) {
let nibble_path = NibblePath::new(new_key.to_vec());
let mut nibbles = nibble_path.nibbles();
for i in 0..ROOT_NIBBLE_HEIGHT {
let child_index = u8::from(nibbles.next().expect("This nibble must exist.")) as usize;
assert!(i < self.partial_nodes.len());
match self.partial_nodes[i].children[child_index] {
Some(ref child_info) => {
if let ChildInfo::Leaf { node } = child_info {
assert_eq!(
i,
self.partial_nodes.len() - 1,
"If we see a leaf, there will be no more partial internal nodes on \
lower level, since they would have been frozen.",
);
let existing_leaf = node.clone();
self.insert_at_leaf(
child_index,
existing_leaf,
new_key,
new_value,
nibbles,
);
break;
}
}
None => {
self.freeze(i + 1);
self.partial_nodes[i].set_child(
child_index,
ChildInfo::Leaf {
node: LeafNode::new(new_key, new_value),
},
);
break;
}
}
}
}
fn insert_at_leaf(
&mut self,
child_index: usize,
existing_leaf: LeafNode<V>,
new_key: HashValue,
new_value: V,
mut remaining_nibbles: NibbleIterator,
) {
let num_existing_partial_nodes = self.partial_nodes.len();
self.partial_nodes[num_existing_partial_nodes - 1]
.set_child(child_index, ChildInfo::Internal { hash: None });
let common_prefix_len = existing_leaf
.account_key()
.common_prefix_nibbles_len(new_key);
for _ in num_existing_partial_nodes..common_prefix_len {
let visited_nibbles = remaining_nibbles.visited_nibbles().collect();
let next_nibble = remaining_nibbles.next().expect("This nibble must exist.");
let new_node_key = NodeKey::new(self.version, visited_nibbles);
let mut internal_info = InternalInfo::new_empty(new_node_key);
internal_info.set_child(
u8::from(next_nibble) as usize,
ChildInfo::Internal { hash: None },
);
self.partial_nodes.push(internal_info);
}
let visited_nibbles = remaining_nibbles.visited_nibbles().collect();
let new_node_key = NodeKey::new(self.version, visited_nibbles);
let mut internal_info = InternalInfo::new_empty(new_node_key);
let existing_child_index = existing_leaf.account_key().get_nibble(common_prefix_len);
internal_info.set_child(
u8::from(existing_child_index) as usize,
ChildInfo::Leaf {
node: existing_leaf,
},
);
self.partial_nodes.push(internal_info);
self.freeze(self.partial_nodes.len());
let new_child_index = new_key.get_nibble(common_prefix_len);
assert!(
new_child_index > existing_child_index,
"New leaf must be on the right.",
);
self.partial_nodes
.last_mut()
.expect("This node must exist.")
.set_child(
u8::from(new_child_index) as usize,
ChildInfo::Leaf {
node: LeafNode::new(new_key, new_value),
},
);
}
fn freeze(&mut self, num_remaining_partial_nodes: usize) {
self.freeze_previous_leaf();
self.freeze_internal_nodes(num_remaining_partial_nodes);
}
fn freeze_previous_leaf(&mut self) {
if self.num_keys_received == 0 {
return;
}
let last_node = self
.partial_nodes
.last()
.expect("Must have at least one partial node.");
let rightmost_child_index = last_node
.children
.iter()
.rposition(|x| x.is_some())
.expect("Must have at least one child.");
match last_node.children[rightmost_child_index] {
Some(ChildInfo::Leaf { ref node }) => {
let child_node_key = last_node
.node_key
.gen_child_node_key(self.version, (rightmost_child_index as u8).into());
self.frozen_nodes
.insert(child_node_key, node.clone().into());
}
_ => panic!("Must have at least one child and must not have further internal nodes."),
}
}
fn freeze_internal_nodes(&mut self, num_remaining_nodes: usize) {
while self.partial_nodes.len() > num_remaining_nodes {
let last_node = self.partial_nodes.pop().expect("This node must exist.");
let (node_key, internal_node) = last_node.into_internal_node(self.version);
let node_hash = internal_node.hash();
self.frozen_nodes.insert(node_key, internal_node.into());
if let Some(parent_node) = self.partial_nodes.last_mut() {
let rightmost_child_index = parent_node
.children
.iter()
.rposition(|x| x.is_some())
.expect("Must have at least one child.");
match parent_node.children[rightmost_child_index] {
Some(ChildInfo::Internal { ref mut hash }) => {
assert_eq!(hash.replace(node_hash), None);
}
_ => panic!(
"Must have at least one child and the rightmost child must not be a leaf."
),
}
}
}
}
#[allow(clippy::collapsible_if)]
fn verify(&self, proof: SparseMerkleRangeProof) -> Result<()> {
let previous_leaf = self
.previous_leaf
.as_ref()
.expect("The previous leaf must exist.");
let previous_key = previous_leaf.account_key();
let mut left_siblings = vec![];
let mut num_visited_right_siblings = 0;
for (i, bit) in previous_key.iter_bits().enumerate() {
if bit {
let sibling = if i >= self.partial_nodes.len() * 4 {
*SPARSE_MERKLE_PLACEHOLDER_HASH
} else {
Self::compute_left_sibling(
&self.partial_nodes[i / 4],
previous_key.get_nibble(i / 4),
(3 - i % 4) as u8,
)
};
left_siblings.push(sibling);
} else {
num_visited_right_siblings += 1;
}
}
ensure!(
num_visited_right_siblings >= proof.right_siblings().len(),
"Too many right siblings in the proof.",
);
for bit in previous_key.iter_bits().rev() {
if bit {
if *left_siblings.last().expect("This sibling must exist.")
== *SPARSE_MERKLE_PLACEHOLDER_HASH
{
left_siblings.pop();
} else {
break;
}
} else if num_visited_right_siblings > proof.right_siblings().len() {
num_visited_right_siblings -= 1;
} else {
break;
}
}
let num_siblings = left_siblings.len() + proof.right_siblings().len();
let mut left_sibling_iter = left_siblings.iter().rev();
let mut right_sibling_iter = proof.right_siblings().iter();
let mut current_hash = previous_leaf.hash();
for bit in previous_key
.iter_bits()
.rev()
.skip(HashValue::LENGTH_IN_BITS - num_siblings)
{
let (left_hash, right_hash) = if bit {
(
*left_sibling_iter
.next()
.ok_or_else(|| format_err!("Missing left sibling."))?,
current_hash,
)
} else {
(
current_hash,
*right_sibling_iter
.next()
.ok_or_else(|| format_err!("Missing right sibling."))?,
)
};
current_hash = SparseMerkleInternalNode::new(left_hash, right_hash).hash();
}
ensure!(
current_hash == self.expected_root_hash,
"Root hashes do not match. Actual root hash: {:x}. Expected root hash: {:x}.",
current_hash,
self.expected_root_hash,
);
Ok(())
}
fn compute_left_sibling(partial_node: &InternalInfo<V>, n: Nibble, height: u8) -> HashValue {
assert!(height < 4);
let width = 1usize << height;
let start = get_child_and_sibling_half_start(n, height).1 as usize;
Self::compute_left_sibling_impl(&partial_node.children[start..start + width]).0
}
fn compute_left_sibling_impl(children: &[Option<ChildInfo<V>>]) -> (HashValue, bool) {
assert!(!children.is_empty());
let num_children = children.len();
assert!(num_children.is_power_of_two());
if num_children == 1 {
match &children[0] {
Some(ChildInfo::Internal { hash }) => {
(*hash.as_ref().expect("The hash must be known."), false)
}
Some(ChildInfo::Leaf { node }) => (node.hash(), true),
None => (*SPARSE_MERKLE_PLACEHOLDER_HASH, true),
}
} else {
let (left_hash, left_is_leaf) =
Self::compute_left_sibling_impl(&children[..num_children / 2]);
let (right_hash, right_is_leaf) =
Self::compute_left_sibling_impl(&children[num_children / 2..]);
if left_hash == *SPARSE_MERKLE_PLACEHOLDER_HASH && right_is_leaf {
(right_hash, true)
} else if left_is_leaf && right_hash == *SPARSE_MERKLE_PLACEHOLDER_HASH {
(left_hash, true)
} else {
(
SparseMerkleInternalNode::new(left_hash, right_hash).hash(),
false,
)
}
}
}
pub fn finish(mut self) -> Result<()> {
if self.partial_nodes.len() == 1 {
let mut num_children = 0;
let mut leaf = None;
for i in 0..16 {
if let Some(ref child_info) = self.partial_nodes[0].children[i] {
num_children += 1;
if let ChildInfo::Leaf { node } = child_info {
leaf = Some(node.clone());
}
}
}
if num_children == 1 {
if let Some(node) = leaf {
let node_key = NodeKey::new_empty_path(self.version);
assert!(self.frozen_nodes.is_empty());
self.frozen_nodes.insert(node_key, node.into());
self.store.write_node_batch(&self.frozen_nodes)?;
return Ok(());
}
}
}
self.freeze(0);
self.store.write_node_batch(&self.frozen_nodes)
}
}