MerkleTree.sol 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. // SPDX-License-Identifier: MIT
  2. pragma solidity ^0.8.0;
  3. import {Hashes} from "../cryptography/Hashes.sol";
  4. import {Arrays} from "../Arrays.sol";
  5. import {Panic} from "../Panic.sol";
  6. /**
  7. * @dev Library for managing https://wikipedia.org/wiki/Merkle_Tree[Merkle Tree] data structures.
  8. *
  9. * Each tree is a complete binary tree with the ability to sequentially insert leaves, changing them from a zero to a
  10. * non-zero value and updating its root. This structure allows inserting commitments (or other entries) that are not
  11. * stored, but can be proven to be part of the tree at a later time if the root is kept. See {MerkleProof}.
  12. *
  13. * A tree is defined by the following parameters:
  14. *
  15. * * Depth: The number of levels in the tree, it also defines the maximum number of leaves as 2**depth.
  16. * * Zero value: The value that represents an empty leaf. Used to avoid regular zero values to be part of the tree.
  17. * * Hashing function: A cryptographic hash function used to produce internal nodes. Defaults to {Hashes-commutativeKeccak256}.
  18. *
  19. * NOTE: Building trees using non-commutative hashing functions (i.e. `H(a, b) != H(b, a)`) is supported. However,
  20. * proving the inclusion of a leaf in such trees is not possible with the {MerkleProof} library since it only supports
  21. * _commutative_ hashing functions.
  22. *
  23. * _Available since v5.1._
  24. */
  25. library MerkleTree {
  26. /**
  27. * @dev A complete `bytes32` Merkle tree.
  28. *
  29. * The `sides` and `zero` arrays are set to have a length equal to the depth of the tree during setup.
  30. *
  31. * Struct members have an underscore prefix indicating that they are "private" and should not be read or written to
  32. * directly. Use the functions provided below instead. Modifying the struct manually may violate assumptions and
  33. * lead to unexpected behavior.
  34. *
  35. * NOTE: The `root` and the updates history is not stored within the tree. Consider using a secondary structure to
  36. * store a list of historical roots from the values returned from {setup} and {push} (e.g. a mapping, {BitMaps} or
  37. * {Checkpoints}).
  38. *
  39. * WARNING: Updating any of the tree's parameters after the first insertion will result in a corrupted tree.
  40. */
  41. struct Bytes32PushTree {
  42. uint256 _nextLeafIndex;
  43. bytes32[] _sides;
  44. bytes32[] _zeros;
  45. }
  46. /**
  47. * @dev Initialize a {Bytes32PushTree} using {Hashes-commutativeKeccak256} to hash internal nodes.
  48. * The capacity of the tree (i.e. number of leaves) is set to `2**levels`.
  49. *
  50. * Calling this function on MerkleTree that was already setup and used will reset it to a blank state.
  51. *
  52. * Once a tree is setup, any push to it must use the same hashing function. This means that values
  53. * should be pushed to it using the default {xref-MerkleTree-push-struct-MerkleTree-Bytes32PushTree-bytes32-}[push] function.
  54. *
  55. * IMPORTANT: The zero value should be carefully chosen since it will be stored in the tree representing
  56. * empty leaves. It should be a value that is not expected to be part of the tree.
  57. */
  58. function setup(Bytes32PushTree storage self, uint8 levels, bytes32 zero) internal returns (bytes32 initialRoot) {
  59. return setup(self, levels, zero, Hashes.commutativeKeccak256);
  60. }
  61. /**
  62. * @dev Same as {xref-MerkleTree-setup-struct-MerkleTree-Bytes32PushTree-uint8-bytes32-}[setup], but allows to specify a custom hashing function.
  63. *
  64. * Once a tree is setup, any push to it must use the same hashing function. This means that values
  65. * should be pushed to it using the custom push function, which should be the same one as used during the setup.
  66. *
  67. * IMPORTANT: Providing a custom hashing function is a security-sensitive operation since it may
  68. * compromise the soundness of the tree. Consider using functions from {Hashes}.
  69. */
  70. function setup(
  71. Bytes32PushTree storage self,
  72. uint8 levels,
  73. bytes32 zero,
  74. function(bytes32, bytes32) view returns (bytes32) fnHash
  75. ) internal returns (bytes32 initialRoot) {
  76. // Store depth in the dynamic array
  77. Arrays.unsafeSetLength(self._sides, levels);
  78. Arrays.unsafeSetLength(self._zeros, levels);
  79. // Build each root of zero-filled subtrees
  80. bytes32 currentZero = zero;
  81. for (uint32 i = 0; i < levels; ++i) {
  82. Arrays.unsafeAccess(self._zeros, i).value = currentZero;
  83. currentZero = fnHash(currentZero, currentZero);
  84. }
  85. // Set the first root
  86. self._nextLeafIndex = 0;
  87. return currentZero;
  88. }
  89. /**
  90. * @dev Insert a new leaf in the tree, and compute the new root. Returns the position of the inserted leaf in the
  91. * tree, and the resulting root.
  92. *
  93. * Hashing the leaf before calling this function is recommended as a protection against
  94. * second pre-image attacks.
  95. *
  96. * This variant uses {Hashes-commutativeKeccak256} to hash internal nodes. It should only be used on merkle trees
  97. * that were setup using the same (default) hashing function (i.e. by calling
  98. * {xref-MerkleTree-setup-struct-MerkleTree-Bytes32PushTree-uint8-bytes32-}[the default setup] function).
  99. */
  100. function push(Bytes32PushTree storage self, bytes32 leaf) internal returns (uint256 index, bytes32 newRoot) {
  101. return push(self, leaf, Hashes.commutativeKeccak256);
  102. }
  103. /**
  104. * @dev Insert a new leaf in the tree, and compute the new root. Returns the position of the inserted leaf in the
  105. * tree, and the resulting root.
  106. *
  107. * Hashing the leaf before calling this function is recommended as a protection against
  108. * second pre-image attacks.
  109. *
  110. * This variant uses a custom hashing function to hash internal nodes. It should only be called with the same
  111. * function as the one used during the initial setup of the merkle tree.
  112. */
  113. function push(
  114. Bytes32PushTree storage self,
  115. bytes32 leaf,
  116. function(bytes32, bytes32) view returns (bytes32) fnHash
  117. ) internal returns (uint256 index, bytes32 newRoot) {
  118. // Cache read
  119. uint256 levels = self._zeros.length;
  120. // Get leaf index
  121. index = self._nextLeafIndex++;
  122. // Check if tree is full.
  123. if (index >= 1 << levels) {
  124. Panic.panic(Panic.RESOURCE_ERROR);
  125. }
  126. // Rebuild branch from leaf to root
  127. uint256 currentIndex = index;
  128. bytes32 currentLevelHash = leaf;
  129. for (uint32 i = 0; i < levels; i++) {
  130. // Reaching the parent node, is currentLevelHash the left child?
  131. bool isLeft = currentIndex % 2 == 0;
  132. // If so, next time we will come from the right, so we need to save it
  133. if (isLeft) {
  134. Arrays.unsafeAccess(self._sides, i).value = currentLevelHash;
  135. }
  136. // Compute the current node hash by using the hash function
  137. // with either its sibling (side) or the zero value for that level.
  138. currentLevelHash = fnHash(
  139. isLeft ? currentLevelHash : Arrays.unsafeAccess(self._sides, i).value,
  140. isLeft ? Arrays.unsafeAccess(self._zeros, i).value : currentLevelHash
  141. );
  142. // Update node index
  143. currentIndex >>= 1;
  144. }
  145. return (index, currentLevelHash);
  146. }
  147. /**
  148. * @dev Tree's depth (set at initialization)
  149. */
  150. function depth(Bytes32PushTree storage self) internal view returns (uint256) {
  151. return self._zeros.length;
  152. }
  153. }