Debian Codegraph @

cachedtree.go

raw symbols SCIP
1 package merkletree
2
3 import (
4 "errors"
5 "hash"
6 )
7
8 // A CachedTree can be used to build Merkle roots and proofs from the cached
9 // Merkle roots of smaller blocks of data. Each CachedTree has a height,
10 // meaning every element added to the CachedTree is the root of a full Merkle
11 // tree containing 2^height leaves.
12 type CachedTree struct {
13 cachedNodeHeight uint64
14 trueProofIndex uint64
15 Tree
16 }
17
18 // NewCachedTree initializes a CachedTree with a hash object, which will be
19 // used when hashing the input.
20 func NewCachedTree(h hash.Hash, cachedNodeHeight uint64) *CachedTree {
21 return &CachedTree{
22 cachedNodeHeight: cachedNodeHeight,
23
24 Tree: Tree{
25 hash: h,
26
27 cachedTree: true,
28 },
29 }
30 }
31
32 // Prove will create a proof that the leaf at the indicated index is a part of
33 // the data represented by the Merkle root of the Cached Tree. The CachedTree
34 // needs the proof set proving that the index is an element of the cached
35 // element in order to create a correct proof. After proof is called, the
36 // CachedTree is unchanged, and can receive more elements.
37 func (ct *CachedTree) Prove(cachedProofSet [][]byte) (merkleRoot []byte, proofSet [][]byte, proofIndex uint64, numLeaves uint64) {
38 // Determine the proof index within the full tree, and the number of leaves
39 // within the full tree.
40 leavesPerCachedNode := uint64(1) << ct.cachedNodeHeight
41 numLeaves = leavesPerCachedNode * ct.currentIndex
42
43 // Get the proof set tail, which is generated based entirely on cached
44 // nodes.
45 merkleRoot, proofSetTail, _, _ := ct.Tree.Prove()
46 if len(proofSetTail) < 1 {
47 // The proof was invalid, return 'nil' for the proof set but accurate
48 // values for everything else.
49 return merkleRoot, nil, ct.trueProofIndex, numLeaves
50 }
51
52 // The full proof set is going to be the input cachedProofSet combined with
53 // the tail proof set. The one caveat is that the tail proof set has an
54 // extra piece of data at the first element - the verifier will assume that
55 // this data exists and therefore it needs to be omitted from the proof
56 // set.
57 proofSet = append(cachedProofSet, proofSetTail[1:]...)
58 return merkleRoot, proofSet, ct.trueProofIndex, numLeaves
59 }
60
61 // SetIndex will inform the CachedTree of the index of the leaf for which a
62 // storage proof is being created. The index should be the index of the actual
63 // leaf, and not the index of the cached element containing the leaf. SetIndex
64 // must be called on empty CachedTree.
65 func (ct *CachedTree) SetIndex(i uint64) error {
66 if ct.head != nil {
67 return errors.New("cannot call SetIndex on Tree if Tree has not been reset")
68 }
69 ct.trueProofIndex = i
70 return ct.Tree.SetIndex(i / (1 << ct.cachedNodeHeight))
71 }