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

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 (86) 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 +13 -7
  14. package/lib/execution/engine/http.js.map +1 -1
  15. package/lib/execution/engine/interface.d.ts +16 -3
  16. package/lib/execution/engine/interface.d.ts.map +1 -1
  17. package/lib/execution/engine/interface.js +11 -0
  18. package/lib/execution/engine/interface.js.map +1 -1
  19. package/lib/execution/engine/jsonRpcHttpClient.d.ts +2 -0
  20. package/lib/execution/engine/jsonRpcHttpClient.d.ts.map +1 -1
  21. package/lib/execution/engine/jsonRpcHttpClient.js +14 -6
  22. package/lib/execution/engine/jsonRpcHttpClient.js.map +1 -1
  23. package/lib/execution/engine/jsonRpcTransport.d.ts +2 -2
  24. package/lib/execution/engine/jsonRpcTransport.d.ts.map +1 -1
  25. package/lib/execution/engine/jsonRpcTransport.js +4 -4
  26. package/lib/execution/engine/jsonRpcTransport.js.map +1 -1
  27. package/lib/execution/engine/restHttpClient.d.ts.map +1 -1
  28. package/lib/execution/engine/restHttpClient.js +9 -5
  29. package/lib/execution/engine/restHttpClient.js.map +1 -1
  30. package/lib/execution/engine/restTransport.d.ts +2 -2
  31. package/lib/execution/engine/restTransport.d.ts.map +1 -1
  32. package/lib/execution/engine/restTransport.js +4 -4
  33. package/lib/execution/engine/restTransport.js.map +1 -1
  34. package/lib/execution/engine/signal.d.ts +6 -0
  35. package/lib/execution/engine/signal.d.ts.map +1 -0
  36. package/lib/execution/engine/signal.js +24 -0
  37. package/lib/execution/engine/signal.js.map +1 -0
  38. package/lib/execution/engine/transport.d.ts +2 -2
  39. package/lib/execution/engine/transport.d.ts.map +1 -1
  40. package/lib/index.d.ts +1 -1
  41. package/lib/index.d.ts.map +1 -1
  42. package/lib/index.js +1 -1
  43. package/lib/index.js.map +1 -1
  44. package/lib/network/gossip/gossipsub.d.ts +1 -0
  45. package/lib/network/gossip/gossipsub.d.ts.map +1 -1
  46. package/lib/network/gossip/gossipsub.js +3 -0
  47. package/lib/network/gossip/gossipsub.js.map +1 -1
  48. package/lib/network/network.d.ts.map +1 -1
  49. package/lib/network/network.js +6 -1
  50. package/lib/network/network.js.map +1 -1
  51. package/lib/network/peers/peerManager.d.ts.map +1 -1
  52. package/lib/network/peers/peerManager.js +22 -2
  53. package/lib/network/peers/peerManager.js.map +1 -1
  54. package/lib/network/peers/utils/prioritizePeers.d.ts +2 -0
  55. package/lib/network/peers/utils/prioritizePeers.d.ts.map +1 -1
  56. package/lib/network/peers/utils/prioritizePeers.js +11 -2
  57. package/lib/network/peers/utils/prioritizePeers.js.map +1 -1
  58. package/lib/sync/types.d.ts +2 -0
  59. package/lib/sync/types.d.ts.map +1 -1
  60. package/lib/sync/types.js.map +1 -1
  61. package/lib/sync/unknownBlock.d.ts.map +1 -1
  62. package/lib/sync/unknownBlock.js +123 -22
  63. package/lib/sync/unknownBlock.js.map +1 -1
  64. package/lib/sync/utils/downloadByRoot.d.ts.map +1 -1
  65. package/lib/sync/utils/downloadByRoot.js +5 -4
  66. package/lib/sync/utils/downloadByRoot.js.map +1 -1
  67. package/package.json +25 -25
  68. package/src/chain/archiveStore/historicalState/getHistoricalState.ts +9 -0
  69. package/src/chain/archiveStore/utils/pruneHistory.ts +9 -4
  70. package/src/chain/lightClient/index.ts +108 -142
  71. package/src/execution/engine/http.ts +18 -10
  72. package/src/execution/engine/interface.ts +18 -3
  73. package/src/execution/engine/jsonRpcHttpClient.ts +26 -14
  74. package/src/execution/engine/jsonRpcTransport.ts +8 -4
  75. package/src/execution/engine/restHttpClient.ts +17 -11
  76. package/src/execution/engine/restTransport.ts +5 -4
  77. package/src/execution/engine/signal.ts +28 -0
  78. package/src/execution/engine/transport.ts +3 -2
  79. package/src/index.ts +6 -1
  80. package/src/network/gossip/gossipsub.ts +4 -0
  81. package/src/network/network.ts +6 -2
  82. package/src/network/peers/peerManager.ts +26 -2
  83. package/src/network/peers/utils/prioritizePeers.ts +14 -1
  84. package/src/sync/types.ts +2 -0
  85. package/src/sync/unknownBlock.ts +133 -23
  86. 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";
@@ -11,6 +11,8 @@ import {JobItemQueue} from "../../util/queue/index.js";
11
11
  import {
12
12
  ClientVersion,
13
13
  ExecutePayloadResponse,
14
+ ExecutionEngineError,
15
+ ExecutionEngineErrorCode,
14
16
  ExecutionEngineState,
15
17
  ExecutionPayloadStatus,
16
18
  ForkchoiceUpdatedResult,
@@ -334,13 +336,18 @@ export class ExecutionEngineHttp implements IExecutionEngine {
334
336
  headBlockHash: RootHex,
335
337
  safeBlockHash: RootHex,
336
338
  finalizedBlockHash: RootHex,
337
- payloadAttributes?: PayloadAttributes
339
+ payloadAttributes?: PayloadAttributes,
340
+ signal?: AbortSignal
338
341
  ): Promise<ForkchoiceUpdatedResult> {
339
- const result = await this.enqueue(() =>
340
- this.withTransport(fork, undefined, (transport) =>
341
- transport.forkchoiceUpdated(fork, headBlockHash, safeBlockHash, finalizedBlockHash, payloadAttributes)
342
- )
343
- );
342
+ const result = await this.enqueue(() => {
343
+ // Aborted while waiting in the queue, do not select a transport and sign a request that is not sent
344
+ if (signal?.aborted) {
345
+ throw new ErrorAborted("notifyForkchoiceUpdate");
346
+ }
347
+ return this.withTransport(fork, undefined, (transport) =>
348
+ transport.forkchoiceUpdated(fork, headBlockHash, safeBlockHash, finalizedBlockHash, payloadAttributes, signal)
349
+ );
350
+ });
344
351
  const {
345
352
  payloadStatus: {status},
346
353
  payloadId,
@@ -373,7 +380,7 @@ export class ExecutionEngineHttp implements IExecutionEngine {
373
380
  case ExecutionPayloadStatus.SYNCING:
374
381
  // Throw error on syncing if requested to produce a block, else silently ignore
375
382
  if (payloadAttributes) {
376
- throw Error("Execution Layer Syncing");
383
+ throw new ExecutionEngineError({code: ExecutionEngineErrorCode.SYNCING}, "Execution Layer Syncing");
377
384
  }
378
385
  return result;
379
386
 
@@ -394,7 +401,8 @@ export class ExecutionEngineHttp implements IExecutionEngine {
394
401
  */
395
402
  async getPayload(
396
403
  fork: ForkName,
397
- payloadId: PayloadId
404
+ payloadId: PayloadId,
405
+ signal?: AbortSignal
398
406
  ): Promise<{
399
407
  executionPayload: ExecutionPayload;
400
408
  executionPayloadValue: Wei;
@@ -402,7 +410,7 @@ export class ExecutionEngineHttp implements IExecutionEngine {
402
410
  executionRequests?: ExecutionRequests;
403
411
  shouldOverrideBuilder?: boolean;
404
412
  }> {
405
- return this.withTransport(fork, undefined, (transport) => transport.getPayload(fork, payloadId));
413
+ return this.withTransport(fork, undefined, (transport) => transport.getPayload(fork, payloadId, signal));
406
414
  }
407
415
 
408
416
  async prunePayloadIdCache(): Promise<void> {
@@ -19,6 +19,7 @@ import {
19
19
  capella,
20
20
  } from "@lodestar/types";
21
21
  import {BlobAndProofV2} from "@lodestar/types/fulu";
22
+ import {LodestarError} from "@lodestar/utils";
22
23
  import {PayloadId, PayloadIdCache, WithdrawalV1} from "./payloadIdCache.js";
23
24
  import {ExecutionPayloadBodyV2} from "./types.js";
24
25
  import {DATA} from "./utils.js";
@@ -131,6 +132,18 @@ export type PayloadAttributes = {
131
132
 
132
133
  export type VersionedHashes = Uint8Array[];
133
134
 
135
+ export enum ExecutionEngineErrorCode {
136
+ /**
137
+ * `notifyForkchoiceUpdate` requested a payload while the execution client is syncing, the head block is not
138
+ * available to build on yet
139
+ */
140
+ SYNCING = "EXECUTION_ENGINE_ERROR_SYNCING",
141
+ }
142
+
143
+ export type ExecutionEngineErrorType = {code: ExecutionEngineErrorCode.SYNCING};
144
+
145
+ export class ExecutionEngineError extends LodestarError<ExecutionEngineErrorType> {}
146
+
134
147
  /**
135
148
  * Execution engine represents an abstract protocol to interact with execution clients. Potential transports include:
136
149
  * - JSON RPC over network
@@ -180,14 +193,15 @@ export interface IExecutionEngine {
180
193
  * Should be called in response to fork-choice head and finalized events.
181
194
  *
182
195
  * An INVALID verdict is returned, not thrown: the caller feeds it back into fork choice together with the
183
- * `latestValidHash`. Only SYNCING while building a payload is an error.
196
+ * `latestValidHash`. Only SYNCING while building a payload is an error, thrown as `ExecutionEngineError` with code `SYNCING`.
184
197
  */
185
198
  notifyForkchoiceUpdate(
186
199
  fork: ForkName,
187
200
  headBlockHash: RootHex,
188
201
  safeBlockHash: RootHex,
189
202
  finalizedBlockHash: RootHex,
190
- payloadAttributes?: PayloadAttributes
203
+ payloadAttributes?: PayloadAttributes,
204
+ signal?: AbortSignal
191
205
  ): Promise<ForkchoiceUpdatedResult>;
192
206
 
193
207
  /**
@@ -199,7 +213,8 @@ export interface IExecutionEngine {
199
213
  */
200
214
  getPayload(
201
215
  fork: ForkName,
202
- payloadId: PayloadId
216
+ payloadId: PayloadId,
217
+ signal?: AbortSignal
203
218
  ): Promise<{
204
219
  executionPayload: ExecutionPayload;
205
220
  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