merkletree 0.19.0

Light merkle tree implementation with SPV support and dependency agnostic.
Documentation
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
use crate::hash::{Algorithm, Hashable};
use crate::merkle::get_merkle_proof_lemma_len;

use anyhow::Result;
use std::marker::PhantomData;
use typenum::marker_traits::Unsigned;
use typenum::U2;

#[cfg(test)]
use typenum::{U0, U1, U3, U4, U5, U8};

#[cfg(test)]
use crate::merkle::MerkleTree;
#[cfg(test)]
use crate::store::VecStore;
#[cfg(test)]
use crate::test_common::{get_vec_tree_from_slice, Item, XOR128};

/// Merkle tree inclusion proof for data element, for which item = Leaf(Hash(Data Item)).
///
/// Lemma layout:
///
/// ```text
/// [ item h1x h2y h3z ... root ]
/// ```
///
/// Proof validation is positioned hash against lemma path to match root hash.
#[derive(Debug, Clone, Eq, PartialEq)]
/// U is the default tree arity (U2 = binary)
pub struct Proof<T: Eq + Clone + AsRef<[u8]>, BaseTreeArity: Unsigned = U2> {
    // Optional proofs at immediate lower level from current.  Should
    // be None at the base layer.
    pub sub_tree_proof: Option<Box<Proof<T, BaseTreeArity>>>,

    top_layer_nodes: usize,      // arity of top layer
    sub_tree_layer_nodes: usize, // arity of sub-tree layer

    lemma: Vec<T>,
    path: Vec<usize>, // branch index

    _u: PhantomData<BaseTreeArity>, // number of branches per node
}

impl<T: Eq + Clone + AsRef<[u8]>, BaseTreeArity: Unsigned> Proof<T, BaseTreeArity> {
    /// Creates new MT inclusion proof
    pub fn new<TopLayerArity: Unsigned, SubTreeArity: Unsigned>(
        sub_tree_proof: Option<Box<Proof<T, BaseTreeArity>>>,
        lemma: Vec<T>,
        path: Vec<usize>,
    ) -> Result<Proof<T, BaseTreeArity>> {
        if TopLayerArity::to_usize() == 0 && SubTreeArity::to_usize() == 0 {
            ensure!(lemma.len() > 2, "Invalid lemma length (short)");
            ensure!(
                lemma.len()
                    == get_merkle_proof_lemma_len(path.len() + 1, BaseTreeArity::to_usize()),
                "Invalid lemma length"
            );
        }

        Ok(Proof {
            sub_tree_proof,
            top_layer_nodes: TopLayerArity::to_usize(),
            sub_tree_layer_nodes: SubTreeArity::to_usize(),
            lemma,
            path,

            _u: PhantomData,
        })
    }

    /// Return proof target leaf
    pub fn item(&self) -> T {
        self.lemma.first().unwrap().clone()
    }

    /// Return sub tree root
    pub fn sub_tree_root(&self) -> T {
        assert!(self.sub_tree_layer_nodes > 0 && self.sub_tree_proof.is_some());
        self.sub_tree_proof.as_ref().unwrap().root()
    }

    /// Return tree root
    pub fn root(&self) -> T {
        self.lemma.last().unwrap().clone()
    }

    /// Validates sub-tree proofs with the specified arity.
    fn validate_sub_tree_proof<A: Algorithm<T>>(&self, arity: usize) -> Result<bool> {
        // Ensure that the sub_tree validates to the root of that
        // sub_tree.
        let valid = self.sub_tree_proof.as_ref().unwrap().validate::<A>()?;
        if !valid {
            return Ok(valid);
        }

        // Validate top-most/current layer
        //
        // Check that the remaining proof matches the tree root (note
        // that Proof::validate at the base layer cannot handle a
        // proof this small, so this is a version specific for what we
        // know we have in this case).
        let mut a = A::default();
        a.reset();
        let node_count = arity;
        let h = {
            let mut nodes: Vec<T> = Vec::with_capacity(node_count);
            let mut cur_index = 0;
            for j in 0..node_count {
                if j == self.path()[0] {
                    nodes.push(self.sub_tree_root().clone());
                } else {
                    nodes.push(self.lemma()[cur_index].clone());
                    cur_index += 1;
                }
            }

            if cur_index != node_count - 1 {
                return Ok(false);
            }

            a.multi_node(&nodes, 0)
        };

        Ok(h == self.root())
    }

    /// Verifies MT inclusion proof
    pub fn validate<A: Algorithm<T>>(&self) -> Result<bool> {
        if self.top_layer_nodes > 0 {
            // Special Top layer handling here.
            ensure!(
                self.sub_tree_proof.is_some(),
                "Sub tree proof must be present for validation"
            );

            return self.validate_sub_tree_proof::<A>(self.top_layer_nodes);
        }

        if self.sub_tree_layer_nodes > 0 {
            // Sub-tree layer handling here.
            ensure!(
                self.sub_tree_proof.is_some(),
                "Sub tree proof must be present for validation"
            );

            return self.validate_sub_tree_proof::<A>(self.sub_tree_layer_nodes);
        }

        // Base layer handling here.
        ensure!(
            self.sub_tree_layer_nodes == 0,
            "Base layer proof must have 0 as sub-tree layer node count"
        );
        ensure!(
            self.top_layer_nodes == 0,
            "Base layer proof must have 0 as top layer node count"
        );
        ensure!(self.sub_tree_proof.is_none(), "Sub tree proof must be None");

        let size = self.lemma.len();
        if size < 2 {
            return Ok(false);
        }

        let branches = BaseTreeArity::to_usize();
        let mut a = A::default();
        let mut h = self.item();
        let mut path_index = 1;

        for i in (1..size - 1).step_by(branches - 1) {
            a.reset();
            h = {
                let mut nodes: Vec<T> = Vec::with_capacity(branches);
                let mut cur_index = 0;
                for j in 0..branches {
                    if j == self.path[path_index - 1] {
                        nodes.push(h.clone());
                    } else {
                        nodes.push(self.lemma[i + cur_index].clone());
                        cur_index += 1;
                    }
                }

                if cur_index != branches - 1 {
                    return Ok(false);
                }

                path_index += 1;
                a.multi_node(&nodes, i - 1)
            };
        }

        Ok(h == self.root())
    }

    /// Verifies MT inclusion proof and that leaf_data is the original leaf data for which proof was generated.
    pub fn validate_with_data<A: Algorithm<T>>(&self, leaf_data: &dyn Hashable<A>) -> Result<bool> {
        let mut a = A::default();
        leaf_data.hash(&mut a);
        let item = a.hash();
        a.reset();
        let leaf_hash = a.leaf(item);

        if leaf_hash == self.item() {
            self.validate::<A>()
        } else {
            Ok(false)
        }
    }

    /// Returns the path of this proof.
    pub fn path(&self) -> &Vec<usize> {
        &self.path
    }

    /// Returns the lemma of this proof.
    pub fn lemma(&self) -> &Vec<T> {
        &self.lemma
    }

    /// Returns the lemma of this proof as mutable.
    pub fn lemma_mut(&mut self) -> &mut Vec<T> {
        &mut self.lemma
    }

    pub fn top_layer_nodes(&self) -> usize {
        self.top_layer_nodes
    }

    pub fn sub_layer_nodes(&self) -> usize {
        self.sub_tree_layer_nodes
    }
}

#[cfg(test)]
// Break one element inside the proof's top layer (if available).
// Otherwise, break the sub-proof.
fn modify_proof<BaseTreeArity: Unsigned, SubTreeArity: Unsigned, TopTreeArity: Unsigned>(
    proof: &mut Proof<Item, BaseTreeArity>,
) {
    use rand::prelude::*;

    if TopTreeArity::to_usize() > 0 {
        assert!(proof.sub_tree_proof.is_some());
        assert!(proof
            .sub_tree_proof
            .as_ref()
            .unwrap()
            .sub_tree_proof
            .is_some());
    } else if SubTreeArity::to_usize() > 0 {
        assert!(proof.sub_tree_proof.is_some());
    }

    if TopTreeArity::to_usize() > 0 || SubTreeArity::to_usize() > 0 {
        let i = random::<usize>() % proof.sub_tree_proof.as_ref().unwrap().lemma().len();
        let j = random::<usize>();

        let mut a = XOR128::new();
        j.hash(&mut a);

        // Break random sub-tree proof element
        proof.sub_tree_proof.as_ref().unwrap().lemma()[i].hash(&mut a);
        proof.sub_tree_proof.as_mut().unwrap().lemma_mut()[i] = a.hash();
    } else {
        let i = random::<usize>() % proof.lemma.len();
        let k = random::<usize>();

        let mut a = XOR128::new();
        k.hash(&mut a);

        // Break random element
        proof.lemma[i].hash(&mut a);
        proof.lemma[i] = a.hash();
    }
}

#[test]
fn test_proofs() {
    let leafs = 32768;
    let tree = get_vec_tree_from_slice::<U2>(leafs);

    for i in 0..tree.leafs() {
        let mut p = tree.gen_proof(i).unwrap();
        assert!(p.validate::<XOR128>().expect("failed to validate"));

        // Break the proof here and assert negative validation.
        modify_proof::<U2, U0, U0>(&mut p);
        assert!(!p.validate::<XOR128>().expect("failed to validate"));
    }
}

#[test]
fn test_compound_quad_broken_proofs() {
    let leafs = 16384;
    let mt1 = get_vec_tree_from_slice::<U4>(leafs);
    let mt2 = get_vec_tree_from_slice::<U4>(leafs);
    let mt3 = get_vec_tree_from_slice::<U4>(leafs);

    let tree: MerkleTree<Item, XOR128, VecStore<_>, U4, U3> =
        MerkleTree::from_trees(vec![mt1, mt2, mt3]).expect("Failed to build compound tree");

    for i in 0..tree.leafs() {
        let mut p = tree.gen_proof(i).unwrap();
        assert!(p.validate::<XOR128>().expect("failed to validate"));

        modify_proof::<U4, U3, U0>(&mut p);
        assert!(!p.validate::<XOR128>().expect("failed to validate"));
    }
}

#[test]
fn test_compound_single_octree_broken_proofs() {
    let leafs = 32768;
    let mt1 = get_vec_tree_from_slice::<U8>(leafs);

    let tree: MerkleTree<Item, XOR128, VecStore<_>, U8, U1> =
        MerkleTree::from_trees(vec![mt1]).expect("Failed to build compound tree");

    for i in 0..tree.leafs() {
        let mut p = tree.gen_proof(i).unwrap();
        assert!(p.validate::<XOR128>().expect("failed to validate"));

        modify_proof::<U8, U1, U0>(&mut p);
        assert!(!p.validate::<XOR128>().expect("failed to validate"));
    }
}

#[test]
fn test_compound_octree_broken_proofs() {
    let leafs = 32768;
    let mt1 = get_vec_tree_from_slice::<U8>(leafs);
    let mt2 = get_vec_tree_from_slice::<U8>(leafs);
    let mt3 = get_vec_tree_from_slice::<U8>(leafs);
    let mt4 = get_vec_tree_from_slice::<U8>(leafs);

    let tree: MerkleTree<Item, XOR128, VecStore<_>, U8, U4> =
        MerkleTree::from_trees(vec![mt1, mt2, mt3, mt4]).expect("Failed to build compound tree");

    for i in 0..tree.leafs() {
        let mut p = tree.gen_proof(i).unwrap();
        assert!(p.validate::<XOR128>().expect("failed to validate"));

        modify_proof::<U8, U4, U0>(&mut p);
        assert!(!p.validate::<XOR128>().expect("failed to validate"));
    }
}

#[test]
fn test_ccompound_quad_broken_proofs() {
    let leafs = 16384;

    let mt1 = get_vec_tree_from_slice::<U4>(leafs);
    let mt2 = get_vec_tree_from_slice::<U4>(leafs);
    let mt3 = get_vec_tree_from_slice::<U4>(leafs);
    let cmt1: MerkleTree<Item, XOR128, VecStore<_>, U4, U3> =
        MerkleTree::from_trees(vec![mt1, mt2, mt3]).expect("failed to build compound merkle tree");

    let mt4 = get_vec_tree_from_slice::<U4>(leafs);
    let mt5 = get_vec_tree_from_slice::<U4>(leafs);
    let mt6 = get_vec_tree_from_slice::<U4>(leafs);
    let cmt2: MerkleTree<Item, XOR128, VecStore<_>, U4, U3> =
        MerkleTree::from_trees(vec![mt4, mt5, mt6]).expect("failed to build compound merkle tree");

    let mt7 = get_vec_tree_from_slice::<U4>(leafs);
    let mt8 = get_vec_tree_from_slice::<U4>(leafs);
    let mt9 = get_vec_tree_from_slice::<U4>(leafs);
    let cmt3: MerkleTree<Item, XOR128, VecStore<_>, U4, U3> =
        MerkleTree::from_trees(vec![mt7, mt8, mt9]).expect("failed to build compound merkle tree");

    let tree: MerkleTree<Item, XOR128, VecStore<_>, U4, U3, U3> =
        MerkleTree::from_sub_trees(vec![cmt1, cmt2, cmt3]).expect("Failed to build ccompound tree");

    for i in 0..tree.leafs() {
        let mut p = tree.gen_proof(i).unwrap();
        assert!(p.validate::<XOR128>().expect("failed to validate"));

        modify_proof::<U4, U3, U3>(&mut p);
        assert!(!p.validate::<XOR128>().expect("failed to validate"));
    }
}

#[test]
fn test_ccompound_single_quad_broken_proofs() {
    let leafs = 16384;

    let mt1 = get_vec_tree_from_slice::<U4>(leafs);
    let mt2 = get_vec_tree_from_slice::<U4>(leafs);
    let mt3 = get_vec_tree_from_slice::<U4>(leafs);
    let cmt1: MerkleTree<Item, XOR128, VecStore<_>, U4, U3> =
        MerkleTree::from_trees(vec![mt1, mt2, mt3]).expect("failed to build compound merkle tree");

    let tree: MerkleTree<Item, XOR128, VecStore<_>, U4, U3, U1> =
        MerkleTree::from_sub_trees(vec![cmt1]).expect("Failed to build ccompound tree");

    for i in 0..tree.leafs() {
        let mut p = tree.gen_proof(i).unwrap();
        assert!(p.validate::<XOR128>().expect("failed to validate"));

        modify_proof::<U4, U1, U3>(&mut p);
        assert!(!p.validate::<XOR128>().expect("failed to validate"));
    }
}

#[test]
fn test_ccompound_octree_broken_proofs() {
    let leafs = 32768;

    let mt1 = get_vec_tree_from_slice::<U8>(leafs);
    let mt2 = get_vec_tree_from_slice::<U8>(leafs);
    let mt3 = get_vec_tree_from_slice::<U8>(leafs);
    let mt4 = get_vec_tree_from_slice::<U8>(leafs);
    let cmt1: MerkleTree<Item, XOR128, VecStore<_>, U8, U4> =
        MerkleTree::from_trees(vec![mt1, mt2, mt3, mt4]).expect("Failed to build compound tree");

    let mt5 = get_vec_tree_from_slice::<U8>(leafs);
    let mt6 = get_vec_tree_from_slice::<U8>(leafs);
    let mt7 = get_vec_tree_from_slice::<U8>(leafs);
    let mt8 = get_vec_tree_from_slice::<U8>(leafs);
    let cmt2: MerkleTree<Item, XOR128, VecStore<_>, U8, U4> =
        MerkleTree::from_trees(vec![mt5, mt6, mt7, mt8]).expect("Failed to build compound tree");

    let mt9 = get_vec_tree_from_slice::<U8>(leafs);
    let mt10 = get_vec_tree_from_slice::<U8>(leafs);
    let mt11 = get_vec_tree_from_slice::<U8>(leafs);
    let mt12 = get_vec_tree_from_slice::<U8>(leafs);
    let cmt3: MerkleTree<Item, XOR128, VecStore<_>, U8, U4> =
        MerkleTree::from_trees(vec![mt9, mt10, mt11, mt12]).expect("Failed to build compound tree");

    let mt13 = get_vec_tree_from_slice::<U8>(leafs);
    let mt14 = get_vec_tree_from_slice::<U8>(leafs);
    let mt15 = get_vec_tree_from_slice::<U8>(leafs);
    let mt16 = get_vec_tree_from_slice::<U8>(leafs);
    let cmt4: MerkleTree<Item, XOR128, VecStore<_>, U8, U4> =
        MerkleTree::from_trees(vec![mt13, mt14, mt15, mt16])
            .expect("Failed to build compound tree");

    let mt17 = get_vec_tree_from_slice::<U8>(leafs);
    let mt18 = get_vec_tree_from_slice::<U8>(leafs);
    let mt19 = get_vec_tree_from_slice::<U8>(leafs);
    let mt20 = get_vec_tree_from_slice::<U8>(leafs);
    let cmt5: MerkleTree<Item, XOR128, VecStore<_>, U8, U4> =
        MerkleTree::from_trees(vec![mt17, mt18, mt19, mt20])
            .expect("Failed to build compound tree");

    let tree: MerkleTree<Item, XOR128, VecStore<_>, U8, U4, U5> =
        MerkleTree::from_sub_trees(vec![cmt1, cmt2, cmt3, cmt4, cmt5])
            .expect("Failed to build ccompound tree");

    for i in 0..tree.leafs() {
        let mut p = tree.gen_proof(i).unwrap();
        assert!(p.validate::<XOR128>().expect("failed to validate"));

        modify_proof::<U8, U5, U4>(&mut p);
        assert!(!p.validate::<XOR128>().expect("failed to validate"));
    }
}

#[test]
fn test_ccompound_single_octree_broken_proofs() {
    let leafs = 32768;

    let mt1 = get_vec_tree_from_slice::<U8>(leafs);
    let mt2 = get_vec_tree_from_slice::<U8>(leafs);
    let mt3 = get_vec_tree_from_slice::<U8>(leafs);
    let mt4 = get_vec_tree_from_slice::<U8>(leafs);
    let cmt1: MerkleTree<Item, XOR128, VecStore<_>, U8, U4> =
        MerkleTree::from_trees(vec![mt1, mt2, mt3, mt4]).expect("Failed to build compound tree");

    let tree: MerkleTree<Item, XOR128, VecStore<_>, U8, U4, U1> =
        MerkleTree::from_sub_trees(vec![cmt1]).expect("Failed to build ccompound tree");

    for i in 0..tree.leafs() {
        let mut p = tree.gen_proof(i).unwrap();
        assert!(p.validate::<XOR128>().expect("failed to validate"));

        modify_proof::<U8, U1, U4>(&mut p);
        assert!(!p.validate::<XOR128>().expect("failed to validate"));
    }
}