Skip to content

Commit

Permalink
fix: fixed and one-lined hash sort and added additional test case
Browse files Browse the repository at this point in the history
  • Loading branch information
clexmond committed Sep 23, 2022
1 parent ccbfecf commit 023c7c7
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 13 deletions.
12 changes: 8 additions & 4 deletions __tests__/utils/merkle.test.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
import { pedersen } from '../../src/utils/hash';
import { MerkleTree, proofMerklePath } from '../../src/utils/merkle';
import { toBN } from '../../src/utils/number';

describe('MerkleTree class', () => {
describe('calculate hashes', () => {
test('should generate hash with sorted arguments', async () => {
const leaves = ['0x12', '0xa']; // 18, 10

const merkleHash = MerkleTree.hash(leaves[0], leaves[1]);
const rawHash = pedersen([10, 18]);
let leaves = ['0x12', '0xa']; // 18, 10
let merkleHash = MerkleTree.hash(leaves[0], leaves[1]);
let rawHash = pedersen([toBN(leaves[1]), toBN(leaves[0])]);
expect(merkleHash).toBe(rawHash);

leaves = ['0x5bb9440e27889a364bcb678b1f679ecd1347acdedcbf36e83494f857cc58026', '0x3'];
merkleHash = MerkleTree.hash(leaves[0], leaves[1]);
rawHash = pedersen([toBN(leaves[1]), toBN(leaves[0])]);
expect(merkleHash).toBe(rawHash);
});
});
Expand Down
2 changes: 1 addition & 1 deletion __tests__/utils/typedData.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ describe('typedData', () => {
const [, merkleTreeHash] = encodeValue({}, 'merkletree', tree.leaves);
expect(merkleTreeHash).toBe(tree.root);
expect(merkleTreeHash).toMatchInlineSnapshot(
`"0x5cdd7ef6b0b1cf28fba033a8369dec45d1d94101c0550ac8a26bd8133695e07"`
`"0x551b4adb6c35d49c686a00b9192da9332b18c9b262507cad0ece37f3b6918d2"`
);
});

Expand Down
9 changes: 1 addition & 8 deletions src/utils/merkle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,7 @@ export class MerkleTree {
}

static hash(a: string, b: string) {
let aSorted = a;
let bSorted = b;

if (toBN(aSorted) > toBN(bSorted)) {
aSorted = b;
bSorted = a;
}

const [aSorted, bSorted] = [toBN(a), toBN(b)].sort((x: any, y: any) => (x.gte(y) ? 1 : -1));
return pedersen([aSorted, bSorted]);
}

Expand Down

0 comments on commit 023c7c7

Please sign in to comment.