Skip to content

Commit

Permalink
fix(slashing-protection): resolve minEpoch max call stack issue (#5461
Browse files Browse the repository at this point in the history
)

Epochs array might have more than ~10^5 elements, cannot use `Math.min`
as it would throw `RangeError: Maximum call stack size exceeded`.
  • Loading branch information
nflaig committed May 5, 2023
1 parent 65cf9e2 commit 81b9998
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
2 changes: 1 addition & 1 deletion packages/validator/src/slashingProtection/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export function numToString(num: number): string {
}

export function minEpoch(epochs: Epoch[]): Epoch | null {
return epochs.length > 0 ? Math.min(...epochs) : null;
return epochs.length > 0 ? epochs.reduce((minEpoch, epoch) => (minEpoch < epoch ? minEpoch : epoch)) : null;
}

export function uniqueVectorArr(buffers: Uint8Array[]): Uint8Array[] {
Expand Down
20 changes: 20 additions & 0 deletions packages/validator/test/unit/slashingProtection/utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import {expect} from "chai";
import {minEpoch} from "../../../src/slashingProtection/utils.js";

describe("slashingProtection / utils / minEpoch", () => {
it("should return the minimum epoch from an array of epochs", () => {
expect(minEpoch([15, 10, 20, 30, 5, 1, 50])).to.equal(1);
});

it("should return the only epoch if epochs array only contains one element", () => {
expect(minEpoch([10])).to.equal(10);
});

it("should return null if epochs array is empty", () => {
expect(minEpoch([])).to.equal(null);
});

it("should not throw 'RangeError: Maximum call stack size exceeded' for huge epoch arrays", () => {
expect(() => minEpoch(Array.from({length: 1e6}, (_, index) => index))).to.not.throw(RangeError);
});
});

0 comments on commit 81b9998

Please sign in to comment.