@lodestar/beacon-node 1.52.0-dev.5745da1108 → 1.52.0-dev.643dd3c5bf

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 (130) 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/core/events.d.ts +6 -2
  54. package/lib/network/core/events.d.ts.map +1 -1
  55. package/lib/network/core/events.js +9 -0
  56. package/lib/network/core/events.js.map +1 -1
  57. package/lib/network/core/networkCoreWorkerHandler.d.ts.map +1 -1
  58. package/lib/network/core/networkCoreWorkerHandler.js +3 -2
  59. package/lib/network/core/networkCoreWorkerHandler.js.map +1 -1
  60. package/lib/network/reqresp/handlers/dataColumnSidecarsByRange.js +1 -1
  61. package/lib/network/reqresp/handlers/dataColumnSidecarsByRange.js.map +1 -1
  62. package/lib/network/reqresp/handlers/dataColumnSidecarsByRoot.js +1 -1
  63. package/lib/network/reqresp/handlers/dataColumnSidecarsByRoot.js.map +1 -1
  64. package/lib/sync/range/batch.d.ts +4 -0
  65. package/lib/sync/range/batch.d.ts.map +1 -1
  66. package/lib/sync/range/batch.js +12 -0
  67. package/lib/sync/range/batch.js.map +1 -1
  68. package/lib/sync/range/chain.d.ts +17 -2
  69. package/lib/sync/range/chain.d.ts.map +1 -1
  70. package/lib/sync/range/chain.js +52 -19
  71. package/lib/sync/range/chain.js.map +1 -1
  72. package/lib/sync/range/range.d.ts.map +1 -1
  73. package/lib/sync/range/range.js +1 -0
  74. package/lib/sync/range/range.js.map +1 -1
  75. package/lib/sync/range/utils/batches.d.ts +20 -4
  76. package/lib/sync/range/utils/batches.d.ts.map +1 -1
  77. package/lib/sync/range/utils/batches.js +31 -13
  78. package/lib/sync/range/utils/batches.js.map +1 -1
  79. package/lib/sync/range/utils/peerBalancer.d.ts +1 -1
  80. package/lib/sync/range/utils/peerBalancer.d.ts.map +1 -1
  81. package/lib/sync/range/utils/peerBalancer.js +5 -2
  82. package/lib/sync/range/utils/peerBalancer.js.map +1 -1
  83. package/lib/sync/types.d.ts +2 -0
  84. package/lib/sync/types.d.ts.map +1 -1
  85. package/lib/sync/types.js.map +1 -1
  86. package/lib/sync/unknownBlock.d.ts.map +1 -1
  87. package/lib/sync/unknownBlock.js +60 -19
  88. package/lib/sync/unknownBlock.js.map +1 -1
  89. package/lib/sync/utils/downloadByRange.d.ts +8 -0
  90. package/lib/sync/utils/downloadByRange.d.ts.map +1 -1
  91. package/lib/sync/utils/downloadByRange.js +43 -23
  92. package/lib/sync/utils/downloadByRange.js.map +1 -1
  93. package/lib/util/asyncIterableToEvents.d.ts +20 -3
  94. package/lib/util/asyncIterableToEvents.d.ts.map +1 -1
  95. package/lib/util/asyncIterableToEvents.js +76 -20
  96. package/lib/util/asyncIterableToEvents.js.map +1 -1
  97. package/lib/util/dataColumns.d.ts +1 -1
  98. package/lib/util/dataColumns.d.ts.map +1 -1
  99. package/lib/util/dataColumns.js +4 -1
  100. package/lib/util/dataColumns.js.map +1 -1
  101. package/package.json +17 -17
  102. package/src/api/impl/validator/index.ts +2 -4
  103. package/src/chain/archiveStore/utils/archiveBlocks.ts +1 -1
  104. package/src/chain/chain.ts +9 -5
  105. package/src/chain/errors/executionPayloadBid.ts +6 -0
  106. package/src/chain/errors/executionPayloadEnvelope.ts +8 -0
  107. package/src/chain/prepareNextSlot.ts +347 -89
  108. package/src/chain/produceBlock/produceBlockBody.ts +25 -16
  109. package/src/chain/validation/executionPayloadBid.ts +20 -2
  110. package/src/chain/validation/executionPayloadEnvelope.ts +28 -5
  111. package/src/chain/validation/voluntaryExit.ts +44 -6
  112. package/src/execution/engine/blockHash.ts +27 -0
  113. package/src/execution/engine/mock.ts +13 -8
  114. package/src/execution/engine/payloadIdCache.ts +12 -4
  115. package/src/metrics/metrics/beacon.ts +9 -0
  116. package/src/metrics/metrics/lodestar.ts +5 -0
  117. package/src/network/core/events.ts +12 -0
  118. package/src/network/core/networkCoreWorkerHandler.ts +6 -2
  119. package/src/network/reqresp/handlers/dataColumnSidecarsByRange.ts +1 -1
  120. package/src/network/reqresp/handlers/dataColumnSidecarsByRoot.ts +1 -1
  121. package/src/sync/range/batch.ts +13 -0
  122. package/src/sync/range/chain.ts +64 -17
  123. package/src/sync/range/range.ts +1 -0
  124. package/src/sync/range/utils/batches.ts +38 -13
  125. package/src/sync/range/utils/peerBalancer.ts +4 -1
  126. package/src/sync/types.ts +2 -0
  127. package/src/sync/unknownBlock.ts +65 -21
  128. package/src/sync/utils/downloadByRange.ts +60 -26
  129. package/src/util/asyncIterableToEvents.ts +100 -21
  130. package/src/util/dataColumns.ts +4 -1
@@ -326,7 +326,7 @@ export async function produceBlockBody<T extends BlockType>(
326
326
  feeRecipient
327
327
  );
328
328
 
329
- const {prepType, payloadId} = prepareRes;
329
+ const {prepType, payloadId, preparedAtMs} = prepareRes;
330
330
  Object.assign(logMeta, {executionPayloadPrepType: prepType});
331
331
 
332
332
  this.logger.verbose("Prepared execution payload from engine", {
@@ -339,9 +339,7 @@ export async function produceBlockBody<T extends BlockType>(
339
339
  isBuildingOnFull,
340
340
  });
341
341
 
342
- if (prepType !== PayloadPreparationType.Cached) {
343
- await sleep(PAYLOAD_GENERATION_TIME_MS);
344
- }
342
+ await waitForPayloadGeneration(preparedAtMs);
345
343
 
346
344
  this.logger.verbose("Fetching execution payload from engine", {slot: blockSlot, payloadId});
347
345
  const payloadRes = await this.executionEngine.getPayload(fork, payloadId);
@@ -591,17 +589,10 @@ export async function produceBlockBody<T extends BlockType>(
591
589
  feeRecipient
592
590
  );
593
591
 
594
- const {prepType, payloadId} = prepareRes;
592
+ const {prepType, payloadId, preparedAtMs} = prepareRes;
595
593
  Object.assign(logMeta, {executionPayloadPrepType: prepType});
596
594
 
597
- if (prepType !== PayloadPreparationType.Cached) {
598
- // Wait for 500ms to allow EL to add some txs to the payload
599
- // the pitfalls of this have been put forward here, but 500ms delay for block proposal
600
- // seems marginal even with unhealthy network
601
- //
602
- // See: https://discord.com/channels/595666850260713488/892088344438255616/1009882079632314469
603
- await sleep(PAYLOAD_GENERATION_TIME_MS);
604
- }
595
+ await waitForPayloadGeneration(preparedAtMs);
605
596
 
606
597
  this.logger.verbose("Fetching execution payload from engine", {slot: blockSlot, payloadId});
607
598
  const payloadRes = await this.executionEngine.getPayload(fork, payloadId);
@@ -763,7 +754,7 @@ export async function prepareExecutionPayload(
763
754
  suggestedFeeRecipient: string,
764
755
  /** Attributes already computed for the same state and fee recipient, e.g. for the SSE event */
765
756
  payloadAttributes?: PayloadAttributes
766
- ): Promise<{prepType: PayloadPreparationType; payloadId: PayloadId}> {
757
+ ): Promise<{prepType: PayloadPreparationType; payloadId: PayloadId; preparedAtMs: number}> {
767
758
  const timestamp = computeTimeAtSlot(chain.config, state.slot, state.genesisTime);
768
759
  const prevRandao = state.getRandaoMix(state.epoch);
769
760
 
@@ -792,10 +783,11 @@ export async function prepareExecutionPayload(
792
783
  // the EL returns Syncing on this request to prepare a payload
793
784
  // TODO: Handle only this case, DO NOT put a generic try / catch that discards all errors
794
785
  let payloadId: PayloadId | null;
786
+ let preparedAtMs: number;
795
787
  let prepType: PayloadPreparationType;
796
788
 
797
789
  if (payloadIdCached) {
798
- payloadId = payloadIdCached;
790
+ ({payloadId, preparedAtMs} = payloadIdCached);
799
791
  prepType = PayloadPreparationType.Cached;
800
792
  } else {
801
793
  // If there was a payload assigned to this timestamp, it would imply that there some sort
@@ -821,6 +813,7 @@ export async function prepareExecutionPayload(
821
813
  feeRecipient: suggestedFeeRecipient,
822
814
  })
823
815
  );
816
+ preparedAtMs = performance.now();
824
817
  logger.verbose("Prepared payload id from execution engine", {payloadId});
825
818
  }
826
819
 
@@ -833,7 +826,23 @@ export async function prepareExecutionPayload(
833
826
  // We are only returning payloadId here because prepareExecutionPayload is also called from
834
827
  // prepareNextSlot, which is an advance call to execution engine to start building payload
835
828
  // Actual payload isn't produced till getPayload is called.
836
- return {payloadId, prepType};
829
+ return {payloadId, prepType, preparedAtMs};
830
+ }
831
+
832
+ /**
833
+ * Give the engine PAYLOAD_GENERATION_TIME_MS since the payload was requested before fetching it. A payload prepared
834
+ * in advance usually had seconds, one prepared or re-prepared right before the slot gets the same time as a fresh one.
835
+ *
836
+ * The pitfalls of this delay have been put forward here, but 500ms delay for block proposal
837
+ * seems marginal even with unhealthy network
838
+ *
839
+ * See: https://discord.com/channels/595666850260713488/892088344438255616/1009882079632314469
840
+ */
841
+ async function waitForPayloadGeneration(preparedAtMs: number): Promise<void> {
842
+ const remainingMs = PAYLOAD_GENERATION_TIME_MS - (performance.now() - preparedAtMs);
843
+ if (remainingMs > 0) {
844
+ await sleep(remainingMs);
845
+ }
837
846
  }
838
847
 
839
848
  async function prepareExecutionPayloadHeader(
@@ -19,8 +19,9 @@ import {RegenCaller} from "../regen/index.js";
19
19
  /**
20
20
  * Check whether a bid builds on one of the paths compatible with the local head branch.
21
21
  *
22
- * Building directly on the parent is allowed for proposer-boost reorgs, including at epoch
23
- * boundaries when the head is weak enough that a reorg onto the strong parent is predicted.
22
+ * Building directly on the parent is allowed for the slot after the head if the head was late or
23
+ * its proposer equivocated, the conditions under which a proposer may re-org the head. At epoch
24
+ * boundaries the parent must also be the predicted proposer head.
24
25
  * Otherwise the bid must build on the local head's full or empty payload variant, as selected for its slot.
25
26
  */
26
27
  function isBidCompatibleWithHead(
@@ -34,6 +35,11 @@ function isBidCompatibleWithHead(
34
35
  const buildsOnParentPayload = bidParentBlockHash === head.parentBlockHash;
35
36
 
36
37
  if (buildsOnParentBlock && buildsOnParentPayload) {
38
+ const bidSlotOk = head.slot + 1 === bidSlot;
39
+ const headLate = !head.timeliness;
40
+ if (!bidSlotOk || !(headLate || chain.forkChoice.isProposerEquivocation(head))) {
41
+ return false;
42
+ }
37
43
  if (!isStartSlotOfEpoch(bidSlot)) {
38
44
  return true;
39
45
  }
@@ -114,6 +120,18 @@ async function validateExecutionPayloadBid(
114
120
  });
115
121
  }
116
122
 
123
+ // [IGNORE] The bid is received after the payload attestation deadline of `bid.slot - 1`
124
+ if (
125
+ chain.clock.msFromSlot(bid.slot - 1) <
126
+ chain.config.getPayloadAttestationDueMs(chain.config.getForkName(bid.slot - 1))
127
+ ) {
128
+ throw new ExecutionPayloadBidError(GossipAction.IGNORE, {
129
+ code: ExecutionPayloadBidErrorCode.BEFORE_PAYLOAD_ATTESTATION_DEADLINE,
130
+ builderIndex: bid.builderIndex,
131
+ slot: bid.slot,
132
+ });
133
+ }
134
+
117
135
  // [IGNORE] The bid is received after the inclusion list deadline of `bid.slot - 1`
118
136
  if (
119
137
  isForkPostHeze(chain.config.getForkName(bid.slot)) &&
@@ -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",
@@ -5,6 +5,7 @@ import {
5
5
  IteratorEvent,
6
6
  RequestCancelEvent,
7
7
  RequestEvent,
8
+ ResponsePullEvent,
8
9
  } from "../../util/asyncIterableToEvents.js";
9
10
  import {StrictEventEmitterSingleArg} from "../../util/strictEvents.js";
10
11
  import {EventDirection} from "../events.js";
@@ -14,18 +15,22 @@ export enum ReqRespBridgeEvent {
14
15
  outgoingRequest = "reqresp.outgoingRequest",
15
16
  outgoingRequestCancel = "reqresp.outgoingRequestCancel",
16
17
  outgoingResponse = "reqresp.outgoingResponse",
18
+ outgoingResponsePull = "reqresp.outgoingResponsePull",
17
19
  incomingRequest = "reqresp.incomingRequest",
18
20
  incomingRequestCancel = "reqresp.incomingRequestCancel",
19
21
  incomingResponse = "reqresp.incomingResponse",
22
+ incomingResponsePull = "reqresp.incomingResponsePull",
20
23
  }
21
24
 
22
25
  export type ReqRespBridgeEventData = {
23
26
  [ReqRespBridgeEvent.outgoingRequest]: RequestEvent<OutgoingRequestArgs>;
24
27
  [ReqRespBridgeEvent.outgoingRequestCancel]: RequestCancelEvent;
25
28
  [ReqRespBridgeEvent.outgoingResponse]: IteratorEvent<ResponseOutgoing>;
29
+ [ReqRespBridgeEvent.outgoingResponsePull]: ResponsePullEvent;
26
30
  [ReqRespBridgeEvent.incomingRequest]: RequestEvent<IncomingRequestArgs>;
27
31
  [ReqRespBridgeEvent.incomingRequestCancel]: RequestCancelEvent;
28
32
  [ReqRespBridgeEvent.incomingResponse]: IteratorEvent<ResponseIncoming>;
33
+ [ReqRespBridgeEvent.incomingResponsePull]: ResponsePullEvent;
29
34
  };
30
35
 
31
36
  type IReqRespBridgeEventBus = StrictEventEmitterSingleArg<ReqRespBridgeEventData>;
@@ -37,9 +42,12 @@ export const reqRespBridgeEventDirection: Record<ReqRespBridgeEvent, EventDirect
37
42
  [ReqRespBridgeEvent.outgoingRequest]: EventDirection.mainToWorker,
38
43
  [ReqRespBridgeEvent.outgoingRequestCancel]: EventDirection.mainToWorker,
39
44
  [ReqRespBridgeEvent.outgoingResponse]: EventDirection.mainToWorker,
45
+ // Credit flows from the consumer back to the producer, opposite the response it paces
46
+ [ReqRespBridgeEvent.outgoingResponsePull]: EventDirection.workerToMain,
40
47
  [ReqRespBridgeEvent.incomingRequest]: EventDirection.workerToMain,
41
48
  [ReqRespBridgeEvent.incomingRequestCancel]: EventDirection.workerToMain,
42
49
  [ReqRespBridgeEvent.incomingResponse]: EventDirection.workerToMain,
50
+ [ReqRespBridgeEvent.incomingResponsePull]: EventDirection.mainToWorker,
43
51
  };
44
52
 
45
53
  export function getReqRespBridgeReqEvents(
@@ -49,9 +57,11 @@ export function getReqRespBridgeReqEvents(
49
57
  emitRequest: (data) => events.emit(ReqRespBridgeEvent.outgoingRequest, data),
50
58
  emitRequestCancel: (data) => events.emit(ReqRespBridgeEvent.outgoingRequestCancel, data),
51
59
  emitResponse: (data) => events.emit(ReqRespBridgeEvent.incomingResponse, data),
60
+ emitResponsePull: (data) => events.emit(ReqRespBridgeEvent.incomingResponsePull, data),
52
61
  onRequest: (cb) => events.on(ReqRespBridgeEvent.outgoingRequest, cb),
53
62
  onRequestCancel: (cb) => events.on(ReqRespBridgeEvent.outgoingRequestCancel, cb),
54
63
  onResponse: (cb) => events.on(ReqRespBridgeEvent.incomingResponse, cb),
64
+ onResponsePull: (cb) => events.on(ReqRespBridgeEvent.incomingResponsePull, cb),
55
65
  };
56
66
  }
57
67
 
@@ -62,9 +72,11 @@ export function getReqRespBridgeRespEvents(
62
72
  emitRequest: (data) => events.emit(ReqRespBridgeEvent.incomingRequest, data),
63
73
  emitRequestCancel: (data) => events.emit(ReqRespBridgeEvent.incomingRequestCancel, data),
64
74
  emitResponse: (data) => events.emit(ReqRespBridgeEvent.outgoingResponse, data),
75
+ emitResponsePull: (data) => events.emit(ReqRespBridgeEvent.outgoingResponsePull, data),
65
76
  onRequest: (cb) => events.on(ReqRespBridgeEvent.incomingRequest, cb),
66
77
  onRequestCancel: (cb) => events.on(ReqRespBridgeEvent.incomingRequestCancel, cb),
67
78
  onResponse: (cb) => events.on(ReqRespBridgeEvent.outgoingResponse, cb),
79
+ onResponsePull: (cb) => events.on(ReqRespBridgeEvent.outgoingResponsePull, cb),
68
80
  };
69
81
  }
70
82
 
@@ -74,8 +74,12 @@ export class WorkerNetworkCore implements INetworkCore {
74
74
  private readonly reqRespBridgeEventBus = new ReqRespBridgeEventBus();
75
75
 
76
76
  constructor(private readonly modules: WorkerNetworkCoreModules) {
77
- // Get called from main thread to issue a ReqResp request, and emits event to worker
78
- this.reqRespBridgeReqCaller = new AsyncIterableBridgeCaller(getReqRespBridgeReqEvents(this.reqRespBridgeEventBus));
77
+ // Get called from main thread to issue a ReqResp request, and emits event to worker. Unbounded: we
78
+ // buffer the whole response into an array anyway, so pacing the worker only risks a read buffer overflow
79
+ this.reqRespBridgeReqCaller = new AsyncIterableBridgeCaller(
80
+ getReqRespBridgeReqEvents(this.reqRespBridgeEventBus),
81
+ Infinity
82
+ );
79
83
  // Handles ReqResp response from worker and calls async generator in main thread
80
84
  this.reqRespBridgeRespHandler = new AsyncIterableBridgeHandler(
81
85
  getReqRespBridgeRespEvents(this.reqRespBridgeEventBus),
@@ -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