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
#[cfg(test)]
mod iterator_test;
use crate::{
node_type::{InternalNode, Node, NodeKey},
TreeReader,
};
use anyhow::{format_err, Result};
use diem_crypto::HashValue;
use diem_types::{
nibble::{nibble_path::NibblePath, Nibble},
transaction::Version,
};
use std::{marker::PhantomData, sync::Arc};
#[derive(Debug)]
struct NodeVisitInfo {
node_key: NodeKey,
node: InternalNode,
children_bitmap: u16,
next_child_to_visit: u16,
}
impl NodeVisitInfo {
fn new(node_key: NodeKey, node: InternalNode) -> Self {
let (children_bitmap, _) = node.generate_bitmaps();
assert!(children_bitmap != 0);
Self {
node_key,
node,
children_bitmap,
next_child_to_visit: 1 << children_bitmap.trailing_zeros(),
}
}
fn new_next_child_to_visit(
node_key: NodeKey,
node: InternalNode,
next_child_to_visit: Nibble,
) -> Self {
let (children_bitmap, _) = node.generate_bitmaps();
let mut next_child_to_visit = 1 << u8::from(next_child_to_visit);
assert!(children_bitmap >= next_child_to_visit);
while next_child_to_visit & children_bitmap == 0 {
next_child_to_visit <<= 1;
}
Self {
node_key,
node,
children_bitmap,
next_child_to_visit,
}
}
fn is_rightmost(&self) -> bool {
assert!(self.next_child_to_visit.leading_zeros() >= self.children_bitmap.leading_zeros());
self.next_child_to_visit.leading_zeros() == self.children_bitmap.leading_zeros()
}
fn advance(&mut self) {
assert!(!self.is_rightmost(), "Advancing past rightmost child.");
self.next_child_to_visit <<= 1;
while self.next_child_to_visit & self.children_bitmap == 0 {
self.next_child_to_visit <<= 1;
}
}
}
pub struct JellyfishMerkleIterator<R, V> {
reader: Arc<R>,
version: Version,
parent_stack: Vec<NodeVisitInfo>,
done: bool,
phantom_value: PhantomData<V>,
}
impl<R, V> JellyfishMerkleIterator<R, V>
where
R: TreeReader<V>,
V: crate::Value,
{
pub fn new(reader: Arc<R>, version: Version, starting_key: HashValue) -> Result<Self> {
let mut parent_stack = vec![];
let mut done = false;
let mut current_node_key = NodeKey::new_empty_path(version);
let nibble_path = NibblePath::new(starting_key.to_vec());
let mut nibble_iter = nibble_path.nibbles();
while let Node::Internal(internal_node) = reader.get_node(¤t_node_key)? {
let child_index = nibble_iter.next().expect("Should have enough nibbles.");
match internal_node.child(child_index) {
Some(child) => {
parent_stack.push(NodeVisitInfo::new_next_child_to_visit(
current_node_key.clone(),
internal_node.clone(),
child_index,
));
current_node_key =
current_node_key.gen_child_node_key(child.version, child_index);
}
None => {
let (bitmap, _) = internal_node.generate_bitmaps();
if u32::from(u8::from(child_index)) < 15 - bitmap.leading_zeros() {
parent_stack.push(NodeVisitInfo::new_next_child_to_visit(
current_node_key,
internal_node,
child_index,
));
} else {
Self::cleanup_stack(&mut parent_stack);
}
return Ok(Self {
reader,
version,
parent_stack,
done,
phantom_value: PhantomData,
});
}
}
}
match reader.get_node(¤t_node_key)? {
Node::Internal(_) => unreachable!("Should have reached the bottom of the tree."),
Node::Leaf(leaf_node) => {
if leaf_node.account_key() < starting_key {
Self::cleanup_stack(&mut parent_stack);
if parent_stack.is_empty() {
done = true;
}
}
}
Node::Null => done = true,
}
Ok(Self {
reader,
version,
parent_stack,
done,
phantom_value: PhantomData,
})
}
fn cleanup_stack(parent_stack: &mut Vec<NodeVisitInfo>) {
while let Some(info) = parent_stack.last_mut() {
if info.is_rightmost() {
parent_stack.pop();
} else {
info.advance();
break;
}
}
}
}
impl<R, V> Iterator for JellyfishMerkleIterator<R, V>
where
R: TreeReader<V>,
V: crate::Value,
{
type Item = Result<(HashValue, V)>;
fn next(&mut self) -> Option<Self::Item> {
if self.done {
return None;
}
if self.parent_stack.is_empty() {
let root_node_key = NodeKey::new_empty_path(self.version);
match self.reader.get_node(&root_node_key) {
Ok(Node::Leaf(leaf_node)) => {
self.done = true;
return Some(Ok((leaf_node.account_key(), leaf_node.value().clone())));
}
Ok(Node::Internal(_)) => {
return None;
}
Ok(Node::Null) => unreachable!("We would have set done to true in new."),
Err(err) => return Some(Err(err)),
}
}
loop {
let last_visited_node_info = self
.parent_stack
.last()
.expect("We have checked that self.parent_stack is not empty.");
let child_index =
Nibble::from(last_visited_node_info.next_child_to_visit.trailing_zeros() as u8);
let node_key = last_visited_node_info.node_key.gen_child_node_key(
last_visited_node_info
.node
.child(child_index)
.expect("Child should exist.")
.version,
child_index,
);
match self.reader.get_node(&node_key) {
Ok(Node::Internal(internal_node)) => {
let visit_info = NodeVisitInfo::new(node_key, internal_node);
self.parent_stack.push(visit_info);
}
Ok(Node::Leaf(leaf_node)) => {
let ret = (leaf_node.account_key(), leaf_node.value().clone());
Self::cleanup_stack(&mut self.parent_stack);
return Some(Ok(ret));
}
Ok(Node::Null) => return Some(Err(format_err!("Should not reach a null node."))),
Err(err) => return Some(Err(err)),
}
}
}
}