import { BytesLike, HexString, toHex } from './bytes'; import { MultiProof, processProof, processMultiProof } from './core'; import { MerkleTreeData, MerkleTreeImpl } from './merkletree'; import { MerkleTreeOptions } from './options'; import { standardLeafHash } from './hashes'; import { validateArgument } from './utils/errors'; export interface StandardMerkleTreeData extends MerkleTreeData { format: 'standard-v1'; leafEncoding: string[]; } export class StandardMerkleTree extends MerkleTreeImpl { protected constructor( protected readonly tree: HexString[], protected readonly values: StandardMerkleTreeData['values'], protected readonly leafEncoding: string[], ) { super(tree, values, leaf => standardLeafHash(leafEncoding, leaf)); } static of( values: T[], leafEncoding: string[], options: MerkleTreeOptions = {}, ): StandardMerkleTree { // use default nodeHash (standardNodeHash) const [tree, indexedValues] = MerkleTreeImpl.prepare(values, options, leaf => standardLeafHash(leafEncoding, leaf)); return new StandardMerkleTree(tree, indexedValues, leafEncoding); } static load(data: StandardMerkleTreeData): StandardMerkleTree { validateArgument(data.format === 'standard-v1', `Unknown format '${data.format}'`); validateArgument(data.leafEncoding !== undefined, 'Expected leaf encoding'); const tree = new StandardMerkleTree(data.tree, data.values, data.leafEncoding); tree.validate(); return tree; } static verify(root: BytesLike, leafEncoding: string[], leaf: T, proof: BytesLike[]): boolean { // use default nodeHash (standardNodeHash) for processProof return toHex(root) === processProof(standardLeafHash(leafEncoding, leaf), proof); } static verifyMultiProof( root: BytesLike, leafEncoding: string[], multiproof: MultiProof, ): boolean { // use default nodeHash (standardNodeHash) for processMultiProof return ( toHex(root) === processMultiProof({ leaves: multiproof.leaves.map(leaf => standardLeafHash(leafEncoding, leaf)), proof: multiproof.proof, proofFlags: multiproof.proofFlags, }) ); } dump(): StandardMerkleTreeData { return { format: 'standard-v1', leafEncoding: this.leafEncoding, tree: this.tree, values: this.values, }; } }