Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a 'sortLeaves' options #29

Merged
merged 18 commits into from
Jan 10, 2024
5 changes: 3 additions & 2 deletions src/standard.test.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import assert from 'assert/strict';
import { keccak256 } from 'ethereum-cryptography/keccak';
import { hex } from './bytes';
import { StandardMerkleTree, StandardMerkleTreeOptions } from './standard';
import { MerkleTreeOptions } from './options';
Amxx marked this conversation as resolved.
Show resolved Hide resolved
import { StandardMerkleTree } from './standard';

const zeroBytes = new Uint8Array(32);
const zero = hex(zeroBytes);

const makeTree = (s: string, opts: StandardMerkleTreeOptions = {}) => {
const makeTree = (s: string, opts: MerkleTreeOptions = {}) => {
const l = s.split('').map(c => [c]);
const t = StandardMerkleTree.of(l, ['string'], opts);
return { l, t };
Expand Down
16 changes: 3 additions & 13 deletions src/standard.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,11 @@
import { equalsBytes, hexToBytes } from 'ethereum-cryptography/utils';
import { Bytes, compareBytes, hex } from './bytes';
import { getProof, isValidMerkleTree, makeMerkleTree, processProof, renderMerkleTree, MultiProof, getMultiProof, processMultiProof } from './core';
import { MerkleTreeOptions, withDefault } from './options';
import { checkBounds } from './utils/check-bounds';
import { throwError } from './utils/throw-error';
import { standardLeafHash } from './utils/standard-leaf-hash';

// MerkleTree building options
export type StandardMerkleTreeOptions = Partial<{
sortLeaves: boolean;
}>;

// For backward compatibility reasons, leaves are sorted by default.
// This can be disabled for usecases where leaves ordering needs to be preserved
const defaultOptions: Required<StandardMerkleTreeOptions> = {
sortLeaves: true,
};

interface StandardMerkleTreeData<T extends any[]> {
format: 'standard-v1';
tree: string[];
Expand All @@ -41,8 +31,8 @@ export class StandardMerkleTree<T extends any[]> {
]));
}

static of<T extends any[]>(values: T[], leafEncoding: string[], options: StandardMerkleTreeOptions = {}) {
const { sortLeaves } = { ...defaultOptions, ...options };
static of<T extends any[]>(values: T[], leafEncoding: string[], options: MerkleTreeOptions = {}) {
const { sortLeaves } = withDefault(options);

const hashedValues = values.map((value, valueIndex) => ({ value, valueIndex, hash: standardLeafHash(value, leafEncoding) }));

Expand Down
Loading