@lodestar/fork-choice 1.52.0-dev.0f379f3b22 → 1.52.0-dev.119f1f9fe6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/lib/forkChoice/fastConfirmation/data.d.ts.map +1 -1
  2. package/lib/forkChoice/fastConfirmation/data.js +3 -2
  3. package/lib/forkChoice/fastConfirmation/data.js.map +1 -1
  4. package/lib/forkChoice/fastConfirmation/types.d.ts +30 -4
  5. package/lib/forkChoice/fastConfirmation/types.d.ts.map +1 -1
  6. package/lib/forkChoice/fastConfirmation/types.js.map +1 -1
  7. package/lib/forkChoice/fastConfirmation/utils.d.ts +13 -15
  8. package/lib/forkChoice/fastConfirmation/utils.d.ts.map +1 -1
  9. package/lib/forkChoice/fastConfirmation/utils.js +189 -119
  10. package/lib/forkChoice/fastConfirmation/utils.js.map +1 -1
  11. package/lib/forkChoice/forkChoice.d.ts +4 -2
  12. package/lib/forkChoice/forkChoice.d.ts.map +1 -1
  13. package/lib/forkChoice/forkChoice.js +13 -3
  14. package/lib/forkChoice/forkChoice.js.map +1 -1
  15. package/lib/forkChoice/interface.d.ts +3 -1
  16. package/lib/forkChoice/interface.d.ts.map +1 -1
  17. package/lib/protoArray/errors.d.ts +8 -10
  18. package/lib/protoArray/errors.d.ts.map +1 -1
  19. package/lib/protoArray/errors.js +7 -7
  20. package/lib/protoArray/errors.js.map +1 -1
  21. package/lib/protoArray/protoArray.d.ts +9 -8
  22. package/lib/protoArray/protoArray.d.ts.map +1 -1
  23. package/lib/protoArray/protoArray.js +33 -23
  24. package/lib/protoArray/protoArray.js.map +1 -1
  25. package/package.json +8 -8
  26. package/src/forkChoice/fastConfirmation/data.ts +3 -2
  27. package/src/forkChoice/fastConfirmation/types.ts +28 -4
  28. package/src/forkChoice/fastConfirmation/utils.ts +241 -167
  29. package/src/forkChoice/forkChoice.ts +13 -7
  30. package/src/forkChoice/interface.ts +3 -1
  31. package/src/protoArray/errors.ts +8 -5
  32. package/src/protoArray/protoArray.ts +32 -22
@@ -1,37 +1,36 @@
1
- import {SLOTS_PER_EPOCH} from "@lodestar/params";
1
+ import {EFFECTIVE_BALANCE_INCREMENT, SLOTS_PER_EPOCH} from "@lodestar/params";
2
2
  import {
3
3
  EffectiveBalanceIncrements,
4
4
  IBeaconStateView,
5
5
  computeEpochAtSlot,
6
- computeSlotsSinceEpochStart,
7
6
  computeStartSlotAtEpoch,
8
7
  isActiveValidator,
9
8
  isStartSlotOfEpoch,
10
9
  } from "@lodestar/state-transition";
11
- import {Epoch, RootHex, Slot, ValidatorIndex} from "@lodestar/types";
10
+ import {Epoch, RootHex, Slot} from "@lodestar/types";
12
11
  import {Logger, fromHex} from "@lodestar/utils";
13
12
  import {ExecutionStatus, PayloadStatus, ProtoBlock} from "../../protoArray/interface.js";
14
13
  import {CheckpointWithHex, computeTotalBalance, equalCheckpointWithHex} from "../store.js";
15
14
  import {
15
+ ActiveBalances,
16
+ type BalanceSourceCacheKey,
16
17
  type BalanceSourceKey,
18
+ CommitteeSweep,
17
19
  FastConfirmationBalanceSource,
18
20
  FastConfirmationCache,
19
21
  FastConfirmationContext,
20
22
  FastConfirmationSnapshot,
21
23
  IFastConfirmationStore,
22
- type TotalActiveBalanceCacheKey,
23
24
  } from "./types.js";
24
25
 
25
- // Spec: adjust_committee_weight_estimate_to_ensure_safety
26
- // https://github.com/ethereum/consensus-specs/blob/master/specs/phase0/fast-confirmation.md#adjust_committee_weight_estimate_to_ensure_safety
27
- const COMMITTEE_WEIGHT_ESTIMATION_ADJUSTMENT_FACTOR = 5;
26
+ const EFFECTIVE_BALANCE_INCREMENT_BIGINT = BigInt(EFFECTIVE_BALANCE_INCREMENT);
28
27
 
29
28
  const SAFETY_THRESHOLD_UNREACHABLE = Object.freeze({
30
- threshold: Number.POSITIVE_INFINITY,
31
- proposerScore: 0,
32
- maximumSupport: 0,
33
- supportDiscount: 0,
34
- adversarialWeight: 0,
29
+ threshold: 2n ** 64n,
30
+ proposerScore: 0n,
31
+ maximumSupport: 0n,
32
+ supportDiscount: 0n,
33
+ adversarialWeight: 0n,
35
34
  });
36
35
 
37
36
  export function getBlock(ctx: FastConfirmationContext, cache: FastConfirmationCache, root: RootHex): ProtoBlock | null {
@@ -180,25 +179,43 @@ export function getCheckpointState(
180
179
  return state ?? null;
181
180
  }
182
181
 
183
- export function getSlotCommittee(
182
+ /**
183
+ * Spec: get_slot_committee, for the slots `startSlot..endSlot`.
184
+ * Chain-walk queries ending at `current_slot - 1` share this sweep across many start slots.
185
+ * Extending it backwards avoids rebuilding a union of up to the full validator set per block.
186
+ */
187
+ function getCommitteeSweep(
188
+ ctx: FastConfirmationContext,
189
+ store: IFastConfirmationStore,
184
190
  cache: FastConfirmationCache,
185
- state: IBeaconStateView,
186
- slot: Slot
187
- ): Set<ValidatorIndex> {
188
- if (cache.committeeBySlot.has(slot)) {
189
- return cache.committeeBySlot.get(slot) ?? new Set();
190
- }
191
- const epoch = computeEpochAtSlot(slot);
192
- const committeesCount = state.getBeaconCommitteeCountPerSlot(epoch);
193
- const participants = new Set<ValidatorIndex>();
194
- for (let i = 0; i < committeesCount; i++) {
195
- const committee = state.getBeaconCommittee(slot, i);
196
- for (const index of committee) {
197
- participants.add(index);
191
+ startSlot: Slot,
192
+ endSlot: Slot
193
+ ): CommitteeSweep {
194
+ const headState = getHeadState(ctx, store, cache);
195
+ let sweep = cache.committeeSweepByEndSlot.get(endSlot);
196
+ if (sweep === undefined) {
197
+ sweep = {
198
+ seen: new Uint8Array(headState.validatorCount),
199
+ order: new Uint32Array(headState.validatorCount),
200
+ lengths: [],
201
+ weightsByKey: new Map(),
202
+ };
203
+ cache.committeeSweepByEndSlot.set(endSlot, sweep);
204
+ }
205
+
206
+ let length = sweep.lengths.at(-1) ?? 0;
207
+ for (let slot = endSlot - sweep.lengths.length; slot >= startSlot; slot--) {
208
+ const committeesCount = headState.getBeaconCommitteeCountPerSlot(computeEpochAtSlot(slot));
209
+ for (let i = 0; i < committeesCount; i++) {
210
+ for (const index of headState.getBeaconCommittee(slot, i)) {
211
+ if (sweep.seen[index] === 1) continue;
212
+ sweep.seen[index] = 1;
213
+ sweep.order[length++] = index;
214
+ }
198
215
  }
216
+ sweep.lengths.push(length);
199
217
  }
200
- cache.committeeBySlot.set(slot, participants);
201
- return participants;
218
+ return sweep;
202
219
  }
203
220
 
204
221
  function getSlotRangeParticipants(
@@ -207,17 +224,47 @@ function getSlotRangeParticipants(
207
224
  cache: FastConfirmationCache,
208
225
  startSlot: Slot,
209
226
  endSlot: Slot
210
- ): Set<ValidatorIndex> {
211
- const participants = new Set<ValidatorIndex>();
212
- const headState = getHeadState(ctx, store, cache);
213
-
214
- for (let slot = startSlot; slot <= endSlot; slot++) {
215
- for (const index of getSlotCommittee(cache, headState, slot)) {
216
- participants.add(index);
227
+ ): Uint32Array {
228
+ // Empty-slot discounts end at different block slots. A sweep per endpoint would allocate
229
+ // 5 bytes per registered validator for each gap, even when the gap spans just one slot.
230
+ // Cache compact participants instead, shared by support and adversarial-weight calculations.
231
+ if (endSlot !== ctx.getCurrentSlot() - 1) {
232
+ const key = `${startSlot}:${endSlot}`;
233
+ const cached = cache.participantsByRange.get(key);
234
+ if (cached !== undefined) return cached;
235
+
236
+ const state = getHeadState(ctx, store, cache);
237
+ const committees: Uint32Array[] = [];
238
+ let length = 0;
239
+ for (let slot = startSlot; slot <= endSlot; slot++) {
240
+ const count = state.getBeaconCommitteeCountPerSlot(computeEpochAtSlot(slot));
241
+ for (let i = 0; i < count; i++) {
242
+ const committee = state.getBeaconCommittee(slot, i);
243
+ committees.push(committee);
244
+ length += committee.length;
245
+ }
217
246
  }
247
+ let participants: Uint32Array;
248
+ // Within an epoch committees partition the active validator set.
249
+ if (computeEpochAtSlot(startSlot) === computeEpochAtSlot(endSlot)) {
250
+ participants = new Uint32Array(length);
251
+ let offset = 0;
252
+ for (const committee of committees) {
253
+ participants.set(committee, offset);
254
+ offset += committee.length;
255
+ }
256
+ } else {
257
+ const unique = new Set<number>();
258
+ for (const committee of committees) {
259
+ for (const index of committee) unique.add(index);
260
+ }
261
+ participants = Uint32Array.from(unique);
262
+ }
263
+ cache.participantsByRange.set(key, participants);
264
+ return participants;
218
265
  }
219
-
220
- return participants;
266
+ const sweep = getCommitteeSweep(ctx, store, cache, startSlot, endSlot);
267
+ return sweep.order.subarray(0, sweep.lengths[endSlot - startSlot]);
221
268
  }
222
269
 
223
270
  function isDescendantCached(
@@ -278,72 +325,94 @@ function getZeroInactiveBalances(balanceSource: FastConfirmationBalanceSource):
278
325
  return balanceSource.state?.getEffectiveBalanceIncrementsZeroInactive() ?? balanceSource.balances;
279
326
  }
280
327
 
281
- export function getTotalActiveBalance(
282
- balanceSource: FastConfirmationBalanceSource,
283
- cache: FastConfirmationCache
284
- ): number {
285
- // Invariant per balance source within a run, but read many times per is_one_confirmed evaluation
286
- // across the epoch-boundary chain walk; memoize so the full validator-set scan runs once per run.
287
- const key: TotalActiveBalanceCacheKey = balanceSource.state ?? balanceSource.balances;
288
- const cached = cache.totalActiveBalanceByKey.get(key);
328
+ /**
329
+ * Balances read by `get_total_active_balance` and `compute_committee_weight_between_slots`. Unlike the
330
+ * vote scans, these keep slashed validators: the maximum support and the adversarial budget they bound
331
+ * must cover slashed equivocators, whose weight `getEquivocationScore` subtracts. `unslashedTotal` serves
332
+ * `compute_proposer_score`, whose `calculate_committee_fraction` excludes slashed validators.
333
+ * Invariant per balance source within a run, but read many times per is_one_confirmed evaluation
334
+ * across the epoch-boundary chain walk; memoized so the full validator-set scan runs once per run.
335
+ */
336
+ function getActiveBalances(balanceSource: FastConfirmationBalanceSource, cache: FastConfirmationCache): ActiveBalances {
337
+ const key: BalanceSourceCacheKey = balanceSource.state ?? balanceSource.balances;
338
+ const cached = cache.activeBalancesByKey.get(key);
289
339
  if (cached !== undefined) return cached;
290
340
 
291
- const total = computeTotalBalance(getZeroInactiveBalances(balanceSource));
341
+ let active: ActiveBalances;
342
+ if (balanceSource.state) {
343
+ const {effectiveBalanceIncrements} = balanceSource.state;
344
+ const unslashedBalances = balanceSource.state.getEffectiveBalanceIncrementsZeroInactive();
345
+ const balances = new Uint16Array(balanceSource.state.validatorCount);
346
+ let total = 0;
347
+ let unslashedTotal = 0;
348
+ for (const i of balanceSource.state.getCurrentShuffling().activeIndices) {
349
+ balances[i] = effectiveBalanceIncrements[i];
350
+ total += balances[i];
351
+ unslashedTotal += unslashedBalances[i];
352
+ }
353
+ active = {balances, total, unslashedTotal};
354
+ } else {
355
+ // Fallback balances come from the justified-balance path, which also zeroes slashed validators
356
+ const total = computeTotalBalance(balanceSource.balances);
357
+ active = {balances: balanceSource.balances, total, unslashedTotal: total};
358
+ }
292
359
 
293
- cache.totalActiveBalanceByKey.set(key, total);
294
- return total;
360
+ cache.activeBalancesByKey.set(key, active);
361
+ return active;
295
362
  }
296
363
 
297
- export function estimateCommitteeWeightBetweenSlots(
364
+ export function getTotalActiveBalance(
298
365
  balanceSource: FastConfirmationBalanceSource,
366
+ cache: FastConfirmationCache
367
+ ): number {
368
+ return getActiveBalances(balanceSource, cache).total;
369
+ }
370
+
371
+ export function computeCommitteeWeightBetweenSlots(
372
+ ctx: FastConfirmationContext,
373
+ store: IFastConfirmationStore,
299
374
  cache: FastConfirmationCache,
375
+ balanceSource: FastConfirmationBalanceSource,
300
376
  startSlot: Slot,
301
377
  endSlot: Slot
302
- ): number {
303
- if (startSlot > endSlot) return 0;
304
- const totalActiveBalance = getTotalActiveBalance(balanceSource, cache);
305
- const startEpoch = computeEpochAtSlot(startSlot);
306
- const endEpoch = computeEpochAtSlot(endSlot);
378
+ ): bigint {
379
+ if (startSlot > endSlot) return 0n;
307
380
 
308
381
  if (isFullValidatorSetCovered(startSlot, endSlot)) {
309
- return totalActiveBalance;
382
+ return BigInt(getTotalActiveBalance(balanceSource, cache)) * EFFECTIVE_BALANCE_INCREMENT_BIGINT;
310
383
  }
311
384
 
312
- const committeeWeightPerSlot = Math.floor(totalActiveBalance / SLOTS_PER_EPOCH);
313
-
314
- if (startEpoch === endEpoch) {
315
- return committeeWeightPerSlot * (endSlot - startSlot + 1);
385
+ // Only the shared endpoint benefits from incremental weight prefixes across the chain walk.
386
+ // Other ranges reuse their compact participants without allocating a validator-sized sweep.
387
+ if (endSlot !== ctx.getCurrentSlot() - 1) {
388
+ const {balances} = getActiveBalances(balanceSource, cache);
389
+ let weight = 0;
390
+ for (const index of getSlotRangeParticipants(ctx, store, cache, startSlot, endSlot)) {
391
+ weight += balances[index] ?? 0;
392
+ }
393
+ return BigInt(weight) * EFFECTIVE_BALANCE_INCREMENT_BIGINT;
316
394
  }
317
395
 
318
- const numSlotsInStartEpoch = SLOTS_PER_EPOCH - computeSlotsSinceEpochStart(startSlot);
319
- const numSlotsInEndEpoch = computeSlotsSinceEpochStart(endSlot) + 1;
320
- const remainingSlotsInEndEpoch = SLOTS_PER_EPOCH - numSlotsInEndEpoch;
321
-
322
- const startEpochWeight = committeeWeightPerSlot * numSlotsInStartEpoch;
323
- const endEpochWeight = committeeWeightPerSlot * numSlotsInEndEpoch;
324
- // For ranges that cross exactly one epoch boundary without covering a full epoch,
325
- // the spec models overlap as:
326
- // startEpochWeightProRated = startEpochWeight * (1 - numSlotsInEndEpoch / SLOTS_PER_EPOCH)
327
- // = startEpochWeight * remainingSlotsInEndEpoch / SLOTS_PER_EPOCH
328
- // We keep the spec's "pro-rate the start epoch" form so integer rounding matches it exactly.
329
- const startEpochWeightProRated = Math.floor(startEpochWeight / SLOTS_PER_EPOCH) * remainingSlotsInEndEpoch;
330
-
331
- return adjustCommitteeWeightEstimateToEnsureSafety(startEpochWeightProRated + endEpochWeight);
332
- }
396
+ const sweep = getCommitteeSweep(ctx, store, cache, startSlot, endSlot);
397
+ const key: BalanceSourceCacheKey = balanceSource.state ?? balanceSource.balances;
398
+ let weights = sweep.weightsByKey.get(key);
399
+ if (weights === undefined) {
400
+ weights = [];
401
+ sweep.weightsByKey.set(key, weights);
402
+ }
333
403
 
334
- export function adjustCommitteeWeightEstimateToEnsureSafety(estimate: number): number {
335
- // The spec applies this adjustment in raw Gwei:
336
- // ceil(estimate_gwei / 1000) * (1000 + factor)
337
- //
338
- // Lodestar carries effective balance increments instead, where:
339
- // 1 increment = EFFECTIVE_BALANCE_INCREMENT = 1e9 Gwei
340
- //
341
- // Since each increment is already far larger than 1000 Gwei, the spec's
342
- // `ceil(... / 1000)` becomes a no-op at our unit scale. The equivalent
343
- // conservative adjustment in increments is therefore:
344
- // ceil(estimate_increments * (1000 + factor) / 1000)
345
- // The `+ 999` is integer ceiling division by 1000.
346
- return Math.floor((estimate * (1000 + COMMITTEE_WEIGHT_ESTIMATION_ADJUSTMENT_FACTOR) + 999) / 1000);
404
+ const slotCount = endSlot - startSlot + 1;
405
+ if (weights.length < slotCount) {
406
+ const {balances} = getActiveBalances(balanceSource, cache);
407
+ let weight = weights.at(-1) ?? 0;
408
+ for (let i = weights.length; i < slotCount; i++) {
409
+ for (let j = i > 0 ? sweep.lengths[i - 1] : 0; j < sweep.lengths[i]; j++) {
410
+ weight += balances[sweep.order[j]] ?? 0;
411
+ }
412
+ weights.push(weight);
413
+ }
414
+ }
415
+ return BigInt(weights[slotCount - 1]) * EFFECTIVE_BALANCE_INCREMENT_BIGINT;
347
416
  }
348
417
 
349
418
  export function isFullValidatorSetCovered(startSlot: Slot, endSlot: Slot): boolean {
@@ -356,10 +425,11 @@ export function computeProposerScore(
356
425
  ctx: FastConfirmationContext,
357
426
  balanceSource: FastConfirmationBalanceSource,
358
427
  cache: FastConfirmationCache
359
- ): number {
360
- const totalActiveBalance = getTotalActiveBalance(balanceSource, cache);
361
- const committeeWeight = Math.floor(totalActiveBalance / SLOTS_PER_EPOCH);
362
- return Math.floor((committeeWeight * ctx.config.PROPOSER_SCORE_BOOST) / 100);
428
+ ): bigint {
429
+ const unslashedTotal =
430
+ BigInt(getActiveBalances(balanceSource, cache).unslashedTotal) * EFFECTIVE_BALANCE_INCREMENT_BIGINT;
431
+ const committeeWeight = unslashedTotal / BigInt(SLOTS_PER_EPOCH);
432
+ return (committeeWeight * BigInt(ctx.config.PROPOSER_SCORE_BOOST)) / 100n;
363
433
  }
364
434
 
365
435
  /**
@@ -419,14 +489,14 @@ export function getNodeSupportBetweenSlots(
419
489
  cache: FastConfirmationCache,
420
490
  balanceSource: FastConfirmationBalanceSource,
421
491
  nodeRoot: RootHex,
422
- nodePayloadStatus: PayloadStatus,
492
+ nodePayloadStatuses: readonly PayloadStatus[],
423
493
  startSlot: Slot,
424
494
  endSlot: Slot
425
495
  ): number {
426
496
  if (startSlot > endSlot) return 0;
427
497
  const balances = getZeroInactiveBalances(balanceSource);
428
498
  const participants = getSlotRangeParticipants(ctx, store, cache, startSlot, endSlot);
429
- if (participants.size === 0) return 0;
499
+ if (participants.length === 0) return 0;
430
500
 
431
501
  const equivocating = ctx.getEquivocatingIndices();
432
502
  let score = 0;
@@ -435,7 +505,7 @@ export function getNodeSupportBetweenSlots(
435
505
  if (weight === 0) continue;
436
506
  if (equivocating.has(i)) continue;
437
507
  const latestMessage = ctx.getLatestMessage(i);
438
- if (latestMessage?.root === nodeRoot && latestMessage.payloadStatus === nodePayloadStatus) {
508
+ if (latestMessage?.root === nodeRoot && nodePayloadStatuses.includes(latestMessage.payloadStatus)) {
439
509
  score += weight;
440
510
  }
441
511
  }
@@ -463,7 +533,7 @@ export function getEquivocationScore(
463
533
  const state = balanceSource.state;
464
534
  const stateEpoch = state ? computeEpochAtSlot(state.slot) : null;
465
535
  const participants = getSlotRangeParticipants(ctx, store, cache, startSlot, endSlot);
466
- if (participants.size === 0) return 0;
536
+ if (participants.length === 0) return 0;
467
537
 
468
538
  let score = 0;
469
539
  for (const i of participants) {
@@ -485,14 +555,13 @@ export function computeAdversarialWeight(
485
555
  balanceSource: FastConfirmationBalanceSource,
486
556
  startSlot: Slot,
487
557
  endSlot: Slot
488
- ): number {
489
- const maximumWeight = estimateCommitteeWeightBetweenSlots(balanceSource, cache, startSlot, endSlot);
490
- // The spec uses raw Gwei and computes `maximum_weight // 100 * threshold`.
491
- // Lodestar carries effective-balance increments instead, so divide after multiplying to avoid
492
- // dropping the adversarial budget to zero for small validator sets/minimal presets.
493
- const maxAdversarialWeight = Math.floor((maximumWeight * ctx.config.CONFIRMATION_BYZANTINE_THRESHOLD) / 100);
494
- const equivocationScore = getEquivocationScore(ctx, store, cache, balanceSource, startSlot, endSlot);
495
- return maxAdversarialWeight > equivocationScore ? maxAdversarialWeight - equivocationScore : 0;
558
+ ): bigint {
559
+ const maximumWeight = computeCommitteeWeightBetweenSlots(ctx, store, cache, balanceSource, startSlot, endSlot);
560
+ const maxAdversarialWeight = (maximumWeight / 100n) * BigInt(ctx.config.CONFIRMATION_BYZANTINE_THRESHOLD);
561
+ const equivocationScore =
562
+ BigInt(getEquivocationScore(ctx, store, cache, balanceSource, startSlot, endSlot)) *
563
+ EFFECTIVE_BALANCE_INCREMENT_BIGINT;
564
+ return maxAdversarialWeight > equivocationScore ? maxAdversarialWeight - equivocationScore : 0n;
496
565
  }
497
566
 
498
567
  export function getAdversarialWeight(
@@ -501,13 +570,13 @@ export function getAdversarialWeight(
501
570
  cache: FastConfirmationCache,
502
571
  balanceSource: FastConfirmationBalanceSource,
503
572
  blockRoot: RootHex
504
- ): number {
573
+ ): bigint {
505
574
  const currentSlot = ctx.getCurrentSlot();
506
- if (currentSlot === 0) return 0;
575
+ if (currentSlot === 0) return 0n;
507
576
  const block = getBlock(ctx, cache, blockRoot);
508
- if (!block) return 0;
577
+ if (!block) return 0n;
509
578
  const parentBlock = getBlock(ctx, cache, block.parentRoot);
510
- if (!parentBlock) return 0;
579
+ if (!parentBlock) return 0n;
511
580
  const blockEpoch = computeEpochAtSlot(block.slot);
512
581
  const parentEpoch = computeEpochAtSlot(parentBlock.slot);
513
582
 
@@ -524,31 +593,35 @@ export function computeEmptySlotSupportDiscount(
524
593
  cache: FastConfirmationCache,
525
594
  balanceSource: FastConfirmationBalanceSource,
526
595
  blockRoot: RootHex
527
- ): number {
596
+ ): bigint {
528
597
  const block = getBlock(ctx, cache, blockRoot);
529
- if (!block) return 0;
598
+ if (!block) return 0n;
530
599
  const parentBlock = getBlock(ctx, cache, block.parentRoot);
531
- if (!parentBlock) return 0;
600
+ if (!parentBlock) return 0n;
532
601
 
533
602
  if (parentBlock.slot + 1 === block.slot) {
534
- return 0;
603
+ return 0n;
535
604
  }
536
605
 
537
- // Post-Gloas the parent block has PENDING, EMPTY and FULL nodes. Only the support of the node this
538
- // block actually extends is discounted; votes for the other parent nodes are not support for it.
606
+ // Post-Gloas the parent block has PENDING, EMPTY and FULL nodes. Support for PENDING(P) and for the
607
+ // payload node this block extends is discounted. Support for the other payload node counts against
608
+ // this block. `parentBlock` is the default variant, PENDING post-Gloas and the only node pre-Gloas.
539
609
  const parentNodePayloadStatus = ctx.getParentNodePayloadStatus(blockRoot);
540
- if (parentNodePayloadStatus === null) return 0;
541
-
542
- const parentSupportInEmptySlots = getNodeSupportBetweenSlots(
543
- ctx,
544
- store,
545
- cache,
546
- balanceSource,
547
- block.parentRoot,
548
- parentNodePayloadStatus,
549
- (parentBlock.slot + 1) as Slot,
550
- (block.slot - 1) as Slot
551
- );
610
+ if (parentNodePayloadStatus === null) return 0n;
611
+
612
+ const parentSupportInEmptySlots =
613
+ BigInt(
614
+ getNodeSupportBetweenSlots(
615
+ ctx,
616
+ store,
617
+ cache,
618
+ balanceSource,
619
+ block.parentRoot,
620
+ [parentBlock.payloadStatus, parentNodePayloadStatus],
621
+ (parentBlock.slot + 1) as Slot,
622
+ (block.slot - 1) as Slot
623
+ )
624
+ ) * EFFECTIVE_BALANCE_INCREMENT_BIGINT;
552
625
  const adversarialWeight = computeAdversarialWeight(
553
626
  ctx,
554
627
  store,
@@ -558,7 +631,7 @@ export function computeEmptySlotSupportDiscount(
558
631
  (block.slot - 1) as Slot
559
632
  );
560
633
 
561
- return parentSupportInEmptySlots > adversarialWeight ? parentSupportInEmptySlots - adversarialWeight : 0;
634
+ return parentSupportInEmptySlots > adversarialWeight ? parentSupportInEmptySlots - adversarialWeight : 0n;
562
635
  }
563
636
 
564
637
  export function computeSafetyThreshold(
@@ -568,11 +641,11 @@ export function computeSafetyThreshold(
568
641
  balanceSource: FastConfirmationBalanceSource,
569
642
  blockRoot: RootHex
570
643
  ): {
571
- threshold: number;
572
- proposerScore: number;
573
- maximumSupport: number;
574
- supportDiscount: number;
575
- adversarialWeight: number;
644
+ threshold: bigint;
645
+ proposerScore: bigint;
646
+ maximumSupport: bigint;
647
+ supportDiscount: bigint;
648
+ adversarialWeight: bigint;
576
649
  } {
577
650
  const currentSlot = ctx.getCurrentSlot();
578
651
  const block = getBlock(ctx, cache, blockRoot);
@@ -588,21 +661,23 @@ export function computeSafetyThreshold(
588
661
  // Build the threshold from the same terms used in the paper/spec:
589
662
  // max possible committee support, proposer boost, empty-slot discount, and adversarial budget.
590
663
  const proposerScore = computeProposerScore(ctx, balanceSource, cache);
591
- const maximumSupport = estimateCommitteeWeightBetweenSlots(
592
- balanceSource,
664
+ const maximumSupport = computeCommitteeWeightBetweenSlots(
665
+ ctx,
666
+ store,
593
667
  cache,
668
+ balanceSource,
594
669
  (parentBlock.slot + 1) as Slot,
595
670
  (currentSlot - 1) as Slot
596
671
  );
597
672
  const supportDiscount = computeEmptySlotSupportDiscount(ctx, store, cache, balanceSource, blockRoot);
598
673
  const adversarialWeight = getAdversarialWeight(ctx, store, cache, balanceSource, blockRoot);
599
674
 
600
- // Spec underflow guard:
601
- // if the discount alone already exceeds the threshold budget, the safety threshold is zero.
602
- const threshold =
603
- supportDiscount > maximumSupport + proposerScore + 2 * adversarialWeight
604
- ? 0
605
- : Math.floor((maximumSupport + proposerScore + 2 * adversarialWeight - supportDiscount) / 2);
675
+ // The discounted votes come from committees within the maximum support range and are weighed with
676
+ // the same balances, so exceeding it means the computation is wrong rather than an underflow to guard.
677
+ if (supportDiscount > maximumSupport) {
678
+ throw new Error(`Fast confirmation support discount ${supportDiscount} exceeds maximum support ${maximumSupport}`);
679
+ }
680
+ const threshold = (maximumSupport + proposerScore + 2n * adversarialWeight - supportDiscount) / 2n;
606
681
 
607
682
  return {threshold, proposerScore, maximumSupport, supportDiscount, adversarialWeight};
608
683
  }
@@ -626,7 +701,8 @@ export function isOneConfirmed(
626
701
 
627
702
  // Spec: is_one_confirmed(store, balance_source, block_root)
628
703
  // Compare actual support for this block against the computed LMD-GHOST safety threshold.
629
- const support = getAttestationScore(ctx, cache, balanceSource, blockRoot, sourceKey);
704
+ const support =
705
+ BigInt(getAttestationScore(ctx, cache, balanceSource, blockRoot, sourceKey)) * EFFECTIVE_BALANCE_INCREMENT_BIGINT;
630
706
  const {threshold, proposerScore, maximumSupport, supportDiscount, adversarialWeight} = computeSafetyThreshold(
631
707
  ctx,
632
708
  store,
@@ -709,18 +785,15 @@ export function getCurrentTargetScore(
709
785
  }
710
786
 
711
787
  function computeHonestFfgSupport(
712
- totalActiveBalance: number,
713
- ffgSupport: number,
714
- ffgWeightTillNow: number,
715
- adversarialWeight: number,
788
+ totalActiveBalance: bigint,
789
+ ffgSupport: bigint,
790
+ ffgWeightTillNow: bigint,
791
+ adversarialWeight: bigint,
716
792
  byzantineThreshold: number
717
- ): number {
793
+ ): bigint {
718
794
  const remainingFfgWeight = totalActiveBalance - ffgWeightTillNow;
719
- // The spec rounds in raw Gwei as `remaining_ffg_weight // 100 * honest_percent`.
720
- // In Lodestar this value is in effective-balance increments, so multiply before dividing by 100
721
- // to preserve the same percentage semantics at our coarser unit scale.
722
- const remainingHonestFfgWeight = Math.floor((remainingFfgWeight * (100 - byzantineThreshold)) / 100);
723
- const minHonestFfgSupport = ffgSupport - Math.min(adversarialWeight, ffgSupport);
795
+ const remainingHonestFfgWeight = (remainingFfgWeight / 100n) * BigInt(100 - byzantineThreshold);
796
+ const minHonestFfgSupport = ffgSupport > adversarialWeight ? ffgSupport - adversarialWeight : 0n;
724
797
  return minHonestFfgSupport + remainingHonestFfgWeight;
725
798
  }
726
799
 
@@ -728,18 +801,21 @@ export function computeHonestFfgSupportForCurrentTarget(
728
801
  ctx: FastConfirmationContext,
729
802
  store: IFastConfirmationStore,
730
803
  cache: FastConfirmationCache
731
- ): number {
804
+ ): bigint {
732
805
  const currentSlot = ctx.getCurrentSlot();
733
- if (currentSlot === 0) return 0;
806
+ if (currentSlot === 0) return 0n;
734
807
  const currentEpoch = computeEpochAtSlot(currentSlot);
735
808
  const targetState = getCurrentEpochState(ctx, store, cache);
736
- if (!targetState) return 0;
809
+ if (!targetState) return 0n;
737
810
  const targetBalanceSource = {state: targetState, balances: targetState.effectiveBalanceIncrements};
738
- const totalActiveBalance = getTotalActiveBalance(targetBalanceSource, cache);
739
- const ffgSupport = getCurrentTargetScore(ctx, store, cache);
740
- const tillNowFFGWeight = estimateCommitteeWeightBetweenSlots(
741
- targetBalanceSource,
811
+ const totalActiveBalance =
812
+ BigInt(getTotalActiveBalance(targetBalanceSource, cache)) * EFFECTIVE_BALANCE_INCREMENT_BIGINT;
813
+ const ffgSupport = BigInt(getCurrentTargetScore(ctx, store, cache)) * EFFECTIVE_BALANCE_INCREMENT_BIGINT;
814
+ const tillNowFFGWeight = computeCommitteeWeightBetweenSlots(
815
+ ctx,
816
+ store,
742
817
  cache,
818
+ targetBalanceSource,
743
819
  computeStartSlotAtEpoch(currentEpoch),
744
820
  (currentSlot - 1) as Slot
745
821
  );
@@ -772,12 +848,11 @@ export function willNoConflictingCheckpointBeJustified(
772
848
  }
773
849
  const targetState = getCurrentEpochState(ctx, store, cache);
774
850
  if (!targetState) return false;
775
- const totalActiveBalance = getTotalActiveBalance(
776
- {state: targetState, balances: targetState.effectiveBalanceIncrements},
777
- cache
778
- );
851
+ const totalActiveBalance =
852
+ BigInt(getTotalActiveBalance({state: targetState, balances: targetState.effectiveBalanceIncrements}, cache)) *
853
+ EFFECTIVE_BALANCE_INCREMENT_BIGINT;
779
854
  const honestSupport = computeHonestFfgSupportForCurrentTarget(ctx, store, cache);
780
- return 3 * honestSupport > 1 * totalActiveBalance;
855
+ return 3n * honestSupport > 1n * totalActiveBalance;
781
856
  }
782
857
 
783
858
  export function willCurrentTargetBeJustified(
@@ -787,12 +862,11 @@ export function willCurrentTargetBeJustified(
787
862
  ): boolean {
788
863
  const targetState = getCurrentEpochState(ctx, store, cache);
789
864
  if (!targetState) return false;
790
- const totalActiveBalance = getTotalActiveBalance(
791
- {state: targetState, balances: targetState.effectiveBalanceIncrements},
792
- cache
793
- );
865
+ const totalActiveBalance =
866
+ BigInt(getTotalActiveBalance({state: targetState, balances: targetState.effectiveBalanceIncrements}, cache)) *
867
+ EFFECTIVE_BALANCE_INCREMENT_BIGINT;
794
868
  const honestSupport = computeHonestFfgSupportForCurrentTarget(ctx, store, cache);
795
- return 3 * honestSupport >= 2 * totalActiveBalance;
869
+ return 3n * honestSupport >= 2n * totalActiveBalance;
796
870
  }
797
871
 
798
872
  export function isConfirmedChainSafe(