From ccbfecfa63aa5037455405d929aea6322590d6ac Mon Sep 17 00:00:00 2001 From: Chris Lexmond Date: Fri, 23 Sep 2022 10:10:13 -0400 Subject: [PATCH] fix: fixed hash arg sorting in merkle tree generation --- CONTRIBUTING.md | 4 ++-- __tests__/utils/merkle.test.ts | 11 +++++++++++ __tests__/utils/typedData.test.ts | 2 +- src/utils/merkle.ts | 10 +++++++++- 4 files changed, 23 insertions(+), 4 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index dc49a8d6f..1682d3d6a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -19,7 +19,7 @@ ALways start from `develop` branch and merge back to `develop` branch. To build you changes run: ```bash -npm build +npm run build ``` Run linters and tests: @@ -31,7 +31,7 @@ npm test Or run tests in watch mode: ```bash -npm run test --watch +npm test --watch ``` **Don’t forget to add tests and update documentation for your changes.** diff --git a/__tests__/utils/merkle.test.ts b/__tests__/utils/merkle.test.ts index 2c1fb8764..41980d017 100644 --- a/__tests__/utils/merkle.test.ts +++ b/__tests__/utils/merkle.test.ts @@ -1,6 +1,17 @@ +import { pedersen } from '../../src/utils/hash'; import { MerkleTree, proofMerklePath } from '../../src/utils/merkle'; 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]); + + expect(merkleHash).toBe(rawHash); + }); + }); describe('generate roots', () => { test('should generate valid root for 1 elements', async () => { const leaves = ['0x1']; diff --git a/__tests__/utils/typedData.test.ts b/__tests__/utils/typedData.test.ts index 78d82b78c..1ba42f29f 100644 --- a/__tests__/utils/typedData.test.ts +++ b/__tests__/utils/typedData.test.ts @@ -72,7 +72,7 @@ describe('typedData', () => { const [, merkleTreeHash] = encodeValue({}, 'merkletree', tree.leaves); expect(merkleTreeHash).toBe(tree.root); expect(merkleTreeHash).toMatchInlineSnapshot( - `"0x551b4adb6c35d49c686a00b9192da9332b18c9b262507cad0ece37f3b6918d2"` + `"0x5cdd7ef6b0b1cf28fba033a8369dec45d1d94101c0550ac8a26bd8133695e07"` ); }); diff --git a/src/utils/merkle.ts b/src/utils/merkle.ts index 1dd288c0c..4812560f0 100644 --- a/src/utils/merkle.ts +++ b/src/utils/merkle.ts @@ -1,4 +1,5 @@ import { pedersen } from './hash'; +import { toBN } from './number'; export class MerkleTree { public leaves: string[]; @@ -31,7 +32,14 @@ export class MerkleTree { } static hash(a: string, b: string) { - const [aSorted, bSorted] = [a, b].sort(); + let aSorted = a; + let bSorted = b; + + if (toBN(aSorted) > toBN(bSorted)) { + aSorted = b; + bSorted = a; + } + return pedersen([aSorted, bSorted]); }