@lodestar/beacon-node 1.50.0-dev.45e4260336 → 1.50.0-dev.52b7101ea2

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 (133) hide show
  1. package/lib/api/impl/beacon/state/index.d.ts.map +1 -1
  2. package/lib/api/impl/beacon/state/index.js +28 -6
  3. package/lib/api/impl/beacon/state/index.js.map +1 -1
  4. package/lib/api/impl/debug/index.d.ts.map +1 -1
  5. package/lib/api/impl/debug/index.js +4 -0
  6. package/lib/api/impl/debug/index.js.map +1 -1
  7. package/lib/chain/archiveStore/archiveStore.d.ts +5 -0
  8. package/lib/chain/archiveStore/archiveStore.d.ts.map +1 -1
  9. package/lib/chain/archiveStore/archiveStore.js +13 -23
  10. package/lib/chain/archiveStore/archiveStore.js.map +1 -1
  11. package/lib/chain/archiveStore/utils/pruneHistory.d.ts +1 -1
  12. package/lib/chain/archiveStore/utils/pruneHistory.d.ts.map +1 -1
  13. package/lib/chain/archiveStore/utils/pruneHistory.js +2 -1
  14. package/lib/chain/archiveStore/utils/pruneHistory.js.map +1 -1
  15. package/lib/chain/blocks/importBlock.d.ts.map +1 -1
  16. package/lib/chain/blocks/importBlock.js +13 -6
  17. package/lib/chain/blocks/importBlock.js.map +1 -1
  18. package/lib/chain/blocks/verifyBlock.d.ts.map +1 -1
  19. package/lib/chain/blocks/verifyBlock.js +6 -6
  20. package/lib/chain/blocks/verifyBlock.js.map +1 -1
  21. package/lib/chain/chain.d.ts +2 -1
  22. package/lib/chain/chain.d.ts.map +1 -1
  23. package/lib/chain/chain.js +42 -19
  24. package/lib/chain/chain.js.map +1 -1
  25. package/lib/chain/opPools/aggregatedAttestationPool.d.ts +4 -2
  26. package/lib/chain/opPools/aggregatedAttestationPool.d.ts.map +1 -1
  27. package/lib/chain/opPools/aggregatedAttestationPool.js +30 -8
  28. package/lib/chain/opPools/aggregatedAttestationPool.js.map +1 -1
  29. package/lib/chain/opPools/opPool.d.ts.map +1 -1
  30. package/lib/chain/opPools/opPool.js +1 -23
  31. package/lib/chain/opPools/opPool.js.map +1 -1
  32. package/lib/chain/opPools/proposerPreferencesPool.d.ts +4 -0
  33. package/lib/chain/opPools/proposerPreferencesPool.d.ts.map +1 -1
  34. package/lib/chain/opPools/proposerPreferencesPool.js +13 -1
  35. package/lib/chain/opPools/proposerPreferencesPool.js.map +1 -1
  36. package/lib/chain/opPools/utils.d.ts +11 -0
  37. package/lib/chain/opPools/utils.d.ts.map +1 -1
  38. package/lib/chain/opPools/utils.js +22 -0
  39. package/lib/chain/opPools/utils.js.map +1 -1
  40. package/lib/chain/seenCache/seenGossipBlockInput.d.ts +7 -0
  41. package/lib/chain/seenCache/seenGossipBlockInput.d.ts.map +1 -1
  42. package/lib/chain/seenCache/seenGossipBlockInput.js +21 -0
  43. package/lib/chain/seenCache/seenGossipBlockInput.js.map +1 -1
  44. package/lib/chain/shufflingCache.d.ts +18 -8
  45. package/lib/chain/shufflingCache.d.ts.map +1 -1
  46. package/lib/chain/shufflingCache.js +72 -18
  47. package/lib/chain/shufflingCache.js.map +1 -1
  48. package/lib/db/beacon.d.ts +4 -1
  49. package/lib/db/beacon.d.ts.map +1 -1
  50. package/lib/db/beacon.js +6 -1
  51. package/lib/db/beacon.js.map +1 -1
  52. package/lib/db/buckets.d.ts +3 -1
  53. package/lib/db/buckets.d.ts.map +1 -1
  54. package/lib/db/buckets.js +2 -0
  55. package/lib/db/buckets.js.map +1 -1
  56. package/lib/db/interface.d.ts +4 -1
  57. package/lib/db/interface.d.ts.map +1 -1
  58. package/lib/db/repositories/blockArchiveIndex.d.ts +2 -2
  59. package/lib/db/repositories/blockArchiveIndex.d.ts.map +1 -1
  60. package/lib/db/repositories/earliestAvailableSlot.d.ts +11 -0
  61. package/lib/db/repositories/earliestAvailableSlot.d.ts.map +1 -0
  62. package/lib/db/repositories/earliestAvailableSlot.js +19 -0
  63. package/lib/db/repositories/earliestAvailableSlot.js.map +1 -0
  64. package/lib/db/repositories/index.d.ts +1 -0
  65. package/lib/db/repositories/index.d.ts.map +1 -1
  66. package/lib/db/repositories/index.js +1 -0
  67. package/lib/db/repositories/index.js.map +1 -1
  68. package/lib/db/repositories/proposerPreferences.d.ts +14 -0
  69. package/lib/db/repositories/proposerPreferences.d.ts.map +1 -0
  70. package/lib/db/repositories/proposerPreferences.js +21 -0
  71. package/lib/db/repositories/proposerPreferences.js.map +1 -0
  72. package/lib/metrics/metrics/lodestar.d.ts +7 -0
  73. package/lib/metrics/metrics/lodestar.d.ts.map +1 -1
  74. package/lib/metrics/metrics/lodestar.js +17 -0
  75. package/lib/metrics/metrics/lodestar.js.map +1 -1
  76. package/lib/network/processor/gossipHandlers.d.ts.map +1 -1
  77. package/lib/network/processor/gossipHandlers.js +59 -63
  78. package/lib/network/processor/gossipHandlers.js.map +1 -1
  79. package/lib/node/nodejs.d.ts +3 -1
  80. package/lib/node/nodejs.d.ts.map +1 -1
  81. package/lib/node/nodejs.js +2 -1
  82. package/lib/node/nodejs.js.map +1 -1
  83. package/lib/sync/range/batch.d.ts +5 -5
  84. package/lib/sync/range/batch.d.ts.map +1 -1
  85. package/lib/sync/range/batch.js +11 -17
  86. package/lib/sync/range/batch.js.map +1 -1
  87. package/lib/sync/range/chain.d.ts +4 -4
  88. package/lib/sync/range/chain.d.ts.map +1 -1
  89. package/lib/sync/range/chain.js +7 -5
  90. package/lib/sync/range/chain.js.map +1 -1
  91. package/lib/sync/range/range.d.ts.map +1 -1
  92. package/lib/sync/range/range.js +25 -11
  93. package/lib/sync/range/range.js.map +1 -1
  94. package/lib/sync/unknownBlock.d.ts +5 -2
  95. package/lib/sync/unknownBlock.d.ts.map +1 -1
  96. package/lib/sync/unknownBlock.js +44 -20
  97. package/lib/sync/unknownBlock.js.map +1 -1
  98. package/lib/sync/utils/downloadByRange.d.ts +38 -14
  99. package/lib/sync/utils/downloadByRange.d.ts.map +1 -1
  100. package/lib/sync/utils/downloadByRange.js +84 -39
  101. package/lib/sync/utils/downloadByRange.js.map +1 -1
  102. package/lib/util/metadata.d.ts.map +1 -1
  103. package/lib/util/metadata.js +2 -1
  104. package/lib/util/metadata.js.map +1 -1
  105. package/package.json +16 -16
  106. package/src/api/impl/beacon/state/index.ts +43 -6
  107. package/src/api/impl/debug/index.ts +4 -0
  108. package/src/chain/archiveStore/archiveStore.ts +18 -24
  109. package/src/chain/archiveStore/utils/pruneHistory.ts +4 -1
  110. package/src/chain/blocks/importBlock.ts +16 -5
  111. package/src/chain/blocks/verifyBlock.ts +7 -6
  112. package/src/chain/chain.ts +53 -18
  113. package/src/chain/opPools/aggregatedAttestationPool.ts +34 -10
  114. package/src/chain/opPools/opPool.ts +1 -31
  115. package/src/chain/opPools/proposerPreferencesPool.ts +20 -1
  116. package/src/chain/opPools/utils.ts +31 -0
  117. package/src/chain/seenCache/seenGossipBlockInput.ts +23 -0
  118. package/src/chain/shufflingCache.ts +84 -22
  119. package/src/db/beacon.ts +6 -0
  120. package/src/db/buckets.ts +2 -0
  121. package/src/db/interface.ts +4 -0
  122. package/src/db/repositories/earliestAvailableSlot.ts +19 -0
  123. package/src/db/repositories/index.ts +1 -0
  124. package/src/db/repositories/proposerPreferences.ts +23 -0
  125. package/src/metrics/metrics/lodestar.ts +18 -0
  126. package/src/network/processor/gossipHandlers.ts +90 -76
  127. package/src/node/nodejs.ts +4 -0
  128. package/src/sync/range/batch.ts +14 -19
  129. package/src/sync/range/chain.ts +9 -7
  130. package/src/sync/range/range.ts +26 -12
  131. package/src/sync/unknownBlock.ts +57 -21
  132. package/src/sync/utils/downloadByRange.ts +123 -58
  133. package/src/util/metadata.ts +2 -1
@@ -113,7 +113,9 @@ export class ArchiveStore {
113
113
  this.logger,
114
114
  this.metrics,
115
115
  this.opts.anchorState.finalizedCheckpoint.epoch,
116
- this.chain.clock.currentEpoch
116
+ this.chain.clock.currentEpoch,
117
+ this.statePruneFromSlot,
118
+ this.advanceEarliestAvailableSlot
117
119
  ),
118
120
  () => this.logger.info("Still pruning historical data, please wait..."),
119
121
  30_000,
@@ -122,26 +124,6 @@ export class ArchiveStore {
122
124
  this.statePruneFromSlot = stateCutoffSlot;
123
125
  }
124
126
 
125
- // Initialize earliestAvailableSlot from the earliest block actually retained (after any pruning
126
- // above), rather than the anchor state slot set in the constructor. On an in-place restart the DB
127
- // still holds finalized history below the anchor; leaving the value at the anchor makes the node
128
- // reject by_range requests (beacon_blocks, execution_payload_envelopes and data_column_sidecars
129
- // all gate on this slot) for data it still retains. An empty archive (e.g. a fresh checkpoint
130
- // sync with nothing below the anchor) leaves the constructor's anchor slot in place.
131
- const earliestArchivedBlockSlot = await this.db.blockArchive.firstKey();
132
- if (earliestArchivedBlockSlot != null) {
133
- const oldEarliestAvailableSlot = this.chain.earliestAvailableSlot;
134
- this.chain.earliestAvailableSlot = earliestArchivedBlockSlot;
135
- this.logger.verbose("Initialized earliestAvailableSlot from retained block archive", {
136
- oldEarliestAvailableSlot,
137
- newEarliestAvailableSlot: earliestArchivedBlockSlot,
138
- });
139
- } else {
140
- this.logger.verbose("Empty block archive on init, keeping anchor earliestAvailableSlot", {
141
- earliestAvailableSlot: this.chain.earliestAvailableSlot,
142
- });
143
- }
144
-
145
127
  if (this.opts.serveHistoricalState) {
146
128
  this.historicalStateRegen = await HistoricalStateRegen.init({
147
129
  opts: {
@@ -158,6 +140,18 @@ export class ArchiveStore {
158
140
  }
159
141
  }
160
142
 
143
+ /**
144
+ * The CLI owns the initial value; this only advances it during pruneHistory.
145
+ * Persisted before any deletion so a crash mid-prune never leaves the floor below deleted data.
146
+ */
147
+ private advanceEarliestAvailableSlot = async (blockCutoffSlot: Slot): Promise<void> => {
148
+ const earliestAvailableSlot = Math.max(this.chain.earliestAvailableSlot, blockCutoffSlot);
149
+ if (earliestAvailableSlot !== this.chain.earliestAvailableSlot) {
150
+ await this.db.earliestAvailableSlot.set(earliestAvailableSlot);
151
+ this.chain.earliestAvailableSlot = earliestAvailableSlot;
152
+ }
153
+ };
154
+
161
155
  async close(): Promise<void> {
162
156
  await this.historicalStateRegen?.close();
163
157
  }
@@ -259,17 +253,17 @@ export class ArchiveStore {
259
253
 
260
254
  if (this.opts.pruneHistory) {
261
255
  timer = this.metrics?.processFinalizedCheckpoint.durationByTask.startTimer();
262
- const {blockCutoffSlot, stateCutoffSlot} = await pruneHistory(
256
+ const {stateCutoffSlot} = await pruneHistory(
263
257
  this.chain.config,
264
258
  this.db,
265
259
  this.logger,
266
260
  this.metrics,
267
261
  finalizedEpoch,
268
262
  this.chain.clock.currentEpoch,
269
- this.statePruneFromSlot
263
+ this.statePruneFromSlot,
264
+ this.advanceEarliestAvailableSlot
270
265
  );
271
266
  this.statePruneFromSlot = stateCutoffSlot;
272
- this.chain.earliestAvailableSlot = Math.max(this.chain.earliestAvailableSlot, blockCutoffSlot);
273
267
  timer?.({source: ArchiveStoreTask.PruneHistory});
274
268
  }
275
269
 
@@ -12,7 +12,8 @@ export async function pruneHistory(
12
12
  metrics: Metrics | null | undefined,
13
13
  finalizedEpoch: Epoch,
14
14
  currentEpoch: Epoch,
15
- statePruneFromSlot: Slot = 0
15
+ statePruneFromSlot: Slot,
16
+ beforePrune: (blockCutoffSlot: Slot) => Promise<void>
16
17
  ): Promise<{blockCutoffSlot: Slot; stateCutoffSlot: Slot}> {
17
18
  const blockCutoffEpoch = Math.min(
18
19
  // set by config, with underflow protection
@@ -51,6 +52,8 @@ export async function pruneHistory(
51
52
  stateSlots: prettyPrintIndices(states),
52
53
  });
53
54
 
55
+ await beforePrune(blockCutoffSlot);
56
+
54
57
  const step1 = metrics?.pruneHistory.pruneKeys.startTimer();
55
58
  await Promise.all([
56
59
  // ->
@@ -22,6 +22,7 @@ import {
22
22
  RootCache,
23
23
  computeEpochAtSlot,
24
24
  computeTimeAtSlot,
25
+ getBeaconCommittees,
25
26
  isStatePostAltair,
26
27
  isStatePostBellatrix,
27
28
  } from "@lodestar/state-transition";
@@ -129,11 +130,17 @@ export async function importBlock(
129
130
 
130
131
  // Should compute checkpoint balances before forkchoice.onBlock
131
132
  this.checkpointBalancesCache.processState(blockRootHex, postState);
132
- if (fork >= ForkSeq.gloas) {
133
+ if (isGloasBeaconBlock(block.message)) {
134
+ // A gloas block has no payload of its own, it inherits the status of the payload it builds on,
135
+ // i.e. the parent variant matching the bid's parent block hash. The parent's default (PENDING)
136
+ // variant does not reflect a SYNCING parent payload, and onBlock would then mark that payload VALID.
133
137
  const parentRootHex = toRootHex(block.message.parentRoot);
134
- const parentBlock = this.forkChoice.getBlockHexDefaultStatus(parentRootHex);
138
+ const parentBlockHashHex = toRootHex(block.message.body.signedExecutionPayloadBid.message.parentBlockHash);
139
+ const parentBlock = this.forkChoice.getBlockHexAndBlockHash(parentRootHex, parentBlockHashHex);
135
140
  if (parentBlock === null) {
136
- throw Error(`Parent block not found in forkChoice, parentRoot=${parentRootHex}`);
141
+ throw Error(
142
+ `Parent block not found in forkChoice, parentRoot=${parentRootHex} parentBlockHash=${parentBlockHashHex}`
143
+ );
137
144
  }
138
145
  if (parentBlock.executionStatus === ExecutionStatus.Invalid) {
139
146
  throw Error(`Parent block has invalid execution status, parentRoot=${parentRootHex}`);
@@ -657,8 +664,12 @@ export function addAttestationPostElectra(
657
664
  } else {
658
665
  const attSlot = attestation.data.slot;
659
666
  const attEpoch = computeEpochAtSlot(attSlot);
660
- const decisionRoot = state.getShufflingDecisionRoot(attEpoch);
661
- const committees = this.shufflingCache.getBeaconCommittees(attEpoch, decisionRoot, attSlot, committeeIndices);
667
+ // calling getShufflingAtEpoch may take some time for NativeBeaconStateView
668
+ // we should have the shuffling inside ShufflingCache most of the time
669
+ const shuffling =
670
+ this.shufflingCache.getSync(attEpoch, state.getShufflingDecisionRoot(attEpoch)) ??
671
+ state.getShufflingAtEpoch(attEpoch);
672
+ const committees = getBeaconCommittees(shuffling, attSlot, committeeIndices);
662
673
  const aggregationBools = attestation.aggregationBits.toBoolArray();
663
674
  let offset = 0;
664
675
  for (let i = 0; i < committees.length; i++) {
@@ -4,6 +4,7 @@ import {
4
4
  DataAvailabilityStatus,
5
5
  IBeaconStateView,
6
6
  computeEpochAtSlot,
7
+ getIndexedAttestation,
7
8
  signedBlockToSignedHeader,
8
9
  } from "@lodestar/state-transition";
9
10
  import {IndexedAttestation, Slot, deneb} from "@lodestar/types";
@@ -81,10 +82,6 @@ export async function verifyBlocksInEpoch(
81
82
  throw new BlockError(block0, {code: BlockErrorCode.PRESTATE_MISSING, error: e as Error});
82
83
  });
83
84
 
84
- // in forky condition, make sure to populate ShufflingCache with regened state
85
- // otherwise it may fail to get indexed attestations from shuffling cache later
86
- this.shufflingCache.processState(preState0);
87
-
88
85
  if (!preState0.isStateValidatorsNodesPopulated()) {
89
86
  this.logger.verbose("verifyBlocksInEpoch preState0 SSZ cache stats", {
90
87
  slot: preState0.slot,
@@ -117,8 +114,12 @@ export async function verifyBlocksInEpoch(
117
114
  for (const [i, block] of blocks.entries()) {
118
115
  indexedAttestationsByBlock[i] = block.message.body.attestations.map((attestation) => {
119
116
  const attEpoch = computeEpochAtSlot(attestation.data.slot);
120
- const decisionRoot = preState0.getShufflingDecisionRoot(attEpoch);
121
- return this.shufflingCache.getIndexedAttestation(attEpoch, decisionRoot, fork, attestation);
117
+ // calling getShufflingAtEpoch may take some time for NativeBeaconStateView
118
+ // we should have the shuffling inside ShufflingCache most of the time
119
+ const shuffling =
120
+ this.shufflingCache.getSync(attEpoch, preState0.getShufflingDecisionRoot(attEpoch)) ??
121
+ preState0.getShufflingAtEpoch(attEpoch);
122
+ return getIndexedAttestation(shuffling, fork, attestation);
122
123
  });
123
124
  }
124
125
 
@@ -128,7 +128,7 @@ import {SeenAggregatedAttestations} from "./seenCache/seenAggregateAndProof.js";
128
128
  import {SeenAttestationDatas} from "./seenCache/seenAttestationData.js";
129
129
  import {SeenBlockAttesters} from "./seenCache/seenBlockAttesters.js";
130
130
  import {SeenBlockInput} from "./seenCache/seenGossipBlockInput.js";
131
- import {ShufflingCache} from "./shufflingCache.js";
131
+ import {ShufflingCache, ShufflingPromiseCancelReason} from "./shufflingCache.js";
132
132
  import {DbCPStateDatastore, checkpointToDatastoreKey} from "./stateCache/datastore/db.js";
133
133
  import {FileCPStateDatastore} from "./stateCache/datastore/file.js";
134
134
  import {CPStateDatastore} from "./stateCache/datastore/types.js";
@@ -279,6 +279,7 @@ export class BeaconChain implements IBeaconChain {
279
279
  validatorMonitor,
280
280
  anchorState,
281
281
  isAnchorStateFinalized,
282
+ earliestAvailableSlot,
282
283
  executionEngine,
283
284
  executionBuilder,
284
285
  builderApiClientOpts,
@@ -298,6 +299,7 @@ export class BeaconChain implements IBeaconChain {
298
299
  validatorMonitor: ValidatorMonitor | null;
299
300
  anchorState: IBeaconStateView;
300
301
  isAnchorStateFinalized: boolean;
302
+ earliestAvailableSlot: Slot;
301
303
  executionEngine: IExecutionEngine;
302
304
  executionBuilder?: IExecutionBuilder;
303
305
  builderApiClientOpts?: BuilderApiClientOpts;
@@ -326,7 +328,7 @@ export class BeaconChain implements IBeaconChain {
326
328
 
327
329
  this.blacklistedBlocks = new Map((opts.blacklistedBlocks ?? []).map((hex) => [hex, null]));
328
330
  this.attestationPool = new AttestationPool(config, clock, this.opts?.preaggregateSlotDistance, metrics);
329
- this.aggregatedAttestationPool = new AggregatedAttestationPool(this.config, metrics);
331
+ this.aggregatedAttestationPool = new AggregatedAttestationPool(this.config, metrics, logger);
330
332
  this.syncCommitteeMessagePool = new SyncCommitteeMessagePool(config, clock, this.opts?.preaggregateSlotDistance);
331
333
  this.syncContributionAndProofPool = new SyncContributionAndProofPool(config, clock, metrics, logger);
332
334
  this.executionPayloadBidPool = new ExecutionPayloadBidPool();
@@ -363,7 +365,7 @@ export class BeaconChain implements IBeaconChain {
363
365
  logger,
364
366
  });
365
367
 
366
- this._earliestAvailableSlot = anchorState.slot;
368
+ this._earliestAvailableSlot = earliestAvailableSlot;
367
369
 
368
370
  this.shufflingCache = new ShufflingCache(metrics, logger, this.opts, [
369
371
  {
@@ -574,7 +576,11 @@ export class BeaconChain implements IBeaconChain {
574
576
  }
575
577
 
576
578
  seenBlock(blockRoot: RootHex): boolean {
577
- return this.seenBlockInputCache.hasBlock(blockRoot) || this.forkChoice.hasBlockHexUnsafe(blockRoot);
579
+ return (
580
+ this.seenBlockInputCache.hasBlock(blockRoot) ||
581
+ this.seenBlockInputCache.isValidatingBlock(blockRoot) ||
582
+ this.forkChoice.hasBlockHexUnsafe(blockRoot)
583
+ );
578
584
  }
579
585
 
580
586
  seenPayloadEnvelope(blockRoot: RootHex): boolean {
@@ -614,12 +620,14 @@ export class BeaconChain implements IBeaconChain {
614
620
  async loadFromDisk(): Promise<void> {
615
621
  await this.regen.init();
616
622
  await this.opPool.fromPersisted(this.db, this.getHeadState(), this.bls, this.clock.currentSlot);
623
+ await this.proposerPreferencesPool.fromPersisted(this.db, this.clock.currentSlot);
617
624
  }
618
625
 
619
626
  /** Persist in-memory data to the DB. Call at least once before stopping the process */
620
627
  async persistToDisk(): Promise<void> {
621
628
  await this.archiveStore.persistToDisk();
622
629
  await this.opPool.toPersisted(this.db);
630
+ await this.proposerPreferencesPool.toPersisted(this.db);
623
631
  }
624
632
 
625
633
  getHeadState(): IBeaconStateView {
@@ -1623,21 +1631,48 @@ export class BeaconChain implements IBeaconChain {
1623
1631
  const blockEpoch = computeEpochAtSlot(attHeadBlock.slot);
1624
1632
 
1625
1633
  let state: IBeaconStateView;
1626
- if (blockEpoch < attEpoch - 1) {
1627
- // thanks to one epoch look ahead, we don't need to dial up to attEpoch
1628
- const targetSlot = computeStartSlotAtEpoch(attEpoch - 1);
1629
- this.metrics?.gossipAttestation.useHeadBlockStateDialedToTargetEpoch.inc({caller: regenCaller});
1630
- state = await this.regen.getBlockSlotState(attHeadBlock, targetSlot, {dontTransferCache: true}, regenCaller);
1631
- } else if (blockEpoch > attEpoch) {
1632
- // should not happen, handled inside attestation verification code
1633
- throw Error(`Block epoch ${blockEpoch} is after attestation epoch ${attEpoch}`);
1634
- } else {
1635
- // should use either current or next shuffling of head state
1636
- // it's not likely to hit this since these shufflings are cached already
1637
- // so handle just in case
1638
- this.metrics?.gossipAttestation.useHeadBlockState.inc({caller: regenCaller});
1639
- state = await this.regen.getState(attHeadBlock.stateRoot, regenCaller);
1634
+ try {
1635
+ if (blockEpoch < attEpoch - 1) {
1636
+ // thanks to one epoch look ahead, we don't need to dial up to attEpoch
1637
+ const targetSlot = computeStartSlotAtEpoch(attEpoch - 1);
1638
+ this.metrics?.gossipAttestation.useHeadBlockStateDialedToTargetEpoch.inc({caller: regenCaller});
1639
+ state = await this.regen.getBlockSlotState(attHeadBlock, targetSlot, {dontTransferCache: true}, regenCaller);
1640
+ } else if (blockEpoch > attEpoch) {
1641
+ // should not happen, handled inside attestation verification code
1642
+ throw Error(`Block epoch ${blockEpoch} is after attestation epoch ${attEpoch}`);
1643
+ } else {
1644
+ // should use either current or next shuffling of head state
1645
+ // it's not likely to hit this since these shufflings are cached already
1646
+ // so handle just in case
1647
+ this.metrics?.gossipAttestation.useHeadBlockState.inc({caller: regenCaller});
1648
+ state = await this.regen.getState(attHeadBlock.stateRoot, regenCaller);
1649
+ }
1650
+ } catch (e) {
1651
+ this.shufflingCache.cancelPromise(attEpoch, shufflingDependentRoot, ShufflingPromiseCancelReason.regenError);
1652
+ throw e;
1640
1653
  }
1654
+
1655
+ const stateDecisionRoot = state.getShufflingDecisionRoot(attEpoch);
1656
+ if (stateDecisionRoot !== shufflingDependentRoot) {
1657
+ // the promise would never be resolved by the state's shuffling
1658
+ this.shufflingCache.cancelPromise(
1659
+ attEpoch,
1660
+ shufflingDependentRoot,
1661
+ ShufflingPromiseCancelReason.decisionRootMismatch
1662
+ );
1663
+ this.logger.debug("Shuffling decision root mismatch on attestation regen", {
1664
+ slot: attHeadBlock.slot,
1665
+ root: attHeadBlock.blockRoot,
1666
+ epoch: attEpoch,
1667
+ shufflingDependentRoot,
1668
+ stateDecisionRoot,
1669
+ });
1670
+
1671
+ throw Error(
1672
+ `Shuffling decision root mismatch epoch=${attEpoch} slot=${attHeadBlock.slot} root=${attHeadBlock.blockRoot} expected=${shufflingDependentRoot} actual=${stateDecisionRoot}`
1673
+ );
1674
+ }
1675
+
1641
1676
  // resolve the promise to unblock other calls of the same epoch and dependent root
1642
1677
  this.shufflingCache.processState(state);
1643
1678
  return state.getShufflingAtEpoch(attEpoch);
@@ -30,7 +30,7 @@ import {
30
30
  isStatePostGloas,
31
31
  } from "@lodestar/state-transition";
32
32
  import {Attestation, Epoch, RootHex, Slot, electra, isElectraAttestation, phase0, ssz} from "@lodestar/types";
33
- import {MapDef, assert, toRootHex} from "@lodestar/utils";
33
+ import {Logger, MapDef, assert, toRootHex} from "@lodestar/utils";
34
34
  import {Metrics} from "../../metrics/metrics.js";
35
35
  import {IntersectResult, intersectUint8Arrays} from "../../util/bitArray.js";
36
36
  import {getShufflingDependentRoot} from "../../util/dependentRoot.js";
@@ -58,7 +58,7 @@ export type AttestationsConsolidation = {
58
58
 
59
59
  /**
60
60
  * This function returns not seen participation for a given epoch and slot and committee index.
61
- * Return null if all validators are seen or no info to check.
61
+ * Return an empty set if all validators are seen, or null if the committee cannot be computed (e.g. missing shuffling).
62
62
  */
63
63
  type GetNotSeenValidatorsFn = (epoch: Epoch, slot: Slot, committeeIndex: number) => Set<number> | null;
64
64
 
@@ -140,7 +140,8 @@ export class AggregatedAttestationPool {
140
140
 
141
141
  constructor(
142
142
  private readonly config: BeaconConfig,
143
- private readonly metrics: Metrics | null = null
143
+ private readonly metrics: Metrics | null = null,
144
+ private readonly logger: Logger | null = null
144
145
  ) {
145
146
  metrics?.opPool.aggregatedAttestationPool.attDataPerSlot.addCollect(() => this.onScrapeMetrics(metrics));
146
147
  }
@@ -244,6 +245,7 @@ export class AggregatedAttestationPool {
244
245
  const consolidations = new Map<AttestationsConsolidation, number>();
245
246
  let scannedSlots = 0;
246
247
  let stopReason: ScannedSlotsTerminationReason | null = null;
248
+ const missingShufflingCommitteesByEpoch = new Map<Epoch, number>();
247
249
  slot: for (const slot of slots) {
248
250
  const attestationGroupByIndexByDataHash = this.attestationGroupByIndexByDataHexBySlot.get(slot);
249
251
  // should not happen
@@ -295,7 +297,12 @@ export class AggregatedAttestationPool {
295
297
 
296
298
  for (const [committeeIndex, attestationGroup] of attestationGroupByIndex.entries()) {
297
299
  const notSeenCommitteeMembers = notSeenValidatorsFn(epoch, slot, committeeIndex);
298
- if (notSeenCommitteeMembers === null || notSeenCommitteeMembers.size === 0) {
300
+ if (notSeenCommitteeMembers === null) {
301
+ // skip this committee instead of failing the whole block production, other epochs may still have shuffling
302
+ missingShufflingCommitteesByEpoch.set(epoch, (missingShufflingCommitteesByEpoch.get(epoch) ?? 0) + 1);
303
+ continue;
304
+ }
305
+ if (notSeenCommitteeMembers.size === 0) {
299
306
  this.metrics?.opPool.aggregatedAttestationPool.packedAttestations.seenCommittees.inc();
300
307
  continue;
301
308
  }
@@ -386,6 +393,18 @@ export class AggregatedAttestationPool {
386
393
  scannedSlots++;
387
394
  }
388
395
 
396
+ for (const [epoch, missingCommittees] of missingShufflingCommitteesByEpoch) {
397
+ this.metrics?.opPool.aggregatedAttestationPool.packedAttestations.missingShufflingCommittees.inc(
398
+ missingCommittees
399
+ );
400
+ this.logger?.debug("Missing shuffling when packing attestations, skipped committees", {
401
+ slot: stateSlot,
402
+ epoch,
403
+ decisionRoot: state.getShufflingDecisionRoot(epoch),
404
+ missingCommittees,
405
+ });
406
+ }
407
+
389
408
  this.metrics?.opPool.aggregatedAttestationPool.packedAttestations.totalConsolidations.set(consolidations.size);
390
409
 
391
410
  const sortedConsolidationsByScore = Array.from(consolidations.entries())
@@ -770,13 +789,18 @@ export function getNotSeenValidatorsFn(
770
789
  }
771
790
  const cacheKey = slot + "_" + committeeIndex;
772
791
  let notSeenCommitteeMembers = cachedNotSeenValidators.get(cacheKey);
773
- if (notSeenCommitteeMembers != null) {
774
- // if all validators are seen then return null, we don't need to check for any attestations of same committee again
775
- return notSeenCommitteeMembers.size === 0 ? null : notSeenCommitteeMembers;
792
+ if (notSeenCommitteeMembers !== undefined) {
793
+ return notSeenCommitteeMembers;
776
794
  }
777
795
 
778
796
  const decisionRoot = state.getShufflingDecisionRoot(computeEpochAtSlot(slot));
779
- const committee = shufflingCache.getBeaconCommittee(epoch, decisionRoot, slot, committeeIndex);
797
+ const committee = shufflingCache.getBeaconCommitteeOrNull(epoch, decisionRoot, slot, committeeIndex);
798
+ if (committee === null) {
799
+ // attestations in the pool were validated against a cached shuffling of the previous or current epoch,
800
+ // so a miss is a ShufflingCache bug. Return null so the caller tracks it via metrics/logs without failing
801
+ // block production. Don't fall back to the state's shuffling, that would hide the bug
802
+ return null;
803
+ }
780
804
  notSeenCommitteeMembers = new Set<number>();
781
805
  for (const [i, validatorIndex] of committee.entries()) {
782
806
  // no need to check flagIsTimelySource as if validator is not seen, it's participation status is 0
@@ -786,8 +810,8 @@ export function getNotSeenValidatorsFn(
786
810
  }
787
811
  }
788
812
  cachedNotSeenValidators.set(cacheKey, notSeenCommitteeMembers);
789
- // if all validators are seen then return null, we don't need to check for any attestations of same committee again
790
- return notSeenCommitteeMembers.size === 0 ? null : notSeenCommitteeMembers;
813
+ // an empty set means all validators are seen, we don't need to check for any attestations of same committee again
814
+ return notSeenCommitteeMembers;
791
815
  };
792
816
  }
793
817
 
@@ -1,5 +1,4 @@
1
1
  import {BeaconConfig} from "@lodestar/config";
2
- import {DbBatch, Id, Repository} from "@lodestar/db";
3
2
  import {
4
3
  BLS_WITHDRAWAL_PREFIX,
5
4
  ForkName,
@@ -42,6 +41,7 @@ import {
42
41
  getAttesterSlashingSignatureDomains,
43
42
  getProposerSlashingSignatureDomain,
44
43
  isValidBlsToExecutionChangeForBlockInclusion,
44
+ persistDiff,
45
45
  } from "./utils.js";
46
46
 
47
47
  type HexRoot = string;
@@ -500,33 +500,3 @@ function isVoluntaryExitSignatureIncludable(stateFork: ForkSeq, voluntaryExitFor
500
500
  function isSlashableAtEpoch(validator: phase0.Validator, epoch: Epoch): boolean {
501
501
  return !validator.slashed && validator.activationEpoch <= epoch && epoch < validator.withdrawableEpoch;
502
502
  }
503
-
504
- /**
505
- * Persist target items `items` in `dbRepo` doing minimum put and delete writes.
506
- * Reads all keys in repository to compute the diff between current persisted data and target data.
507
- */
508
- async function persistDiff<K extends Id, V>(
509
- dbRepo: Repository<K, V>,
510
- items: {key: K; value: V}[],
511
- serializeKey: (key: K) => number | string,
512
- opts: {updateExisting?: boolean} = {}
513
- ): Promise<void> {
514
- const persistedKeys = await dbRepo.keys();
515
- const batch: DbBatch<K, V> = [];
516
-
517
- const persistedKeysSerialized = new Set(persistedKeys.map(serializeKey));
518
- for (const item of items) {
519
- if (opts.updateExisting || !persistedKeysSerialized.has(serializeKey(item.key))) {
520
- batch.push({type: "put", key: item.key, value: item.value});
521
- }
522
- }
523
-
524
- const targetKeysSerialized = new Set(items.map((item) => serializeKey(item.key)));
525
- for (const persistedKey of persistedKeys) {
526
- if (!targetKeysSerialized.has(serializeKey(persistedKey))) {
527
- batch.push({type: "del", key: persistedKey});
528
- }
529
- }
530
-
531
- if (batch.length > 0) await dbRepo.batch(batch);
532
- }
@@ -1,5 +1,7 @@
1
1
  import {RootHex, Slot, ValidatorIndex, gloas} from "@lodestar/types";
2
- import {toRootHex} from "@lodestar/utils";
2
+ import {toHex, toRootHex} from "@lodestar/utils";
3
+ import {IBeaconDb} from "../../db/index.js";
4
+ import {persistDiff} from "./utils.js";
3
5
 
4
6
  /**
5
7
  * Pool of validated `SignedProposerPreferences` indexed by `(slot, dependent_root)`.
@@ -64,4 +66,21 @@ export class ProposerPreferencesPool {
64
66
  if (slot < currentSlot) this.bySlot.delete(slot);
65
67
  }
66
68
  }
69
+
70
+ /** Restore the preferences of upcoming slots, they were validated before they were persisted */
71
+ async fromPersisted(db: IBeaconDb, currentSlot: Slot): Promise<void> {
72
+ for (const signed of await db.proposerPreferences.values()) {
73
+ if (signed.message.proposalSlot >= currentSlot) {
74
+ this.add(signed);
75
+ }
76
+ }
77
+ }
78
+
79
+ async toPersisted(db: IBeaconDb): Promise<void> {
80
+ await persistDiff(
81
+ db.proposerPreferences,
82
+ this.getAll().map((signed) => ({key: db.proposerPreferences.getId(signed), value: signed})),
83
+ toHex
84
+ );
85
+ }
67
86
  }
@@ -1,5 +1,6 @@
1
1
  import {Signature} from "@chainsafe/lodestar-z/blst";
2
2
  import {BeaconConfig} from "@lodestar/config";
3
+ import {DbBatch, Id, Repository} from "@lodestar/db";
3
4
  import {BLS_WITHDRAWAL_PREFIX, DOMAIN_BEACON_ATTESTER, DOMAIN_BEACON_PROPOSER} from "@lodestar/params";
4
5
  import {IBeaconStateView, computeStartSlotAtEpoch} from "@lodestar/state-transition";
5
6
  import {AttesterSlashing, Domain, Slot, capella, phase0} from "@lodestar/types";
@@ -91,3 +92,33 @@ export function isValidBlsToExecutionChangeForBlockInclusion(
91
92
  export function isElectraAggregate(aggregate: AggregateFast): aggregate is AggregateFastElectra {
92
93
  return (aggregate as AggregateFastElectra).committeeBits !== undefined;
93
94
  }
95
+
96
+ /**
97
+ * Persist target items `items` in `dbRepo` doing minimum put and delete writes.
98
+ * Reads all keys in repository to compute the diff between current persisted data and target data.
99
+ */
100
+ export async function persistDiff<K extends Id, V>(
101
+ dbRepo: Repository<K, V>,
102
+ items: {key: K; value: V}[],
103
+ serializeKey: (key: K) => number | string,
104
+ opts: {updateExisting?: boolean} = {}
105
+ ): Promise<void> {
106
+ const persistedKeys = await dbRepo.keys();
107
+ const batch: DbBatch<K, V> = [];
108
+
109
+ const persistedKeysSerialized = new Set(persistedKeys.map(serializeKey));
110
+ for (const item of items) {
111
+ if (opts.updateExisting || !persistedKeysSerialized.has(serializeKey(item.key))) {
112
+ batch.push({type: "put", key: item.key, value: item.value});
113
+ }
114
+ }
115
+
116
+ const targetKeysSerialized = new Set(items.map((item) => serializeKey(item.key)));
117
+ for (const persistedKey of persistedKeys) {
118
+ if (!targetKeysSerialized.has(serializeKey(persistedKey))) {
119
+ batch.push({type: "del", key: persistedKey});
120
+ }
121
+ }
122
+
123
+ if (batch.length > 0) await dbRepo.batch(batch);
124
+ }
@@ -111,6 +111,9 @@ export class SeenBlockInput {
111
111
  // there should only 1 block root per slot but we need to always compare against rootHex
112
112
  // and the signature to ensure we only skip verification if both match
113
113
  private verifiedProposerSignatures = new Map<Slot, Map<RootHex, BLSSignature>>();
114
+ // Roots of gossip blocks under validation, counted because blocks with the same root but different signatures
115
+ // can be validated concurrently
116
+ private validatingBlockRoots = new Map<RootHex, number>();
114
117
 
115
118
  constructor({
116
119
  config,
@@ -153,6 +156,26 @@ export class SeenBlockInput {
153
156
  return this.blockInputs.get(rootHex)?.hasBlock() ?? false;
154
157
  }
155
158
 
159
+ /**
160
+ * Mark a gossip block root as under validation, every call MUST be paired with `unmarkValidatingBlock()`
161
+ */
162
+ markValidatingBlock(rootHex: RootHex): void {
163
+ this.validatingBlockRoots.set(rootHex, (this.validatingBlockRoots.get(rootHex) ?? 0) + 1);
164
+ }
165
+
166
+ unmarkValidatingBlock(rootHex: RootHex): void {
167
+ const count = this.validatingBlockRoots.get(rootHex) ?? 0;
168
+ if (count <= 1) {
169
+ this.validatingBlockRoots.delete(rootHex);
170
+ } else {
171
+ this.validatingBlockRoots.set(rootHex, count - 1);
172
+ }
173
+ }
174
+
175
+ isValidatingBlock(rootHex: RootHex): boolean {
176
+ return this.validatingBlockRoots.has(rootHex);
177
+ }
178
+
156
179
  get(rootHex: RootHex): IBlockInput | undefined {
157
180
  return this.blockInputs.get(rootHex);
158
181
  }