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
use anyhow::Result;
use std::marker::PhantomData;
use typenum::marker_traits::Unsigned;
use typenum::U2;

use crate::hash::{Algorithm, Hashable};
use crate::merkle::get_merkle_proof_lemma_len;

/// 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()
            .expect("[item] requested element is empty")
            .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());
        // unwrap is safe as we checked sub_tree_proof to be initialised
        self.sub_tree_proof.as_ref().unwrap().root()
    }

    /// Return tree root
    pub fn root(&self) -> T {
        self.lemma
            .last()
            .expect("[root] requested element is empty")
            .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()
            .expect("[validate_sub_tree_proof] couldn't get sub_tree_proof value")
            .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)]
mod tests {
    use crate::hash::{Algorithm, Hashable};
    use crate::merkle::Element;
    use crate::merkle::MerkleTree;
    use crate::proof::Proof;
    use crate::store::VecStore;
    use crate::test_legacy::{get_vec_tree_from_slice, Item, Sha256Hasher, XOR128};
    use typenum::{Unsigned, U0, U1, U2, U3, U4, U5, U8};

    // Break one element inside the proof's top layer (if available).
    // Otherwise, break the sub-proof.
    fn modify_proof<
        E: Element,
        A: Algorithm<E>,
        BaseTreeArity: Unsigned,
        SubTreeArity: Unsigned,
        TopTreeArity: Unsigned,
    >(
        proof: &mut Proof<E, BaseTreeArity>,
    ) {
        use rand::prelude::*;

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

        let mut hasher_alg = A::default();
        let mut tmp = vec![0u8; E::byte_len()];

        if TopTreeArity::to_usize() > 0 || SubTreeArity::to_usize() > 0 {
            // unwrap is safe as we checked sub_tree_proof to be initialised
            let i = random::<usize>() % proof.sub_tree_proof.as_ref().unwrap().lemma().len();
            let j = random::<usize>();

            j.hash(&mut hasher_alg);

            // Break random sub-tree proof element

            // unwrap is safe as we checked sub_tree_proof to be initialised
            proof.sub_tree_proof.as_ref().unwrap().lemma()[i].copy_to_slice(&mut tmp);
            tmp.hash(&mut hasher_alg);
            // unwrap is safe as we checked sub_tree_proof to be initialised
            proof.sub_tree_proof.as_mut().unwrap().lemma_mut()[i] = hasher_alg.hash();
        } else {
            let i = random::<usize>() % proof.lemma.len();
            let k = random::<usize>();

            k.hash(&mut hasher_alg);

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

    #[test]
    fn test_proofs() {
        fn run_test<
            E: Element,
            A: Algorithm<E>,
            BaseTreeArity: Unsigned,
            SubTreeArity: Unsigned,
            TopTreeArity: Unsigned,
        >() {
            let leafs = 32768;
            let tree = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);

            for i in 0..tree.leafs() {
                let mut p = tree
                    .gen_proof(i)
                    .expect("[test_proofs] failed to generate Merkle proof");
                assert!(p.validate::<A>().expect("[test_proofs] failed to validate"));

                // Break the proof here and assert negative validation.
                modify_proof::<E, A, BaseTreeArity, SubTreeArity, TopTreeArity>(&mut p);
                assert!(!p.validate::<A>().expect("[test_proofs] failed to validate"));
            }
        }

        run_test::<Item, XOR128, U2, U0, U0>();
        run_test::<Item, Sha256Hasher, U2, U0, U0>();
    }

    #[test]
    fn test_compound_quad_broken_proofs() {
        fn run_test<
            E: Element,
            A: Algorithm<E>,
            BaseTreeArity: Unsigned,
            SubTreeArity: Unsigned,
            TopTreeArity: Unsigned,
        >() {
            let leafs = 16384;
            let mt1 = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);
            let mt2 = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);
            let mt3 = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);

            let tree: MerkleTree<E, A, VecStore<E>, BaseTreeArity, SubTreeArity> =
                MerkleTree::from_trees(vec![mt1, mt2, mt3])
                    .expect("[test_compound_quad_broken_proofs] Failed to build compound tree");

            for i in 0..tree.leafs() {
                let mut p = tree
                    .gen_proof(i)
                    .expect("[test_compound_quad_broken_proofs] failed to generate Merkle proof");
                assert!(p
                    .validate::<A>()
                    .expect("[test_compound_quad_broken_proofs] failed to validate"));

                modify_proof::<E, A, BaseTreeArity, SubTreeArity, TopTreeArity>(&mut p);
                assert!(!p
                    .validate::<A>()
                    .expect("[test_compound_quad_broken_proofs] failed to validate"));
            }
        }
        run_test::<Item, XOR128, U4, U3, U0>();
        run_test::<Item, Sha256Hasher, U4, U3, U0>();
    }

    #[test]
    fn test_compound_single_octree_broken_proofs() {
        fn run_test<
            E: Element,
            A: Algorithm<E>,
            BaseTreeArity: Unsigned,
            SubTreeArity: Unsigned,
            TopTreeArity: Unsigned,
        >() {
            let leafs = 32768;
            let mt1 = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);

            let tree: MerkleTree<E, A, VecStore<E>, BaseTreeArity, SubTreeArity> =
                MerkleTree::from_trees(vec![mt1]).expect(
                    "[test_compound_single_octree_broken_proofs] Failed to build compound tree",
                );

            for i in 0..tree.leafs() {
                let mut p = tree.gen_proof(i).expect(
                    "[test_compound_single_octree_broken_proofs] failed to generate Merkle proof",
                );
                assert!(p
                    .validate::<A>()
                    .expect("[test_compound_single_octree_broken_proofs] failed to validate"));

                modify_proof::<E, A, BaseTreeArity, SubTreeArity, TopTreeArity>(&mut p);
                assert!(!p
                    .validate::<A>()
                    .expect("[test_compound_single_octree_broken_proofs] failed to validate"));
            }
        }
        run_test::<Item, XOR128, U8, U1, U0>();
        run_test::<Item, Sha256Hasher, U8, U1, U0>();
    }

    #[test]
    #[ignore]
    fn test_compound_octree_broken_proofs() {
        fn run_test<
            E: Element,
            A: Algorithm<E>,
            BaseTreeArity: Unsigned,
            SubTreeArity: Unsigned,
            TopTreeArity: Unsigned,
        >() {
            let leafs = 32768;
            let mt1 = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);
            let mt2 = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);
            let mt3 = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);
            let mt4 = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);

            let tree: MerkleTree<E, A, VecStore<E>, BaseTreeArity, SubTreeArity> =
                MerkleTree::from_trees(vec![mt1, mt2, mt3, mt4])
                    .expect("[test_compound_octree_broken_proofs] Failed to build compound tree");

            for i in 0..tree.leafs() {
                let mut p = tree
                    .gen_proof(i)
                    .expect("[test_compound_octree_broken_proofs] failed to generate Merkle proof");
                assert!(p
                    .validate::<A>()
                    .expect("[test_compound_octree_broken_proofs] failed to validate"));

                modify_proof::<E, A, BaseTreeArity, SubTreeArity, TopTreeArity>(&mut p);
                assert!(!p
                    .validate::<A>()
                    .expect("[test_compound_octree_broken_proofs] failed to validate"));
            }
        }
        run_test::<Item, XOR128, U8, U4, U0>();
        run_test::<Item, Sha256Hasher, U8, U4, U0>();
    }

    #[test]
    fn test_compound_compound_quad_broken_proofs() {
        fn run_test<
            E: Element,
            A: Algorithm<E>,
            BaseTreeArity: Unsigned,
            SubTreeArity: Unsigned,
            TopTreeArity: Unsigned,
        >() {
            let leafs = 16384;

            let mt1 = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);
            let mt2 = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);
            let mt3 = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);
            let cmt1: MerkleTree<E, A, VecStore<E>, BaseTreeArity, SubTreeArity> =
                MerkleTree::from_trees(vec![mt1, mt2, mt3])
                    .expect("[test_compound_compound_quad_broken_proofs] failed to build compound merkle tree");

            let mt4 = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);
            let mt5 = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);
            let mt6 = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);
            let cmt2: MerkleTree<E, A, VecStore<E>, BaseTreeArity, SubTreeArity> =
                MerkleTree::from_trees(vec![mt4, mt5, mt6])
                    .expect("[test_compound_compound_quad_broken_proofs] failed to build compound merkle tree");

            let mt7 = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);
            let mt8 = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);
            let mt9 = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);
            let cmt3: MerkleTree<E, A, VecStore<E>, BaseTreeArity, SubTreeArity> =
                MerkleTree::from_trees(vec![mt7, mt8, mt9])
                    .expect("[test_compound_compound_quad_broken_proofs] failed to build compound merkle tree");

            let tree: MerkleTree<E, A, VecStore<E>, BaseTreeArity, SubTreeArity, TopTreeArity> =
                MerkleTree::from_sub_trees(vec![cmt1, cmt2, cmt3])
                    .expect("[test_compound_compound_quad_broken_proofs] Failed to build compound-compound tree");

            for i in 0..tree.leafs() {
                let mut p = tree.gen_proof(i).expect("failed to generate Merkle proof");
                assert!(p
                    .validate::<A>()
                    .expect("[test_compound_compound_quad_broken_proofs] failed to validate"));

                modify_proof::<E, A, BaseTreeArity, SubTreeArity, TopTreeArity>(&mut p);
                assert!(!p
                    .validate::<A>()
                    .expect("[test_compound_compound_quad_broken_proofs] failed to validate"));
            }
        }

        run_test::<Item, XOR128, U4, U3, U3>();
        run_test::<Item, Sha256Hasher, U4, U3, U3>();
    }

    #[test]
    #[ignore]
    fn test_compound_compound_single_quad_broken_proofs() {
        fn run_test<
            E: Element,
            A: Algorithm<E>,
            BaseTreeArity: Unsigned,
            SubTreeArity: Unsigned,
            TopTreeArity: Unsigned,
        >() {
            let leafs = 16384;

            let mt1 = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);
            let mt2 = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);
            let mt3 = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);
            let cmt1: MerkleTree<E, A, VecStore<E>, BaseTreeArity, SubTreeArity> =
                MerkleTree::from_trees(vec![mt1, mt2, mt3])
                    .expect("[test_compound_compound_single_quad_broken_proofs] failed to build compound merkle tree");

            let tree: MerkleTree<E, A, VecStore<E>, BaseTreeArity, SubTreeArity, TopTreeArity> =
                MerkleTree::from_sub_trees(vec![cmt1])
                    .expect("[test_compound_compound_single_quad_broken_proofs] Failed to build compound-compound tree");

            for i in 0..tree.leafs() {
                let mut p = tree.gen_proof(i).expect("[test_compound_compound_single_quad_broken_proofs] failed to generate Merkle proof");
                assert!(p.validate::<A>().expect(
                    "[test_compound_compound_single_quad_broken_proofs] failed to validate"
                ));

                // TODO investigate why SubTree and TopTree are substituted (in origin test)
                modify_proof::<E, A, BaseTreeArity, TopTreeArity, SubTreeArity>(&mut p);
                assert!(!p.validate::<A>().expect(
                    "[test_compound_compound_single_quad_broken_proofs] failed to validate"
                ));
            }
        }
        run_test::<Item, XOR128, U4, U3, U1>();
        run_test::<Item, Sha256Hasher, U4, U3, U1>();
    }

    #[test]
    #[ignore]
    fn test_compound_compound_octree_broken_proofs() {
        fn run_test<
            E: Element,
            A: Algorithm<E>,
            BaseTreeArity: Unsigned,
            SubTreeArity: Unsigned,
            TopTreeArity: Unsigned,
        >() {
            let leafs = 32768;

            let mt1 = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);
            let mt2 = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);
            let mt3 = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);
            let mt4 = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);
            let cmt1: MerkleTree<E, A, VecStore<E>, BaseTreeArity, SubTreeArity> =
                MerkleTree::from_trees(vec![mt1, mt2, mt3, mt4]).expect(
                    "[test_compound_compound_octree_broken_proofs] Failed to build compound tree",
                );

            let mt5 = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);
            let mt6 = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);
            let mt7 = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);
            let mt8 = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);
            let cmt2: MerkleTree<E, A, VecStore<E>, BaseTreeArity, SubTreeArity> =
                MerkleTree::from_trees(vec![mt5, mt6, mt7, mt8]).expect(
                    "[test_compound_compound_octree_broken_proofs] Failed to build compound tree",
                );

            let mt9 = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);
            let mt10 = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);
            let mt11 = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);
            let mt12 = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);
            let cmt3: MerkleTree<E, A, VecStore<E>, BaseTreeArity, SubTreeArity> =
                MerkleTree::from_trees(vec![mt9, mt10, mt11, mt12]).expect(
                    "[test_compound_compound_octree_broken_proofs] Failed to build compound tree",
                );

            let mt13 = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);
            let mt14 = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);
            let mt15 = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);
            let mt16 = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);
            let cmt4: MerkleTree<E, A, VecStore<E>, BaseTreeArity, SubTreeArity> =
                MerkleTree::from_trees(vec![mt13, mt14, mt15, mt16]).expect(
                    "[test_compound_compound_octree_broken_proofs] Failed to build compound tree",
                );

            let mt17 = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);
            let mt18 = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);
            let mt19 = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);
            let mt20 = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);
            let cmt5: MerkleTree<E, A, VecStore<E>, BaseTreeArity, SubTreeArity> =
                MerkleTree::from_trees(vec![mt17, mt18, mt19, mt20]).expect(
                    "[test_compound_compound_octree_broken_proofs] Failed to build compound tree",
                );

            let tree: MerkleTree<E, A, VecStore<E>, BaseTreeArity, SubTreeArity, TopTreeArity> =
                MerkleTree::from_sub_trees(vec![cmt1, cmt2, cmt3, cmt4, cmt5])
                    .expect("[test_compound_compound_octree_broken_proofs] Failed to build compound-compound tree");

            for i in 0..tree.leafs() {
                let mut p = tree.gen_proof(i).expect(
                    "[test_compound_compound_octree_broken_proofs] failed to generate Merkle proof",
                );
                assert!(p
                    .validate::<A>()
                    .expect("[test_compound_compound_octree_broken_proofs] failed to validate"));

                // TODO investigate why SubTree and TopTree are substituted (in origin test)
                modify_proof::<E, A, BaseTreeArity, TopTreeArity, SubTreeArity>(&mut p);
                assert!(!p
                    .validate::<A>()
                    .expect("[test_compound_compound_octree_broken_proofs] failed to validate"));
            }
        }
        run_test::<Item, XOR128, U8, U4, U5>();
        run_test::<Item, Sha256Hasher, U8, U4, U5>();
    }

    #[test]
    #[ignore]
    fn test_compound_compound_single_octree_broken_proofs() {
        fn run_test<
            E: Element,
            A: Algorithm<E>,
            BaseTreeArity: Unsigned,
            SubTreeArity: Unsigned,
            TopTreeArity: Unsigned,
        >() {
            let leafs = 32768;

            let mt1 = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);
            let mt2 = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);
            let mt3 = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);
            let mt4 = get_vec_tree_from_slice::<E, A, BaseTreeArity>(leafs);
            let cmt1: MerkleTree<E, A, VecStore<E>, BaseTreeArity, SubTreeArity> =
                MerkleTree::from_trees(vec![mt1, mt2, mt3, mt4])
                    .expect("[test_compound_compound_single_octree_broken_proofs] Failed to build compound tree");

            let tree: MerkleTree<E, A, VecStore<E>, BaseTreeArity, SubTreeArity, TopTreeArity> =
                MerkleTree::from_sub_trees(vec![cmt1]).expect("[test_compound_compound_single_octree_broken_proofs] Failed to build ccompound tree");

            for i in 0..tree.leafs() {
                let mut p = tree.gen_proof(i).expect("[test_compound_compound_single_octree_broken_proofs] failed to generate Merkle proof");
                assert!(p.validate::<A>().expect(
                    "[test_compound_compound_single_octree_broken_proofs] failed to validate"
                ));

                // TODO investigate why SubTree and TopTree are substituted (in origin test)
                modify_proof::<E, A, BaseTreeArity, TopTreeArity, SubTreeArity>(&mut p);
                assert!(!p.validate::<A>().expect(
                    "[test_compound_compound_single_octree_broken_proofs] failed to validate"
                ));
            }
        }

        run_test::<Item, XOR128, U8, U4, U1>();
        run_test::<Item, Sha256Hasher, U8, U4, U1>();
    }
}