MerkleTree.sol 7.1 KB

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