@lodestar/beacon-node 1.52.0-dev.dad8e3af98 → 1.52.0-dev.e33126114e

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 (75) hide show
  1. package/lib/chain/archiveStore/historicalState/getHistoricalState.d.ts.map +1 -1
  2. package/lib/chain/archiveStore/historicalState/getHistoricalState.js +7 -0
  3. package/lib/chain/archiveStore/historicalState/getHistoricalState.js.map +1 -1
  4. package/lib/chain/archiveStore/utils/pruneHistory.d.ts.map +1 -1
  5. package/lib/chain/archiveStore/utils/pruneHistory.js +8 -4
  6. package/lib/chain/archiveStore/utils/pruneHistory.js.map +1 -1
  7. package/lib/chain/lightClient/index.d.ts +13 -6
  8. package/lib/chain/lightClient/index.d.ts.map +1 -1
  9. package/lib/chain/lightClient/index.js +95 -115
  10. package/lib/chain/lightClient/index.js.map +1 -1
  11. package/lib/execution/engine/http.d.ts +2 -2
  12. package/lib/execution/engine/http.d.ts.map +1 -1
  13. package/lib/execution/engine/http.js +11 -5
  14. package/lib/execution/engine/http.js.map +1 -1
  15. package/lib/execution/engine/interface.d.ts +2 -2
  16. package/lib/execution/engine/interface.d.ts.map +1 -1
  17. package/lib/execution/engine/jsonRpcHttpClient.d.ts +2 -0
  18. package/lib/execution/engine/jsonRpcHttpClient.d.ts.map +1 -1
  19. package/lib/execution/engine/jsonRpcHttpClient.js +14 -6
  20. package/lib/execution/engine/jsonRpcHttpClient.js.map +1 -1
  21. package/lib/execution/engine/jsonRpcTransport.d.ts +2 -2
  22. package/lib/execution/engine/jsonRpcTransport.d.ts.map +1 -1
  23. package/lib/execution/engine/jsonRpcTransport.js +4 -4
  24. package/lib/execution/engine/jsonRpcTransport.js.map +1 -1
  25. package/lib/execution/engine/restHttpClient.d.ts.map +1 -1
  26. package/lib/execution/engine/restHttpClient.js +9 -5
  27. package/lib/execution/engine/restHttpClient.js.map +1 -1
  28. package/lib/execution/engine/restTransport.d.ts +2 -2
  29. package/lib/execution/engine/restTransport.d.ts.map +1 -1
  30. package/lib/execution/engine/restTransport.js +4 -4
  31. package/lib/execution/engine/restTransport.js.map +1 -1
  32. package/lib/execution/engine/signal.d.ts +6 -0
  33. package/lib/execution/engine/signal.d.ts.map +1 -0
  34. package/lib/execution/engine/signal.js +24 -0
  35. package/lib/execution/engine/signal.js.map +1 -0
  36. package/lib/execution/engine/transport.d.ts +2 -2
  37. package/lib/execution/engine/transport.d.ts.map +1 -1
  38. package/lib/network/gossip/gossipsub.d.ts +1 -0
  39. package/lib/network/gossip/gossipsub.d.ts.map +1 -1
  40. package/lib/network/gossip/gossipsub.js +3 -0
  41. package/lib/network/gossip/gossipsub.js.map +1 -1
  42. package/lib/network/network.d.ts.map +1 -1
  43. package/lib/network/network.js +6 -1
  44. package/lib/network/network.js.map +1 -1
  45. package/lib/network/peers/peerManager.d.ts.map +1 -1
  46. package/lib/network/peers/peerManager.js +22 -2
  47. package/lib/network/peers/peerManager.js.map +1 -1
  48. package/lib/network/peers/utils/prioritizePeers.d.ts +2 -0
  49. package/lib/network/peers/utils/prioritizePeers.d.ts.map +1 -1
  50. package/lib/network/peers/utils/prioritizePeers.js +11 -2
  51. package/lib/network/peers/utils/prioritizePeers.js.map +1 -1
  52. package/lib/sync/unknownBlock.d.ts.map +1 -1
  53. package/lib/sync/unknownBlock.js +63 -3
  54. package/lib/sync/unknownBlock.js.map +1 -1
  55. package/lib/sync/utils/downloadByRoot.d.ts.map +1 -1
  56. package/lib/sync/utils/downloadByRoot.js +5 -4
  57. package/lib/sync/utils/downloadByRoot.js.map +1 -1
  58. package/package.json +25 -25
  59. package/src/chain/archiveStore/historicalState/getHistoricalState.ts +9 -0
  60. package/src/chain/archiveStore/utils/pruneHistory.ts +9 -4
  61. package/src/chain/lightClient/index.ts +108 -142
  62. package/src/execution/engine/http.ts +15 -9
  63. package/src/execution/engine/interface.ts +4 -2
  64. package/src/execution/engine/jsonRpcHttpClient.ts +26 -14
  65. package/src/execution/engine/jsonRpcTransport.ts +8 -4
  66. package/src/execution/engine/restHttpClient.ts +17 -11
  67. package/src/execution/engine/restTransport.ts +5 -4
  68. package/src/execution/engine/signal.ts +28 -0
  69. package/src/execution/engine/transport.ts +3 -2
  70. package/src/network/gossip/gossipsub.ts +4 -0
  71. package/src/network/network.ts +6 -2
  72. package/src/network/peers/peerManager.ts +26 -2
  73. package/src/network/peers/utils/prioritizePeers.ts +14 -1
  74. package/src/sync/unknownBlock.ts +68 -2
  75. package/src/sync/utils/downloadByRoot.ts +7 -5
@@ -1,4 +1,5 @@
1
1
  import {ChainForkConfig} from "@lodestar/config";
2
+ import {GENESIS_SLOT} from "@lodestar/params";
2
3
  import {computeStartSlotAtEpoch} from "@lodestar/state-transition";
3
4
  import {Epoch, Slot} from "@lodestar/types";
4
5
  import {Logger, prettyPrintIndices} from "@lodestar/utils";
@@ -13,6 +14,9 @@ import {Metrics} from "../../../metrics/index.js";
13
14
  */
14
15
  export const MAX_PRUNE_BLOCK_SLOTS_PER_RUN = 4096;
15
16
 
17
+ // Genesis is kept so the block and state stay available via the API, e.g. for checkpoint providers
18
+ const FIRST_PRUNABLE_SLOT = GENESIS_SLOT + 1;
19
+
16
20
  export async function pruneHistory(
17
21
  config: ChainForkConfig,
18
22
  db: IBeaconDb,
@@ -30,11 +34,12 @@ export async function pruneHistory(
30
34
  // ensure that during (extremely lol) long periods of non-finality we don't delete unfinalized epoch data
31
35
  finalizedEpoch
32
36
  );
33
- const firstBlockSlot = (await db.blockArchive.firstKey()) ?? 0;
37
+ const [firstBlockSlot = FIRST_PRUNABLE_SLOT] = await db.blockArchive.keys({gte: FIRST_PRUNABLE_SLOT, limit: 1});
34
38
  const blockCutoffSlot = Math.min(computeStartSlotAtEpoch(blockCutoffEpoch), firstBlockSlot + maxBlockSlots);
35
39
  // The latest archived state is the anchor on restart and can trail finalization by a few epochs
36
40
  const lastArchivedStateSlot = (await db.stateArchive.lastKey()) ?? 0;
37
41
  const stateCutoffSlot = Math.min(computeStartSlotAtEpoch(finalizedEpoch), lastArchivedStateSlot);
42
+ const stateStartSlot = Math.max(statePruneFromSlot, FIRST_PRUNABLE_SLOT);
38
43
 
39
44
  logger.debug("Preparing to prune history", {
40
45
  currentEpoch,
@@ -46,9 +51,9 @@ export async function pruneHistory(
46
51
 
47
52
  const step0 = metrics?.pruneHistory.fetchKeys.startTimer();
48
53
  const [blocks, envelopes, states] = await Promise.all([
49
- db.blockArchive.keys({gte: 0, lt: blockCutoffSlot}),
50
- db.executionPayloadEnvelopeArchive.keys({gte: 0, lt: blockCutoffSlot}),
51
- stateCutoffSlot > statePruneFromSlot ? db.stateArchive.keys({gte: statePruneFromSlot, lt: stateCutoffSlot}) : [],
54
+ db.blockArchive.keys({gte: FIRST_PRUNABLE_SLOT, lt: blockCutoffSlot}),
55
+ db.executionPayloadEnvelopeArchive.keys({gte: FIRST_PRUNABLE_SLOT, lt: blockCutoffSlot}),
56
+ stateCutoffSlot > stateStartSlot ? db.stateArchive.keys({gte: stateStartSlot, lt: stateCutoffSlot}) : [],
52
57
  ]);
53
58
  step0?.();
54
59
 
@@ -8,6 +8,7 @@ import {
8
8
  ForkPostGloas,
9
9
  ForkPreGloas,
10
10
  ForkSeq,
11
+ GENESIS_EPOCH,
11
12
  MIN_SYNC_COMMITTEE_PARTICIPANTS,
12
13
  SLOTS_PER_EPOCH,
13
14
  SYNC_COMMITTEE_SIZE,
@@ -16,8 +17,6 @@ import {
16
17
  } from "@lodestar/params";
17
18
  import {
18
19
  type IBeaconStateViewAltair,
19
- computeStartSlotAtEpoch,
20
- computeSyncPeriodAtEpoch,
21
20
  computeSyncPeriodAtSlot,
22
21
  executionPayloadToPayloadHeader,
23
22
  } from "@lodestar/state-transition";
@@ -44,8 +43,7 @@ import {
44
43
  phase0,
45
44
  ssz,
46
45
  } from "@lodestar/types";
47
- import {Logger, MapDef, byteArrayEquals, pruneSetToMax, toRootHex} from "@lodestar/utils";
48
- import {ZERO_HASH} from "../../constants/index.js";
46
+ import {Logger, MapDef, pruneSetToMax, toRootHex} from "@lodestar/utils";
49
47
  import {IBeaconDb} from "../../db/index.js";
50
48
  import {NUM_WITNESS, NUM_WITNESS_ELECTRA} from "../../db/repositories/lightclientSyncCommitteeWitness.js";
51
49
  import {Metrics} from "../../metrics/index.js";
@@ -72,16 +70,9 @@ export type SyncAttestedData = {
72
70
  attestedHeader: LightClientHeader;
73
71
  /** Precomputed root to prevent re-hashing */
74
72
  blockRoot: Uint8Array;
75
- } & (
76
- | {
77
- isFinalized: true;
78
- finalityBranch: Uint8Array[];
79
- finalizedCheckpoint: phase0.Checkpoint;
80
- }
81
- | {
82
- isFinalized: false;
83
- }
84
- );
73
+ finalizedCheckpoint: phase0.Checkpoint;
74
+ finalityBranch: Uint8Array[];
75
+ };
85
76
 
86
77
  type LightClientServerModules = {
87
78
  config: ChainForkConfig;
@@ -435,33 +426,14 @@ export class LightClientServer {
435
426
  // Store header in case it is referenced latter by a future finalized checkpoint
436
427
  await this.db.checkpointHeader.put(blockRoot, header);
437
428
 
438
- // Store finalized checkpoint data
439
- const finalizedCheckpoint = postState.finalizedCheckpoint;
440
- const finalizedCheckpointPeriod = computeSyncPeriodAtEpoch(finalizedCheckpoint.epoch);
441
- const isFinalized =
442
- finalizedCheckpointPeriod === period &&
443
- // Consider the edge case of genesis: Genesis state's finalizedCheckpoint is zero'ed.
444
- // If finalizedCheckpoint is zeroed, consider not finalized (ignore) since there won't exist a
445
- // finalized header for that root
446
- finalizedCheckpoint.epoch !== 0 &&
447
- !byteArrayEquals(finalizedCheckpoint.root, ZERO_HASH);
448
-
449
- this.prevHeadData.set(
450
- blockRootHex,
451
- isFinalized
452
- ? {
453
- isFinalized: true,
454
- attestedHeader: header,
455
- blockRoot,
456
- finalityBranch: postState.getFinalizedRootProof(),
457
- finalizedCheckpoint,
458
- }
459
- : {
460
- isFinalized: false,
461
- attestedHeader: header,
462
- blockRoot,
463
- }
464
- );
429
+ // Store finalized checkpoint data. The finality branch only depends on the post state, so it is
430
+ // collected for every block; see `buildUpdate` for the cases in which it is served.
431
+ this.prevHeadData.set(blockRootHex, {
432
+ attestedHeader: header,
433
+ blockRoot,
434
+ finalizedCheckpoint: postState.finalizedCheckpoint,
435
+ finalityBranch: postState.getFinalizedRootProof(),
436
+ });
465
437
 
466
438
  pruneSetToMax(this.prevHeadData, MAX_PREV_HEAD_DATA);
467
439
  }
@@ -505,7 +477,7 @@ export class LightClientServer {
505
477
  return;
506
478
  }
507
479
 
508
- const {attestedHeader, isFinalized} = attestedData;
480
+ const {attestedHeader} = attestedData;
509
481
  const attestedPeriod = computeSyncPeriodAtSlot(attestedHeader.beacon.slot);
510
482
  if (syncPeriod !== attestedPeriod) {
511
483
  this.logger.debug("attested data period different than signature period", {syncPeriod, attestedPeriod});
@@ -555,41 +527,36 @@ export class LightClientServer {
555
527
  this.metrics?.lightclientServer.onSyncAggregate.inc({event: "update_latest_head_update"});
556
528
  }
557
529
 
558
- if (isFinalized) {
559
- const finalizedCheckpointRoot = attestedData.finalizedCheckpoint.root;
560
- let finalizedHeader = await this.getFinalizedHeader(finalizedCheckpointRoot);
561
-
562
- if (
563
- finalizedHeader &&
564
- (!this.finalized ||
565
- finalizedHeader.beacon.slot > this.finalized.finalizedHeader.beacon.slot ||
566
- syncAggregateParticipation > sumBits(this.finalized.syncAggregate.syncCommitteeBits))
567
- ) {
568
- if (this.config.getForkName(finalizedHeader.beacon.slot) !== attestedFork) {
569
- finalizedHeader = upgradeLightClientHeader(this.config, attestedFork, finalizedHeader);
570
- }
571
- this.finalized = {
572
- attestedHeader,
573
- finalizedHeader,
574
- syncAggregate,
575
- finalityBranch: attestedData.finalityBranch,
576
- signatureSlot,
577
- };
578
- this.metrics?.lightclientServer.onSyncAggregate.inc({event: "update_latest_finalized_update"});
579
-
580
- if (!isStaleLightClientUpdate) {
581
- // Note: Ignores gossip rule to always emit finality_update with higher finalized_header.slot, for simplicity
582
- this.emitter.emit(routes.events.EventType.lightClientFinalityUpdate, {
583
- version: attestedFork,
584
- data: this.finalized,
585
- });
586
- }
530
+ const builtUpdate = await this.buildUpdate(attestedData, syncAggregate, signatureSlot);
531
+ if (
532
+ builtUpdate?.hasFinality &&
533
+ (!this.finalized ||
534
+ builtUpdate.update.finalizedHeader.beacon.slot > this.finalized.finalizedHeader.beacon.slot ||
535
+ syncAggregateParticipation > sumBits(this.finalized.syncAggregate.syncCommitteeBits))
536
+ ) {
537
+ this.finalized = {
538
+ attestedHeader,
539
+ finalizedHeader: builtUpdate.update.finalizedHeader,
540
+ syncAggregate,
541
+ finalityBranch: builtUpdate.update.finalityBranch,
542
+ signatureSlot,
543
+ };
544
+ this.metrics?.lightclientServer.onSyncAggregate.inc({event: "update_latest_finalized_update"});
545
+
546
+ if (!isStaleLightClientUpdate) {
547
+ // Note: Ignores gossip rule to always emit finality_update with higher finalized_header.slot, for simplicity
548
+ this.emitter.emit(routes.events.EventType.lightClientFinalityUpdate, {
549
+ version: attestedFork,
550
+ data: this.finalized,
551
+ });
587
552
  }
588
553
  }
589
554
 
590
555
  // Check if this update is better, otherwise ignore
591
556
  try {
592
- await this.maybeStoreNewBestUpdate(syncPeriod, syncAggregate, signatureSlot, attestedData);
557
+ if (builtUpdate) {
558
+ await this.maybeStoreNewBestUpdate(syncPeriod, builtUpdate);
559
+ }
593
560
  } catch (e) {
594
561
  this.logger.error(
595
562
  "Error updating best LightClientUpdate",
@@ -605,36 +572,50 @@ export class LightClientServer {
605
572
  */
606
573
  private async maybeStoreNewBestUpdate(
607
574
  syncPeriod: SyncPeriod,
608
- syncAggregate: altair.SyncAggregate,
609
- signatureSlot: Slot,
610
- attestedData: SyncAttestedData
575
+ built: {update: LightClientUpdate; summary: LightClientUpdateSummary}
611
576
  ): Promise<void> {
612
577
  const prevBestUpdate = await this.db.bestLightClientUpdate.get(syncPeriod);
613
- const {attestedHeader} = attestedData;
578
+ if (prevBestUpdate && !isBetterUpdate(built.summary, toLightClientUpdateSummary(prevBestUpdate))) {
579
+ this.metrics?.lightclientServer.updateNotBetter.inc();
580
+ return;
581
+ }
614
582
 
615
- if (prevBestUpdate) {
616
- const prevBestUpdateSummary = toLightClientUpdateSummary(prevBestUpdate);
583
+ // attestedData and the block of syncAggregate may not be in same sync period
584
+ // should not use attested data slot as sync period
585
+ // see https://github.com/ChainSafe/lodestar/issues/3933
586
+ await this.db.bestLightClientUpdate.put(syncPeriod, built.update);
587
+ this.logger.debug("Stored new PartialLightClientUpdate", {
588
+ syncPeriod,
589
+ isFinalized: built.summary.isFinalityUpdate,
590
+ participation: sumBits(built.update.syncAggregate.syncCommitteeBits) / SYNC_COMMITTEE_SIZE,
591
+ });
617
592
 
618
- const nextBestUpdate: LightClientUpdateSummary = {
619
- activeParticipants: sumBits(syncAggregate.syncCommitteeBits),
620
- attestedHeaderSlot: attestedHeader.beacon.slot,
621
- signatureSlot,
622
- // The actual finalizedHeader is fetched below. To prevent a DB read we approximate the actual slot.
623
- // If update is not finalized finalizedHeaderSlot does not matter (see is_better_update), so setting
624
- // to zero to set it some number.
625
- finalizedHeaderSlot: attestedData.isFinalized
626
- ? computeStartSlotAtEpoch(attestedData.finalizedCheckpoint.epoch)
627
- : 0,
628
- // All updates include a valid `nextSyncCommitteeBranch`, see below code
629
- isSyncCommitteeUpdate: true,
630
- isFinalityUpdate: attestedData.isFinalized,
631
- };
593
+ // Count total persisted updates per type. DB metrics don't diff between each type.
594
+ // The frequency of finalized vs non-finalized is critical to debug if finalizedHeader is not available
595
+ this.metrics?.lightclientServer.onSyncAggregate.inc({
596
+ event: built.summary.isFinalityUpdate ? "store_finalized_update" : "store_nonfinalized_update",
597
+ });
598
+ this.metrics?.lightclientServer.highestSlot.set(
599
+ {item: built.summary.isFinalityUpdate ? "best_finalized_update" : "best_nonfinalized_update"},
600
+ built.update.attestedHeader.beacon.slot
601
+ );
602
+ }
632
603
 
633
- if (!isBetterUpdate(nextBestUpdate, prevBestUpdateSummary)) {
634
- this.metrics?.lightclientServer.updateNotBetter.inc();
635
- return;
636
- }
637
- }
604
+ /**
605
+ * Build the update for `syncAggregate` attesting to `attestedData`.
606
+ *
607
+ * Finality is indicated whenever it can be proven, in one of three ways:
608
+ * - the finalized checkpoint is genesis: the branch is served, the header stays empty, since
609
+ * genesis cannot be proven by a header and the branch alone proves that `finalized_root` is zero
610
+ * - the finalized header is available locally: both the header and the branch are served
611
+ * - the finalized header is not available: neither is served, and `hasFinality` is false
612
+ */
613
+ private async buildUpdate(
614
+ attestedData: SyncAttestedData,
615
+ syncAggregate: altair.SyncAggregate,
616
+ signatureSlot: Slot
617
+ ): Promise<{update: LightClientUpdate; summary: LightClientUpdateSummary; hasFinality: boolean} | null> {
618
+ const {attestedHeader} = attestedData;
638
619
 
639
620
  const syncCommitteeWitness = await this.db.syncCommitteeWitness.get(attestedData.blockRoot);
640
621
  if (!syncCommitteeWitness) {
@@ -662,41 +643,34 @@ export class LightClientServer {
662
643
  throw Error("nextSyncCommittee not available");
663
644
  }
664
645
  const nextSyncCommitteeBranch = getNextSyncCommitteeBranch(syncCommitteeWitness);
665
- const finalizedHeaderAttested = attestedData.isFinalized
666
- ? await this.getFinalizedHeader(attestedData.finalizedCheckpoint.root)
667
- : null;
668
646
 
669
- let isFinalized: boolean, finalityBranch: Uint8Array[], finalizedHeader: LightClientHeader;
647
+ const zeroFinality = this.getZeroFinality(attestedFork, attestedHeader.beacon.slot);
648
+ const {finalizedCheckpoint} = attestedData;
649
+ let finalityBranch = zeroFinality.finalityBranch;
650
+ let finalizedHeader = zeroFinality.finalizedHeader;
651
+ let hasFinality = false;
670
652
 
671
- if (
672
- attestedData.isFinalized &&
673
- finalizedHeaderAttested &&
674
- computeSyncPeriodAtSlot(finalizedHeaderAttested.beacon.slot) === syncPeriod
675
- ) {
676
- isFinalized = true;
653
+ if (finalizedCheckpoint.epoch === GENESIS_EPOCH) {
654
+ // Genesis cannot be proven by a header, the branch alone proves that finalized_root is zero
677
655
  finalityBranch = attestedData.finalityBranch;
678
- finalizedHeader = finalizedHeaderAttested;
679
- // Fork of LightClientUpdate is based off on attested header's fork
680
- if (this.config.getForkName(finalizedHeader.beacon.slot) !== attestedFork) {
681
- finalizedHeader = upgradeLightClientHeader(this.config, attestedFork, finalizedHeader);
682
- }
656
+ hasFinality = true;
683
657
  } else {
684
- isFinalized = false;
685
- let zeroFinality = this.zeroFinalityByFork.get(attestedFork);
686
- if (!zeroFinality) {
687
- const {finalityBranch, finalizedHeader} = this.config
688
- .getPostAltairForkTypes(attestedHeader.beacon.slot)
689
- .LightClientUpdate.defaultValue();
690
- zeroFinality = {finalityBranch, finalizedHeader};
691
- this.zeroFinalityByFork.set(attestedFork, zeroFinality);
658
+ const finalizedHeaderAttested = await this.getFinalizedHeader(finalizedCheckpoint.root);
659
+ // If the finalized block is not available locally, both stay empty
660
+ if (finalizedHeaderAttested) {
661
+ finalityBranch = attestedData.finalityBranch;
662
+ finalizedHeader = finalizedHeaderAttested;
663
+ hasFinality = true;
664
+ // Fork of LightClientUpdate is based off on attested header's fork
665
+ if (this.config.getForkName(finalizedHeader.beacon.slot) !== attestedFork) {
666
+ finalizedHeader = upgradeLightClientHeader(this.config, attestedFork, finalizedHeader);
667
+ }
692
668
  }
693
- finalityBranch = zeroFinality.finalityBranch;
694
- finalizedHeader = zeroFinality.finalizedHeader;
695
669
  }
696
670
 
697
- const newUpdate = {
671
+ const update = {
698
672
  attestedHeader,
699
- nextSyncCommittee: nextSyncCommittee,
673
+ nextSyncCommittee,
700
674
  nextSyncCommitteeBranch,
701
675
  finalizedHeader,
702
676
  finalityBranch,
@@ -704,25 +678,17 @@ export class LightClientServer {
704
678
  signatureSlot,
705
679
  } as LightClientUpdate;
706
680
 
707
- // attestedData and the block of syncAggregate may not be in same sync period
708
- // should not use attested data slot as sync period
709
- // see https://github.com/ChainSafe/lodestar/issues/3933
710
- await this.db.bestLightClientUpdate.put(syncPeriod, newUpdate);
711
- this.logger.debug("Stored new PartialLightClientUpdate", {
712
- syncPeriod,
713
- isFinalized,
714
- participation: sumBits(syncAggregate.syncCommitteeBits) / SYNC_COMMITTEE_SIZE,
715
- });
681
+ return {update, summary: toLightClientUpdateSummary(update), hasFinality};
682
+ }
716
683
 
717
- // Count total persisted updates per type. DB metrics don't diff between each type.
718
- // The frequency of finalized vs non-finalized is critical to debug if finalizedHeader is not available
719
- this.metrics?.lightclientServer.onSyncAggregate.inc({
720
- event: isFinalized ? "store_finalized_update" : "store_nonfinalized_update",
721
- });
722
- this.metrics?.lightclientServer.highestSlot.set(
723
- {item: isFinalized ? "best_finalized_update" : "best_nonfinalized_update"},
724
- newUpdate.attestedHeader.beacon.slot
725
- );
684
+ private getZeroFinality(attestedFork: ForkName, attestedSlot: Slot): LightClientZeroFinality {
685
+ let zeroFinality = this.zeroFinalityByFork.get(attestedFork);
686
+ if (!zeroFinality) {
687
+ const zero = this.config.getPostAltairForkTypes(attestedSlot).LightClientUpdate.defaultValue();
688
+ zeroFinality = {finalityBranch: zero.finalityBranch, finalizedHeader: zero.finalizedHeader};
689
+ this.zeroFinalityByFork.set(attestedFork, zeroFinality);
690
+ }
691
+ return zeroFinality;
726
692
  }
727
693
 
728
694
  private async storeSyncCommittee(syncCommittee: altair.SyncCommittee, syncCommitteeRoot: Uint8Array): Promise<void> {
@@ -2,7 +2,7 @@ import {Logger} from "@lodestar/logger";
2
2
  import {ForkName, ForkPostFulu, ForkSeq, SLOTS_PER_EPOCH, isForkPostBellatrix} from "@lodestar/params";
3
3
  import {BlobsBundle, ExecutionPayload, ExecutionRequests, Root, RootHex, Wei, bellatrix} from "@lodestar/types";
4
4
  import {BlobAndProofV2} from "@lodestar/types/fulu";
5
- import {isErrorAborted} from "@lodestar/utils";
5
+ import {ErrorAborted, isErrorAborted} from "@lodestar/utils";
6
6
  import {Metrics} from "../../metrics/index.js";
7
7
  import {EPOCHS_PER_BATCH} from "../../sync/constants.js";
8
8
  import {getLodestarClientVersion} from "../../util/metadata.js";
@@ -334,13 +334,18 @@ export class ExecutionEngineHttp implements IExecutionEngine {
334
334
  headBlockHash: RootHex,
335
335
  safeBlockHash: RootHex,
336
336
  finalizedBlockHash: RootHex,
337
- payloadAttributes?: PayloadAttributes
337
+ payloadAttributes?: PayloadAttributes,
338
+ signal?: AbortSignal
338
339
  ): Promise<ForkchoiceUpdatedResult> {
339
- const result = await this.enqueue(() =>
340
- this.withTransport(fork, undefined, (transport) =>
341
- transport.forkchoiceUpdated(fork, headBlockHash, safeBlockHash, finalizedBlockHash, payloadAttributes)
342
- )
343
- );
340
+ const result = await this.enqueue(() => {
341
+ // Aborted while waiting in the queue, do not select a transport and sign a request that is not sent
342
+ if (signal?.aborted) {
343
+ throw new ErrorAborted("notifyForkchoiceUpdate");
344
+ }
345
+ return this.withTransport(fork, undefined, (transport) =>
346
+ transport.forkchoiceUpdated(fork, headBlockHash, safeBlockHash, finalizedBlockHash, payloadAttributes, signal)
347
+ );
348
+ });
344
349
  const {
345
350
  payloadStatus: {status},
346
351
  payloadId,
@@ -394,7 +399,8 @@ export class ExecutionEngineHttp implements IExecutionEngine {
394
399
  */
395
400
  async getPayload(
396
401
  fork: ForkName,
397
- payloadId: PayloadId
402
+ payloadId: PayloadId,
403
+ signal?: AbortSignal
398
404
  ): Promise<{
399
405
  executionPayload: ExecutionPayload;
400
406
  executionPayloadValue: Wei;
@@ -402,7 +408,7 @@ export class ExecutionEngineHttp implements IExecutionEngine {
402
408
  executionRequests?: ExecutionRequests;
403
409
  shouldOverrideBuilder?: boolean;
404
410
  }> {
405
- return this.withTransport(fork, undefined, (transport) => transport.getPayload(fork, payloadId));
411
+ return this.withTransport(fork, undefined, (transport) => transport.getPayload(fork, payloadId, signal));
406
412
  }
407
413
 
408
414
  async prunePayloadIdCache(): Promise<void> {
@@ -187,7 +187,8 @@ export interface IExecutionEngine {
187
187
  headBlockHash: RootHex,
188
188
  safeBlockHash: RootHex,
189
189
  finalizedBlockHash: RootHex,
190
- payloadAttributes?: PayloadAttributes
190
+ payloadAttributes?: PayloadAttributes,
191
+ signal?: AbortSignal
191
192
  ): Promise<ForkchoiceUpdatedResult>;
192
193
 
193
194
  /**
@@ -199,7 +200,8 @@ export interface IExecutionEngine {
199
200
  */
200
201
  getPayload(
201
202
  fork: ForkName,
202
- payloadId: PayloadId
203
+ payloadId: PayloadId,
204
+ signal?: AbortSignal
203
205
  ): Promise<{
204
206
  executionPayload: ExecutionPayload;
205
207
  executionPayloadValue: Wei;
@@ -2,6 +2,7 @@ import {EventEmitter} from "node:events";
2
2
  import {StrictEventEmitter} from "strict-event-emitter-types";
3
3
  import {ErrorAborted, Gauge, Histogram, TimeoutError, fetch, isValidHttpUrl, retry} from "@lodestar/utils";
4
4
  import {JwtClaim, encodeJwtToken} from "./jwt.js";
5
+ import {withRequestSignal} from "./signal.js";
5
6
  import {EngineTransportMetrics} from "./transportMetrics.js";
6
7
  import {IJson, RpcPayload} from "./utils.js";
7
8
 
@@ -54,6 +55,8 @@ export type ReqOpts = {
54
55
  retries?: number;
55
56
  retryDelay?: number;
56
57
  shouldRetry?: (lastError: Error) => boolean;
58
+ /** Aborts this request only, in addition to the signal of the client */
59
+ signal?: AbortSignal;
57
60
  };
58
61
 
59
62
  export type JsonRpcHttpClientMetrics = EngineTransportMetrics & {
@@ -157,19 +160,23 @@ export class JsonRpcHttpClient implements IJsonRpcHttpClient {
157
160
  return this.wrapWithEvents(async () => {
158
161
  const routeId = opts?.routeId ?? "unknown";
159
162
 
160
- const res = await retry<RpcResponse<R>>(
161
- async (_attempt) => {
162
- return this.fetchJson({jsonrpc: "2.0", id: this.id++, ...payload}, opts);
163
- },
164
- {
165
- retries: opts?.retries ?? this.opts?.retries ?? 0,
166
- retryDelay: opts?.retryDelay ?? this.opts?.retryDelay,
167
- shouldRetry: opts?.shouldRetry,
168
- signal: this.opts?.signal,
169
- onRetry: () => {
170
- this.opts?.metrics?.retryCount.inc({routeId});
163
+ // The delay between retries has to end with the request signal as well
164
+ const res = await withRequestSignal(this.opts?.signal, opts?.signal, (signal) =>
165
+ retry<RpcResponse<R>>(
166
+ async (_attempt) => {
167
+ return this.fetchJson({jsonrpc: "2.0", id: this.id++, ...payload}, opts);
171
168
  },
172
- }
169
+ {
170
+ retries: opts?.retries ?? this.opts?.retries ?? 0,
171
+ retryDelay: opts?.retryDelay ?? this.opts?.retryDelay,
172
+ // An aborted request is no longer of interest to its caller
173
+ shouldRetry: (lastError) => !opts?.signal?.aborted && (opts?.shouldRetry?.(lastError) ?? true),
174
+ signal,
175
+ onRetry: () => {
176
+ this.opts?.metrics?.retryCount.inc({routeId});
177
+ },
178
+ }
179
+ )
173
180
  );
174
181
  return parseRpcResponse(res, payload);
175
182
  }, payload);
@@ -244,6 +251,10 @@ export class JsonRpcHttpClient implements IJsonRpcHttpClient {
244
251
 
245
252
  const onParentSignalAbort = (): void => controller.abort();
246
253
  this.opts?.signal?.addEventListener("abort", onParentSignalAbort, {once: true});
254
+ opts?.signal?.addEventListener("abort", onParentSignalAbort, {once: true});
255
+ if (opts?.signal?.aborted) {
256
+ controller.abort();
257
+ }
247
258
 
248
259
  // Default to "unknown" to prevent mixing metrics with others.
249
260
  const routeId = opts?.routeId ?? "unknown";
@@ -306,8 +317,8 @@ export class JsonRpcHttpClient implements IJsonRpcHttpClient {
306
317
  } catch (e) {
307
318
  this.metrics?.requestErrors.inc({routeId});
308
319
  if (controller.signal.aborted) {
309
- // controller will abort on both parent signal abort + timeout of this specific request
310
- if (this.opts?.signal?.aborted) {
320
+ // controller will abort on parent signal abort, request signal abort + timeout of this specific request
321
+ if (this.opts?.signal?.aborted || opts?.signal?.aborted) {
311
322
  throw new ErrorAborted("request");
312
323
  }
313
324
  throw new TimeoutError("request");
@@ -319,6 +330,7 @@ export class JsonRpcHttpClient implements IJsonRpcHttpClient {
319
330
 
320
331
  clearTimeout(timeout);
321
332
  this.opts?.signal?.removeEventListener("abort", onParentSignalAbort);
333
+ opts?.signal?.removeEventListener("abort", onParentSignalAbort);
322
334
  }
323
335
  }
324
336
  }
@@ -141,7 +141,8 @@ export class JsonRpcEngineTransport implements IEngineTransport {
141
141
  headBlockHash: RootHex,
142
142
  safeBlockHash: RootHex,
143
143
  finalizedBlockHash: RootHex,
144
- payloadAttributes?: PayloadAttributes
144
+ payloadAttributes?: PayloadAttributes,
145
+ signal?: AbortSignal
145
146
  ): Promise<ForkchoiceUpdatedResult> {
146
147
  const method =
147
148
  ForkSeq[fork] >= ForkSeq.heze
@@ -161,12 +162,15 @@ export class JsonRpcEngineTransport implements IEngineTransport {
161
162
  const {payloadStatus, payloadId} = await this.rpc.fetchWithRetries<
162
163
  EngineApiRpcReturnTypes[typeof method],
163
164
  EngineApiRpcParamTypes[typeof method]
164
- >({method, params: [{headBlockHash, safeBlockHash, finalizedBlockHash}, payloadAttributesRpc]}, fcUReqOpts);
165
+ >(
166
+ {method, params: [{headBlockHash, safeBlockHash, finalizedBlockHash}, payloadAttributesRpc]},
167
+ {...fcUReqOpts, signal}
168
+ );
165
169
 
166
170
  return {payloadStatus, payloadId: payloadId && payloadId !== "0x" ? payloadId : null};
167
171
  }
168
172
 
169
- async getPayload(fork: ForkName, payloadId: PayloadId): Promise<GetPayloadResult> {
173
+ async getPayload(fork: ForkName, payloadId: PayloadId, signal?: AbortSignal): Promise<GetPayloadResult> {
170
174
  let method: keyof EngineApiRpcReturnTypes;
171
175
  switch (fork) {
172
176
  case ForkName.phase0:
@@ -193,7 +197,7 @@ export class JsonRpcEngineTransport implements IEngineTransport {
193
197
  const payloadResponse = await this.rpc.fetchWithRetries<
194
198
  EngineApiRpcReturnTypes[typeof method],
195
199
  EngineApiRpcParamTypes[typeof method]
196
- >({method, params: [payloadId]}, getPayloadOpts);
200
+ >({method, params: [payloadId]}, {...getPayloadOpts, signal});
197
201
  return parseExecutionPayload(fork, payloadResponse);
198
202
  }
199
203
 
@@ -6,6 +6,7 @@ import {
6
6
  ReqOpts,
7
7
  } from "./jsonRpcHttpClient.js";
8
8
  import {JwtClaim, encodeJwtToken} from "./jwt.js";
9
+ import {withRequestSignal} from "./signal.js";
9
10
  import {ExecutionForkName} from "./sszTypes.js";
10
11
 
11
12
  export const ENGINE_REST_BASE_PATH = "/engine/v1";
@@ -115,15 +116,18 @@ export class EngineRestHttpClient {
115
116
  /** Perform request with retries without emitting events, used to probe support for the REST API */
116
117
  async requestWithRetries(req: EngineRestRequest, opts?: ReqOpts): Promise<EngineRestResponse> {
117
118
  const routeId = opts?.routeId ?? "unknown";
118
- return retry(() => this.requestAnyUrl(req, opts), {
119
- retries: opts?.retries ?? this.opts.retries ?? 0,
120
- retryDelay: opts?.retryDelay ?? this.opts.retryDelay,
121
- shouldRetry: opts?.shouldRetry ?? isRetryableEngineRestError,
122
- signal: this.opts.signal,
123
- onRetry: () => {
124
- this.metrics?.retryCount.inc({routeId});
125
- },
126
- });
119
+ // The delay between retries has to end with the request signal as well
120
+ return withRequestSignal(this.opts.signal, opts?.signal, (signal) =>
121
+ retry(() => this.requestAnyUrl(req, opts), {
122
+ retries: opts?.retries ?? this.opts.retries ?? 0,
123
+ retryDelay: opts?.retryDelay ?? this.opts.retryDelay,
124
+ shouldRetry: opts?.shouldRetry ?? isRetryableEngineRestError,
125
+ signal,
126
+ onRetry: () => {
127
+ this.metrics?.retryCount.inc({routeId});
128
+ },
129
+ })
130
+ );
127
131
  }
128
132
 
129
133
  private async requestAnyUrl(req: EngineRestRequest, opts?: ReqOpts): Promise<EngineRestResponse> {
@@ -154,7 +158,8 @@ export class EngineRestHttpClient {
154
158
  // Not AbortSignal.any(), Node retains every composite until the long-lived parent signal aborts
155
159
  const onParentSignalAbort = (): void => controller.abort();
156
160
  this.opts.signal?.addEventListener("abort", onParentSignalAbort, {once: true});
157
- if (this.opts.signal?.aborted) {
161
+ opts?.signal?.addEventListener("abort", onParentSignalAbort, {once: true});
162
+ if (this.opts.signal?.aborted || opts?.signal?.aborted) {
158
163
  controller.abort();
159
164
  }
160
165
 
@@ -223,7 +228,7 @@ export class EngineRestHttpClient {
223
228
  } catch (e) {
224
229
  this.metrics?.requestErrors.inc({routeId});
225
230
  if (controller.signal.aborted) {
226
- if (this.opts.signal?.aborted) {
231
+ if (this.opts.signal?.aborted || opts?.signal?.aborted) {
227
232
  throw new ErrorAborted("request");
228
233
  }
229
234
  throw new TimeoutError("request");
@@ -235,6 +240,7 @@ export class EngineRestHttpClient {
235
240
 
236
241
  clearTimeout(timeout);
237
242
  this.opts.signal?.removeEventListener("abort", onParentSignalAbort);
243
+ opts?.signal?.removeEventListener("abort", onParentSignalAbort);
238
244
  }
239
245
  }
240
246
  }