@lodestar/beacon-node 1.52.0-dev.f2144dd2ac → 1.52.0-dev.f343d455cc

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 (298) hide show
  1. package/lib/api/impl/beacon/blocks/index.d.ts.map +1 -1
  2. package/lib/api/impl/beacon/blocks/index.js +22 -8
  3. package/lib/api/impl/beacon/blocks/index.js.map +1 -1
  4. package/lib/api/impl/beacon/pool/index.d.ts.map +1 -1
  5. package/lib/api/impl/beacon/pool/index.js +3 -1
  6. package/lib/api/impl/beacon/pool/index.js.map +1 -1
  7. package/lib/api/impl/beacon/state/utils.d.ts.map +1 -1
  8. package/lib/api/impl/beacon/state/utils.js +2 -1
  9. package/lib/api/impl/beacon/state/utils.js.map +1 -1
  10. package/lib/api/impl/debug/index.d.ts.map +1 -1
  11. package/lib/api/impl/debug/index.js +6 -2
  12. package/lib/api/impl/debug/index.js.map +1 -1
  13. package/lib/api/impl/validator/index.d.ts.map +1 -1
  14. package/lib/api/impl/validator/index.js +15 -8
  15. package/lib/api/impl/validator/index.js.map +1 -1
  16. package/lib/chain/ColumnReconstructionTracker.d.ts +4 -0
  17. package/lib/chain/ColumnReconstructionTracker.d.ts.map +1 -1
  18. package/lib/chain/ColumnReconstructionTracker.js +4 -0
  19. package/lib/chain/ColumnReconstructionTracker.js.map +1 -1
  20. package/lib/chain/archiveStore/historicalState/getHistoricalState.d.ts.map +1 -1
  21. package/lib/chain/archiveStore/historicalState/getHistoricalState.js +7 -0
  22. package/lib/chain/archiveStore/historicalState/getHistoricalState.js.map +1 -1
  23. package/lib/chain/archiveStore/utils/archiveBlocks.js +1 -1
  24. package/lib/chain/archiveStore/utils/archiveBlocks.js.map +1 -1
  25. package/lib/chain/archiveStore/utils/pruneHistory.d.ts.map +1 -1
  26. package/lib/chain/archiveStore/utils/pruneHistory.js +8 -4
  27. package/lib/chain/archiveStore/utils/pruneHistory.js.map +1 -1
  28. package/lib/chain/blocks/importExecutionPayload.d.ts +1 -1
  29. package/lib/chain/blocks/importExecutionPayload.d.ts.map +1 -1
  30. package/lib/chain/blocks/importExecutionPayload.js +9 -3
  31. package/lib/chain/blocks/importExecutionPayload.js.map +1 -1
  32. package/lib/chain/blocks/index.d.ts.map +1 -1
  33. package/lib/chain/blocks/index.js +3 -17
  34. package/lib/chain/blocks/index.js.map +1 -1
  35. package/lib/chain/chain.d.ts +6 -5
  36. package/lib/chain/chain.d.ts.map +1 -1
  37. package/lib/chain/chain.js +71 -25
  38. package/lib/chain/chain.js.map +1 -1
  39. package/lib/chain/errors/attestationError.d.ts +15 -1
  40. package/lib/chain/errors/attestationError.d.ts.map +1 -1
  41. package/lib/chain/errors/attestationError.js +8 -0
  42. package/lib/chain/errors/attestationError.js.map +1 -1
  43. package/lib/chain/errors/executionPayloadBid.d.ts +6 -1
  44. package/lib/chain/errors/executionPayloadBid.d.ts.map +1 -1
  45. package/lib/chain/errors/executionPayloadBid.js +1 -0
  46. package/lib/chain/errors/executionPayloadBid.js.map +1 -1
  47. package/lib/chain/errors/executionPayloadEnvelope.d.ts +55 -0
  48. package/lib/chain/errors/executionPayloadEnvelope.d.ts.map +1 -1
  49. package/lib/chain/errors/executionPayloadEnvelope.js +8 -0
  50. package/lib/chain/errors/executionPayloadEnvelope.js.map +1 -1
  51. package/lib/chain/interface.d.ts +1 -1
  52. package/lib/chain/interface.d.ts.map +1 -1
  53. package/lib/chain/lightClient/index.d.ts +13 -6
  54. package/lib/chain/lightClient/index.d.ts.map +1 -1
  55. package/lib/chain/lightClient/index.js +95 -115
  56. package/lib/chain/lightClient/index.js.map +1 -1
  57. package/lib/chain/opPools/opPool.js +6 -6
  58. package/lib/chain/opPools/opPool.js.map +1 -1
  59. package/lib/chain/prepareNextSlot.d.ts +45 -0
  60. package/lib/chain/prepareNextSlot.d.ts.map +1 -1
  61. package/lib/chain/prepareNextSlot.js +265 -69
  62. package/lib/chain/prepareNextSlot.js.map +1 -1
  63. package/lib/chain/produceBlock/produceBlockBody.d.ts +1 -0
  64. package/lib/chain/produceBlock/produceBlockBody.d.ts.map +1 -1
  65. package/lib/chain/produceBlock/produceBlockBody.js +23 -15
  66. package/lib/chain/produceBlock/produceBlockBody.js.map +1 -1
  67. package/lib/chain/seenCache/seenAttesters.d.ts +1 -0
  68. package/lib/chain/seenCache/seenAttesters.d.ts.map +1 -1
  69. package/lib/chain/seenCache/seenAttesters.js +1 -1
  70. package/lib/chain/seenCache/seenAttesters.js.map +1 -1
  71. package/lib/chain/seenCache/seenBlockAttesters.d.ts +8 -2
  72. package/lib/chain/seenCache/seenBlockAttesters.d.ts.map +1 -1
  73. package/lib/chain/seenCache/seenBlockAttesters.js +43 -6
  74. package/lib/chain/seenCache/seenBlockAttesters.js.map +1 -1
  75. package/lib/chain/validation/aggregateAndProof.d.ts.map +1 -1
  76. package/lib/chain/validation/aggregateAndProof.js +24 -7
  77. package/lib/chain/validation/aggregateAndProof.js.map +1 -1
  78. package/lib/chain/validation/attestation.d.ts.map +1 -1
  79. package/lib/chain/validation/attestation.js +32 -16
  80. package/lib/chain/validation/attestation.js.map +1 -1
  81. package/lib/chain/validation/block.d.ts.map +1 -1
  82. package/lib/chain/validation/block.js +9 -1
  83. package/lib/chain/validation/block.js.map +1 -1
  84. package/lib/chain/validation/executionPayloadBid.d.ts.map +1 -1
  85. package/lib/chain/validation/executionPayloadBid.js +18 -31
  86. package/lib/chain/validation/executionPayloadBid.js.map +1 -1
  87. package/lib/chain/validation/executionPayloadEnvelope.d.ts.map +1 -1
  88. package/lib/chain/validation/executionPayloadEnvelope.js +100 -9
  89. package/lib/chain/validation/executionPayloadEnvelope.js.map +1 -1
  90. package/lib/chain/validation/payloadAttestationMessage.js +9 -0
  91. package/lib/chain/validation/payloadAttestationMessage.js.map +1 -1
  92. package/lib/chain/validation/voluntaryExit.d.ts.map +1 -1
  93. package/lib/chain/validation/voluntaryExit.js +39 -6
  94. package/lib/chain/validation/voluntaryExit.js.map +1 -1
  95. package/lib/chain/validatorMonitor.js +43 -43
  96. package/lib/chain/validatorMonitor.js.map +1 -1
  97. package/lib/execution/engine/blockHash.d.ts +12 -0
  98. package/lib/execution/engine/blockHash.d.ts.map +1 -0
  99. package/lib/execution/engine/blockHash.js +17 -0
  100. package/lib/execution/engine/blockHash.js.map +1 -0
  101. package/lib/execution/engine/http.d.ts +2 -2
  102. package/lib/execution/engine/http.d.ts.map +1 -1
  103. package/lib/execution/engine/http.js +13 -7
  104. package/lib/execution/engine/http.js.map +1 -1
  105. package/lib/execution/engine/interface.d.ts +16 -3
  106. package/lib/execution/engine/interface.d.ts.map +1 -1
  107. package/lib/execution/engine/interface.js +11 -0
  108. package/lib/execution/engine/interface.js.map +1 -1
  109. package/lib/execution/engine/jsonRpcHttpClient.d.ts +2 -0
  110. package/lib/execution/engine/jsonRpcHttpClient.d.ts.map +1 -1
  111. package/lib/execution/engine/jsonRpcHttpClient.js +14 -6
  112. package/lib/execution/engine/jsonRpcHttpClient.js.map +1 -1
  113. package/lib/execution/engine/jsonRpcTransport.d.ts +2 -2
  114. package/lib/execution/engine/jsonRpcTransport.d.ts.map +1 -1
  115. package/lib/execution/engine/jsonRpcTransport.js +4 -4
  116. package/lib/execution/engine/jsonRpcTransport.js.map +1 -1
  117. package/lib/execution/engine/mock.d.ts.map +1 -1
  118. package/lib/execution/engine/mock.js +6 -6
  119. package/lib/execution/engine/mock.js.map +1 -1
  120. package/lib/execution/engine/payloadIdCache.d.ts +6 -1
  121. package/lib/execution/engine/payloadIdCache.d.ts.map +1 -1
  122. package/lib/execution/engine/payloadIdCache.js +7 -2
  123. package/lib/execution/engine/payloadIdCache.js.map +1 -1
  124. package/lib/execution/engine/restHttpClient.d.ts.map +1 -1
  125. package/lib/execution/engine/restHttpClient.js +9 -5
  126. package/lib/execution/engine/restHttpClient.js.map +1 -1
  127. package/lib/execution/engine/restTransport.d.ts +2 -2
  128. package/lib/execution/engine/restTransport.d.ts.map +1 -1
  129. package/lib/execution/engine/restTransport.js +4 -4
  130. package/lib/execution/engine/restTransport.js.map +1 -1
  131. package/lib/execution/engine/signal.d.ts +6 -0
  132. package/lib/execution/engine/signal.d.ts.map +1 -0
  133. package/lib/execution/engine/signal.js +24 -0
  134. package/lib/execution/engine/signal.js.map +1 -0
  135. package/lib/execution/engine/transport.d.ts +2 -2
  136. package/lib/execution/engine/transport.d.ts.map +1 -1
  137. package/lib/index.d.ts +1 -1
  138. package/lib/index.d.ts.map +1 -1
  139. package/lib/index.js +1 -1
  140. package/lib/index.js.map +1 -1
  141. package/lib/metrics/metrics/beacon.d.ts +5 -0
  142. package/lib/metrics/metrics/beacon.d.ts.map +1 -1
  143. package/lib/metrics/metrics/beacon.js +5 -0
  144. package/lib/metrics/metrics/beacon.js.map +1 -1
  145. package/lib/metrics/metrics/lodestar.d.ts +1 -0
  146. package/lib/metrics/metrics/lodestar.d.ts.map +1 -1
  147. package/lib/metrics/metrics/lodestar.js +5 -0
  148. package/lib/metrics/metrics/lodestar.js.map +1 -1
  149. package/lib/network/core/events.d.ts +6 -2
  150. package/lib/network/core/events.d.ts.map +1 -1
  151. package/lib/network/core/events.js +9 -0
  152. package/lib/network/core/events.js.map +1 -1
  153. package/lib/network/core/networkCoreWorkerHandler.d.ts.map +1 -1
  154. package/lib/network/core/networkCoreWorkerHandler.js +3 -2
  155. package/lib/network/core/networkCoreWorkerHandler.js.map +1 -1
  156. package/lib/network/gossip/gossipsub.d.ts +1 -0
  157. package/lib/network/gossip/gossipsub.d.ts.map +1 -1
  158. package/lib/network/gossip/gossipsub.js +5 -2
  159. package/lib/network/gossip/gossipsub.js.map +1 -1
  160. package/lib/network/gossip/topic.d.ts +1 -7
  161. package/lib/network/gossip/topic.d.ts.map +1 -1
  162. package/lib/network/gossip/topic.js +0 -13
  163. package/lib/network/gossip/topic.js.map +1 -1
  164. package/lib/network/network.d.ts.map +1 -1
  165. package/lib/network/network.js +6 -1
  166. package/lib/network/network.js.map +1 -1
  167. package/lib/network/peers/peerManager.d.ts.map +1 -1
  168. package/lib/network/peers/peerManager.js +22 -2
  169. package/lib/network/peers/peerManager.js.map +1 -1
  170. package/lib/network/peers/utils/prioritizePeers.d.ts +2 -0
  171. package/lib/network/peers/utils/prioritizePeers.d.ts.map +1 -1
  172. package/lib/network/peers/utils/prioritizePeers.js +11 -2
  173. package/lib/network/peers/utils/prioritizePeers.js.map +1 -1
  174. package/lib/network/processor/gossipHandlers.d.ts.map +1 -1
  175. package/lib/network/processor/gossipHandlers.js +19 -6
  176. package/lib/network/processor/gossipHandlers.js.map +1 -1
  177. package/lib/network/processor/index.d.ts.map +1 -1
  178. package/lib/network/processor/index.js +4 -2
  179. package/lib/network/processor/index.js.map +1 -1
  180. package/lib/network/reqresp/handlers/dataColumnSidecarsByRange.js +1 -1
  181. package/lib/network/reqresp/handlers/dataColumnSidecarsByRange.js.map +1 -1
  182. package/lib/network/reqresp/handlers/dataColumnSidecarsByRoot.js +1 -1
  183. package/lib/network/reqresp/handlers/dataColumnSidecarsByRoot.js.map +1 -1
  184. package/lib/sync/range/batch.d.ts +10 -0
  185. package/lib/sync/range/batch.d.ts.map +1 -1
  186. package/lib/sync/range/batch.js +29 -0
  187. package/lib/sync/range/batch.js.map +1 -1
  188. package/lib/sync/range/chain.d.ts +17 -2
  189. package/lib/sync/range/chain.d.ts.map +1 -1
  190. package/lib/sync/range/chain.js +60 -20
  191. package/lib/sync/range/chain.js.map +1 -1
  192. package/lib/sync/range/range.d.ts.map +1 -1
  193. package/lib/sync/range/range.js +44 -3
  194. package/lib/sync/range/range.js.map +1 -1
  195. package/lib/sync/range/utils/batches.d.ts +20 -4
  196. package/lib/sync/range/utils/batches.d.ts.map +1 -1
  197. package/lib/sync/range/utils/batches.js +31 -13
  198. package/lib/sync/range/utils/batches.js.map +1 -1
  199. package/lib/sync/range/utils/peerBalancer.d.ts +1 -1
  200. package/lib/sync/range/utils/peerBalancer.d.ts.map +1 -1
  201. package/lib/sync/range/utils/peerBalancer.js +5 -2
  202. package/lib/sync/range/utils/peerBalancer.js.map +1 -1
  203. package/lib/sync/types.d.ts +14 -1
  204. package/lib/sync/types.d.ts.map +1 -1
  205. package/lib/sync/types.js +2 -0
  206. package/lib/sync/types.js.map +1 -1
  207. package/lib/sync/unknownBlock.d.ts +28 -1
  208. package/lib/sync/unknownBlock.d.ts.map +1 -1
  209. package/lib/sync/unknownBlock.js +340 -27
  210. package/lib/sync/unknownBlock.js.map +1 -1
  211. package/lib/sync/utils/downloadByRange.d.ts +22 -1
  212. package/lib/sync/utils/downloadByRange.d.ts.map +1 -1
  213. package/lib/sync/utils/downloadByRange.js +55 -25
  214. package/lib/sync/utils/downloadByRange.js.map +1 -1
  215. package/lib/sync/utils/downloadByRoot.d.ts +24 -2
  216. package/lib/sync/utils/downloadByRoot.d.ts.map +1 -1
  217. package/lib/sync/utils/downloadByRoot.js +48 -5
  218. package/lib/sync/utils/downloadByRoot.js.map +1 -1
  219. package/lib/util/asyncIterableToEvents.d.ts +20 -3
  220. package/lib/util/asyncIterableToEvents.d.ts.map +1 -1
  221. package/lib/util/asyncIterableToEvents.js +76 -20
  222. package/lib/util/asyncIterableToEvents.js.map +1 -1
  223. package/lib/util/dataColumns.d.ts +1 -1
  224. package/lib/util/dataColumns.d.ts.map +1 -1
  225. package/lib/util/dataColumns.js +4 -1
  226. package/lib/util/dataColumns.js.map +1 -1
  227. package/lib/util/eventLoop.d.ts +3 -3
  228. package/lib/util/eventLoop.d.ts.map +1 -1
  229. package/lib/util/eventLoop.js +3 -3
  230. package/lib/util/eventLoop.js.map +1 -1
  231. package/package.json +27 -27
  232. package/src/api/impl/beacon/blocks/index.ts +24 -8
  233. package/src/api/impl/beacon/pool/index.ts +9 -7
  234. package/src/api/impl/beacon/state/utils.ts +2 -1
  235. package/src/api/impl/debug/index.ts +6 -2
  236. package/src/api/impl/validator/index.ts +17 -9
  237. package/src/chain/ColumnReconstructionTracker.ts +5 -0
  238. package/src/chain/archiveStore/historicalState/getHistoricalState.ts +9 -0
  239. package/src/chain/archiveStore/utils/archiveBlocks.ts +1 -1
  240. package/src/chain/archiveStore/utils/pruneHistory.ts +9 -4
  241. package/src/chain/blocks/importExecutionPayload.ts +9 -2
  242. package/src/chain/blocks/index.ts +3 -31
  243. package/src/chain/chain.ts +104 -42
  244. package/src/chain/errors/attestationError.ts +11 -1
  245. package/src/chain/errors/executionPayloadBid.ts +6 -0
  246. package/src/chain/errors/executionPayloadEnvelope.ts +58 -0
  247. package/src/chain/interface.ts +1 -1
  248. package/src/chain/lightClient/index.ts +108 -142
  249. package/src/chain/opPools/opPool.ts +6 -6
  250. package/src/chain/prepareNextSlot.ts +347 -89
  251. package/src/chain/produceBlock/produceBlockBody.ts +25 -16
  252. package/src/chain/seenCache/seenAttesters.ts +1 -1
  253. package/src/chain/seenCache/seenBlockAttesters.ts +48 -6
  254. package/src/chain/validation/aggregateAndProof.ts +24 -9
  255. package/src/chain/validation/attestation.ts +31 -20
  256. package/src/chain/validation/block.ts +9 -1
  257. package/src/chain/validation/executionPayloadBid.ts +21 -33
  258. package/src/chain/validation/executionPayloadEnvelope.ts +115 -8
  259. package/src/chain/validation/payloadAttestationMessage.ts +10 -0
  260. package/src/chain/validation/voluntaryExit.ts +44 -6
  261. package/src/chain/validatorMonitor.ts +43 -43
  262. package/src/execution/engine/blockHash.ts +27 -0
  263. package/src/execution/engine/http.ts +18 -10
  264. package/src/execution/engine/interface.ts +18 -3
  265. package/src/execution/engine/jsonRpcHttpClient.ts +26 -14
  266. package/src/execution/engine/jsonRpcTransport.ts +8 -4
  267. package/src/execution/engine/mock.ts +13 -8
  268. package/src/execution/engine/payloadIdCache.ts +12 -4
  269. package/src/execution/engine/restHttpClient.ts +17 -11
  270. package/src/execution/engine/restTransport.ts +5 -4
  271. package/src/execution/engine/signal.ts +28 -0
  272. package/src/execution/engine/transport.ts +3 -2
  273. package/src/index.ts +6 -1
  274. package/src/metrics/metrics/beacon.ts +9 -0
  275. package/src/metrics/metrics/lodestar.ts +5 -0
  276. package/src/network/core/events.ts +12 -0
  277. package/src/network/core/networkCoreWorkerHandler.ts +6 -2
  278. package/src/network/gossip/gossipsub.ts +6 -2
  279. package/src/network/gossip/topic.ts +1 -14
  280. package/src/network/network.ts +6 -2
  281. package/src/network/peers/peerManager.ts +26 -2
  282. package/src/network/peers/utils/prioritizePeers.ts +14 -1
  283. package/src/network/processor/gossipHandlers.ts +25 -13
  284. package/src/network/processor/index.ts +7 -2
  285. package/src/network/reqresp/handlers/dataColumnSidecarsByRange.ts +1 -1
  286. package/src/network/reqresp/handlers/dataColumnSidecarsByRoot.ts +1 -1
  287. package/src/sync/range/batch.ts +33 -0
  288. package/src/sync/range/chain.ts +72 -17
  289. package/src/sync/range/range.ts +57 -3
  290. package/src/sync/range/utils/batches.ts +38 -13
  291. package/src/sync/range/utils/peerBalancer.ts +4 -1
  292. package/src/sync/types.ts +13 -0
  293. package/src/sync/unknownBlock.ts +389 -29
  294. package/src/sync/utils/downloadByRange.ts +89 -29
  295. package/src/sync/utils/downloadByRoot.ts +75 -7
  296. package/src/util/asyncIterableToEvents.ts +100 -21
  297. package/src/util/dataColumns.ts +4 -1
  298. package/src/util/eventLoop.ts +3 -3
@@ -1,7 +1,14 @@
1
1
  import {routes} from "@lodestar/api";
2
2
  import {ChainForkConfig} from "@lodestar/config";
3
- import {getFinalizedExecutionBlockHash, getSafeExecutionBlockHash} from "@lodestar/fork-choice";
4
3
  import {
4
+ ProtoBlock,
5
+ PtcQuorumEvent,
6
+ getFinalizedExecutionBlockHash,
7
+ getPtcVerdict,
8
+ getSafeExecutionBlockHash,
9
+ } from "@lodestar/fork-choice";
10
+ import {
11
+ ForkName,
5
12
  ForkPostBellatrix,
6
13
  ForkSeq,
7
14
  SLOTS_PER_EPOCH,
@@ -21,7 +28,7 @@ import {
21
28
  isStatePostFulu,
22
29
  isStatePostGloas,
23
30
  } from "@lodestar/state-transition";
24
- import {Bytes32, Slot, ValidatorIndex} from "@lodestar/types";
31
+ import {Bytes32, RootHex, Slot, ValidatorIndex} from "@lodestar/types";
25
32
  import {Logger, fromHex, isErrorAborted, sleep, toHex} from "@lodestar/utils";
26
33
  import {GENESIS_SLOT} from "../constants/constants.js";
27
34
  import {BuilderStatus} from "../execution/builder/http.js";
@@ -29,6 +36,7 @@ import {PayloadAttributes} from "../execution/index.js";
29
36
  import {Metrics} from "../metrics/index.js";
30
37
  import {ClockEvent} from "../util/clock.js";
31
38
  import {isQueueErrorAborted} from "../util/queue/index.js";
39
+ import {ChainEvent} from "./emitter.js";
32
40
  import {ForkchoiceCaller} from "./forkChoice/index.js";
33
41
  import {IBeaconChain} from "./interface.js";
34
42
  import {
@@ -38,8 +46,13 @@ import {
38
46
  } from "./produceBlock/produceBlockBody.js";
39
47
  import {RegenCaller} from "./regen/index.js";
40
48
 
41
- // TODO GLOAS: re-evaluate this timing
42
- /* With 12s slot times, this scheduler will run 4s before the start of each slot (`12 - 0.6667 * 12 = 4`). */
49
+ /**
50
+ * With 12s slot times, this scheduler will run 4s before the start of each slot (`12 - 0.6667 * 12 = 4`).
51
+ *
52
+ * Post-Gloas this is after the payload deadline (50% of the slot), so the parent's payload has normally been
53
+ * imported, and before the PTC deadline (75%). The parent choice is revisited when the PTC verdict or a timely
54
+ * payload comes in after the scheduled run, see `reprepare`.
55
+ */
43
56
  export const PREPARE_NEXT_SLOT_BPS = 6667;
44
57
 
45
58
  /* We don't want to do more epoch transition than this */
@@ -58,6 +71,28 @@ const BUILDER_PREVERIFY_LIMIT_BPS = 2000;
58
71
  */
59
72
  const BUILDER_STATUS_CHECK_BEFORE_SLOT_BPS = 1667;
60
73
 
74
+ export enum PreparePayloadReason {
75
+ /** The scheduled run at PREPARE_NEXT_SLOT_BPS of the slot */
76
+ scheduled = "scheduled",
77
+ /** The PTC reached a verdict on the payload of the current slot's block */
78
+ ptcQuorum = "ptc_quorum",
79
+ /** A timely payload of the current slot's block was imported after the scheduled run */
80
+ payloadImported = "payload_imported",
81
+ }
82
+
83
+ /** Inputs the payload for `prepareSlot` was last prepared with, a re-prepare with the same inputs is skipped */
84
+ type PreparedPayload = {
85
+ prepareSlot: Slot;
86
+ proposerIndex: ValidatorIndex;
87
+ headRoot: RootHex;
88
+ /** Whether the payload builds on the parent's full payload or its empty variant, `null` pre-Gloas */
89
+ buildOnFull: boolean | null;
90
+ /** `undefined` if the proposer is not ours, only the payload attributes event was emitted */
91
+ feeRecipient: string | undefined;
92
+ /** The forkchoiceUpdated failed, so a re-prepare retries it even with unchanged inputs */
93
+ failed: boolean;
94
+ };
95
+
61
96
  /**
62
97
  * At Bellatrix, if we are responsible for proposing in next slot, we want to prepare payload
63
98
  * 4s before the start of next slot at PREPARE_NEXT_SLOT_BPS of the current slot.
@@ -70,6 +105,11 @@ const BUILDER_STATUS_CHECK_BEFORE_SLOT_BPS = 1667;
70
105
  *
71
106
  */
72
107
  export class PrepareNextSlotScheduler {
108
+ private lastPrepared: PreparedPayload | null = null;
109
+ /** Slot a payload preparation is in flight for, a re-prepare requested meanwhile runs after it */
110
+ private preparingSlot: Slot | null = null;
111
+ private queuedReason: PreparePayloadReason | null = null;
112
+
73
113
  constructor(
74
114
  private readonly chain: IBeaconChain,
75
115
  private readonly config: ChainForkConfig,
@@ -78,10 +118,14 @@ export class PrepareNextSlotScheduler {
78
118
  private readonly signal: AbortSignal
79
119
  ) {
80
120
  this.chain.clock.on(ClockEvent.slot, this.prepareForNextSlot);
121
+ this.chain.emitter.on(ChainEvent.forkChoicePtcQuorum, this.onPtcQuorum);
122
+ this.chain.emitter.on(routes.events.EventType.executionPayload, this.onExecutionPayloadImported);
81
123
  this.signal.addEventListener(
82
124
  "abort",
83
125
  () => {
84
126
  this.chain.clock.off(ClockEvent.slot, this.prepareForNextSlot);
127
+ this.chain.emitter.off(ChainEvent.forkChoicePtcQuorum, this.onPtcQuorum);
128
+ this.chain.emitter.off(routes.events.EventType.executionPayload, this.onExecutionPayloadImported);
85
129
  },
86
130
  {once: true}
87
131
  );
@@ -109,6 +153,10 @@ export class PrepareNextSlotScheduler {
109
153
  // or precompute epoch transition
110
154
  await sleep(this.config.getSlotComponentDurationMs(currentFork, PREPARE_NEXT_SLOT_BPS), this.signal);
111
155
 
156
+ // Re-prepare requests from here on are queued until this run is done. Earlier ones are
157
+ // dropped, the head computed below already reflects them.
158
+ this.preparingSlot = prepareSlot;
159
+
112
160
  // calling updateHead() here before we produce a block to reduce reorg possibility
113
161
  const headBlock = this.chain.recomputeForkChoiceHead(ForkchoiceCaller.prepareNextSlot);
114
162
  const {slot: headSlot, blockRoot: headRoot} = headBlock;
@@ -163,15 +211,7 @@ export class PrepareNextSlotScheduler {
163
211
  };
164
212
 
165
213
  const proposerIndex = await getProposerIndex();
166
- if (this.chain.beaconProposerCache.has(proposerIndex)) {
167
- const pooledPreferences = isForkPostGloas(fork)
168
- ? getPooledProposerPreferences(this.chain, prepareSlot, headRoot)
169
- : null;
170
- feeRecipient =
171
- pooledPreferences !== null
172
- ? toHex(pooledPreferences.feeRecipient)
173
- : this.chain.beaconProposerCache.getOrDefault(proposerIndex);
174
- }
214
+ feeRecipient = this.getFeeRecipient(fork, prepareSlot, headRoot, proposerIndex);
175
215
 
176
216
  // Predict the proposer head of the next slot when either:
177
217
  // - we are proposing the next slot (single-slot proposer-boost-reorg), or
@@ -231,82 +271,15 @@ export class PrepareNextSlotScheduler {
231
271
  );
232
272
  }
233
273
 
234
- if (!isStatePostBellatrix(preparedState)) {
235
- throw new Error("Expected Bellatrix state for payload attributes");
236
- }
237
-
238
- let parentBlockHash: Bytes32;
239
- // Apply parent payload once here as it's reused by EL prep and SSE emit below
240
- let stateAfterParentPayload: IBeaconStateViewBellatrix = preparedState;
241
- if (isStatePostGloas(preparedState)) {
242
- // Spec: should_build_on_full(store, head, slot) - see produceBlockBody.ts for context.
243
- if (this.chain.forkChoice.shouldBuildOnFull(updatedHead, prepareSlot)) {
244
- parentBlockHash = preparedState.latestExecutionPayloadBid.blockHash;
245
- // Skip applying parent payload unless we're proposing the next slot or have to emit payload_attributes events
246
- if (feeRecipient !== undefined || this.chain.opts.emitPayloadAttributes === true) {
247
- const parentExecutionRequests = await this.chain.getParentExecutionRequests(
248
- updatedHead.slot,
249
- updatedHead.blockRoot
250
- );
251
- stateAfterParentPayload = preparedState.withParentPayloadApplied(parentExecutionRequests);
252
- }
253
- } else {
254
- parentBlockHash = preparedState.latestExecutionPayloadBid.parentBlockHash;
255
- }
256
- } else {
257
- parentBlockHash = preparedState.latestExecutionPayloadHeader.blockHash;
258
- }
259
-
260
- // The payload_attributes event must carry the same hashes we send to the EL
261
- const safeBlockHash = getSafeExecutionBlockHash(this.chain.forkChoice, this.logger);
262
- const finalizedBlockHash = getFinalizedExecutionBlockHash(this.chain.forkChoice);
263
-
264
- let payloadAttributes: PayloadAttributes | undefined;
265
- // If emitPayloadAttributes is true emit a SSE payloadAttributes event for
266
- // every slot. Without the flag, only emit the event if we are proposing in the next slot.
267
- if (
268
- (feeRecipient || this.chain.opts.emitPayloadAttributes === true) &&
269
- this.chain.emitter.listenerCount(routes.events.EventType.payloadAttributes)
270
- ) {
271
- const data = getPayloadAttributesForSSE(fork as ForkPostBellatrix, this.chain, {
272
- prepareState: stateAfterParentPayload,
273
- prepareSlot,
274
- parentBlockRoot: fromHex(updatedHead.blockRoot),
275
- parentBlockHash,
276
- safeBlockHash,
277
- finalizedBlockHash,
278
- feeRecipient: feeRecipient ?? "0x0000000000000000000000000000000000000000",
279
- });
280
- this.chain.emitter.emit(routes.events.EventType.payloadAttributes, {data, version: fork});
281
- payloadAttributes = data.payloadAttributes;
282
- }
283
-
284
- if (feeRecipient) {
285
- const preparationTime =
286
- computeTimeAtSlot(this.config, prepareSlot, this.chain.genesisTime) - Date.now() / 1000;
287
- this.metrics?.blockPayload.payloadAdvancePrepTime.observe(preparationTime);
288
-
289
- // awaiting here instead of throwing an async call because there is no other task
290
- // left for scheduler and this gives nice semantics to catch and log errors in the
291
- // try/catch wrapper here.
292
- await prepareExecutionPayload(
293
- this.chain,
294
- this.logger,
295
- fork as ForkPostBellatrix, // State is of execution type
296
- fromHex(updatedHead.blockRoot),
297
- parentBlockHash,
298
- safeBlockHash,
299
- finalizedBlockHash,
300
- stateAfterParentPayload,
301
- feeRecipient,
302
- payloadAttributes
303
- );
304
- this.logger.verbose("PrepareNextSlotScheduler prepared new payload", {
305
- prepareSlot,
306
- proposerIndex,
307
- feeRecipient,
308
- });
309
- }
274
+ await this.preparePayload({
275
+ reason: PreparePayloadReason.scheduled,
276
+ fork: fork as ForkPostBellatrix,
277
+ prepareSlot,
278
+ proposerIndex,
279
+ feeRecipient,
280
+ head: updatedHead,
281
+ state: preparedState,
282
+ });
310
283
 
311
284
  this.computeStateHashTreeRoot(preparedState, isEpochTransition);
312
285
  } else {
@@ -416,9 +389,294 @@ export class PrepareNextSlotScheduler {
416
389
  this.metrics?.precomputeNextEpochTransition.count.inc({result: "error"}, 1);
417
390
  this.logger.error("Failed to run prepareForNextSlot", {nextEpoch, isEpochTransition, prepareSlot}, e as Error);
418
391
  }
392
+ } finally {
393
+ this.finishRun(prepareSlot);
419
394
  }
420
395
  };
421
396
 
397
+ /**
398
+ * Choose the parent the payload for `prepareSlot` builds on, emit the payload attributes and ask the engine
399
+ * to build the payload. Records the inputs so a later `reprepare` can skip an unchanged result.
400
+ */
401
+ private async preparePayload({
402
+ reason,
403
+ fork,
404
+ prepareSlot,
405
+ proposerIndex,
406
+ feeRecipient,
407
+ head,
408
+ state,
409
+ }: {
410
+ reason: PreparePayloadReason;
411
+ fork: ForkPostBellatrix;
412
+ prepareSlot: Slot;
413
+ proposerIndex: ValidatorIndex;
414
+ feeRecipient: string | undefined;
415
+ head: ProtoBlock;
416
+ state: IBeaconStateView;
417
+ }): Promise<void> {
418
+ if (!isStatePostBellatrix(state)) {
419
+ throw new Error("Expected Bellatrix state for payload attributes");
420
+ }
421
+
422
+ let parentBlockHash: Bytes32;
423
+ let buildOnFull: boolean | null = null;
424
+ // Apply parent payload once here as it's reused by EL prep and SSE emit below
425
+ let stateAfterParentPayload: IBeaconStateViewBellatrix = state;
426
+ if (isStatePostGloas(state)) {
427
+ // Spec: should_build_on_full(store, head, slot) - see produceBlockBody.ts for context.
428
+ buildOnFull = this.chain.forkChoice.shouldBuildOnFull(head, prepareSlot);
429
+ if (buildOnFull) {
430
+ parentBlockHash = state.latestExecutionPayloadBid.blockHash;
431
+ // Skip applying parent payload unless we're proposing the next slot or have to emit payload_attributes events
432
+ if (feeRecipient !== undefined || this.chain.opts.emitPayloadAttributes === true) {
433
+ const parentExecutionRequests = await this.chain.getParentExecutionRequests(head.slot, head.blockRoot);
434
+ stateAfterParentPayload = state.withParentPayloadApplied(parentExecutionRequests);
435
+ }
436
+ } else {
437
+ parentBlockHash = state.latestExecutionPayloadBid.parentBlockHash;
438
+ }
439
+ } else {
440
+ parentBlockHash = state.latestExecutionPayloadHeader.blockHash;
441
+ }
442
+
443
+ // Block production owns the engine head once the proposal slot started, a late fcU could move it back
444
+ if (reason !== PreparePayloadReason.scheduled && this.chain.clock.currentSlot >= prepareSlot) {
445
+ this.metrics?.blockPayload.payloadReprepare.inc({reason, result: "dropped"});
446
+ this.logger.debug("Proposal slot started, not re-preparing", {prepareSlot, reason, headRoot: head.blockRoot});
447
+ return;
448
+ }
449
+
450
+ // The payload_attributes event must carry the same hashes we send to the EL
451
+ const safeBlockHash = getSafeExecutionBlockHash(this.chain.forkChoice, this.logger);
452
+ const finalizedBlockHash = getFinalizedExecutionBlockHash(this.chain.forkChoice);
453
+
454
+ let payloadAttributes: PayloadAttributes | undefined;
455
+ // If emitPayloadAttributes is true emit a SSE payloadAttributes event for
456
+ // every slot. Without the flag, only emit the event if we are proposing in the next slot.
457
+ if (
458
+ (feeRecipient || this.chain.opts.emitPayloadAttributes === true) &&
459
+ this.chain.emitter.listenerCount(routes.events.EventType.payloadAttributes)
460
+ ) {
461
+ const data = getPayloadAttributesForSSE(fork, this.chain, {
462
+ prepareState: stateAfterParentPayload,
463
+ prepareSlot,
464
+ parentBlockRoot: fromHex(head.blockRoot),
465
+ parentBlockHash,
466
+ safeBlockHash,
467
+ finalizedBlockHash,
468
+ feeRecipient: feeRecipient ?? "0x0000000000000000000000000000000000000000",
469
+ });
470
+ this.chain.emitter.emit(routes.events.EventType.payloadAttributes, {data, version: fork});
471
+ payloadAttributes = data.payloadAttributes;
472
+ }
473
+
474
+ // Builders take the parent from the payload attributes event, so re-prepare whenever it was emitted. Recorded
475
+ // before the engine call, a failed forkchoiceUpdated must not drop the later re-prepares for this slot
476
+ const prepared = feeRecipient !== undefined || payloadAttributes !== undefined;
477
+ const record: PreparedPayload = {
478
+ prepareSlot,
479
+ proposerIndex,
480
+ headRoot: head.blockRoot,
481
+ buildOnFull,
482
+ feeRecipient,
483
+ failed: false,
484
+ };
485
+ if (prepared) {
486
+ this.lastPrepared = record;
487
+ }
488
+
489
+ if (feeRecipient) {
490
+ // Only for the scheduled run, a re-prepare later in the slot would add a second, shorter sample
491
+ if (reason === PreparePayloadReason.scheduled) {
492
+ const preparationTime = computeTimeAtSlot(this.config, prepareSlot, this.chain.genesisTime) - Date.now() / 1000;
493
+ this.metrics?.blockPayload.payloadAdvancePrepTime.observe(preparationTime);
494
+ }
495
+
496
+ // awaiting here instead of throwing an async call because there is no other task
497
+ // left for scheduler and this gives nice semantics to catch and log errors in the
498
+ // try/catch wrapper here.
499
+ try {
500
+ await prepareExecutionPayload(
501
+ this.chain,
502
+ this.logger,
503
+ fork, // State is of execution type
504
+ fromHex(head.blockRoot),
505
+ parentBlockHash,
506
+ safeBlockHash,
507
+ finalizedBlockHash,
508
+ stateAfterParentPayload,
509
+ feeRecipient,
510
+ payloadAttributes
511
+ );
512
+ } catch (e) {
513
+ record.failed = true;
514
+ throw e;
515
+ }
516
+ this.logger.verbose("PrepareNextSlotScheduler prepared new payload", {
517
+ prepareSlot,
518
+ proposerIndex,
519
+ feeRecipient,
520
+ reason,
521
+ headRoot: head.blockRoot,
522
+ buildOnFull,
523
+ });
524
+ }
525
+
526
+ if (prepared && reason !== PreparePayloadReason.scheduled) {
527
+ this.metrics?.blockPayload.payloadReprepare.inc({reason, result: "changed"});
528
+ }
529
+ }
530
+
531
+ /** Fee recipient of our validator proposing `prepareSlot`, `undefined` if the proposer is not ours */
532
+ private getFeeRecipient(
533
+ fork: ForkName,
534
+ prepareSlot: Slot,
535
+ headRoot: RootHex,
536
+ proposerIndex: ValidatorIndex
537
+ ): string | undefined {
538
+ if (!this.chain.beaconProposerCache.has(proposerIndex)) {
539
+ return undefined;
540
+ }
541
+ const pooledPreferences = isForkPostGloas(fork)
542
+ ? getPooledProposerPreferences(this.chain, prepareSlot, headRoot)
543
+ : null;
544
+ return pooledPreferences !== null
545
+ ? toHex(pooledPreferences.feeRecipient)
546
+ : this.chain.beaconProposerCache.getOrDefault(proposerIndex);
547
+ }
548
+
549
+ /**
550
+ * The PTC verdict on the current slot's block decides whether the next proposal extends its payload.
551
+ * Spec: the proposer SHOULD call `prepare_execution_payload` again once the parent's payload attestations are in.
552
+ */
553
+ private onPtcQuorum = (data: PtcQuorumEvent): void => {
554
+ if (data.slot === this.chain.clock.currentSlot) {
555
+ this.requestReprepare(PreparePayloadReason.ptcQuorum);
556
+ }
557
+ };
558
+
559
+ /**
560
+ * A payload of the current slot's block imported after the scheduled run moves the head to its full variant.
561
+ * Only react to a payload the PTC votes present: seen before the payload deadline, or already voted present. The
562
+ * event is only emitted once the payload's data is available. A late one without that verdict will likely be voted
563
+ * absent and the re-prepare undone.
564
+ */
565
+ private onExecutionPayloadImported = ({slot, blockRoot}: {slot: Slot; blockRoot: RootHex}): void => {
566
+ if (slot !== this.chain.clock.currentSlot) {
567
+ return;
568
+ }
569
+ const payloadInput = this.chain.seenPayloadEnvelopeInputCache.get(blockRoot);
570
+ if (payloadInput === undefined || !payloadInput.hasPayloadEnvelope()) {
571
+ return;
572
+ }
573
+ const seenSec = this.chain.clock.secFromSlot(slot, payloadInput.getPayloadEnvelopeSource().seenTimestampSec);
574
+ const quorum = this.chain.forkChoice.getPtcQuorum(blockRoot);
575
+ if (
576
+ seenSec >= this.config.getPayloadDueMs(this.config.getForkName(slot)) / 1000 &&
577
+ (quorum === null || getPtcVerdict(quorum) !== true)
578
+ ) {
579
+ return;
580
+ }
581
+ this.requestReprepare(PreparePayloadReason.payloadImported);
582
+ };
583
+
584
+ /**
585
+ * Re-run the payload preparation for the next slot after its inputs may have changed. Waits for an in-flight
586
+ * preparation, drops the request if neither a payload nor payload attributes were prepared for the next slot.
587
+ */
588
+ private requestReprepare(reason: PreparePayloadReason): void {
589
+ const prepareSlot = this.chain.clock.currentSlot + 1;
590
+ if (this.preparingSlot !== null) {
591
+ if (this.preparingSlot === prepareSlot) {
592
+ this.queuedReason = reason;
593
+ }
594
+ return;
595
+ }
596
+ if (this.lastPrepared?.prepareSlot !== prepareSlot) {
597
+ return;
598
+ }
599
+
600
+ this.preparingSlot = prepareSlot;
601
+ this.reprepare(prepareSlot, reason)
602
+ .catch((e) => {
603
+ if (!isErrorAborted(e) && !isQueueErrorAborted(e)) {
604
+ this.metrics?.blockPayload.payloadReprepare.inc({reason, result: "error"});
605
+ this.logger.error("Failed to re-prepare payload for next slot", {prepareSlot, reason}, e as Error);
606
+ }
607
+ })
608
+ .finally(() => this.finishRun(prepareSlot));
609
+ }
610
+
611
+ private finishRun(prepareSlot: Slot): void {
612
+ if (this.preparingSlot !== prepareSlot) {
613
+ return;
614
+ }
615
+ this.preparingSlot = null;
616
+ const queued = this.queuedReason;
617
+ this.queuedReason = null;
618
+ if (queued !== null) {
619
+ this.requestReprepare(queued);
620
+ }
621
+ }
622
+
623
+ private async reprepare(prepareSlot: Slot, reason: PreparePayloadReason): Promise<void> {
624
+ const prepared = this.lastPrepared;
625
+ const fork = this.config.getForkName(prepareSlot);
626
+ if (prepared === null || prepared.prepareSlot !== prepareSlot || !isForkPostBellatrix(fork)) {
627
+ return;
628
+ }
629
+
630
+ // Same head resolution as the scheduled run, the head may have changed since
631
+ const headBlock = this.chain.recomputeForkChoiceHead(ForkchoiceCaller.prepareNextSlot);
632
+ const feeRecipient = this.getFeeRecipient(fork, prepareSlot, headBlock.blockRoot, prepared.proposerIndex);
633
+ // Without a local proposer a re-prepare only re-emits the payload attributes, skip it if nobody listens
634
+ if (
635
+ feeRecipient === undefined &&
636
+ (this.chain.opts.emitPayloadAttributes !== true ||
637
+ this.chain.emitter.listenerCount(routes.events.EventType.payloadAttributes) === 0)
638
+ ) {
639
+ return;
640
+ }
641
+ const isEpochTransition = computeEpochAtSlot(prepareSlot) > computeEpochAtSlot(prepareSlot - 1);
642
+ const proposerHead = feeRecipient !== undefined || isEpochTransition ? this.chain.predictProposerHead() : headBlock;
643
+ const head = proposerHead.blockRoot !== headBlock.blockRoot ? proposerHead : headBlock;
644
+
645
+ const buildOnFull = isForkPostGloas(fork) ? this.chain.forkChoice.shouldBuildOnFull(head, prepareSlot) : null;
646
+ const logCtx = {prepareSlot, reason, headRoot: head.blockRoot, buildOnFull};
647
+ if (
648
+ !prepared.failed &&
649
+ head.blockRoot === prepared.headRoot &&
650
+ buildOnFull === prepared.buildOnFull &&
651
+ feeRecipient === prepared.feeRecipient
652
+ ) {
653
+ this.metrics?.blockPayload.payloadReprepare.inc({reason, result: "unchanged"});
654
+ this.logger.debug("Payload for next slot unchanged, not re-preparing", logCtx);
655
+ return;
656
+ }
657
+ this.logger.verbose("Re-preparing payload for next slot", {
658
+ ...logCtx,
659
+ prevHeadRoot: prepared.headRoot,
660
+ prevBuildOnFull: prepared.buildOnFull,
661
+ });
662
+
663
+ const state = await this.chain.regen.getBlockSlotState(
664
+ head,
665
+ prepareSlot,
666
+ {dontTransferCache: !isEpochTransition},
667
+ head === headBlock ? RegenCaller.precomputeEpoch : RegenCaller.predictProposerHead
668
+ );
669
+ await this.preparePayload({
670
+ reason,
671
+ fork,
672
+ prepareSlot,
673
+ proposerIndex: prepared.proposerIndex,
674
+ feeRecipient,
675
+ head,
676
+ state,
677
+ });
678
+ }
679
+
422
680
  /**
423
681
  * Pre-establish the builder connections so the handshake lands outside the bid deadline. Scheduled
424
682
  * later in the slot, connecting at PREPARE_NEXT_SLOT_BPS would go cold before bids are requested.
@@ -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(
@@ -22,7 +22,7 @@ import {MapDef} from "@lodestar/utils";
22
22
  //
23
23
  // Assuming we're at epoch 99 while all other nodes at epoch 100, they all accept attestations at epoch 99, 100.
24
24
  // If MAX_RETAINED_EPOCH = 2 then lowestPermissibleEpoch is 97 which is more than enough
25
- const EPOCH_LOOKBACK_LIMIT = 2;
25
+ export const EPOCH_LOOKBACK_LIMIT = 2;
26
26
 
27
27
  /**
28
28
  * Keeps a cache to filter unaggregated attestations from the same validator in the same epoch.
@@ -1,18 +1,60 @@
1
1
  import {Epoch, ValidatorIndex} from "@lodestar/types";
2
- import {SeenAttesters} from "./seenAttesters.js";
3
- // TODO abstract out the Seen* caches into an abstract abstract data structure
4
- // that all the caches can extend since they share similar structure.
2
+ import {EPOCH_LOOKBACK_LIMIT} from "./seenAttesters.js";
5
3
 
6
- export class SeenBlockAttesters extends SeenAttesters {
4
+ /** A bitset per epoch, block import adds tens of thousands of indices per block on the main thread */
5
+ export class SeenBlockAttesters {
6
+ private readonly bitsByEpoch = new Map<Epoch, Uint8Array>();
7
+ private lowestPermissibleEpoch: Epoch = 0;
8
+ private byteLength = 0;
9
+
10
+ isKnown(epoch: Epoch, validatorIndex: ValidatorIndex): boolean {
11
+ const bits = this.bitsByEpoch.get(epoch);
12
+ // The index comes from API requests, the bitwise operators below would truncate it and alias a tracked index
13
+ if (
14
+ bits === undefined ||
15
+ !Number.isInteger(validatorIndex) ||
16
+ validatorIndex < 0 ||
17
+ validatorIndex >= bits.length * 8
18
+ ) {
19
+ return false;
20
+ }
21
+ // Validator i is bit (i % 8) of byte floor(i / 8): `>>> 3` picks the byte, `& 7` the bit inside it
22
+ return (bits[validatorIndex >>> 3] & (1 << (validatorIndex & 7))) !== 0;
23
+ }
24
+
25
+ /** `validatorIndexes` must be indices of the validator registry */
7
26
  addIndices(epoch: Epoch, validatorIndexes: ValidatorIndex[]): void {
8
27
  if (epoch < this.lowestPermissibleEpoch) {
9
28
  throw Error(`EpochTooLow ${epoch} < ${this.lowestPermissibleEpoch}`);
10
29
  }
11
30
 
12
- const indexesByEpoch = this.validatorIndexesByEpoch.getOrDefault(epoch);
31
+ let bits = this.bitsByEpoch.get(epoch);
32
+ if (bits === undefined) {
33
+ bits = new Uint8Array(this.byteLength);
34
+ this.bitsByEpoch.set(epoch, bits);
35
+ }
13
36
 
14
37
  for (const index of validatorIndexes) {
15
- indexesByEpoch.add(index);
38
+ // floor(index / 8), the byte that holds this validator's bit
39
+ const byteIndex = index >>> 3;
40
+ if (byteIndex >= bits.length) {
41
+ const grown: Uint8Array = new Uint8Array(Math.max(byteIndex + 1, bits.length * 2));
42
+ grown.set(bits);
43
+ bits = grown;
44
+ this.bitsByEpoch.set(epoch, bits);
45
+ this.byteLength = Math.max(this.byteLength, bits.length);
46
+ }
47
+ // Set bit (index % 8) of that byte
48
+ bits[byteIndex] |= 1 << (index & 7);
49
+ }
50
+ }
51
+
52
+ prune(currentEpoch: Epoch): void {
53
+ this.lowestPermissibleEpoch = Math.max(currentEpoch - EPOCH_LOOKBACK_LIMIT, 0);
54
+ for (const epoch of this.bitsByEpoch.keys()) {
55
+ if (epoch < this.lowestPermissibleEpoch) {
56
+ this.bitsByEpoch.delete(epoch);
57
+ }
16
58
  }
17
59
  }
18
60
  }