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

fix(relayer): Ensure argument keys are sorted before hashing #2061

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion src/utils/EventUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -216,8 +216,26 @@ export class EventManager {
*/
hashEvent(event: Log): string {
const { event: eventName, blockNumber, blockHash, transactionHash, transactionIndex, logIndex, args } = event;
const _args = Object.values(args).join("-");
const _args = this.flattenObject(args);
const key = `${eventName}-${blockNumber}-${blockHash}-${transactionHash}-${transactionIndex}-${logIndex}-${_args}`;
return ethersUtils.id(key);
}

/**
* Recurse through an object and sort its keys in order to produce an ordered string of values.
* @param obj Object to iterate through.
* @returns string A hyphenated string containing all arguments of the object, sorted by key.
*/
private flattenObject(obj: Record<string, unknown>): string {
const args = Object.keys(obj)
.sort()
.map((k) => {
const val = obj[k];
// When val is a nested object, recursively flatten and stringify it.
return typeof val === "object" ? this.flattenObject(val as Record<string, unknown>) : val;
})
.join("-");

return args;
}
}
41 changes: 40 additions & 1 deletion test/EventManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ describe("EventManager: Event Handling ", async function () {
expect(events.length).to.equal(0);
});

it("Hashes events correctly", async function () {
it("Hashes events correctly: uniqueness", async function () {
const log1 = eventTemplate;
const hash1 = eventMgr.hashEvent(log1);
expect(hash1).to.exist;
Expand All @@ -130,6 +130,45 @@ describe("EventManager: Event Handling ", async function () {
expect(hash3).to.equal(hash1);
});

it("Hashes events correctly: sorting", async function () {
const log = {
...eventTemplate,
args: {
c: 3,
b: 2,
f: {
h: 7,
i: 8,
g: 6,
},
a: 1,
d: 4,
e: 5,
},
};
const sortedLog = {
...log,
args: {
a: 1,
b: 2,
c: 3,
d: 4,
e: 5,
f: {
g: 6,
h: 7,
i: 8,
},
},
};

const hash1 = eventMgr.hashEvent(log);
expect(hash1).to.exist;

const hash2 = eventMgr.hashEvent(sortedLog);
expect(hash2).to.equal(hash1);
});

it("Does not submit duplicate events", async function () {
expect(quorum).to.equal(2);

Expand Down