Skip to content

Commit

Permalink
fix: fixed hash arg sorting in merkle tree generation
Browse files Browse the repository at this point in the history
  • Loading branch information
clexmond committed Sep 23, 2022
1 parent 48ff4eb commit ccbfecf
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 4 deletions.
4 changes: 2 additions & 2 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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.**
Expand Down
11 changes: 11 additions & 0 deletions __tests__/utils/merkle.test.ts
Original file line number Diff line number Diff line change
@@ -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'];
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(
`"0x551b4adb6c35d49c686a00b9192da9332b18c9b262507cad0ece37f3b6918d2"`
`"0x5cdd7ef6b0b1cf28fba033a8369dec45d1d94101c0550ac8a26bd8133695e07"`
);
});

Expand Down
10 changes: 9 additions & 1 deletion src/utils/merkle.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { pedersen } from './hash';
import { toBN } from './number';

export class MerkleTree {
public leaves: string[];
Expand Down Expand Up @@ -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]);
}

Expand Down

0 comments on commit ccbfecf

Please sign in to comment.