@gotbit/merkle
v0.1.9
Published
Merkle tree tools
Downloads
7
Readme
@gotbit/merkle
Library for work with Merkle Tree
Was choosen sorted version of Merkle Tree, with keccak256
hash function from ethers.js
Features
- Calculate root from raw leaves
- Generate proofs
- Verify proof
Examples
Root
Calculation of root
for Merkle tree you need to prepare array of leaves (hashed values)
import { calculateRoot } from '@gotbit/merkle'
const leaves = [
'0xbc45a2b14ce263793725c93e12afa83d2cc6312b9abe44ed06fb66afd4394175',
'0x67cdf3d02c0c38e81f3def6251132aaae3d70cd50a1639b039b3c87c99a6092b',
'0x85e0c2c66b77fed6c821710352651309dc3792db7db10788af32daa42706a527',
'0xdb5425be7bb655e161ff2939dfe331a07c16e42933b133c624d1dce76f66fb6b',
]
const root = calculateRoot(leaves)
Proof
Generation of proof for specific leafe
import { generateProof } from '@gotbit/merkle'
const leaves = [
'0xbc45a2b14ce263793725c93e12afa83d2cc6312b9abe44ed06fb66afd4394175',
'0x67cdf3d02c0c38e81f3def6251132aaae3d70cd50a1639b039b3c87c99a6092b',
'0x85e0c2c66b77fed6c821710352651309dc3792db7db10788af32daa42706a527',
'0xdb5425be7bb655e161ff2939dfe331a07c16e42933b133c624d1dce76f66fb6b',
]
const i = 0
const proof = generateProof(leaves, leaves[i]) // generates proof for i-leaf
Verify
To verify correctness of proof you can use typescript
or make on-chain with Merkle
solidity library
Typescript
import { generateProof, calculateRoot, verify } from '@gotbit/merkle'
const leaves = [
'0xbc45a2b14ce263793725c93e12afa83d2cc6312b9abe44ed06fb66afd4394175',
'0x67cdf3d02c0c38e81f3def6251132aaae3d70cd50a1639b039b3c87c99a6092b',
'0x85e0c2c66b77fed6c821710352651309dc3792db7db10788af32daa42706a527',
'0xdb5425be7bb655e161ff2939dfe331a07c16e42933b133c624d1dce76f66fb6b',
]
const root = calculateRoot(leaves)
const index = 0
const proof = generateProof(leaves, leaves[index]) // generates proof for i-leaf
const result = verify(proof, root, leaves[index]) // return `true` if proof is correct
Solidity
import "@gotbit/merkle/contracts/Merkle.sol";
contract Vesting {
using Merkle for bytes32[];
bytes32 ROOT;
function verify(bytes32[] memory proof) external {
bytes32 leaf = abi.encode(msg.sender);
require(proof.verify(ROOT, leaf), 'Incorrect proof');
}
}