@lodestar/beacon-node 1.52.0-dev.3a9c790524 → 1.52.0-dev.3ba097203c

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 (108) hide show
  1. package/lib/api/impl/validator/index.d.ts.map +1 -1
  2. package/lib/api/impl/validator/index.js +2 -4
  3. package/lib/api/impl/validator/index.js.map +1 -1
  4. package/lib/chain/archiveStore/utils/archiveBlocks.js +1 -1
  5. package/lib/chain/archiveStore/utils/archiveBlocks.js.map +1 -1
  6. package/lib/chain/chain.d.ts.map +1 -1
  7. package/lib/chain/chain.js +9 -5
  8. package/lib/chain/chain.js.map +1 -1
  9. package/lib/chain/errors/executionPayloadBid.d.ts +6 -1
  10. package/lib/chain/errors/executionPayloadBid.d.ts.map +1 -1
  11. package/lib/chain/errors/executionPayloadBid.js +1 -0
  12. package/lib/chain/errors/executionPayloadBid.js.map +1 -1
  13. package/lib/chain/errors/executionPayloadEnvelope.d.ts +7 -0
  14. package/lib/chain/errors/executionPayloadEnvelope.d.ts.map +1 -1
  15. package/lib/chain/errors/executionPayloadEnvelope.js +1 -0
  16. package/lib/chain/errors/executionPayloadEnvelope.js.map +1 -1
  17. package/lib/chain/prepareNextSlot.d.ts +45 -0
  18. package/lib/chain/prepareNextSlot.d.ts.map +1 -1
  19. package/lib/chain/prepareNextSlot.js +265 -69
  20. package/lib/chain/prepareNextSlot.js.map +1 -1
  21. package/lib/chain/produceBlock/produceBlockBody.d.ts +1 -0
  22. package/lib/chain/produceBlock/produceBlockBody.d.ts.map +1 -1
  23. package/lib/chain/produceBlock/produceBlockBody.js +23 -15
  24. package/lib/chain/produceBlock/produceBlockBody.js.map +1 -1
  25. package/lib/chain/validation/executionPayloadBid.d.ts.map +1 -1
  26. package/lib/chain/validation/executionPayloadBid.js +17 -2
  27. package/lib/chain/validation/executionPayloadBid.js.map +1 -1
  28. package/lib/chain/validation/executionPayloadEnvelope.d.ts.map +1 -1
  29. package/lib/chain/validation/executionPayloadEnvelope.js +21 -5
  30. package/lib/chain/validation/executionPayloadEnvelope.js.map +1 -1
  31. package/lib/chain/validation/voluntaryExit.d.ts.map +1 -1
  32. package/lib/chain/validation/voluntaryExit.js +39 -6
  33. package/lib/chain/validation/voluntaryExit.js.map +1 -1
  34. package/lib/execution/engine/blockHash.d.ts +12 -0
  35. package/lib/execution/engine/blockHash.d.ts.map +1 -0
  36. package/lib/execution/engine/blockHash.js +17 -0
  37. package/lib/execution/engine/blockHash.js.map +1 -0
  38. package/lib/execution/engine/mock.d.ts.map +1 -1
  39. package/lib/execution/engine/mock.js +6 -6
  40. package/lib/execution/engine/mock.js.map +1 -1
  41. package/lib/execution/engine/payloadIdCache.d.ts +6 -1
  42. package/lib/execution/engine/payloadIdCache.d.ts.map +1 -1
  43. package/lib/execution/engine/payloadIdCache.js +7 -2
  44. package/lib/execution/engine/payloadIdCache.js.map +1 -1
  45. package/lib/metrics/metrics/beacon.d.ts +5 -0
  46. package/lib/metrics/metrics/beacon.d.ts.map +1 -1
  47. package/lib/metrics/metrics/beacon.js +5 -0
  48. package/lib/metrics/metrics/beacon.js.map +1 -1
  49. package/lib/metrics/metrics/lodestar.d.ts +1 -0
  50. package/lib/metrics/metrics/lodestar.d.ts.map +1 -1
  51. package/lib/metrics/metrics/lodestar.js +5 -0
  52. package/lib/metrics/metrics/lodestar.js.map +1 -1
  53. package/lib/network/reqresp/handlers/dataColumnSidecarsByRange.js +1 -1
  54. package/lib/network/reqresp/handlers/dataColumnSidecarsByRange.js.map +1 -1
  55. package/lib/network/reqresp/handlers/dataColumnSidecarsByRoot.js +1 -1
  56. package/lib/network/reqresp/handlers/dataColumnSidecarsByRoot.js.map +1 -1
  57. package/lib/sync/range/batch.d.ts +4 -0
  58. package/lib/sync/range/batch.d.ts.map +1 -1
  59. package/lib/sync/range/batch.js +12 -0
  60. package/lib/sync/range/batch.js.map +1 -1
  61. package/lib/sync/range/chain.d.ts +17 -2
  62. package/lib/sync/range/chain.d.ts.map +1 -1
  63. package/lib/sync/range/chain.js +52 -19
  64. package/lib/sync/range/chain.js.map +1 -1
  65. package/lib/sync/range/range.d.ts.map +1 -1
  66. package/lib/sync/range/range.js +1 -0
  67. package/lib/sync/range/range.js.map +1 -1
  68. package/lib/sync/range/utils/batches.d.ts +20 -4
  69. package/lib/sync/range/utils/batches.d.ts.map +1 -1
  70. package/lib/sync/range/utils/batches.js +31 -13
  71. package/lib/sync/range/utils/batches.js.map +1 -1
  72. package/lib/sync/range/utils/peerBalancer.d.ts +1 -1
  73. package/lib/sync/range/utils/peerBalancer.d.ts.map +1 -1
  74. package/lib/sync/range/utils/peerBalancer.js +5 -2
  75. package/lib/sync/range/utils/peerBalancer.js.map +1 -1
  76. package/lib/sync/utils/downloadByRange.d.ts +8 -0
  77. package/lib/sync/utils/downloadByRange.d.ts.map +1 -1
  78. package/lib/sync/utils/downloadByRange.js +43 -23
  79. package/lib/sync/utils/downloadByRange.js.map +1 -1
  80. package/lib/util/dataColumns.d.ts +1 -1
  81. package/lib/util/dataColumns.d.ts.map +1 -1
  82. package/lib/util/dataColumns.js +4 -1
  83. package/lib/util/dataColumns.js.map +1 -1
  84. package/package.json +17 -17
  85. package/src/api/impl/validator/index.ts +2 -4
  86. package/src/chain/archiveStore/utils/archiveBlocks.ts +1 -1
  87. package/src/chain/chain.ts +9 -5
  88. package/src/chain/errors/executionPayloadBid.ts +6 -0
  89. package/src/chain/errors/executionPayloadEnvelope.ts +8 -0
  90. package/src/chain/prepareNextSlot.ts +347 -89
  91. package/src/chain/produceBlock/produceBlockBody.ts +25 -16
  92. package/src/chain/validation/executionPayloadBid.ts +20 -2
  93. package/src/chain/validation/executionPayloadEnvelope.ts +28 -5
  94. package/src/chain/validation/voluntaryExit.ts +44 -6
  95. package/src/execution/engine/blockHash.ts +27 -0
  96. package/src/execution/engine/mock.ts +13 -8
  97. package/src/execution/engine/payloadIdCache.ts +12 -4
  98. package/src/metrics/metrics/beacon.ts +9 -0
  99. package/src/metrics/metrics/lodestar.ts +5 -0
  100. package/src/network/reqresp/handlers/dataColumnSidecarsByRange.ts +1 -1
  101. package/src/network/reqresp/handlers/dataColumnSidecarsByRoot.ts +1 -1
  102. package/src/sync/range/batch.ts +13 -0
  103. package/src/sync/range/chain.ts +64 -17
  104. package/src/sync/range/range.ts +1 -0
  105. package/src/sync/range/utils/batches.ts +38 -13
  106. package/src/sync/range/utils/peerBalancer.ts +4 -1
  107. package/src/sync/utils/downloadByRange.ts +60 -26
  108. package/src/util/dataColumns.ts +4 -1
@@ -7,6 +7,7 @@ import {
7
7
  } from "@lodestar/state-transition";
8
8
  import {gloas, ssz} from "@lodestar/types";
9
9
  import {byteArrayEquals, toRootHex} from "@lodestar/utils";
10
+ import {computeExecutionBlockHash} from "../../execution/engine/blockHash.js";
10
11
  import {
11
12
  getBeaconBlockRootFromExecutionPayloadEnvelopeSerialized,
12
13
  getSlotFromExecutionPayloadEnvelopeSerialized,
@@ -55,7 +56,7 @@ export function validateGossipExecutionPayloadEnvelopeSerialized(
55
56
 
56
57
  const maxTransactionCount = getMaxTransactionCount(chain, block, payloadInput);
57
58
  if (BigInt(transactionCount) > maxTransactionCount) {
58
- throw new ExecutionPayloadEnvelopeError(GossipAction.IGNORE, {
59
+ throw new ExecutionPayloadEnvelopeError(GossipAction.REJECT, {
59
60
  code: ExecutionPayloadEnvelopeErrorCode.TOO_MANY_TRANSACTIONS,
60
61
  slot,
61
62
  root: blockRootHex,
@@ -199,12 +200,13 @@ async function validateExecutionPayloadEnvelope(
199
200
  });
200
201
  }
201
202
 
202
- // [IGNORE] The number of transactions is within the limit implied by the parent payload's gas limit
203
- // TODO GLOAS: [REJECT] once https://github.com/ethereum/consensus-specs/pull/5802 is released,
204
- // also in validateGossipExecutionPayloadEnvelopeSerialized
203
+ // Execution request and withdrawal count limits are enforced by the SSZ list limits on decode
204
+
205
+ // [REJECT] The number of transactions is within the limit implied by the parent payload's gas limit,
206
+ // also checked before deserialization in validateGossipExecutionPayloadEnvelopeSerialized
205
207
  const maxTransactionCount = getMaxTransactionCount(chain, block, payloadInput);
206
208
  if (BigInt(payload.transactions.length) > maxTransactionCount) {
207
- throw new ExecutionPayloadEnvelopeError(GossipAction.IGNORE, {
209
+ throw new ExecutionPayloadEnvelopeError(GossipAction.REJECT, {
208
210
  code: ExecutionPayloadEnvelopeErrorCode.TOO_MANY_TRANSACTIONS,
209
211
  slot: payload.slotNumber,
210
212
  root: blockRootHex,
@@ -251,6 +253,8 @@ async function validateExecutionPayloadEnvelope(
251
253
  }
252
254
 
253
255
  // [REJECT] The payload contains no empty transactions
256
+ // An empty transaction is a deletion in the transactions trie, so trailing empty transactions would not change
257
+ // the block hash. The EL rejects such a payload, as `verify_and_notify_new_payload` does before hashing.
254
258
  for (let i = 0; i < payload.transactions.length; i++) {
255
259
  if (payload.transactions.getSize(i) === 0) {
256
260
  throw new ExecutionPayloadEnvelopeError(GossipAction.REJECT, {
@@ -275,6 +279,25 @@ async function validateExecutionPayloadEnvelope(
275
279
  });
276
280
  }
277
281
 
282
+ // [REJECT] The payload's block hash is computed correctly
283
+ const timer = chain.metrics?.gossipExecutionPayloadEnvelope.blockHashTime.startTimer();
284
+ const computedBlockHash = computeExecutionBlockHash(
285
+ blockState.forkName,
286
+ payload,
287
+ envelope.parentBeaconBlockRoot,
288
+ envelope.executionRequests
289
+ );
290
+ timer?.();
291
+ if (!byteArrayEquals(computedBlockHash, payload.blockHash)) {
292
+ throw new ExecutionPayloadEnvelopeError(GossipAction.REJECT, {
293
+ code: ExecutionPayloadEnvelopeErrorCode.INVALID_BLOCK_HASH,
294
+ slot: payload.slotNumber,
295
+ root: blockRootHex,
296
+ blockHash: toRootHex(payload.blockHash),
297
+ computedBlockHash: toRootHex(computedBlockHash),
298
+ });
299
+ }
300
+
278
301
  // [REJECT] `signed_execution_payload_envelope.signature` is valid as verified
279
302
  // by `verify_execution_payload_envelope_signature`.
280
303
  const signatureSet = getExecutionPayloadEnvelopeSignatureSet(
@@ -1,4 +1,5 @@
1
- import {VoluntaryExitValidity, getVoluntaryExitSignatureSet} from "@lodestar/state-transition";
1
+ import {FAR_FUTURE_EPOCH} from "@lodestar/params";
2
+ import {VoluntaryExitValidity, computeEpochAtSlot, getVoluntaryExitSignatureSet} from "@lodestar/state-transition";
2
3
  import {phase0} from "@lodestar/types";
3
4
  import {
4
5
  GossipAction,
@@ -99,19 +100,56 @@ async function validateVoluntaryExit(
99
100
  // The only condition that is time sensitive and may require a non-head state is
100
101
  // -> Validator is active && validator has not initiated exit
101
102
  // The voluntaryExit.epoch must be in the past but the validator's status may change in recent epochs.
102
- // We dial the head state to the current epoch to get the current status of the validator. This is
103
- // relevant on periods of many skipped slots.
104
- const state = await chain.getHeadStateAtCurrentEpoch(RegenCaller.validateGossipVoluntaryExit);
103
+ // We dial the head state to the current epoch (with a MAXIMUM_GOSSIP_CLOCK_DISPARITY allowance) to get the
104
+ // current status of the validator. This is relevant on periods of many skipped slots.
105
+ const state = await chain.getHeadStateAtEpoch(
106
+ computeEpochAtSlot(chain.clock.currentSlotWithGossipDisparity),
107
+ RegenCaller.validateGossipVoluntaryExit
108
+ );
105
109
 
106
- // [REJECT] All of the conditions within process_voluntary_exit pass validation.
107
110
  // verifySignature = false, verified in batch below
108
111
  const validity = state.getVoluntaryExitValidity(voluntaryExit, false);
109
112
  if (validity !== VoluntaryExitValidity.valid) {
110
- throw new VoluntaryExitError(GossipAction.REJECT, {
113
+ let action: GossipAction;
114
+ switch (validity) {
115
+ // [IGNORE] The voluntary exit epoch is not in the future
116
+ case VoluntaryExitValidity.earlyEpoch:
117
+ // [IGNORE] The validator has not already initiated exit
118
+ case VoluntaryExitValidity.alreadyExited:
119
+ // [IGNORE] The validator has no pending partial withdrawals
120
+ case VoluntaryExitValidity.pendingWithdrawals:
121
+ action = GossipAction.IGNORE;
122
+ break;
123
+ // [REJECT] The validator index is valid
124
+ // [REJECT] The validator is active
125
+ // An exit in a future epoch or of a validator past its exit epoch can also be reported as inactive,
126
+ // the spec checks both conditions first and ignores the exit
127
+ case VoluntaryExitValidity.inactive: {
128
+ const {epoch, validatorIndex} = voluntaryExit.message;
129
+ if (epoch > state.epoch) {
130
+ throw new VoluntaryExitError(GossipAction.IGNORE, {code: VoluntaryExitErrorCode.EARLY_EPOCH});
131
+ }
132
+ if (
133
+ validatorIndex < state.validatorCount &&
134
+ state.getValidator(validatorIndex).exitEpoch !== FAR_FUTURE_EPOCH
135
+ ) {
136
+ throw new VoluntaryExitError(GossipAction.IGNORE, {code: VoluntaryExitErrorCode.ALREADY_EXITED});
137
+ }
138
+ action = GossipAction.REJECT;
139
+ break;
140
+ }
141
+ // [REJECT] The validator has been active long enough
142
+ case VoluntaryExitValidity.shortTimeActive:
143
+ case VoluntaryExitValidity.invalidSignature:
144
+ action = GossipAction.REJECT;
145
+ break;
146
+ }
147
+ throw new VoluntaryExitError(action, {
111
148
  code: voluntaryExitValidityToErrorCode(validity),
112
149
  });
113
150
  }
114
151
 
152
+ // [REJECT] The signature is valid
115
153
  const signatureSet = getVoluntaryExitSignatureSet(chain.config, state, voluntaryExit);
116
154
  if (!(await chain.bls.verifySignatureSets([signatureSet], {batchable: true, priority: prioritizeBls}))) {
117
155
  throw new VoluntaryExitError(GossipAction.REJECT, {
@@ -0,0 +1,27 @@
1
+ import {computeExecutionBlockHash as computeExecutionBlockHashNative} from "@lodestar/native/execution-block-hash";
2
+ import {ForkPostBellatrix, ForkSeq, isForkPostElectra} from "@lodestar/params";
3
+ import {ExecutionPayload, ExecutionRequests, Root, sszTypesFor} from "@lodestar/types";
4
+
5
+ /**
6
+ * Compute the execution block hash of `payload`: keccak256 of the RLP-encoded execution block header,
7
+ * with the header fields laid out as in execution-specs for the execution fork paired with `fork`.
8
+ *
9
+ * `parentBeaconBlockRoot` is required from deneb and `executionRequests` from electra.
10
+ *
11
+ * Throws if a transaction is empty. It would be a deletion in the transactions trie and not change the hash.
12
+ */
13
+ export function computeExecutionBlockHash(
14
+ fork: ForkPostBellatrix,
15
+ payload: ExecutionPayload,
16
+ parentBeaconBlockRoot: Root | null,
17
+ executionRequests: ExecutionRequests | null
18
+ ): Uint8Array {
19
+ return computeExecutionBlockHashNative(
20
+ ForkSeq[fork],
21
+ sszTypesFor(fork).ExecutionPayload.serialize(payload),
22
+ parentBeaconBlockRoot ?? undefined,
23
+ executionRequests !== null && isForkPostElectra(fork)
24
+ ? sszTypesFor(fork).ExecutionRequests.serialize(executionRequests)
25
+ : undefined
26
+ );
27
+ }
@@ -10,14 +10,16 @@ import {
10
10
  ForkPostCapella,
11
11
  ForkSeq,
12
12
  SLOTS_PER_EPOCH,
13
+ isForkPostElectra,
13
14
  } from "@lodestar/params";
14
15
  import {computeTimeAtSlot} from "@lodestar/state-transition";
15
- import {ExecutionPayload, RootHex, bellatrix, deneb, gloas, ssz} from "@lodestar/types";
16
+ import {ExecutionPayload, RootHex, bellatrix, deneb, gloas, ssz, sszTypesFor} from "@lodestar/types";
16
17
  import {fromHex, toRootHex} from "@lodestar/utils";
17
18
  import {ZERO_HASH_HEX} from "../../constants/index.js";
18
19
  import {INTEROP_BLOCK_HASH} from "../../node/utils/interop/state.js";
19
20
  import {kzgCommitmentToVersionedHash} from "../../util/blobs.js";
20
21
  import {kzg} from "../../util/kzg.js";
22
+ import {computeExecutionBlockHash} from "./blockHash.js";
21
23
  import {ClientCode, ExecutionPayloadStatus, PayloadIdCache} from "./interface.js";
22
24
  import {
23
25
  BlobsBundleRpc,
@@ -351,7 +353,6 @@ export class ExecutionEngineMockBackend implements JsonRpcBackend {
351
353
  executionPayload.gasLimit = INTEROP_GAS_LIMIT;
352
354
  executionPayload.gasUsed = Math.floor(0.5 * INTEROP_GAS_LIMIT);
353
355
  executionPayload.timestamp = payloadAttributes.timestamp;
354
- executionPayload.blockHash = crypto.randomBytes(32);
355
356
  const transactions: Uint8Array[] = [];
356
357
 
357
358
  // Between 0 and 4 transactions for all forks
@@ -401,6 +402,15 @@ export class ExecutionEngineMockBackend implements JsonRpcBackend {
401
402
  (executionPayload as gloas.ExecutionPayload).slotNumber = payloadAttributes.slotNumber;
402
403
  }
403
404
 
405
+ const executionRequests = isForkPostElectra(fork) ? sszTypesFor(fork).ExecutionRequests.defaultValue() : null;
406
+
407
+ executionPayload.blockHash = computeExecutionBlockHash(
408
+ fork,
409
+ executionPayload,
410
+ payloadAttributes.parentBeaconBlockRoot ?? null,
411
+ executionRequests
412
+ );
413
+
404
414
  this.preparingPayloads.set(payloadId, {
405
415
  executionPayload: serializeExecutionPayload(fork, executionPayload),
406
416
  blobsBundle: serializeBlobsBundle({
@@ -408,12 +418,7 @@ export class ExecutionEngineMockBackend implements JsonRpcBackend {
408
418
  blobs,
409
419
  proofs,
410
420
  }),
411
- executionRequests: serializeExecutionRequests(
412
- fork,
413
- ForkSeq[fork] >= ForkSeq.gloas
414
- ? ssz.gloas.ExecutionRequests.defaultValue()
415
- : ssz.electra.ExecutionRequests.defaultValue()
416
- ),
421
+ executionRequests: executionRequests !== null ? serializeExecutionRequests(fork, executionRequests) : [],
417
422
  });
418
423
 
419
424
  // IF the payload is deemed VALID and the build process has begun
@@ -12,6 +12,9 @@ const MAX_PAYLOAD_IDS = SLOTS_PER_EPOCH;
12
12
  // Since we do no processing with this id, we have no need to deserialize it
13
13
  export type PayloadId = string;
14
14
 
15
+ /** Payload id returned by the engine and when the payload was requested from it, monotonic `performance.now()` ms */
16
+ export type PreparedPayloadId = {payloadId: PayloadId; preparedAtMs: number};
17
+
15
18
  export type WithdrawalV1 = {
16
19
  index: QUANTITY;
17
20
  validatorIndex: QUANTITY;
@@ -26,7 +29,7 @@ type FcuAttributes = {headBlockHash: DATA} & Omit<PayloadAttributesRpc, "withdra
26
29
  export class PayloadIdCache {
27
30
  private readonly payloadIdByFcuAttributes = new Map<
28
31
  string,
29
- {payloadId: PayloadId; fullKey: string; inclusionListTransactions?: bellatrix.Transactions}
32
+ PreparedPayloadId & {fullKey: string; inclusionListTransactions?: bellatrix.Transactions}
30
33
  >();
31
34
 
32
35
  getFullKey({headBlockHash, timestamp, prevRandao, suggestedFeeRecipient}: FcuAttributes): string {
@@ -45,7 +48,12 @@ export class PayloadIdCache {
45
48
  const key = this.getKey(fcuAttributes);
46
49
  const fullKey = this.getFullKey(fcuAttributes);
47
50
  const {inclusionListTransactions} = fcuAttributes;
48
- this.payloadIdByFcuAttributes.set(key, {payloadId, fullKey, inclusionListTransactions});
51
+ this.payloadIdByFcuAttributes.set(key, {
52
+ payloadId,
53
+ preparedAtMs: performance.now(),
54
+ fullKey,
55
+ inclusionListTransactions,
56
+ });
49
57
  }
50
58
 
51
59
  prune(): void {
@@ -53,13 +61,13 @@ export class PayloadIdCache {
53
61
  pruneSetToMax(this.payloadIdByFcuAttributes, MAX_PAYLOAD_IDS);
54
62
  }
55
63
 
56
- get(fcuAttributes: FcuAttributes): PayloadId | undefined {
64
+ get(fcuAttributes: FcuAttributes): PreparedPayloadId | undefined {
57
65
  const key = this.getKey(fcuAttributes);
58
66
  const fullKey = this.getFullKey(fcuAttributes);
59
67
  const payloadInfo = this.payloadIdByFcuAttributes.get(key);
60
68
  return payloadInfo?.fullKey === fullKey &&
61
69
  isSameInclusionList(payloadInfo.inclusionListTransactions, fcuAttributes.inclusionListTransactions)
62
- ? payloadInfo.payloadId
70
+ ? {payloadId: payloadInfo.payloadId, preparedAtMs: payloadInfo.preparedAtMs}
63
71
  : undefined;
64
72
  }
65
73
  }
@@ -1,6 +1,7 @@
1
1
  import {ProducedBlockSource} from "@lodestar/types";
2
2
  import {BlockSelectionResult} from "../../api/impl/validator/index.js";
3
3
  import {InclusionListSource} from "../../chain/blocks/types.js";
4
+ import {PreparePayloadReason} from "../../chain/prepareNextSlot.js";
4
5
  import {BlockProductionStep, PayloadPreparationType} from "../../chain/produceBlock/index.js";
5
6
  import {RegistryMetricCreator} from "../utils/registryMetricCreator.js";
6
7
 
@@ -164,6 +165,14 @@ export function createBeaconMetrics(register: RegistryMetricCreator) {
164
165
  help: "Time for preparing payload in advance",
165
166
  buckets: [0.1, 1, 3, 5, 10],
166
167
  }),
168
+ payloadReprepare: register.counter<{
169
+ reason: PreparePayloadReason;
170
+ result: "changed" | "unchanged" | "dropped" | "error";
171
+ }>({
172
+ name: "beacon_block_payload_reprepare_total",
173
+ help: "Re-runs of the next slot payload preparation after the scheduled run, by reason and result: prepared again as the head or its parent payload changed, unchanged, dropped as the proposal slot started, or failed",
174
+ labelNames: ["reason", "result"],
175
+ }),
167
176
  executionPayloadEnvelopeProcessingTime: register.histogram({
168
177
  name: "beacon_block_payload_envelope_processing_seconds",
169
178
  help: "Time to process execution payload envelope during block production",
@@ -1068,6 +1068,11 @@ export function createLodestarMetrics(
1068
1068
  help: "Count of errors, by error type, while processing execution payload envelopes",
1069
1069
  labelNames: ["error"],
1070
1070
  }),
1071
+ blockHashTime: register.histogram({
1072
+ name: "lodestar_gossip_execution_payload_envelope_block_hash_seconds",
1073
+ help: "Time to compute the execution block hash of a gossip execution payload envelope",
1074
+ buckets: [0.001, 0.002, 0.005, 0.01, 0.025, 0.05, 0.1, 0.5, 1],
1075
+ }),
1071
1076
  executionPayload: {
1072
1077
  recvToValidation: register.histogram({
1073
1078
  name: "lodestar_gossip_execution_payload_envelope_received_to_execution_payload_verification_seconds",
@@ -216,7 +216,7 @@ export function validateDataColumnSidecarsByRangeRequest(
216
216
  throw new ResponseError(RespStatus.INVALID_REQUEST, "startSlot < genesis");
217
217
  }
218
218
 
219
- // Spec: [max(compute_blob_data_retention_start_epoch(current_epoch), FULU_FORK_EPOCH), current_epoch]
219
+ // Spec: [max(current_epoch - MIN_EPOCHS_FOR_DATA_COLUMN_SIDECARS_REQUESTS, FULU_FORK_EPOCH), current_epoch]
220
220
  const minimumRequestEpoch = Math.max(getBlobDataRetentionStartEpoch(config, currentEpoch), config.FULU_FORK_EPOCH);
221
221
  if (computeEpochAtSlot(startSlot) < minimumRequestEpoch) {
222
222
  throw new ResponseError(RespStatus.RESOURCE_UNAVAILABLE, "startSlot is before the blob data retention window");
@@ -19,7 +19,7 @@ export async function* onDataColumnSidecarsByRoot(
19
19
  peerId: PeerId,
20
20
  peerClient: string
21
21
  ): AsyncIterable<ResponseOutgoing> {
22
- // SPEC: minimum_request_epoch = max(compute_blob_data_retention_start_epoch(current_epoch), FULU_FORK_EPOCH)
22
+ // SPEC: minimum_request_epoch = max(current_epoch - MIN_EPOCHS_FOR_DATA_COLUMN_SIDECARS_REQUESTS, FULU_FORK_EPOCH)
23
23
  const currentEpoch = chain.clock.currentEpoch;
24
24
  const minimumRequestEpoch = Math.max(
25
25
  getBlobDataRetentionStartEpoch(chain.config, currentEpoch),
@@ -430,6 +430,19 @@ export class Batch {
430
430
  return [...this.failedProcessingAttempts, ...this.executionErrorAttempts].filter((a) => a.peerAttributable);
431
431
  }
432
432
 
433
+ /**
434
+ * How many failed processing/execution attempts each peer took part in, peer-attributable or not
435
+ */
436
+ getTriedPeerCounts(): Map<PeerIdStr, number> {
437
+ const counts = new Map<PeerIdStr, number>();
438
+ for (const attempt of [...this.failedProcessingAttempts, ...this.executionErrorAttempts]) {
439
+ for (const peer of attempt.peers) {
440
+ counts.set(peer, (counts.get(peer) ?? 0) + 1);
441
+ }
442
+ }
443
+ return counts;
444
+ }
445
+
433
446
  /**
434
447
  * True only if the peer has already returned a successful response for the current request.
435
448
  * A by_range success may update `this.requests` to parent_payload, and the same peer is then
@@ -1,5 +1,5 @@
1
1
  import {ChainForkConfig} from "@lodestar/config";
2
- import {Epoch, Root, Slot} from "@lodestar/types";
2
+ import {Epoch, Root, RootHex, Slot} from "@lodestar/types";
3
3
  import {ErrorAborted, LodestarError, Logger, prettyPrintIndices, toRootHex} from "@lodestar/utils";
4
4
  import {isBlockInputColumns} from "../../chain/blocks/blockInput/blockInput.js";
5
5
  import {BlockInputErrorCode} from "../../chain/blocks/blockInput/errors.js";
@@ -68,6 +68,8 @@ export type SyncChainFns = {
68
68
  onEnd: (err: Error | null, target: ChainTarget | null) => void;
69
69
  /** Deletes an array of BlockInputs from the BlockInputCache */
70
70
  pruneBlockInputs: (blockInputs: IBlockInput[]) => void;
71
+ /** Returns true if the block is known to fork choice */
72
+ hasBlock: (blockRoot: Root) => boolean;
71
73
  };
72
74
 
73
75
  /**
@@ -81,6 +83,15 @@ export type ChainTarget = {
81
83
 
82
84
  export class SyncChainStartError extends Error {}
83
85
 
86
+ export enum SyncChainErrorCode {
87
+ /** The terminal batch has 0 blocks but the target block is not known */
88
+ MISSING_TARGET_BLOCK = "SYNC_CHAIN_ERROR_MISSING_TARGET_BLOCK",
89
+ }
90
+
91
+ type SyncChainErrorType = {code: SyncChainErrorCode.MISSING_TARGET_BLOCK; targetSlot: Slot; targetRoot: RootHex};
92
+
93
+ export class SyncChainError extends LodestarError<SyncChainErrorType> {}
94
+
84
95
  export type SyncChainDebugState = {
85
96
  targetRoot: string | null;
86
97
  targetSlot: number | null;
@@ -136,6 +147,7 @@ export class SyncChain {
136
147
  private readonly reportPeer: SyncChainFns["reportPeer"];
137
148
  private readonly getConnectedPeerSyncMeta: SyncChainFns["getConnectedPeerSyncMeta"];
138
149
  private readonly pruneBlockInputs: SyncChainFns["pruneBlockInputs"];
150
+ private readonly hasBlock: SyncChainFns["hasBlock"];
139
151
 
140
152
  /** AsyncIterable that guarantees processChainSegment is run only at once at anytime */
141
153
  private readonly batchProcessor = new ItTrigger();
@@ -178,6 +190,7 @@ export class SyncChain {
178
190
  this.downloadByRange = fns.downloadByRange;
179
191
  this.reportPeer = fns.reportPeer;
180
192
  this.pruneBlockInputs = fns.pruneBlockInputs;
193
+ this.hasBlock = fns.hasBlock;
181
194
  this.getConnectedPeerSyncMeta = fns.getConnectedPeerSyncMeta;
182
195
  this.config = config;
183
196
  this.clock = clock;
@@ -335,6 +348,32 @@ export class SyncChain {
335
348
 
336
349
  // Returns true if SyncChain has processed all possible blocks with slot <= target.slot
337
350
  if (isSyncChainDone(toArr(this.batches), this.lastEpochWithProcessBlocks, this.target.slot)) {
351
+ // A 0-block terminal batch is only trusted once the target block is known, otherwise a peer returning no
352
+ // blocks for the last range ends the chain short of its target
353
+ const lastAwaitingValidation = toArr(this.batches).findLast(
354
+ (b) => b.state.status === BatchStatus.AwaitingValidation
355
+ );
356
+ if (
357
+ lastAwaitingValidation !== undefined &&
358
+ lastAwaitingValidation.getBlocks().length === 0 &&
359
+ !this.hasBlock(this.target.root)
360
+ ) {
361
+ this.logger.verbose("Terminal 0-block batch without target block", {
362
+ id: this.logId,
363
+ ...lastAwaitingValidation.getMetadata(),
364
+ });
365
+ // Not peer attributable: throws MAX_PROCESSING_ATTEMPTS after MAX_BATCH_PROCESSING_ATTEMPTS without
366
+ // reporting any peer
367
+ lastAwaitingValidation.validationError(
368
+ new SyncChainError({
369
+ code: SyncChainErrorCode.MISSING_TARGET_BLOCK,
370
+ targetSlot: this.target.slot,
371
+ targetRoot: toRootHex(this.target.root),
372
+ })
373
+ );
374
+ this.triggerBatchDownloader();
375
+ continue;
376
+ }
338
377
  break;
339
378
  }
340
379
 
@@ -509,9 +548,12 @@ export class SyncChain {
509
548
  // if last processed epoch is n, we don't want to request batches with epoch > n + MAX_LOOK_AHEAD_EPOCHS
510
549
  // we should have enough batches to process in the buffer: n + 1, ..., n + MAX_LOOK_AHEAD_EPOCHS
511
550
  // let's focus on redownloading these batches first because it may have to reach different peers to get enough sampled columns
551
+ // Note: Don't count batches in the AwaitingValidation state, 0-block batches never advance
552
+ // lastEpochWithProcessBlocks so more than MAX_LOOK_AHEAD_EPOCHS of them in a row would stall sync
553
+ const pendingBatches = batches.filter((batch) => batch.state.status !== BatchStatus.AwaitingValidation);
512
554
  if (
513
- batches.length > 0 &&
514
- Math.max(...batches.map((b) => b.startEpoch)) >= this.lastEpochWithProcessBlocks + MAX_LOOK_AHEAD_EPOCHS
555
+ pendingBatches.length > 0 &&
556
+ Math.max(...pendingBatches.map((b) => b.startEpoch)) >= this.lastEpochWithProcessBlocks + MAX_LOOK_AHEAD_EPOCHS
515
557
  ) {
516
558
  return null;
517
559
  }
@@ -576,6 +618,7 @@ export class SyncChain {
576
618
  }
577
619
  }
578
620
  switch (errCode) {
621
+ case DownloadByRangeErrorCode.DATA_WITHOUT_BLOCKS:
579
622
  case DownloadByRangeErrorCode.EXTRA_BLOCKS:
580
623
  case DownloadByRangeErrorCode.OUT_OF_ORDER_BLOCKS:
581
624
  case DownloadByRangeErrorCode.OUT_OF_RANGE_BLOCKS:
@@ -722,39 +765,43 @@ export class SyncChain {
722
765
  } else {
723
766
  this.logger.verbose("Batch process error", logCtx, res.err);
724
767
 
725
- const invalidatePreviousBatches = (): number => {
726
- let invalidatedCount = 0;
768
+ // advanceChain() drops every batch before the last batch with blocks, so the AwaitingValidation batches before
769
+ // `batch` are that batch followed by 0-block batches, see classifyProcessingFault(). With no batch with blocks
770
+ // yet, fall back to the first 0-block batch so a wrong 0-block answer at the start of the chain is retried
771
+ const awaitingValidationBefore = toArr(this.batches).filter(
772
+ (b) => b.startEpoch < batch.startEpoch && b.state.status === BatchStatus.AwaitingValidation
773
+ );
774
+ const parentBatch =
775
+ awaitingValidationBefore.findLast((b) => b.getBlocks().length > 0) ?? awaitingValidationBefore[0];
776
+ // The 0-block batches after `parentBatch` are invalidated with it: an AwaitingValidation batch must not follow a
777
+ // batch that is downloaded again, see validateBatchesStatus()
778
+ const invalidateFromParentBatch = (faultyParentBatch: Batch): void => {
727
779
  for (const pendingBatch of this.batches.values()) {
728
780
  if (
781
+ pendingBatch.startEpoch >= faultyParentBatch.startEpoch &&
729
782
  pendingBatch.startEpoch < batch.startEpoch &&
730
783
  pendingBatch.state.status === BatchStatus.AwaitingValidation
731
784
  ) {
732
785
  this.logger.verbose("Batch validation error", {id: this.logId, ...pendingBatch.getMetadata()});
733
786
  pendingBatch.validationError(res.err);
734
- invalidatedCount++;
735
787
  }
736
788
  }
737
- return invalidatedCount;
738
789
  };
739
790
 
740
- const prevBatch = this.batches.get(batch.startEpoch - EPOCHS_PER_BATCH);
741
- switch (classifyProcessingFault(res.err, batch, prevBatch)) {
791
+ const fault = classifyProcessingFault(res.err, batch, parentBatch);
792
+ switch (fault.kind) {
742
793
  case ProcessingFaultKind.CurrentBatch:
743
794
  batch.processingError(res.err);
744
795
  break;
745
796
 
746
- case ProcessingFaultKind.PreviousBatch:
747
- // If no previous batch was invalidated, it means the error is on this batch
748
- if (invalidatePreviousBatches() === 0) {
749
- batch.processingError(res.err);
750
- } else {
751
- batch.retainForReprocessing();
752
- }
797
+ case ProcessingFaultKind.ParentBatch:
798
+ invalidateFromParentBatch(fault.parentBatch);
799
+ batch.retainForReprocessing();
753
800
  break;
754
801
 
755
802
  case ProcessingFaultKind.Ambiguous:
756
803
  batch.processingError(res.err);
757
- invalidatePreviousBatches();
804
+ invalidateFromParentBatch(fault.parentBatch);
758
805
  break;
759
806
  }
760
807
  }
@@ -461,6 +461,7 @@ export class RangeSync extends (EventEmitter as {new (): RangeSyncEmitter}) {
461
461
  reportPeer: this.reportPeer,
462
462
  getConnectedPeerSyncMeta: this.getConnectedPeerSyncMeta,
463
463
  pruneBlockInputs: this.pruneBlockInputs,
464
+ hasBlock: (blockRoot) => this.chain.forkChoice.hasBlock(blockRoot),
464
465
  onEnd: this.onSyncChainEnd,
465
466
  },
466
467
  {
@@ -125,39 +125,64 @@ export function isSyncChainDone(batches: Batch[], lastEpochWithProcessBlocks: Ep
125
125
  export enum ProcessingFaultKind {
126
126
  /** This batch's own blocks are bad or incomplete, so redownload this batch. */
127
127
  CurrentBatch = "CurrentBatch",
128
- /** This batch is valid, but a previous batch did not deliver the parent. */
129
- PreviousBatch = "PreviousBatch",
130
- /** The fault could be in this batch or a previous batch, so hedge both ways. */
128
+ /** This batch is valid, but the parent batch did not deliver the parent. */
129
+ ParentBatch = "ParentBatch",
130
+ /** The fault could be in this batch or the parent batch, so hedge both ways. */
131
131
  Ambiguous = "Ambiguous",
132
132
  }
133
133
 
134
+ export type ProcessingFault =
135
+ | {kind: ProcessingFaultKind.CurrentBatch}
136
+ | {kind: ProcessingFaultKind.ParentBatch; parentBatch: Batch}
137
+ | {kind: ProcessingFaultKind.Ambiguous; parentBatch: Batch};
138
+
134
139
  /**
135
140
  * Classify a processChainSegment error for a batch so range sync only redownloads
136
141
  * the batch or batches that could actually be at fault.
137
142
  * Note that range sync is supposed to only handle linear chain, for forky condition we'll handle it via backward sync
138
143
  * in BlockInputSync or the upcoming/TODO beacon_blocks_by_head req/resp.
144
+ *
145
+ * `parentBatch` is the last batch with blocks before `batch`, it may be followed by 0-block batches. If no batch with
146
+ * blocks awaits validation, it is the first 0-block batch before `batch`.
147
+ * Epochs with 0 blocks usually happen on devnets, during periods of poor liveness when no proposer gets a block
148
+ * included for whole epochs. A wrong 0-block response only shows up as an unknown parent in `batch`, so with 0-block
149
+ * batches in between the fault is never pinned on `batch` alone: `parentBatch` and the 0-block batches after it are
150
+ * downloaded again.
139
151
  */
140
- export function classifyProcessingFault(err: Error, batch: Batch, prevBatch: Batch | undefined): ProcessingFaultKind {
152
+ export function classifyProcessingFault(err: Error, batch: Batch, parentBatch: Batch | undefined): ProcessingFault {
141
153
  if (!(err instanceof BlockError)) {
142
- return ProcessingFaultKind.CurrentBatch;
154
+ return {kind: ProcessingFaultKind.CurrentBatch};
143
155
  }
144
156
 
145
157
  const {code} = err.type;
146
158
  if (code !== BlockErrorCode.PARENT_BLOCK_UNKNOWN && code !== BlockErrorCode.PARENT_PAYLOAD_UNKNOWN) {
147
- return ProcessingFaultKind.CurrentBatch;
159
+ return {kind: ProcessingFaultKind.CurrentBatch};
160
+ }
161
+
162
+ if (parentBatch === undefined) {
163
+ return {kind: ProcessingFaultKind.CurrentBatch};
148
164
  }
149
165
 
150
166
  const firstErrorSlot = err.signedBlock.message.slot;
151
167
  if (firstErrorSlot === batch.startSlot) {
152
- // note that range sync is for linear chain, so this is clearly an issue of the previous batch
153
- return prevBatch === undefined ? ProcessingFaultKind.CurrentBatch : ProcessingFaultKind.PreviousBatch;
168
+ // note that range sync is for linear chain, so this is clearly an issue of the parent batch
169
+ return {kind: ProcessingFaultKind.ParentBatch, parentBatch};
154
170
  }
155
171
 
156
- const prevTailSlot = batch.startSlot - 1;
157
- const prevHasFullTail =
172
+ // `parentBatch` can be followed by 0-block batches, so its tail is the end of its own range
173
+ const parentTailSlot = parentBatch.startSlot + parentBatch.count - 1;
174
+ const parentHasFullTail =
158
175
  code === BlockErrorCode.PARENT_PAYLOAD_UNKNOWN
159
- ? (prevBatch?.getPayloadEnvelopes()?.get(prevTailSlot)?.hasPayloadEnvelope() ?? false)
160
- : (prevBatch?.getBlocks().some((b) => b.slot === prevTailSlot) ?? false);
176
+ ? (parentBatch.getPayloadEnvelopes()?.get(parentTailSlot)?.hasPayloadEnvelope() ?? false)
177
+ : parentBatch.getBlocks().some((b) => b.slot === parentTailSlot);
161
178
 
162
- return prevHasFullTail ? ProcessingFaultKind.CurrentBatch : ProcessingFaultKind.Ambiguous;
179
+ // With 0-block batches in between, it could be a wrong 0-block batch
180
+ const hasZeroBlockGap = parentTailSlot + 1 < batch.startSlot;
181
+
182
+ // Assumes the tail block / payload delivered by `parentBatch` is canonical. If it is orphaned, `parentBatch` is at
183
+ // fault: `batch` keeps failing until MAX_PROCESSING_ATTEMPTS and a new SyncChain is created.
184
+ if (parentHasFullTail && !hasZeroBlockGap) {
185
+ return {kind: ProcessingFaultKind.CurrentBatch};
186
+ }
187
+ return {kind: ProcessingFaultKind.Ambiguous, parentBatch};
163
188
  }
@@ -52,7 +52,7 @@ export class ChainPeersBalancer {
52
52
 
53
53
  /**
54
54
  * Return the most suitable peer to retry
55
- * Sort peers by (1) less active requests (2) most columns we need.
55
+ * Sort peers by (1) fewer failed attempts for this batch (2) less active requests (3) most columns we need.
56
56
  * Peers that failed this batch or already succeeded for the same request are excluded inside `filterPeers`.
57
57
  */
58
58
  bestPeerToRetryBatch(batch: Batch): PeerSyncMeta | undefined {
@@ -63,9 +63,12 @@ export class ChainPeersBalancer {
63
63
  // TODO(fulu): This is fulu specific and hinders our peer selection PreFulu
64
64
  const pendingDataColumns = columnsRequest?.columns ?? this.custodyConfig.sampledColumns;
65
65
  const eligiblePeers = this.filterPeers(batch, pendingDataColumns, false);
66
+ const triedPeerCounts = batch.getTriedPeerCounts();
66
67
 
67
68
  const sortedBestPeers = sortBy(
68
69
  eligiblePeers,
70
+ // prefer peers not tried for this batch yet
71
+ ({syncInfo}) => triedPeerCounts.get(syncInfo.peerId) ?? 0,
69
72
  ({syncInfo}) => this.activeRequestsByPeer.get(syncInfo.peerId) ?? 0, // prefer peers with least active req
70
73
  ({columns}) => -1 * columns // prefer peers with the most columns
71
74
  );