Skip to content

Instantly share code, notes, and snippets.

@a2468834
Created January 3, 2023 07:48
Show Gist options
  • Save a2468834/7864d072377c0ae917219a9167431a81 to your computer and use it in GitHub Desktop.
Save a2468834/7864d072377c0ae917219a9167431a81 to your computer and use it in GitHub Desktop.
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.17;
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
contract C {
struct MerkleRoot {
bytes32 data;
bytes32 signatures;
}
event AppendNewMerkleRoots(uint64 indexed batchIndex, bytes32 dataMerkleRoot, bytes32 sigMerkleRoot);
mapping(uint64 => MerkleRoot) public rootHistory;
function update(uint64 batchIndex, bytes32 dataMerkleRoot, bytes32 sigMerkleRoot) public {
MerkleRoot memory new_value = MerkleRoot({
data: dataMerkleRoot,
signatures: sigMerkleRoot
});
MerkleRoot storage old_value = rootHistory[batchIndex];
if((old_value.data != bytes32(0)) || (old_value.signatures != bytes32(0))) {
revert("Cannot override an existed MerkleRoot slot");
}
else {
rootHistory[batchIndex] = new_value;
}
emit AppendNewMerkleRoots(batchIndex, dataMerkleRoot, sigMerkleRoot);
}
function verifyData(bytes32[] calldata proof, uint64 batchIndex, bytes32 leafData) public view returns (bool) {
MerkleRoot storage merkleRoots = rootHistory[batchIndex];
if((merkleRoots.data == bytes32(0)) && (merkleRoots.signatures == bytes32(0))) {
return false; // There is no Merkle root at the given `batchIndex`.
}
else {
bytes32 leaf = keccak256(bytes.concat(keccak256(abi.encode(batchIndex, leafData))));
bytes32 root = merkleRoots.data;
return MerkleProof.verifyCalldata(
proof,
root,
leaf
);
}
}
function verifySig(bytes32[] calldata proof, uint64 batchIndex, bytes32 leafSig) public view returns (bool) {
MerkleRoot storage merkleRoots = rootHistory[batchIndex];
if((merkleRoots.data == bytes32(0)) && (merkleRoots.signatures == bytes32(0))) {
return false; // There is no Merkle root at the given `batchIndex`.
}
else {
bytes32 leaf = keccak256(bytes.concat(keccak256(abi.encode(batchIndex, leafSig))));
bytes32 root = merkleRoots.signatures;
return MerkleProof.verifyCalldata(
proof,
root,
leaf
);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment