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
use core::convert::Infallible;
use core::fmt;
use std::collections::{BTreeMap, BTreeSet};
use quickcheck::{Arbitrary, Gen};
use serde::{Deserialize, Serialize};
use tiny_keccak::{Hasher, Sha3};
use crate::traits::{CmRDT, CvRDT};
pub type Hash = [u8; 32];
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Node<T> {
pub children: BTreeSet<Hash>,
pub value: T,
}
impl<T: Sha3Hash> Node<T> {
pub fn hash(&self) -> Hash {
let mut sha3 = Sha3::v256();
self.children.iter().for_each(|c| sha3.update(c));
self.value.hash(&mut sha3);
let mut hash = [0u8; 32];
sha3.finalize(&mut hash);
hash
}
}
pub struct Content<'a, T> {
nodes: BTreeMap<Hash, &'a Node<T>>,
}
impl<'a, T> Content<'a, T> {
pub fn is_empty(&self) -> bool {
self.nodes.is_empty()
}
pub fn values(&self) -> impl Iterator<Item = &T> {
self.nodes.values().map(|n| &n.value)
}
pub fn nodes(&self) -> impl Iterator<Item = &Node<T>> {
self.nodes.values().copied()
}
pub fn hashes(&self) -> BTreeSet<Hash> {
self.nodes.keys().copied().collect()
}
pub fn hashes_and_nodes(&self) -> impl Iterator<Item = (Hash, &Node<T>)> {
self.nodes.iter().map(|(hash, node)| (*hash, *node))
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct MerkleReg<T> {
roots: BTreeSet<Hash>,
dag: BTreeMap<Hash, Node<T>>,
orphans: BTreeMap<Hash, Node<T>>,
}
impl<T> Default for MerkleReg<T> {
fn default() -> Self {
Self {
roots: Default::default(),
dag: Default::default(),
orphans: Default::default(),
}
}
}
impl<T> MerkleReg<T> {
pub fn new() -> Self {
Default::default()
}
pub fn read(&self) -> Content<T> {
Content {
nodes: self
.roots
.iter()
.copied()
.filter_map(|root| self.dag.get(&root).map(|node| (root, node)))
.collect(),
}
}
pub fn write(&self, value: T, children: BTreeSet<Hash>) -> Node<T> {
Node { children, value }
}
pub fn node(&self, hash: Hash) -> Option<&Node<T>> {
self.dag.get(&hash).or_else(|| self.orphans.get(&hash))
}
pub fn children(&self, hash: Hash) -> Content<T> {
let nodes = self.dag.get(&hash).map(|node| {
node.children
.iter()
.copied()
.filter_map(|child| self.dag.get(&child).map(|node| (child, node)))
.collect()
});
Content {
nodes: nodes.unwrap_or_default(),
}
}
pub fn parents(&self, hash: Hash) -> Content<T> {
let parents = self
.dag
.iter()
.filter_map(|(h, node)| {
if node.children.contains(&hash) {
Some((*h, node))
} else {
None
}
})
.collect();
Content { nodes: parents }
}
pub fn num_nodes(&self) -> usize {
self.dag.len()
}
pub fn num_orphans(&self) -> usize {
self.orphans.len()
}
fn all_hashes_seen(&self, hashes: &BTreeSet<Hash>) -> bool {
hashes.iter().all(|h| self.dag.contains_key(h))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ValidationError {
MissingChild(Hash),
}
impl fmt::Display for ValidationError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(self, f)
}
}
impl std::error::Error for ValidationError {}
impl<T: Sha3Hash> CmRDT for MerkleReg<T> {
type Op = Node<T>;
type Validation = ValidationError;
fn validate_op(&self, op: &Self::Op) -> Result<(), Self::Validation> {
for child in op.children.iter() {
if !self.dag.contains_key(child) {
return Err(ValidationError::MissingChild(*child));
}
}
Ok(())
}
fn apply(&mut self, node: Self::Op) {
let node_hash = node.hash();
if self.dag.contains_key(&node_hash) || self.orphans.contains_key(&node_hash) {
return;
}
if self.all_hashes_seen(&node.children) {
for child in node.children.iter() {
self.roots.remove(child);
}
self.roots.insert(node_hash);
self.dag.insert(node_hash, node);
let hashes_that_are_now_ready_to_apply = self
.orphans
.iter()
.filter(|(_, node)| self.all_hashes_seen(&node.children))
.map(|(hash, _)| hash)
.copied()
.collect::<Vec<_>>();
let mut nodes_to_apply = Vec::new();
for hash in hashes_that_are_now_ready_to_apply {
if let Some(node) = self.orphans.remove(&hash) {
nodes_to_apply.push(node);
}
}
for node in nodes_to_apply {
self.apply(node);
}
} else {
self.orphans.insert(node_hash, node);
}
}
}
impl<T: Sha3Hash> CvRDT for MerkleReg<T> {
type Validation = Infallible;
fn validate_merge(&self, _: &Self) -> Result<(), Self::Validation> {
Ok(())
}
fn merge(&mut self, other: Self) {
let MerkleReg { dag, orphans, .. } = other;
for (_, node) in dag {
self.apply(node);
}
for (_, node) in orphans {
self.apply(node);
}
}
}
pub trait Sha3Hash {
fn hash(&self, hasher: &mut Sha3);
}
impl<T: AsRef<[u8]>> Sha3Hash for T {
fn hash(&self, hasher: &mut Sha3) {
hasher.update(self.as_ref());
}
}
impl<T: Arbitrary + Sha3Hash> Arbitrary for MerkleReg<T> {
fn arbitrary<G: Gen>(g: &mut G) -> Self {
let mut reg = MerkleReg::new();
let mut nodes: Vec<Node<_>> = Vec::new();
let n_nodes = u8::arbitrary(g) % 12;
for _ in 0..n_nodes {
let value = T::arbitrary(g);
let mut children = BTreeSet::new();
if !nodes.is_empty() {
let n_children = u8::arbitrary(g) % 12;
for _ in 0..n_children {
children.insert(nodes[usize::arbitrary(g) % nodes.len()].hash());
}
}
let op = reg.write(value, children);
nodes.push(op.clone());
reg.apply(op)
}
reg
}
}