Skip to content

Commit

Permalink
fix(slashing-protection): more robust solution to determine min epoch
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 4, 2023
1 parent 597996a commit b532921
Show file tree
Hide file tree
Showing 2 changed files with 29 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
28 changes: 28 additions & 0 deletions packages/validator/test/unit/slashingProtection/utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import {expect} from "chai";
import {Epoch} from "@lodestar/types";
import {minEpoch} from "../../../src/slashingProtection/utils.js";

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

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

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

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

0 comments on commit b532921

Please sign in to comment.