MerkleTree.sol 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. // SPDX-License-Identifier: MIT
  2. pragma solidity ^0.8.20;
  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**treeDepth`.
  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 treeDepth, bytes32 zero) internal returns (bytes32 initialRoot) {
  59. return setup(self, treeDepth, 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.
  69. *
  70. * NOTE: Consider verifying that the hashing function does not manipulate the memory state directly and that it
  71. * follows the Solidity memory safety rules. Otherwise, it may lead to unexpected behavior.
  72. */
  73. function setup(
  74. Bytes32PushTree storage self,
  75. uint8 treeDepth,
  76. bytes32 zero,
  77. function(bytes32, bytes32) view returns (bytes32) fnHash
  78. ) internal returns (bytes32 initialRoot) {
  79. // Store depth in the dynamic array
  80. Arrays.unsafeSetLength(self._sides, treeDepth);
  81. Arrays.unsafeSetLength(self._zeros, treeDepth);
  82. // Build each root of zero-filled subtrees
  83. bytes32 currentZero = zero;
  84. for (uint32 i = 0; i < treeDepth; ++i) {
  85. Arrays.unsafeAccess(self._zeros, i).value = currentZero;
  86. currentZero = fnHash(currentZero, currentZero);
  87. }
  88. // Set the first root
  89. self._nextLeafIndex = 0;
  90. return currentZero;
  91. }
  92. /**
  93. * @dev Insert a new leaf in the tree, and compute the new root. Returns the position of the inserted leaf in the
  94. * tree, and the resulting root.
  95. *
  96. * Hashing the leaf before calling this function is recommended as a protection against
  97. * second pre-image attacks.
  98. *
  99. * This variant uses {Hashes-commutativeKeccak256} to hash internal nodes. It should only be used on merkle trees
  100. * that were setup using the same (default) hashing function (i.e. by calling
  101. * {xref-MerkleTree-setup-struct-MerkleTree-Bytes32PushTree-uint8-bytes32-}[the default setup] function).
  102. */
  103. function push(Bytes32PushTree storage self, bytes32 leaf) internal returns (uint256 index, bytes32 newRoot) {
  104. return push(self, leaf, Hashes.commutativeKeccak256);
  105. }
  106. /**
  107. * @dev Insert a new leaf in the tree, and compute the new root. Returns the position of the inserted leaf in the
  108. * tree, and the resulting root.
  109. *
  110. * Hashing the leaf before calling this function is recommended as a protection against
  111. * second pre-image attacks.
  112. *
  113. * This variant uses a custom hashing function to hash internal nodes. It should only be called with the same
  114. * function as the one used during the initial setup of the merkle tree.
  115. */
  116. function push(
  117. Bytes32PushTree storage self,
  118. bytes32 leaf,
  119. function(bytes32, bytes32) view returns (bytes32) fnHash
  120. ) internal returns (uint256 index, bytes32 newRoot) {
  121. // Cache read
  122. uint256 treeDepth = depth(self);
  123. // Get leaf index
  124. index = self._nextLeafIndex++;
  125. // Check if tree is full.
  126. if (index >= 1 << treeDepth) {
  127. Panic.panic(Panic.RESOURCE_ERROR);
  128. }
  129. // Rebuild branch from leaf to root
  130. uint256 currentIndex = index;
  131. bytes32 currentLevelHash = leaf;
  132. for (uint32 i = 0; i < treeDepth; i++) {
  133. // Reaching the parent node, is currentLevelHash the left child?
  134. bool isLeft = currentIndex % 2 == 0;
  135. // If so, next time we will come from the right, so we need to save it
  136. if (isLeft) {
  137. Arrays.unsafeAccess(self._sides, i).value = currentLevelHash;
  138. }
  139. // Compute the current node hash by using the hash function
  140. // with either its sibling (side) or the zero value for that level.
  141. currentLevelHash = fnHash(
  142. isLeft ? currentLevelHash : Arrays.unsafeAccess(self._sides, i).value,
  143. isLeft ? Arrays.unsafeAccess(self._zeros, i).value : currentLevelHash
  144. );
  145. // Update node index
  146. currentIndex >>= 1;
  147. }
  148. return (index, currentLevelHash);
  149. }
  150. /**
  151. * @dev Tree's depth (set at initialization)
  152. */
  153. function depth(Bytes32PushTree storage self) internal view returns (uint256) {
  154. return self._zeros.length;
  155. }
  156. }