@lodestar/beacon-node 2.1.0-dev.9af51a1670 → 2.1.0-dev.a6c4b2f428

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 (34) hide show
  1. package/lib/chain/blocks/importBlock.d.ts.map +1 -1
  2. package/lib/chain/blocks/importBlock.js +14 -5
  3. package/lib/chain/blocks/importBlock.js.map +1 -1
  4. package/lib/chain/blocks/importExecutionPayload.d.ts.map +1 -1
  5. package/lib/chain/blocks/importExecutionPayload.js +4 -2
  6. package/lib/chain/blocks/importExecutionPayload.js.map +1 -1
  7. package/lib/chain/chain.d.ts.map +1 -1
  8. package/lib/chain/chain.js +13 -1
  9. package/lib/chain/chain.js.map +1 -1
  10. package/lib/chain/forkChoice/index.d.ts +11 -2
  11. package/lib/chain/forkChoice/index.d.ts.map +1 -1
  12. package/lib/chain/forkChoice/index.js +164 -4
  13. package/lib/chain/forkChoice/index.js.map +1 -1
  14. package/lib/chain/opPools/opPool.d.ts +9 -3
  15. package/lib/chain/opPools/opPool.d.ts.map +1 -1
  16. package/lib/chain/opPools/opPool.js +22 -16
  17. package/lib/chain/opPools/opPool.js.map +1 -1
  18. package/lib/chain/options.d.ts.map +1 -1
  19. package/lib/chain/options.js +1 -0
  20. package/lib/chain/options.js.map +1 -1
  21. package/lib/chain/validation/block.d.ts.map +1 -1
  22. package/lib/chain/validation/block.js +8 -5
  23. package/lib/chain/validation/block.js.map +1 -1
  24. package/lib/chain/validation/proposerSlashing.js +5 -1
  25. package/lib/chain/validation/proposerSlashing.js.map +1 -1
  26. package/package.json +17 -17
  27. package/src/chain/blocks/importBlock.ts +14 -7
  28. package/src/chain/blocks/importExecutionPayload.ts +4 -2
  29. package/src/chain/chain.ts +13 -1
  30. package/src/chain/forkChoice/index.ts +218 -4
  31. package/src/chain/opPools/opPool.ts +27 -16
  32. package/src/chain/options.ts +1 -0
  33. package/src/chain/validation/block.ts +8 -5
  34. package/src/chain/validation/proposerSlashing.ts +5 -1
@@ -5,28 +5,33 @@ import {
5
5
  ForkChoice,
6
6
  ForkChoiceStateGetter,
7
7
  ForkChoiceStore,
8
+ IForkChoice,
8
9
  JustifiedBalancesGetter,
10
+ NativeForkChoice,
9
11
  PayloadStatus,
10
12
  ProtoArray,
11
13
  ProtoBlock,
12
14
  ForkChoiceOpts as RawForkChoiceOpts,
13
15
  } from "@lodestar/fork-choice";
14
- import {ZERO_HASH_HEX} from "@lodestar/params";
16
+ import {ForkSeq, SLOTS_PER_HISTORICAL_ROOT, ZERO_HASH_HEX} from "@lodestar/params";
15
17
  import {
16
18
  DataAvailabilityStatus,
17
19
  IBeaconStateView,
20
+ ZERO_HASH,
18
21
  computeEpochAtSlot,
19
22
  computeStartSlotAtEpoch,
20
23
  isStatePostBellatrix,
21
24
  isStatePostGloas,
22
25
  } from "@lodestar/state-transition";
23
- import {Slot, ssz} from "@lodestar/types";
24
- import {Logger, toRootHex} from "@lodestar/utils";
26
+ import {Slot, phase0, ssz} from "@lodestar/types";
27
+ import {Logger, fromHex, toRootHex} from "@lodestar/utils";
25
28
  import {GENESIS_SLOT} from "../../constants/index.js";
26
29
  import {Metrics} from "../../metrics/index.js";
27
30
  import {ChainEvent, ChainEventEmitter} from "../emitter.js";
28
31
 
29
32
  export type ForkChoiceOpts = RawForkChoiceOpts & {
33
+ /** Use the native (Zig) fork choice store instead of the proto-array */
34
+ nativeForkChoice?: boolean;
30
35
  // for testing only
31
36
  forkchoiceConstructor?: typeof ForkChoice;
32
37
  };
@@ -58,7 +63,22 @@ export function initializeForkChoice(
58
63
  stateGetter: ForkChoiceStateGetter,
59
64
  metrics: Metrics | null,
60
65
  logger?: Logger
61
- ): ForkChoice {
66
+ ): IForkChoice {
67
+ if (opts.nativeForkChoice) {
68
+ return initializeNativeForkChoice(
69
+ config,
70
+ emitter,
71
+ currentSlot,
72
+ state,
73
+ isFinalizedState,
74
+ opts,
75
+ justifiedBalancesGetter,
76
+ stateGetter,
77
+ metrics,
78
+ logger
79
+ );
80
+ }
81
+
62
82
  return isFinalizedState
63
83
  ? initializeForkChoiceFromFinalizedState(
64
84
  config,
@@ -183,6 +203,200 @@ export function initializeForkChoiceFromFinalizedState(
183
203
  );
184
204
  }
185
205
 
206
+ /**
207
+ * Initialize the native fork choice. A finalized anchor is both the justified and the finalized
208
+ * checkpoint, as in the spec's `get_forkchoice_store`. An unfinalized one keeps its state's
209
+ * checkpoints, with stand-ins for the ancestors that connect it to them: nothing is reported as
210
+ * finalized that the chain has not finalized.
211
+ */
212
+ export function initializeNativeForkChoice(
213
+ config: ChainForkConfig,
214
+ emitter: ChainEventEmitter,
215
+ currentSlot: Slot,
216
+ state: IBeaconStateView,
217
+ isFinalizedState: boolean,
218
+ opts: ForkChoiceOpts,
219
+ justifiedBalancesGetter: JustifiedBalancesGetter,
220
+ stateGetter: ForkChoiceStateGetter,
221
+ metrics: Metrics | null,
222
+ logger?: Logger
223
+ ): NativeForkChoice {
224
+ const {blockHeader, checkpoint} = state.computeAnchorCheckpoint();
225
+ const anchorRoot = toRootHex(checkpoint.root);
226
+ const isPostGloas = isStatePostGloas(state);
227
+ // A state upgraded to Gloas through skipped slots still holds a pre-Gloas block, which carried its own payload
228
+ const isPostGloasAnchor = isPostGloas && config.getForkSeq(blockHeader.slot) >= ForkSeq.gloas;
229
+ const bid = isPostGloasAnchor ? state.latestExecutionPayloadBid : null;
230
+ const hasPayload = isStatePostBellatrix(state) && state.isExecutionStateType && state.isMergeTransitionComplete;
231
+ // The state caches the bid of its latest block, except at genesis: the genesis block carries no bid
232
+ const anchorBid = blockHeader.slot === GENESIS_SLOT ? null : bid;
233
+
234
+ // The store aliases no root to genesis, so a checkpoint the chain never moved off genesis is
235
+ // given the genesis block root. Only possible while that root is still in the state's history.
236
+ const withGenesisRoot = (cp: phase0.Checkpoint): phase0.Checkpoint => {
237
+ if (!ssz.Root.equals(cp.root, ZERO_HASH)) return cp;
238
+ if (state.slot > GENESIS_SLOT + SLOTS_PER_HISTORICAL_ROOT) {
239
+ throw Error(
240
+ `The native fork choice cannot start from an unfinalized state at slot ${state.slot} of a chain that never justified a checkpoint: the genesis block root has left the state's block roots. Start without --chain.nativeForkChoice`
241
+ );
242
+ }
243
+ return {epoch: cp.epoch, root: state.getBlockRootAtSlot(GENESIS_SLOT)};
244
+ };
245
+ const justifiedCheckpoint = isFinalizedState ? checkpoint : withGenesisRoot(state.currentJustifiedCheckpoint);
246
+ const finalizedCheckpoint = isFinalizedState ? checkpoint : withGenesisRoot(state.finalizedCheckpoint);
247
+ const justifiedRoot = toRootHex(justifiedCheckpoint.root);
248
+ const finalizedRoot = toRootHex(finalizedCheckpoint.root);
249
+
250
+ if (!isFinalizedState) {
251
+ logger?.warn("Initializing fork choice from unfinalized state", {
252
+ currentSlot,
253
+ stateSlot: state.slot,
254
+ headSlot: blockHeader.slot,
255
+ headRoot: anchorRoot,
256
+ finalizedEpoch: finalizedCheckpoint.epoch,
257
+ finalizedRoot,
258
+ justifiedEpoch: justifiedCheckpoint.epoch,
259
+ justifiedRoot,
260
+ });
261
+ }
262
+
263
+ const store = new ForkChoiceStore(
264
+ currentSlot,
265
+ justifiedCheckpoint,
266
+ finalizedCheckpoint,
267
+ // For an unfinalized anchor this is not the justified state, but no other state is at hand
268
+ state.getEffectiveBalanceIncrementsZeroInactive(),
269
+ justifiedBalancesGetter,
270
+ stateGetter,
271
+ {
272
+ onJustified: (cp) => emitter.emit(ChainEvent.forkChoiceJustified, cp),
273
+ onFinalized: (cp) => emitter.emit(ChainEvent.forkChoiceFinalized, cp),
274
+ onFastConfirmation: ({block, slot, currentSlot}) =>
275
+ emitter.emit(routes.events.EventType.fastConfirmation, {block, slot, currentSlot}),
276
+ onPtcQuorum: (data) => emitter.emit(ChainEvent.forkChoicePtcQuorum, data),
277
+ }
278
+ );
279
+
280
+ const checkpoints = {
281
+ justifiedEpoch: justifiedCheckpoint.epoch,
282
+ justifiedRoot,
283
+ finalizedEpoch: finalizedCheckpoint.epoch,
284
+ finalizedRoot,
285
+ unrealizedJustifiedEpoch: justifiedCheckpoint.epoch,
286
+ unrealizedJustifiedRoot: justifiedRoot,
287
+ unrealizedFinalizedEpoch: finalizedCheckpoint.epoch,
288
+ unrealizedFinalizedRoot: finalizedRoot,
289
+ };
290
+
291
+ const block: ProtoBlock = {
292
+ slot: blockHeader.slot,
293
+ parentRoot: toRootHex(blockHeader.parentRoot),
294
+ stateRoot: toRootHex(blockHeader.stateRoot),
295
+ blockRoot: anchorRoot,
296
+ targetRoot: anchorRoot,
297
+ timeliness: true,
298
+ ptcTimeliness: true,
299
+ importedTimely: true,
300
+ proposerIndex: blockHeader.proposerIndex,
301
+ ...checkpoints,
302
+
303
+ ...(hasPayload
304
+ ? {
305
+ executionPayloadBlockHash: isPostGloas
306
+ ? toRootHex(state.latestBlockHash)
307
+ : toRootHex(state.latestExecutionPayloadHeader.blockHash),
308
+ // TODO GLOAS: not tracked in BeaconState post-gloas, see initializeForkChoiceFromFinalizedState
309
+ executionPayloadNumber: isPostGloas ? 0 : state.payloadBlockNumber,
310
+ // The upgrade to Gloas keeps a pre-Gloas block's payload gas limit in the state's bid
311
+ executionPayloadGasLimit: isPostGloasAnchor
312
+ ? 0
313
+ : isPostGloas
314
+ ? Number(state.latestExecutionPayloadBid.gasLimit)
315
+ : state.latestExecutionPayloadHeader.gasLimit,
316
+ // A Gloas payload is judged when its envelope arrives, the genesis one included
317
+ executionStatus:
318
+ blockHeader.slot === GENESIS_SLOT && !isPostGloasAnchor ? ExecutionStatus.Valid : ExecutionStatus.Syncing,
319
+ }
320
+ : {executionPayloadBlockHash: null, executionStatus: ExecutionStatus.PreMerge}),
321
+
322
+ dataAvailabilityStatus: DataAvailabilityStatus.PreData,
323
+ payloadStatus: isPostGloasAnchor ? PayloadStatus.PENDING : PayloadStatus.FULL,
324
+ parentBlockHash: bid === null ? null : toRootHex(bid.parentBlockHash),
325
+ };
326
+
327
+ // Ancestors of the anchor known by root only: the finalized block, the justified block, the
328
+ // anchor's parent, and for the anchor's epoch and the one before the checkpoint block, which the
329
+ // chain can still justify and which current votes target, and the block before it, the
330
+ // dependent root of the next epoch's duties. Their slots are upper bounds and their payloads
331
+ // unknown, so they carry none.
332
+ const unfinalizedAncestors: ProtoBlock[] = [];
333
+ if (!isFinalizedState) {
334
+ const finalizedSlot = computeStartSlotAtEpoch(finalizedCheckpoint.epoch);
335
+ const candidates: [string, Slot][] = [
336
+ [finalizedRoot, finalizedSlot],
337
+ [justifiedRoot, computeStartSlotAtEpoch(justifiedCheckpoint.epoch)],
338
+ [block.parentRoot, blockHeader.slot - 1],
339
+ ];
340
+ const anchorEpoch = computeEpochAtSlot(state.slot);
341
+ for (const epoch of [anchorEpoch - 1, anchorEpoch]) {
342
+ const checkpointSlot = computeStartSlotAtEpoch(epoch);
343
+ for (const slot of [checkpointSlot - 1, checkpointSlot]) {
344
+ if (slot > finalizedSlot && slot < blockHeader.slot) {
345
+ candidates.push([toRootHex(state.getBlockRootAtSlot(slot)), slot]);
346
+ }
347
+ }
348
+ }
349
+ // Roots repeat over skipped slots: a block keeps the lowest slot it is known at
350
+ candidates.sort((a, b) => a[1] - b[1]);
351
+ for (const [blockRoot, slot] of candidates) {
352
+ const isKnown = blockRoot === anchorRoot || unfinalizedAncestors.some((b) => b.blockRoot === blockRoot);
353
+ if (isKnown || blockRoot === ZERO_HASH_HEX) continue;
354
+ const isGloas = config.getForkSeq(slot) >= ForkSeq.gloas;
355
+ const targetSlot = computeStartSlotAtEpoch(computeEpochAtSlot(slot));
356
+ unfinalizedAncestors.push({
357
+ slot,
358
+ blockRoot,
359
+ parentRoot: unfinalizedAncestors.at(-1)?.blockRoot ?? ZERO_HASH_HEX,
360
+ stateRoot: ZERO_HASH_HEX,
361
+ targetRoot: targetSlot === slot ? blockRoot : toRootHex(state.getBlockRootAtSlot(targetSlot)),
362
+ timeliness: false,
363
+ ptcTimeliness: false,
364
+ importedTimely: false,
365
+ proposerIndex: 0,
366
+ ...checkpoints,
367
+ executionPayloadBlockHash: null,
368
+ executionStatus: ExecutionStatus.PreMerge,
369
+ dataAvailabilityStatus: DataAvailabilityStatus.PreData,
370
+ payloadStatus: isGloas ? PayloadStatus.PENDING : PayloadStatus.FULL,
371
+ parentBlockHash: isGloas ? ZERO_HASH_HEX : null,
372
+ });
373
+ }
374
+ }
375
+
376
+ return new NativeForkChoice(
377
+ config,
378
+ store,
379
+ {
380
+ block,
381
+ stateSlot: state.slot,
382
+ genesisTime: state.genesisTime,
383
+ genesisValidatorsRoot: state.genesisValidatorsRoot,
384
+ justifiedCheckpoint: isFinalizedState ? state.currentJustifiedCheckpoint : justifiedCheckpoint,
385
+ finalizedCheckpoint: isFinalizedState ? state.finalizedCheckpoint : finalizedCheckpoint,
386
+ unfinalizedAncestors: isFinalizedState ? undefined : unfinalizedAncestors,
387
+ payloadBlockHash: isPostGloasAnchor
388
+ ? (anchorBid?.blockHash ?? null)
389
+ : block.executionPayloadBlockHash === null
390
+ ? null
391
+ : fromHex(block.executionPayloadBlockHash),
392
+ bidParentBlockHash: anchorBid?.parentBlockHash ?? null,
393
+ },
394
+ metrics,
395
+ opts,
396
+ logger
397
+ );
398
+ }
399
+
186
400
  /**
187
401
  * Initialize forkchoice from an unfinalized state.
188
402
  */
@@ -1,6 +1,7 @@
1
1
  import {BeaconConfig} from "@lodestar/config";
2
2
  import {
3
3
  BLS_WITHDRAWAL_PREFIX,
4
+ FAR_FUTURE_EPOCH,
4
5
  ForkName,
5
6
  ForkSeq,
6
7
  MAX_ATTESTER_SLASHINGS,
@@ -17,6 +18,7 @@ import {
17
18
  getAttesterSlashableIndices,
18
19
  getAttesterSlashingSignatureSets,
19
20
  getProposerSlashingSignatureSets,
21
+ getValidatorFromStateBytes,
20
22
  } from "@lodestar/state-transition";
21
23
  import {
22
24
  AttesterSlashing,
@@ -389,12 +391,19 @@ export class OpPool {
389
391
  }
390
392
 
391
393
  /**
392
- * Prune all types of transactions given the latest head state
394
+ * Prune all types of transactions given the latest head state and the finalized checkpoint state.
395
+ * `finalizedState` is only needed to prune voluntary exits, and may be null when there are none.
393
396
  */
394
- pruneAll(headBlock: SignedBeaconBlock, headState: IBeaconStateView): void {
397
+ pruneAll(
398
+ headBlock: SignedBeaconBlock,
399
+ headState: IBeaconStateView,
400
+ finalizedState: IBeaconStateView | Uint8Array | null
401
+ ): void {
395
402
  this.pruneAttesterSlashings(headState);
396
403
  this.pruneProposerSlashings(headState);
397
- this.pruneVoluntaryExits(headState);
404
+ if (finalizedState !== null) {
405
+ this.pruneVoluntaryExits(finalizedState);
406
+ }
398
407
  this.pruneBlsToExecutionChanges(headBlock, headState);
399
408
  }
400
409
 
@@ -438,21 +447,23 @@ export class OpPool {
438
447
 
439
448
  /**
440
449
  * Call after finalizing
441
- * Prune if validator has already exited at or before the finalized checkpoint of the head.
450
+ * Prune if validator has already exited in the finalized state, so an exit included only in a block that is later
451
+ * orphaned stays in the pool. The finalized state may be serialized bytes if it is not in memory.
452
+ *
453
+ * Exits are not pruned by fork: from Deneb the signature domain is fixed to Capella (EIP-7044), so a fork transition
454
+ * cannot invalidate an exit verified at a Deneb+ state. Exits verified with a pre-Capella domain before crossing into
455
+ * Deneb are not handled, as only chains that cross the Deneb fork are affected.
442
456
  */
443
- private pruneVoluntaryExits(headState: IBeaconStateView): void {
444
- const headStateFork = this.config.getForkSeq(headState.slot);
445
- const finalizedEpoch = headState.finalizedCheckpoint.epoch;
446
-
457
+ private pruneVoluntaryExits(finalizedState: IBeaconStateView | Uint8Array): void {
447
458
  for (const [key, voluntaryExit] of this.voluntaryExits.entries()) {
448
- // VoluntaryExit messages signed in the previous fork become invalid and can never be included in any future
449
- // block, so just drop as the head state advances into the next fork.
450
- if (this.config.getForkSeq(computeStartSlotAtEpoch(voluntaryExit.message.epoch)) < headStateFork) {
451
- this.voluntaryExits.delete(key);
452
- }
453
-
454
- // TODO: Improve this simplistic condition
455
- if (voluntaryExit.message.epoch <= finalizedEpoch) {
459
+ const {validatorIndex} = voluntaryExit.message;
460
+ const finalizedValidator =
461
+ finalizedState instanceof Uint8Array
462
+ ? getValidatorFromStateBytes(this.config, finalizedState, validatorIndex)
463
+ : validatorIndex < finalizedState.validatorCount
464
+ ? finalizedState.getValidator(validatorIndex)
465
+ : null;
466
+ if (finalizedValidator !== null && finalizedValidator.exitEpoch !== FAR_FUTURE_EPOCH) {
456
467
  this.voluntaryExits.delete(key);
457
468
  }
458
469
  }
@@ -132,6 +132,7 @@ export const defaultChainOptions: IChainOptions = {
132
132
  // - it helps debug easier when network is unfinalized
133
133
  nHistoricalStatesFileDataStore: true,
134
134
  nativeStateTransition: true,
135
+ nativeForkChoice: false,
135
136
  maxBlockStates: DEFAULT_MAX_BLOCK_STATES,
136
137
  maxCPStateEpochsInMemory: DEFAULT_MAX_CP_STATE_EPOCHS_IN_MEMORY,
137
138
  maxCPStateEpochsOnDisk: DEFAULT_MAX_CP_STATE_ON_DISK,
@@ -98,13 +98,16 @@ export async function validateGossipBlock(
98
98
  // If fork choice does *not* consider the parent to be a descendant of the finalized block,
99
99
  // then there are two more cases:
100
100
  //
101
- // 1. We have the parent stored in our database. Because fork-choice has confirmed the
102
- // parent is *not* in our post-finalization DAG, all other blocks must be either
103
- // pre-finalization or conflicting with finalization.
101
+ // 1. Fork choice still holds the parent. Because it is *not* in our post-finalization DAG,
102
+ // the parent is either pre-finalization or conflicting with finalization, so the
103
+ // finalized checkpoint is not an ancestor of the block: REJECT.
104
104
  // 2. The parent is unknown to us, we probably want to download it since it might actually
105
105
  // descend from the finalized root.
106
- // (Non-Lighthouse): Since we prune all blocks non-descendant from finalized checking the `db.block` database won't be useful to guard
107
- // against known bad fork blocks, so we throw PARENT_BLOCK_UNKNOWN for cases (1) and (2)
106
+ // Blocks that fork choice has already pruned fall into case (2), as the `db.block` database
107
+ // does not keep non-descendants of the finalized block either.
108
+ if (chain.forkChoice.hasBlockHexUnsafe(parentRoot)) {
109
+ throw new BlockGossipError(GossipAction.REJECT, {code: BlockErrorCode.NOT_FINALIZED_DESCENDANT, parentRoot});
110
+ }
108
111
  throw new BlockGossipError(GossipAction.IGNORE, {code: BlockErrorCode.PARENT_BLOCK_UNKNOWN, parentRoot});
109
112
  }
110
113
 
@@ -36,7 +36,11 @@ async function validateProposerSlashing(
36
36
 
37
37
  // [REJECT] All of the conditions within process_proposer_slashing pass validation.
38
38
  try {
39
- const proposer = state.getValidator(proposerSlashing.signedHeader1.message.proposerIndex);
39
+ const {proposerIndex} = proposerSlashing.signedHeader1.message;
40
+ if (proposerIndex >= state.validatorCount) {
41
+ throw Error(`Unknown proposer index ${proposerIndex}`);
42
+ }
43
+ const proposer = state.getValidator(proposerIndex);
40
44
  // verifySignature = false, verified in batch below
41
45
  assertValidProposerSlashing(chain.config, state.slot, proposerSlashing, proposer, false);
42
46
  } catch (e) {