@lodestar/beacon-node 1.47.0-dev.9572bcc698 → 1.47.0-dev.9ba9a5ce85

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 (148) hide show
  1. package/lib/api/impl/beacon/blocks/index.d.ts.map +1 -1
  2. package/lib/api/impl/beacon/blocks/index.js +41 -10
  3. package/lib/api/impl/beacon/blocks/index.js.map +1 -1
  4. package/lib/api/impl/lodestar/index.js +1 -1
  5. package/lib/api/impl/lodestar/index.js.map +1 -1
  6. package/lib/api/impl/validator/index.d.ts.map +1 -1
  7. package/lib/api/impl/validator/index.js +237 -49
  8. package/lib/api/impl/validator/index.js.map +1 -1
  9. package/lib/api/impl/validator/utils.js +1 -1
  10. package/lib/api/impl/validator/utils.js.map +1 -1
  11. package/lib/chain/archiveStore/archiveStore.js +1 -1
  12. package/lib/chain/archiveStore/archiveStore.js.map +1 -1
  13. package/lib/chain/blocks/index.js +7 -7
  14. package/lib/chain/blocks/index.js.map +1 -1
  15. package/lib/chain/blocks/verifyBlock.d.ts.map +1 -1
  16. package/lib/chain/blocks/verifyBlock.js +5 -2
  17. package/lib/chain/blocks/verifyBlock.js.map +1 -1
  18. package/lib/chain/chain.d.ts +5 -2
  19. package/lib/chain/chain.d.ts.map +1 -1
  20. package/lib/chain/chain.js +6 -2
  21. package/lib/chain/chain.js.map +1 -1
  22. package/lib/chain/errors/executionPayloadBid.d.ts +5 -0
  23. package/lib/chain/errors/executionPayloadBid.d.ts.map +1 -1
  24. package/lib/chain/errors/executionPayloadBid.js +1 -0
  25. package/lib/chain/errors/executionPayloadBid.js.map +1 -1
  26. package/lib/chain/forkChoice/index.d.ts.map +1 -1
  27. package/lib/chain/forkChoice/index.js +4 -0
  28. package/lib/chain/forkChoice/index.js.map +1 -1
  29. package/lib/chain/interface.d.ts +4 -2
  30. package/lib/chain/interface.d.ts.map +1 -1
  31. package/lib/chain/interface.js.map +1 -1
  32. package/lib/chain/opPools/executionPayloadBidPool.d.ts +7 -2
  33. package/lib/chain/opPools/executionPayloadBidPool.d.ts.map +1 -1
  34. package/lib/chain/opPools/executionPayloadBidPool.js +4 -4
  35. package/lib/chain/opPools/executionPayloadBidPool.js.map +1 -1
  36. package/lib/chain/opPools/index.d.ts +1 -1
  37. package/lib/chain/opPools/index.d.ts.map +1 -1
  38. package/lib/chain/opPools/index.js.map +1 -1
  39. package/lib/chain/prepareNextSlot.d.ts +5 -0
  40. package/lib/chain/prepareNextSlot.d.ts.map +1 -1
  41. package/lib/chain/prepareNextSlot.js +47 -6
  42. package/lib/chain/prepareNextSlot.js.map +1 -1
  43. package/lib/chain/produceBlock/computeNewStateRoot.d.ts.map +1 -1
  44. package/lib/chain/produceBlock/computeNewStateRoot.js +3 -25
  45. package/lib/chain/produceBlock/computeNewStateRoot.js.map +1 -1
  46. package/lib/chain/produceBlock/produceBlockBody.js +1 -1
  47. package/lib/chain/produceBlock/produceBlockBody.js.map +1 -1
  48. package/lib/chain/regen/interface.d.ts +3 -2
  49. package/lib/chain/regen/interface.d.ts.map +1 -1
  50. package/lib/chain/regen/interface.js +1 -0
  51. package/lib/chain/regen/interface.js.map +1 -1
  52. package/lib/chain/regen/queued.d.ts +2 -2
  53. package/lib/chain/regen/queued.d.ts.map +1 -1
  54. package/lib/chain/regen/queued.js +5 -5
  55. package/lib/chain/regen/queued.js.map +1 -1
  56. package/lib/chain/stateCache/fifoBlockStateCache.d.ts +5 -1
  57. package/lib/chain/stateCache/fifoBlockStateCache.d.ts.map +1 -1
  58. package/lib/chain/stateCache/fifoBlockStateCache.js +6 -0
  59. package/lib/chain/stateCache/fifoBlockStateCache.js.map +1 -1
  60. package/lib/chain/stateCache/persistentCheckpointsCache.d.ts +47 -5
  61. package/lib/chain/stateCache/persistentCheckpointsCache.d.ts.map +1 -1
  62. package/lib/chain/stateCache/persistentCheckpointsCache.js +117 -7
  63. package/lib/chain/stateCache/persistentCheckpointsCache.js.map +1 -1
  64. package/lib/chain/stateCache/types.d.ts +3 -3
  65. package/lib/chain/stateCache/types.d.ts.map +1 -1
  66. package/lib/chain/validation/block.d.ts.map +1 -1
  67. package/lib/chain/validation/block.js +40 -10
  68. package/lib/chain/validation/block.js.map +1 -1
  69. package/lib/chain/validation/executionPayloadBid.d.ts +15 -3
  70. package/lib/chain/validation/executionPayloadBid.d.ts.map +1 -1
  71. package/lib/chain/validation/executionPayloadBid.js +165 -10
  72. package/lib/chain/validation/executionPayloadBid.js.map +1 -1
  73. package/lib/execution/builder/apiClient.d.ts +70 -0
  74. package/lib/execution/builder/apiClient.d.ts.map +1 -0
  75. package/lib/execution/builder/apiClient.js +202 -0
  76. package/lib/execution/builder/apiClient.js.map +1 -0
  77. package/lib/execution/builder/validateBid.d.ts +23 -0
  78. package/lib/execution/builder/validateBid.d.ts.map +1 -0
  79. package/lib/execution/builder/validateBid.js +119 -0
  80. package/lib/execution/builder/validateBid.js.map +1 -0
  81. package/lib/metrics/metrics/lodestar.d.ts +29 -1
  82. package/lib/metrics/metrics/lodestar.d.ts.map +1 -1
  83. package/lib/metrics/metrics/lodestar.js +61 -3
  84. package/lib/metrics/metrics/lodestar.js.map +1 -1
  85. package/lib/network/network.d.ts.map +1 -1
  86. package/lib/network/network.js +5 -4
  87. package/lib/network/network.js.map +1 -1
  88. package/lib/network/processor/constants.d.ts +7 -0
  89. package/lib/network/processor/constants.d.ts.map +1 -0
  90. package/lib/network/processor/constants.js +7 -0
  91. package/lib/network/processor/constants.js.map +1 -0
  92. package/lib/network/processor/gossipHandlers.js +1 -1
  93. package/lib/network/processor/gossipHandlers.js.map +1 -1
  94. package/lib/network/processor/gossipQueues/indexed.d.ts.map +1 -1
  95. package/lib/network/processor/gossipQueues/indexed.js +0 -1
  96. package/lib/network/processor/gossipQueues/indexed.js.map +1 -1
  97. package/lib/network/processor/index.d.ts +3 -0
  98. package/lib/network/processor/index.d.ts.map +1 -1
  99. package/lib/network/processor/index.js +52 -23
  100. package/lib/network/processor/index.js.map +1 -1
  101. package/lib/node/nodejs.d.ts.map +1 -1
  102. package/lib/node/nodejs.js +5 -0
  103. package/lib/node/nodejs.js.map +1 -1
  104. package/lib/sync/range/chain.d.ts.map +1 -1
  105. package/lib/sync/range/chain.js +9 -2
  106. package/lib/sync/range/chain.js.map +1 -1
  107. package/lib/sync/range/range.js +1 -1
  108. package/lib/sync/range/range.js.map +1 -1
  109. package/lib/sync/unknownBlock.d.ts +6 -2
  110. package/lib/sync/unknownBlock.d.ts.map +1 -1
  111. package/lib/sync/unknownBlock.js +48 -17
  112. package/lib/sync/unknownBlock.js.map +1 -1
  113. package/package.json +15 -15
  114. package/src/api/impl/beacon/blocks/index.ts +48 -13
  115. package/src/api/impl/lodestar/index.ts +1 -1
  116. package/src/api/impl/validator/index.ts +290 -49
  117. package/src/api/impl/validator/utils.ts +1 -1
  118. package/src/chain/archiveStore/archiveStore.ts +1 -1
  119. package/src/chain/blocks/index.ts +7 -7
  120. package/src/chain/blocks/verifyBlock.ts +5 -2
  121. package/src/chain/chain.ts +8 -1
  122. package/src/chain/errors/executionPayloadBid.ts +6 -0
  123. package/src/chain/forkChoice/index.ts +4 -0
  124. package/src/chain/interface.ts +4 -2
  125. package/src/chain/opPools/executionPayloadBidPool.ts +13 -7
  126. package/src/chain/opPools/index.ts +1 -1
  127. package/src/chain/prepareNextSlot.ts +49 -6
  128. package/src/chain/produceBlock/computeNewStateRoot.ts +3 -38
  129. package/src/chain/produceBlock/produceBlockBody.ts +1 -1
  130. package/src/chain/regen/interface.ts +3 -2
  131. package/src/chain/regen/queued.ts +5 -5
  132. package/src/chain/stateCache/fifoBlockStateCache.ts +8 -1
  133. package/src/chain/stateCache/persistentCheckpointsCache.ts +133 -8
  134. package/src/chain/stateCache/types.ts +3 -3
  135. package/src/chain/validation/block.ts +43 -10
  136. package/src/chain/validation/executionPayloadBid.ts +192 -12
  137. package/src/execution/builder/apiClient.ts +264 -0
  138. package/src/execution/builder/validateBid.ts +181 -0
  139. package/src/metrics/metrics/lodestar.ts +64 -4
  140. package/src/network/network.ts +7 -4
  141. package/src/network/processor/constants.ts +6 -0
  142. package/src/network/processor/gossipHandlers.ts +1 -1
  143. package/src/network/processor/gossipQueues/indexed.ts +0 -1
  144. package/src/network/processor/index.ts +67 -30
  145. package/src/node/nodejs.ts +5 -0
  146. package/src/sync/range/chain.ts +9 -2
  147. package/src/sync/range/range.ts +1 -1
  148. package/src/sync/unknownBlock.ts +62 -18
@@ -1,4 +1,4 @@
1
- import {IForkChoice, ProtoBlock} from "@lodestar/fork-choice";
1
+ import {ProtoBlock} from "@lodestar/fork-choice";
2
2
  import {PAYLOAD_BUILDER_VERSION} from "@lodestar/params";
3
3
  import {
4
4
  computeEpochAtSlot,
@@ -46,11 +46,12 @@ function getMinBidValue(currentHighestBid: number): number {
46
46
  /**
47
47
  * Check whether a bid builds on one of the paths compatible with the local head branch.
48
48
  *
49
- * Building directly on the parent is allowed for proposer-boost reorgs outside epoch boundaries.
49
+ * Building directly on the parent is allowed for proposer-boost reorgs, including at epoch
50
+ * boundaries when the head is weak enough that a reorg onto the strong parent is predicted.
50
51
  * Otherwise the bid must build on the local head's full or empty payload variant, as selected for its slot.
51
52
  */
52
53
  function isBidCompatibleWithHead(
53
- forkChoice: IForkChoice,
54
+ chain: IBeaconChain,
54
55
  head: ProtoBlock,
55
56
  bidSlot: Slot,
56
57
  bidParentBlockRoot: RootHex,
@@ -60,9 +61,13 @@ function isBidCompatibleWithHead(
60
61
  const buildsOnParentPayload = bidParentBlockHash === head.parentBlockHash;
61
62
 
62
63
  if (buildsOnParentBlock && buildsOnParentPayload) {
63
- // The spec allows this at epoch boundaries, but Lodestar does not propagate these bids because validating
64
- // them requires an epoch transition for a parent state that cannot be used for proposer-boost reorgs.
65
- return !isStartSlotOfEpoch(bidSlot);
64
+ if (!isStartSlotOfEpoch(bidSlot)) {
65
+ return true;
66
+ }
67
+ // Epoch-boundary reorgs are allowed, but only propagate the bid if its parent matches the block
68
+ // we predict a proposer would reorg onto — predictProposerHead returns the strong parent only
69
+ // when the head is weak.
70
+ return chain.predictProposerHead().blockRoot === bidParentBlockRoot;
66
71
  }
67
72
 
68
73
  if (bidParentBlockRoot !== head.blockRoot) {
@@ -71,18 +76,170 @@ function isBidCompatibleWithHead(
71
76
 
72
77
  const buildsOnHeadPayload = bidParentBlockHash === head.executionPayloadBlockHash;
73
78
 
74
- if (forkChoice.shouldBuildOnFull(head, bidSlot)) {
79
+ if (chain.forkChoice.shouldBuildOnFull(head, bidSlot)) {
75
80
  return buildsOnHeadPayload;
76
81
  }
77
82
 
78
83
  return buildsOnParentPayload;
79
84
  }
80
85
 
86
+ /**
87
+ * Validation for bids submitted via the API by the operator's own builder.
88
+ *
89
+ * Only non-transient checks are applied: slot later than parent, zero execution payment, blob
90
+ * commitment count, builder eligibility, version and balance coverage, prev_randao, and signature.
91
+ * Transient gossip rules (head compatibility, first bid per tuple, value increment, proposer
92
+ * preferences) are not applied, since those only limit forwarding of peers' messages and the
93
+ * builder may legitimately bid on a branch this node does not consider head.
94
+ * The parent-payload builder-exit rule is omitted because this endpoint only accepts bids from
95
+ * the operator's own builder.
96
+ *
97
+ * Throws on any failed check. Also throws if the bid's parent block is unknown or its state is
98
+ * unavailable, since the checks cannot be evaluated against the parent branch.
99
+ */
81
100
  export async function validateApiExecutionPayloadBid(
82
101
  chain: IBeaconChain,
83
102
  signedExecutionPayloadBid: gloas.SignedExecutionPayloadBid
84
- ): Promise<{proposerIndex: ValidatorIndex}> {
85
- return validateExecutionPayloadBid(chain, signedExecutionPayloadBid);
103
+ ): Promise<void> {
104
+ const bid = signedExecutionPayloadBid.message;
105
+ const bidParentBlockRoot = toRootHex(bid.parentBlockRoot);
106
+
107
+ // [IGNORE] `bid.slot` is the current slot, or the next slot (`bid.slot - 1` is current), allowing for `MAXIMUM_GOSSIP_CLOCK_DISPARITY`.
108
+ if (
109
+ !chain.clock.isCurrentSlotGivenGossipDisparity(bid.slot) &&
110
+ !chain.clock.isCurrentSlotGivenGossipDisparity(bid.slot - 1)
111
+ ) {
112
+ throw new ExecutionPayloadBidError(GossipAction.IGNORE, {
113
+ code: ExecutionPayloadBidErrorCode.INVALID_SLOT,
114
+ builderIndex: bid.builderIndex,
115
+ slot: bid.slot,
116
+ });
117
+ }
118
+
119
+ // [IGNORE] `bid.parent_block_root` is the hash tree root of a known beacon block in fork choice.
120
+ // Moved earlier than the spec ordering so we can derive the proposer dependent root for the
121
+ // proposer-preferences lookup below from a known fork-choice block.
122
+ const parentBlock = chain.forkChoice.getBlockHexDefaultStatus(bidParentBlockRoot);
123
+ if (parentBlock === null) {
124
+ throw new ExecutionPayloadBidError(GossipAction.IGNORE, {
125
+ code: ExecutionPayloadBidErrorCode.UNKNOWN_BLOCK_ROOT,
126
+ parentBlockRoot: bidParentBlockRoot,
127
+ });
128
+ }
129
+
130
+ // [REJECT] The bid is for a higher slot than its parent block -- i.e.
131
+ // validate that `bid.slot` is greater than the slot of the block with root
132
+ // `bid.parent_block_root`.
133
+ if (bid.slot <= parentBlock.slot) {
134
+ throw new ExecutionPayloadBidError(GossipAction.REJECT, {
135
+ code: ExecutionPayloadBidErrorCode.NOT_LATER_THAN_PARENT,
136
+ parentSlot: parentBlock.slot,
137
+ slot: bid.slot,
138
+ });
139
+ }
140
+
141
+ // [REJECT] `bid.execution_payment` is zero.
142
+ if (bid.executionPayment !== 0n) {
143
+ throw new ExecutionPayloadBidError(GossipAction.REJECT, {
144
+ code: ExecutionPayloadBidErrorCode.NON_ZERO_EXECUTION_PAYMENT,
145
+ builderIndex: bid.builderIndex,
146
+ executionPayment: bid.executionPayment,
147
+ });
148
+ }
149
+
150
+ // [REJECT] The length of KZG commitments is less than or equal to the limitation defined in the
151
+ // consensus layer -- i.e. validate that
152
+ // `len(bid.blob_kzg_commitments) <= get_blob_parameters(compute_epoch_at_slot(bid.slot)).max_blobs_per_block`.
153
+ const blobKzgCommitmentsLen = bid.blobKzgCommitments.length;
154
+ const maxBlobsPerBlock = chain.config.getMaxBlobsPerBlock(computeEpochAtSlot(bid.slot));
155
+ if (blobKzgCommitmentsLen > maxBlobsPerBlock) {
156
+ throw new ExecutionPayloadBidError(GossipAction.REJECT, {
157
+ code: ExecutionPayloadBidErrorCode.TOO_MANY_KZG_COMMITMENTS,
158
+ blobKzgCommitmentsLen,
159
+ commitmentLimit: maxBlobsPerBlock,
160
+ });
161
+ }
162
+
163
+ const state = await chain.regen
164
+ .getBlockSlotState(parentBlock, bid.slot, {dontTransferCache: true}, RegenCaller.validateApiExecutionPayloadBid)
165
+ .catch(() => {
166
+ throw new ExecutionPayloadBidError(GossipAction.IGNORE, {
167
+ code: ExecutionPayloadBidErrorCode.UNKNOWN_BLOCK_ROOT,
168
+ parentBlockRoot: bidParentBlockRoot,
169
+ });
170
+ });
171
+
172
+ if (!isStatePostGloas(state)) {
173
+ throw new Error(`Expected gloas+ state for execution payload bid validation, got fork=${state.forkName}`);
174
+ }
175
+
176
+ // [REJECT] `bid.builder_index` is within bounds -- i.e. `bid.builder_index < len(state.builders)`.
177
+ // `state.getBuilder` returns a lazy SSZ `getReadonly` view that is not bounds-checked eagerly; an
178
+ // out-of-range index only throws (`LeafNode has no right node`) on deferred field access (e.g. inside
179
+ // `isActiveBuilder`), escaping a try/catch around `getBuilder`. Check the length explicitly instead.
180
+ if (bid.builderIndex >= state.getBuildersLength()) {
181
+ throw new ExecutionPayloadBidError(GossipAction.REJECT, {
182
+ code: ExecutionPayloadBidErrorCode.BUILDER_NOT_ELIGIBLE,
183
+ builderIndex: bid.builderIndex,
184
+ });
185
+ }
186
+
187
+ // [REJECT] `bid.builder_index` is a valid/active builder index -- i.e.
188
+ // `is_active_builder(state, bid.builder_index)` returns `True`.
189
+ const builder = state.getBuilder(bid.builderIndex);
190
+ if (!isActiveBuilder(builder, state.finalizedCheckpoint.epoch)) {
191
+ throw new ExecutionPayloadBidError(GossipAction.REJECT, {
192
+ code: ExecutionPayloadBidErrorCode.BUILDER_NOT_ELIGIBLE,
193
+ builderIndex: bid.builderIndex,
194
+ });
195
+ }
196
+
197
+ // [REJECT] The builder version is `PAYLOAD_BUILDER_VERSION` -- i.e.
198
+ // `state.builders[bid.builder_index].version == PAYLOAD_BUILDER_VERSION`.
199
+ if (builder.version !== PAYLOAD_BUILDER_VERSION) {
200
+ throw new ExecutionPayloadBidError(GossipAction.REJECT, {
201
+ code: ExecutionPayloadBidErrorCode.INVALID_BUILDER_VERSION,
202
+ builderIndex: bid.builderIndex,
203
+ version: builder.version,
204
+ expectedVersion: PAYLOAD_BUILDER_VERSION,
205
+ });
206
+ }
207
+
208
+ // [IGNORE] `bid.value` is less or equal than the builder's excess balance --
209
+ // i.e. `can_builder_cover_bid(state, builder_index, amount)` returns `True`.
210
+ if (!state.canBuilderCoverBid(bid.builderIndex, bid.value)) {
211
+ throw new ExecutionPayloadBidError(GossipAction.IGNORE, {
212
+ code: ExecutionPayloadBidErrorCode.BID_TOO_HIGH,
213
+ bidValue: bid.value,
214
+ builderBalance: builder.balance,
215
+ });
216
+ }
217
+
218
+ // [REJECT] `bid.prev_randao` is the correct RANDAO mix -- i.e. validate that
219
+ // `bid.prev_randao == get_randao_mix(parent_state, get_current_epoch(parent_state))`.
220
+ const randaoMix = state.getRandaoMix(computeEpochAtSlot(state.slot));
221
+ if (!byteArrayEquals(bid.prevRandao, randaoMix)) {
222
+ throw new ExecutionPayloadBidError(GossipAction.REJECT, {
223
+ code: ExecutionPayloadBidErrorCode.INVALID_PREV_RANDAO,
224
+ builderIndex: bid.builderIndex,
225
+ bidPrevRandao: toHex(bid.prevRandao),
226
+ expectedPrevRandao: toHex(randaoMix),
227
+ });
228
+ }
229
+
230
+ // [REJECT] `signed_execution_payload_bid.signature` is valid with respect to the `bid.builder_index`.
231
+ const signatureSet = createSingleSignatureSetFromComponents(
232
+ builder.pubkey,
233
+ getExecutionPayloadBidSigningRoot(chain.config, bid),
234
+ signedExecutionPayloadBid.signature
235
+ );
236
+ if (!(await chain.bls.verifySignatureSets([signatureSet]))) {
237
+ throw new ExecutionPayloadBidError(GossipAction.REJECT, {
238
+ code: ExecutionPayloadBidErrorCode.INVALID_SIGNATURE,
239
+ builderIndex: bid.builderIndex,
240
+ slot: bid.slot,
241
+ });
242
+ }
86
243
  }
87
244
 
88
245
  export async function validateGossipExecutionPayloadBid(
@@ -114,7 +271,7 @@ async function validateExecutionPayloadBid(
114
271
 
115
272
  // [IGNORE] The bid is compatible with the current head branch.
116
273
  const head = chain.forkChoice.getHead();
117
- if (!isBidCompatibleWithHead(chain.forkChoice, head, bid.slot, bidParentBlockRoot, bidParentBlockHash)) {
274
+ if (!isBidCompatibleWithHead(chain, head, bid.slot, bidParentBlockRoot, bidParentBlockHash)) {
118
275
  throw new ExecutionPayloadBidError(GossipAction.IGNORE, {
119
276
  code: ExecutionPayloadBidErrorCode.INCOMPATIBLE_WITH_HEAD,
120
277
  slot: bid.slot,
@@ -313,11 +470,11 @@ async function validateExecutionPayloadBid(
313
470
  // increment, see https://github.com/ethereum/consensus-specs/pull/4831. This prevents spam
314
471
  // from builders submitting numerous bids with minimal value increments.
315
472
  const bestBid = chain.executionPayloadBidPool.getBestBid(bid.slot, bidParentBlockHash, bidParentBlockRoot);
316
- if (bestBid !== null && bid.value < getMinBidValue(bestBid.message.value)) {
473
+ if (bestBid !== null && bid.value < getMinBidValue(bestBid.signedBid.message.value)) {
317
474
  throw new ExecutionPayloadBidError(GossipAction.IGNORE, {
318
475
  code: ExecutionPayloadBidErrorCode.BID_TOO_LOW,
319
476
  bidValue: bid.value,
320
- currentHighestBid: bestBid.message.value,
477
+ currentHighestBid: bestBid.signedBid.message.value,
321
478
  });
322
479
  }
323
480
  // [IGNORE] `bid.value` is less or equal than the builder's excess balance --
@@ -342,6 +499,29 @@ async function validateExecutionPayloadBid(
342
499
  });
343
500
  }
344
501
 
502
+ // [IGNORE] The parent's payload does not try to exit the builder
503
+ if (byteArrayEquals(bid.parentBlockHash, state.latestExecutionPayloadBid.blockHash)) {
504
+ const requests = await chain.getParentExecutionRequests(parentBlock.slot, parentBlock.blockRoot).catch(() => {
505
+ throw new ExecutionPayloadBidError(GossipAction.IGNORE, {
506
+ code: ExecutionPayloadBidErrorCode.UNKNOWN_PARENT_BLOCK_HASH,
507
+ parentBlockHash: bidParentBlockHash,
508
+ });
509
+ });
510
+ if (
511
+ requests.builderExits.some(
512
+ (request) =>
513
+ byteArrayEquals(request.pubkey, builder.pubkey) &&
514
+ byteArrayEquals(request.sourceAddress, builder.executionAddress)
515
+ )
516
+ ) {
517
+ throw new ExecutionPayloadBidError(GossipAction.IGNORE, {
518
+ code: ExecutionPayloadBidErrorCode.BUILDER_MAY_EXIT,
519
+ builderIndex: bid.builderIndex,
520
+ parentBlockRoot: bidParentBlockRoot,
521
+ });
522
+ }
523
+ }
524
+
345
525
  // [REJECT] `signed_execution_payload_bid.signature` is valid with respect to the `bid.builder_index`.
346
526
  const signatureSet = createSingleSignatureSetFromComponents(
347
527
  builder.pubkey,
@@ -0,0 +1,264 @@
1
+ import {routes} from "@lodestar/api";
2
+ import {ApiClient as BuilderApi, getClient} from "@lodestar/api/builder";
3
+ import {ChainForkConfig} from "@lodestar/config";
4
+ import {Logger} from "@lodestar/logger";
5
+ import {DOMAIN_BUILDER_REQUEST_AUTH, ForkPostGloas} from "@lodestar/params";
6
+ import {
7
+ ZERO_HASH,
8
+ computeDomain,
9
+ computeSigningRoot,
10
+ createSingleSignatureSetFromComponents,
11
+ } from "@lodestar/state-transition";
12
+ import {BLSPubkey, Root, SignedBeaconBlock, Slot, WithOptionalBytes, gloas, ssz} from "@lodestar/types";
13
+ import {isValidAsciiHttpUrl, toHex, toPrintableUrl} from "@lodestar/utils";
14
+ import type {IBlsVerifier} from "../../chain/bls/index.js";
15
+ import {Metrics} from "../../metrics/metrics.js";
16
+ import {IClock} from "../../util/clock.js";
17
+
18
+ /**
19
+ * Additional duration to account for potential event loop lag which causes
20
+ * builder bids to be rejected even though the response was sent in time.
21
+ */
22
+ const EVENT_LOOP_LAG_BUFFER = 250;
23
+
24
+ /**
25
+ * Duration given to a builder to provide a `SignedExecutionPayloadBid` before the deadline
26
+ * is reached, advertised on each bid request via the `X-Timeout-Ms` header. The p2p bid is
27
+ * selected after the same duration, only considering bids received up to that point.
28
+ */
29
+ export const BUILDER_BID_DEADLINE_MS = 500;
30
+
31
+ /** Local timeout for bid requests, event loop lag must not discard bids that arrived in time */
32
+ export const BUILDER_BID_REQUEST_TIMEOUT_MS = BUILDER_BID_DEADLINE_MS + EVENT_LOOP_LAG_BUFFER;
33
+
34
+ export type BuilderApiClientOpts = {
35
+ /** Timeout for builder api requests, bid requests always use `BUILDER_BID_REQUEST_TIMEOUT_MS` */
36
+ timeout?: number;
37
+ // Add User-Agent header to all requests
38
+ userAgent?: string;
39
+ };
40
+
41
+ type BuilderUrl = string;
42
+
43
+ /** Decode the SSZ URL bytes without allowing replacement characters or unsafe header values. */
44
+ export function decodeBuilderUrl(value: Uint8Array): BuilderUrl {
45
+ let url: string;
46
+ try {
47
+ url = new TextDecoder("utf8", {fatal: true}).decode(value);
48
+ } catch {
49
+ throw Error("Builder url must be valid UTF-8");
50
+ }
51
+ if (!isValidAsciiHttpUrl(url)) {
52
+ throw Error("Invalid builder url");
53
+ }
54
+ return url;
55
+ }
56
+
57
+ export type BuilderApiBid = {
58
+ url: BuilderUrl;
59
+ entry: routes.validator.BuilderEntry;
60
+ signedBid: gloas.SignedExecutionPayloadBid;
61
+ /** Time in milliseconds from the slot start when the bid was received */
62
+ receivedMs: number;
63
+ };
64
+
65
+ /**
66
+ * External builder integration post-gloas
67
+ *
68
+ * The builder set is driven by the resolved `BuilderConfig` the validator client supplies on
69
+ * each block production request, clients are dialed on demand based on the entry `url`.
70
+ */
71
+ export class BuilderApiClient {
72
+ private readonly clients = new Map<BuilderUrl, BuilderApi>();
73
+
74
+ constructor(
75
+ private readonly opts: BuilderApiClientOpts,
76
+ private readonly config: ChainForkConfig,
77
+ private readonly clock: IClock,
78
+ private readonly bls: IBlsVerifier,
79
+ private readonly metrics: Metrics | null = null,
80
+ private readonly logger?: Logger
81
+ ) {}
82
+
83
+ /**
84
+ * Fan out bid requests to the builders named by the entries, one request per unique
85
+ * `(url, auth.message.data)` pair. Errors and empty responses (204) are logged and filtered
86
+ * out so a single unresponsive builder never fails block production.
87
+ */
88
+ async getExecutionPayloadBids(
89
+ entries: routes.validator.BuilderEntry[],
90
+ slot: Slot,
91
+ parentHash: Root,
92
+ parentRoot: Root,
93
+ proposerPubkey: BLSPubkey
94
+ ): Promise<BuilderApiBid[]> {
95
+ const seenRequests = new Set<string>();
96
+ const requests: {url: BuilderUrl; entry: routes.validator.BuilderEntry}[] = [];
97
+
98
+ for (const entry of entries) {
99
+ const urlForLog = Buffer.from(entry.url).toString("utf8");
100
+ let url: BuilderUrl;
101
+ try {
102
+ url = decodeBuilderUrl(entry.url);
103
+ } catch {
104
+ this.logger?.warn("Ignoring builder entry with invalid url", {slot, url: urlForLog});
105
+ continue;
106
+ }
107
+
108
+ const requestKey = `${url}-${toHex(entry.auth.message.data)}`;
109
+ if (seenRequests.has(requestKey)) {
110
+ continue;
111
+ }
112
+ seenRequests.add(requestKey);
113
+
114
+ // The builder rejects a mismatch, an entry naming a different slot is not used for a bid request
115
+ if (entry.auth.message.slot !== slot) {
116
+ this.logger?.warn("Ignoring builder entry with auth for different slot", {
117
+ slot,
118
+ authSlot: entry.auth.message.slot,
119
+ builder: toPrintableUrl(url),
120
+ });
121
+ continue;
122
+ }
123
+
124
+ requests.push({url, entry});
125
+ }
126
+
127
+ // Collected in arrival order so an earlier received bid wins ties during candidate ranking
128
+ const bids: BuilderApiBid[] = [];
129
+ await Promise.all(
130
+ requests.map(async ({url, entry}) => {
131
+ this.metrics?.builderApi.bidRequests.inc();
132
+ try {
133
+ const client = await this.getOrCreateClient(url, proposerPubkey, entry.auth);
134
+ const res = await client.getExecutionPayloadBid(
135
+ {
136
+ slot,
137
+ parentHash,
138
+ parentRoot,
139
+ proposerPubkey,
140
+ requestAuth: entry.auth,
141
+ dateMilliseconds: Date.now(),
142
+ timeoutMs: BUILDER_BID_DEADLINE_MS,
143
+ },
144
+ {timeoutMs: BUILDER_BID_REQUEST_TIMEOUT_MS}
145
+ );
146
+ const signedBid = res.value();
147
+ if (signedBid === undefined) {
148
+ this.logger?.debug("No bid received from builder", {slot, builder: toPrintableUrl(url)});
149
+ return;
150
+ }
151
+ this.metrics?.builderApi.bidsReceived.inc();
152
+ bids.push({url, entry, signedBid, receivedMs: this.clock.msFromSlot(slot)});
153
+ } catch (e) {
154
+ this.metrics?.builderApi.bidRequestErrors.inc();
155
+ this.logger?.warn("Failed to get bid from builder", {slot, builder: toPrintableUrl(url)}, e as Error);
156
+ }
157
+ })
158
+ );
159
+
160
+ return bids;
161
+ }
162
+
163
+ /** Forward a proposer's builder preferences to the builder at the given url */
164
+ async submitBuilderPreferences(
165
+ url: BuilderUrl,
166
+ proposerPubkey: BLSPubkey,
167
+ request: gloas.BuilderPreferencesRequest
168
+ ): Promise<void> {
169
+ try {
170
+ const client = await this.getOrCreateClient(url, proposerPubkey, request.auth);
171
+ (await client.submitBuilderPreferences({proposerPubkey, request})).assertOk();
172
+ this.metrics?.builderApi.preferencesForwarded.inc({status: "success"});
173
+ } catch (e) {
174
+ this.metrics?.builderApi.preferencesForwarded.inc({status: "error"});
175
+ throw e;
176
+ }
177
+ }
178
+
179
+ /**
180
+ * Submit the signed beacon block to the builder whose bid was included. The builder is
181
+ * then responsible for constructing and broadcasting the corresponding
182
+ * `SignedExecutionPayloadEnvelope`, no further action is required by the proposer.
183
+ */
184
+ async submitSignedBeaconBlock(
185
+ url: BuilderUrl,
186
+ signedBlock: WithOptionalBytes<SignedBeaconBlock<ForkPostGloas>>
187
+ ): Promise<void> {
188
+ const client = this.clients.get(url);
189
+ if (client === undefined) {
190
+ this.metrics?.builderApi.blockSubmissions.inc({status: "error"});
191
+ this.logger?.warn("Ignoring signed block submission to unauthenticated builder", {url});
192
+ return;
193
+ }
194
+
195
+ try {
196
+ (await client.submitSignedBeaconBlock({signedBlock}, {redirect: "manual"})).assertOk();
197
+ this.metrics?.builderApi.blockSubmissions.inc({status: "success"});
198
+ } catch (e) {
199
+ this.metrics?.builderApi.blockSubmissions.inc({status: "error"});
200
+ throw e;
201
+ }
202
+ }
203
+
204
+ /**
205
+ * Establish the connection to every known builder outside the bid deadline, a cold TCP/TLS handshake
206
+ * to a distant builder can exhaust `BUILDER_BID_DEADLINE_MS` on its own, and a long idle connection
207
+ * may be half-open and only fail once written to.
208
+ */
209
+ async checkStatus(): Promise<void> {
210
+ await Promise.all(
211
+ Array.from(this.clients.entries()).map(async ([url, client]) => {
212
+ try {
213
+ (await client.status()).assertOk();
214
+ this.metrics?.builderApi.statusChecks.inc({status: "success"});
215
+ this.logger?.debug("Builder is ready", {builder: toPrintableUrl(url)});
216
+ } catch (e) {
217
+ this.metrics?.builderApi.statusChecks.inc({status: "error"});
218
+ this.logger?.warn("Builder status check failed", {builder: toPrintableUrl(url)}, e as Error);
219
+ }
220
+ })
221
+ );
222
+ }
223
+
224
+ private async getOrCreateClient(
225
+ url: BuilderUrl,
226
+ proposerPubkey: BLSPubkey,
227
+ auth: gloas.SignedBuilderRequestAuth
228
+ ): Promise<BuilderApi> {
229
+ if (auth.message.data.length === 0) {
230
+ throw Error("Builder request auth data must not be empty");
231
+ }
232
+
233
+ let client = this.clients.get(url);
234
+ if (client === undefined) {
235
+ const domain = computeDomain(DOMAIN_BUILDER_REQUEST_AUTH, this.config.GENESIS_FORK_VERSION, ZERO_HASH);
236
+ const signingRoot = computeSigningRoot(ssz.gloas.BuilderRequestAuth, auth.message, domain);
237
+ const signatureSet = createSingleSignatureSetFromComponents(proposerPubkey, signingRoot, auth.signature);
238
+
239
+ let isValid = false;
240
+ try {
241
+ isValid = await this.bls.verifySignatureSets([signatureSet]);
242
+ } catch {
243
+ // Malformed signatures are invalid request authentication.
244
+ }
245
+ if (!isValid) {
246
+ throw Error("Invalid builder request auth");
247
+ }
248
+
249
+ client = getClient(
250
+ {
251
+ baseUrl: url,
252
+ globalInit: {
253
+ timeoutMs: this.opts.timeout,
254
+ headers: this.opts.userAgent ? {"User-Agent": this.opts.userAgent} : undefined,
255
+ },
256
+ },
257
+ {config: this.config, metrics: this.metrics?.builderHttpClient, logger: this.logger}
258
+ );
259
+ this.clients.set(url, client);
260
+ this.logger?.debug("External builder registered", {url: toPrintableUrl(url)});
261
+ }
262
+ return client;
263
+ }
264
+ }