Skip to content

invers-technology/merkle-tree-ts

Repository files navigation

Merkle Tree by Poseidon Hash with Typescript

MIT License Language npm version CI Check

A merkle tree implementation with poseidon hash and circom circuit.

Use at your own risk.

Install

$ npm i merkle-t

Usage

import { MerkleTree, LeafInputs, Leaf } from "merkle-t";
import { poseidon, randomFieldElement } from "poseidon-h";

class MyLeaf implements LeafInputs {
  private inputs: [bigint, bigint, bigint];

  constructor(inputs: [bigint, bigint, bigint]) {
    this.inputs = inputs;
  }

  hash(): Leaf {
    return poseidon(this.inputs);
  }

  zeroHash(): Leaf {
    return poseidon(this.inputs.map(() => BigInt(0)));
  }

  toInputs(): bigint[] {
    return this.inputs;
  }
}

const leaves = Array.from({ length: n }, () =>
  new TestLeaf([
    randomFieldElement(),
    randomFieldElement(),
    randomFieldElement(),
  ]).hash(),
);

const merkleTree = new MerkleTree(leaves, 3);
const proof = merkleTree.prove(leaves[13]);
const isValid = merkleTree.verify(proof);

expect(isValid).toBe(true);

Test

$ yarn test