MerkleTreeMock.sol 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // SPDX-License-Identifier: MIT
  2. pragma solidity ^0.8.20;
  3. import {MerkleTree} from "../utils/structs/MerkleTree.sol";
  4. contract MerkleTreeMock {
  5. using MerkleTree for MerkleTree.Bytes32PushTree;
  6. MerkleTree.Bytes32PushTree private _tree;
  7. // This mock only stored the latest root.
  8. // Production contract may want to store historical values.
  9. bytes32 public root;
  10. event LeafInserted(bytes32 leaf, uint256 index, bytes32 root);
  11. event LeafUpdated(bytes32 oldLeaf, bytes32 newLeaf, uint256 index, bytes32 root);
  12. function setup(uint8 _depth, bytes32 _zero) public {
  13. root = _tree.setup(_depth, _zero);
  14. }
  15. function push(bytes32 leaf) public {
  16. (uint256 leafIndex, bytes32 currentRoot) = _tree.push(leaf);
  17. emit LeafInserted(leaf, leafIndex, currentRoot);
  18. root = currentRoot;
  19. }
  20. function update(uint256 index, bytes32 oldValue, bytes32 newValue, bytes32[] memory proof) public {
  21. (bytes32 oldRoot, bytes32 newRoot) = _tree.update(index, oldValue, newValue, proof);
  22. if (oldRoot != root) revert MerkleTree.MerkleTreeUpdateInvalidProof();
  23. emit LeafUpdated(oldValue, newValue, index, newRoot);
  24. root = newRoot;
  25. }
  26. function depth() public view returns (uint256) {
  27. return _tree.depth();
  28. }
  29. // internal state
  30. function nextLeafIndex() public view returns (uint256) {
  31. return _tree._nextLeafIndex;
  32. }
  33. function sides(uint256 i) public view returns (bytes32) {
  34. return _tree._sides[i];
  35. }
  36. function zeros(uint256 i) public view returns (bytes32) {
  37. return _tree._zeros[i];
  38. }
  39. }