MerkleTree.sol 7.5 KB

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