Skip to content

Instantly share code, notes, and snippets.

@0xAnon101
Last active July 10, 2022 15:59
Show Gist options
  • Select an option

  • Save 0xAnon101/575a6b8dd63461c3e1acc4e516605d80 to your computer and use it in GitHub Desktop.

Select an option

Save 0xAnon101/575a6b8dd63461c3e1acc4e516605d80 to your computer and use it in GitHub Desktop.
Merkle verification for random txn
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
/// @title A simple contract named MerkleTrie
/// @author 0xAnon101
/// @notice Shows you the functioning of Merkle Trie. Not meant to be used in Production environment
/// due to high gas cost in this demo methodology. It is here just to understand the underlining
/// structure of Merkle Trie.
/// @dev Implementaion using custom string based array which includes sample transactions.
contract MerkleTrie {
bytes32[] public hashes;
string[8] transactions = [
"T1: A -> B",
"T2: B -> C",
"T3: D -> E",
"T4: B -> E",
"T5: A -> B",
"T6: B -> C",
"T7: D -> E",
"T8: B -> E"
];
constructor() {
for (uint256 i = 0; i < transactions.length; i++) {
hashes.push(_makeHash(transactions[i]));
}
uint256 leaves = transactions.length; // number of leaves
uint256 offset = 0;
while (leaves > 0) {
for (uint256 i = 0; i < leaves - 1; i += 2) {
hashes.push(
keccak256(
abi.encodePacked(
hashes[offset + i],
hashes[offset + i + 1]
)
)
);
}
offset += leaves;
leaves = leaves / 2;
}
}
function verify(
string memory transaction,
uint256 index,
bytes32 root,
bytes32[] memory proof
) public pure returns (bool) {
bytes32 hash = _makeHash(transaction);
for (uint256 i = 0; i < proof.length; i++) {
bytes32 element = proof[i];
if (index % 2 == 0) {
hash = keccak256(abi.encodePacked(hash, element));
} else {
hash = keccak256(abi.encodePacked(element, hash));
}
index = index / 2;
}
return hash == root;
}
function _makeHash(string memory input) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(input));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment