| 1 | package merkletree |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "hash" |
| 6 | ) |
| 7 | |
| 8 | // A Tree takes data as leaves and returns the Merkle root. Each call to 'Push' |
| 9 | // adds one leaf to the Merkle tree. Calling 'Root' returns the Merkle root. |
| 10 | // The Tree also constructs proof that a single leaf is a part of the tree. The |
| 11 | // leaf can be chosen with 'SetIndex'. The memory footprint of Tree grows in |
| 12 | // O(log(n)) in the number of leaves. |
| 13 | type Tree struct { |
| 14 | // The Tree is stored as a stack of subtrees. Each subtree has a height, |
| 15 | // and is the Merkle root of 2^height leaves. A Tree with 11 nodes is |
| 16 | // represented as a subtree of height 3 (8 nodes), a subtree of height 1 (2 |
| 17 | // nodes), and a subtree of height 0 (1 node). Head points to the smallest |
| 18 | // tree. When a new leaf is inserted, it is inserted as a subtree of height |
| 19 | // 0. If there is another subtree of the same height, both can be removed, |
| 20 | // combined, and then inserted as a subtree of height n + 1. |
| 21 | head *subTree |
| 22 | hash hash.Hash |
| 23 | |
| 24 | // Helper variables used to construct proofs that the data at 'proofIndex' |
| 25 | // is in the Merkle tree. The proofSet is constructed as elements are being |
| 26 | // added to the tree. The first element of the proof set is the original |
| 27 | // data used to create the leaf at index 'proofIndex'. proofTree indicates |
| 28 | // if the tree will be used to create a merkle proof. |
| 29 | currentIndex uint64 |
| 30 | proofIndex uint64 |
| 31 | proofSet [][]byte |
| 32 | proofTree bool |
| 33 | |
| 34 | // The cachedTree flag indicates that the tree is cached, meaning that |
| 35 | // different code is used in 'Push' for creating a new head subtree. Adding |
| 36 | // this flag is somewhat gross, but eliminates needing to duplicate the |
| 37 | // entire 'Push' function when writing the cached tree. |
| 38 | cachedTree bool |
| 39 | } |
| 40 | |
| 41 | // A subTree contains the Merkle root of a complete (2^height leaves) subTree |
| 42 | // of the Tree. 'sum' is the Merkle root of the subTree. If 'next' is not nil, |
| 43 | // it will be a tree with a higher height. |
| 44 | type subTree struct { |
| 45 | next *subTree |
| 46 | height int // Int is okay because a height over 300 is physically unachievable. |
| 47 | sum []byte |
| 48 | } |
| 49 | |
| 50 | // sum returns the hash of the input data using the specified algorithm. |
| 51 | func sum(h hash.Hash, data ...[]byte) []byte { |
| 52 | h.Reset() |
| 53 | for _, d := range data { |
| 54 | // the Hash interface specifies that Write never returns an error |
| 55 | _, _ = h.Write(d) |
| 56 | } |
| 57 | return h.Sum(nil) |
| 58 | } |
| 59 | |
| 60 | // leafSum returns the hash created from data inserted to form a leaf. Leaf |
| 61 | // sums are calculated using: |
| 62 | // Hash(0x00 || data) |
| 63 | func leafSum(h hash.Hash, data []byte) []byte { |
| 64 | return sum(h, []byte{0}, data) |
| 65 | } |
| 66 | |
| 67 | // nodeSum returns the hash created from two sibling nodes being combined into |
| 68 | // a parent node. Node sums are calculated using: |
| 69 | // Hash(0x01 || left sibling sum || right sibling sum) |
| 70 | func nodeSum(h hash.Hash, a, b []byte) []byte { |
| 71 | return sum(h, []byte{1}, a, b) |
| 72 | } |
| 73 | |
| 74 | // joinSubTrees combines two equal sized subTrees into a larger subTree. |
| 75 | func joinSubTrees(h hash.Hash, a, b *subTree) *subTree { |
| 76 | if DEBUG { |
| 77 | if b.next != a { |
| 78 | panic("invalid subtree join - 'a' is not paired with 'b'") |
| 79 | } |
| 80 | if a.height < b.height { |
| 81 | panic("invalid subtree presented - height mismatch") |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | return &subTree{ |
| 86 | next: a.next, |
| 87 | height: a.height + 1, |
| 88 | sum: nodeSum(h, a.sum, b.sum), |
| 89 | } |
| 90 | } |
| 91 | |
| 92 | // New creates a new Tree. The provided hash will be used for all hashing |
| 93 | // operations within the Tree. |
| 94 | func New(h hash.Hash) *Tree { |
| 95 | return &Tree{ |
| 96 | hash: h, |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | // Prove creates a proof that the leaf at the established index (established by |
| 101 | // SetIndex) is an element of the Merkle tree. Prove will return a nil proof |
| 102 | // set if used incorrectly. Prove does not modify the Tree. Prove can only be |
| 103 | // called if SetIndex has been called previously. |
| 104 | func (t *Tree) Prove() (merkleRoot []byte, proofSet [][]byte, proofIndex uint64, numLeaves uint64) { |
| 105 | if !t.proofTree { |
| 106 | panic("wrong usage: can't call prove on a tree if SetIndex wasn't called") |
| 107 | } |
| 108 | |
| 109 | // Return nil if the Tree is empty, or if the proofIndex hasn't yet been |
| 110 | // reached. |
| 111 | if t.head == nil || len(t.proofSet) == 0 { |
| 112 | return t.Root(), nil, t.proofIndex, t.currentIndex |
| 113 | } |
| 114 | proofSet = t.proofSet |
| 115 | |
| 116 | // The set of subtrees must now be collapsed into a single root. The proof |
| 117 | // set already contains all of the elements that are members of a complete |
| 118 | // subtree. Of what remains, there will be at most 1 element provided from |
| 119 | // a sibling on the right, and all of the other proofs will be provided |
| 120 | // from a sibling on the left. This results from the way orphans are |
| 121 | // treated. All subtrees smaller than the subtree containing the proofIndex |
| 122 | // will be combined into a single subtree that gets combined with the |
| 123 | // proofIndex subtree as a single right sibling. All subtrees larger than |
| 124 | // the subtree containing the proofIndex will be combined with the subtree |
| 125 | // containing the proof index as left siblings. |
| 126 | |
| 127 | // Start at the smallest subtree and combine it with larger subtrees until |
| 128 | // it would be combining with the subtree that contains the proof index. We |
| 129 | // can recognize the subtree containing the proof index because the height |
| 130 | // of that subtree will be one less than the current length of the proof |
| 131 | // set. |
| 132 | current := t.head |
| 133 | for current.next != nil && current.next.height < len(proofSet)-1 { |
| 134 | current = joinSubTrees(t.hash, current.next, current) |
| 135 | } |
| 136 | |
| 137 | // Sanity check - check that either 'current' or 'current.next' is the |
| 138 | // subtree containing the proof index. |
| 139 | if DEBUG { |
| 140 | if current.height != len(t.proofSet)-1 && (current.next != nil && current.next.height != len(t.proofSet)-1) { |
| 141 | panic("could not find the subtree containing the proof index") |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | // If the current subtree is not the subtree containing the proof index, |
| 146 | // then it must be an aggregate subtree that is to the right of the subtree |
| 147 | // containing the proof index, and the next subtree is the subtree |
| 148 | // containing the proof index. |
| 149 | if current.next != nil && current.next.height == len(proofSet)-1 { |
| 150 | proofSet = append(proofSet, current.sum) |
| 151 | current = current.next |
| 152 | } |
| 153 | |
| 154 | // The current subtree must be the subtree containing the proof index. This |
| 155 | // subtree does not need an entry, as the entry was created during the |
| 156 | // construction of the Tree. Instead, skip to the next subtree. |
| 157 | current = current.next |
| 158 | |
| 159 | // All remaining subtrees will be added to the proof set as a left sibling, |
| 160 | // completing the proof set. |
| 161 | for current != nil { |
| 162 | proofSet = append(proofSet, current.sum) |
| 163 | current = current.next |
| 164 | } |
| 165 | return t.Root(), proofSet, t.proofIndex, t.currentIndex |
| 166 | } |
| 167 | |
| 168 | // Push will add data to the set, building out the Merkle tree and Root. The |
| 169 | // tree does not remember all elements that are added, instead only keeping the |
| 170 | // log(n) elements that are necessary to build the Merkle root and keeping the |
| 171 | // log(n) elements necessary to build a proof that a piece of data is in the |
| 172 | // Merkle tree. |
| 173 | func (t *Tree) Push(data []byte) { |
| 174 | // The first element of a proof is the data at the proof index. If this |
| 175 | // data is being inserted at the proof index, it is added to the proof set. |
| 176 | if t.currentIndex == t.proofIndex { |
| 177 | t.proofSet = append(t.proofSet, data) |
| 178 | } |
| 179 | |
| 180 | // Hash the data to create a subtree of height 0. The sum of the new node |
| 181 | // is going to be the data for cached trees, and is going to be the result |
| 182 | // of calling leafSum() on the data for standard trees. Doing a check here |
| 183 | // prevents needing to duplicate the entire 'Push' function for the trees. |
| 184 | t.head = &subTree{ |
| 185 | next: t.head, |
| 186 | height: 0, |
| 187 | } |
| 188 | if t.cachedTree { |
| 189 | t.head.sum = data |
| 190 | } else { |
| 191 | t.head.sum = leafSum(t.hash, data) |
| 192 | } |
| 193 | |
| 194 | // Join subTrees if possible. |
| 195 | t.joinAllSubTrees() |
| 196 | |
| 197 | // Update the index. |
| 198 | t.currentIndex++ |
| 199 | |
| 200 | // Sanity check - From head to tail of the stack, the height should be |
| 201 | // strictly increasing. |
| 202 | if DEBUG { |
| 203 | current := t.head |
| 204 | height := current.height |
| 205 | for current.next != nil { |
| 206 | current = current.next |
| 207 | if current.height <= height { |
| 208 | panic("subtrees are out of order") |
| 209 | } |
| 210 | height = current.height |
| 211 | } |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | // PushSubTree pushes a cached subtree into the merkle tree. The subtree has to |
| 216 | // be smaller than the smallest subtree in the merkle tree, it has to be |
| 217 | // balanced and it can't contain the element that needs to be proven. Since we |
| 218 | // can't tell if a subTree is balanced, we can't sanity check for unbalanced |
| 219 | // trees. Therefore an unbalanced tree will cause silent errors, pain and |
| 220 | // misery for the person who wants to debug the resulting error. |
| 221 | func (t *Tree) PushSubTree(height int, sum []byte) error { |
| 222 | // Check if the cached tree that is pushed contains the element at |
| 223 | // proofIndex. This is not allowed. |
| 224 | newIndex := t.currentIndex + 1<<uint64(height) |
| 225 | if t.proofTree && (t.currentIndex == t.proofIndex || |
| 226 | (t.currentIndex < t.proofIndex && t.proofIndex < newIndex)) { |
| 227 | return errors.New("the cached tree shouldn't contain the element to prove") |
| 228 | } |
| 229 | |
| 230 | // We can only add the cached tree if its depth is <= the depth of the |
| 231 | // current subtree. |
| 232 | if t.head != nil && height > t.head.height { |
| 233 | return errors.New("can't add a subtree that is larger than the smallest subtree") |
| 234 | } |
| 235 | |
| 236 | // Insert the cached tree as the new head. |
| 237 | t.head = &subTree{ |
| 238 | height: height, |
| 239 | next: t.head, |
| 240 | sum: sum, |
| 241 | } |
| 242 | |
| 243 | // Join subTrees if possible. |
| 244 | t.joinAllSubTrees() |
| 245 | |
| 246 | // Update the index. |
| 247 | t.currentIndex = newIndex |
| 248 | |
| 249 | // Sanity check - From head to tail of the stack, the height should be |
| 250 | // strictly increasing. |
| 251 | if DEBUG { |
| 252 | current := t.head |
| 253 | height := current.height |
| 254 | for current.next != nil { |
| 255 | current = current.next |
| 256 | if current.height <= height { |
| 257 | panic("subtrees are out of order") |
| 258 | } |
| 259 | height = current.height |
| 260 | } |
| 261 | } |
| 262 | return nil |
| 263 | } |
| 264 | |
| 265 | // Root returns the Merkle root of the data that has been pushed. |
| 266 | func (t *Tree) Root() []byte { |
| 267 | // If the Tree is empty, return nil. |
| 268 | if t.head == nil { |
| 269 | return nil |
| 270 | } |
| 271 | |
| 272 | // The root is formed by hashing together subTrees in order from least in |
| 273 | // height to greatest in height. The taller subtree is the first subtree in |
| 274 | // the join. |
| 275 | current := t.head |
| 276 | for current.next != nil { |
| 277 | current = joinSubTrees(t.hash, current.next, current) |
| 278 | } |
| 279 | return current.sum |
| 280 | } |
| 281 | |
| 282 | // SetIndex will tell the Tree to create a storage proof for the leaf at the |
| 283 | // input index. SetIndex must be called on an empty tree. |
| 284 | func (t *Tree) SetIndex(i uint64) error { |
| 285 | if t.head != nil { |
| 286 | return errors.New("cannot call SetIndex on Tree if Tree has not been reset") |
| 287 | } |
| 288 | t.proofTree = true |
| 289 | t.proofIndex = i |
| 290 | return nil |
| 291 | } |
| 292 | |
| 293 | // joinAllSubTrees inserts the subTree at t.head into the Tree. As long as the |
| 294 | // height of the next subTree is the same as the height of the current subTree, |
| 295 | // the two will be combined into a single subTree of height n+1. |
| 296 | func (t *Tree) joinAllSubTrees() { |
| 297 | for t.head.next != nil && t.head.height == t.head.next.height { |
| 298 | // Before combining subtrees, check whether one of the subtree hashes |
| 299 | // needs to be added to the proof set. This is going to be true IFF the |
| 300 | // subtrees being combined are one height higher than the previous |
| 301 | // subtree added to the proof set. The height of the previous subtree |
| 302 | // added to the proof set is equal to len(t.proofSet) - 1. |
| 303 | if t.head.height == len(t.proofSet)-1 { |
| 304 | // One of the subtrees needs to be added to the proof set. The |
| 305 | // subtree that needs to be added is the subtree that does not |
| 306 | // contain the proofIndex. Because the subtrees being compared are |
| 307 | // the smallest and rightmost trees in the Tree, this can be |
| 308 | // determined by rounding the currentIndex down to the number of |
| 309 | // nodes in the subtree and comparing that index to the proofIndex. |
| 310 | leaves := uint64(1 << uint(t.head.height)) |
| 311 | mid := (t.currentIndex / leaves) * leaves |
| 312 | if t.proofIndex < mid { |
| 313 | t.proofSet = append(t.proofSet, t.head.sum) |
| 314 | } else { |
| 315 | t.proofSet = append(t.proofSet, t.head.next.sum) |
| 316 | } |
| 317 | |
| 318 | // Sanity check - the proofIndex should never be less than the |
| 319 | // midpoint minus the number of leaves in each subtree. |
| 320 | if DEBUG { |
| 321 | if t.proofIndex < mid-leaves { |
| 322 | panic("proof being added with weird values") |
| 323 | } |
| 324 | } |
| 325 | } |
| 326 | |
| 327 | // Join the two subTrees into one subTree with a greater height. Then |
| 328 | // compare the new subTree to the next subTree. |
| 329 | t.head = joinSubTrees(t.hash, t.head.next, t.head) |
| 330 | } |
| 331 | } |