@lodestar/builder 1.50.0-dev.1f38fe79fb → 1.50.0-dev.20062ed60e

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 (42) hide show
  1. package/README.md +1 -1
  2. package/lib/builder.d.ts +7 -0
  3. package/lib/builder.d.ts.map +1 -1
  4. package/lib/builder.js +79 -4
  5. package/lib/builder.js.map +1 -1
  6. package/lib/services/bidLedger.d.ts +1 -0
  7. package/lib/services/bidLedger.d.ts.map +1 -1
  8. package/lib/services/bidLedger.js +4 -0
  9. package/lib/services/bidLedger.js.map +1 -1
  10. package/lib/services/bidSelector.d.ts +67 -0
  11. package/lib/services/bidSelector.d.ts.map +1 -0
  12. package/lib/services/bidSelector.js +59 -0
  13. package/lib/services/bidSelector.js.map +1 -0
  14. package/lib/services/blockObserver.d.ts +1 -2
  15. package/lib/services/blockObserver.d.ts.map +1 -1
  16. package/lib/services/blockObserver.js +3 -35
  17. package/lib/services/blockObserver.js.map +1 -1
  18. package/lib/services/envelopePublisher.d.ts +44 -0
  19. package/lib/services/envelopePublisher.d.ts.map +1 -0
  20. package/lib/services/envelopePublisher.js +96 -0
  21. package/lib/services/envelopePublisher.js.map +1 -0
  22. package/lib/services/executionPayloadEnvelope.d.ts +55 -0
  23. package/lib/services/executionPayloadEnvelope.d.ts.map +1 -0
  24. package/lib/services/executionPayloadEnvelope.js +79 -0
  25. package/lib/services/executionPayloadEnvelope.js.map +1 -0
  26. package/lib/services/payloadOrchestrator.d.ts +42 -0
  27. package/lib/services/payloadOrchestrator.d.ts.map +1 -0
  28. package/lib/services/payloadOrchestrator.js +60 -0
  29. package/lib/services/payloadOrchestrator.js.map +1 -0
  30. package/lib/services/proposerPreferencesTracker.d.ts +0 -6
  31. package/lib/services/proposerPreferencesTracker.d.ts.map +1 -1
  32. package/lib/services/proposerPreferencesTracker.js +0 -38
  33. package/lib/services/proposerPreferencesTracker.js.map +1 -1
  34. package/package.json +11 -11
  35. package/src/builder.ts +91 -5
  36. package/src/services/bidLedger.ts +5 -0
  37. package/src/services/bidSelector.ts +138 -0
  38. package/src/services/blockObserver.ts +3 -41
  39. package/src/services/envelopePublisher.ts +154 -0
  40. package/src/services/executionPayloadEnvelope.ts +156 -0
  41. package/src/services/payloadOrchestrator.ts +107 -0
  42. package/src/services/proposerPreferencesTracker.ts +1 -36
@@ -0,0 +1,138 @@
1
+ import type {ChainForkConfig} from "@lodestar/config";
2
+ import type {ForkPostGloas} from "@lodestar/params";
3
+ import type {BuilderIndex, RootHex, SignedBeaconBlock, Slot} from "@lodestar/types";
4
+ import {sszTypesFor} from "@lodestar/types";
5
+ import {LodestarError, toRootHex} from "@lodestar/utils";
6
+ import type {BidIdentity, BidLedger, BidLedgerRecord} from "./bidLedger.js";
7
+
8
+ export type ObservedPostGloasBlock = {
9
+ blockRoot: RootHex;
10
+ slot: Slot;
11
+ version: ForkPostGloas;
12
+ block: SignedBeaconBlock<ForkPostGloas>;
13
+ };
14
+
15
+ export type BidSelectorModules = {
16
+ config: ChainForkConfig;
17
+ ledger: BidLedger;
18
+ builderIndex: BuilderIndex;
19
+ };
20
+
21
+ export enum BidSelectionIgnoreReason {
22
+ FOREIGN_BUILDER = "foreign_builder",
23
+ }
24
+
25
+ export type BidSelectionResult =
26
+ | {
27
+ status: "selected";
28
+ blockRoot: RootHex;
29
+ bid: BidLedgerRecord;
30
+ }
31
+ | {
32
+ status: "ignored";
33
+ reason: BidSelectionIgnoreReason;
34
+ };
35
+
36
+ export enum BidSelectorErrorCode {
37
+ BLOCK_ROOT_MISMATCH = "BID_SELECTOR_ERROR_BLOCK_ROOT_MISMATCH",
38
+ BLOCK_SLOT_MISMATCH = "BID_SELECTOR_ERROR_BLOCK_SLOT_MISMATCH",
39
+ BLOCK_FORK_MISMATCH = "BID_SELECTOR_ERROR_BLOCK_FORK_MISMATCH",
40
+ BID_SLOT_MISMATCH = "BID_SELECTOR_ERROR_BID_SLOT_MISMATCH",
41
+ UNKNOWN_BID = "BID_SELECTOR_ERROR_UNKNOWN_BID",
42
+ }
43
+
44
+ export type BidSelectorErrorType =
45
+ | {
46
+ code: BidSelectorErrorCode.BLOCK_ROOT_MISMATCH;
47
+ blockRoot: RootHex;
48
+ computedBlockRoot: RootHex;
49
+ }
50
+ | {
51
+ code: BidSelectorErrorCode.BLOCK_SLOT_MISMATCH;
52
+ slot: Slot;
53
+ blockSlot: Slot;
54
+ }
55
+ | {
56
+ code: BidSelectorErrorCode.BLOCK_FORK_MISMATCH;
57
+ version: ForkPostGloas;
58
+ blockFork: string;
59
+ }
60
+ | {
61
+ code: BidSelectorErrorCode.BID_SLOT_MISMATCH;
62
+ slot: Slot;
63
+ bidSlot: Slot;
64
+ }
65
+ | {
66
+ code: BidSelectorErrorCode.UNKNOWN_BID;
67
+ slot: Slot;
68
+ parentBlockHash: RootHex;
69
+ parentBlockRoot: RootHex;
70
+ blockHash: RootHex;
71
+ signedBidRoot: RootHex;
72
+ };
73
+
74
+ export class BidSelectorError extends LodestarError<BidSelectorErrorType> {}
75
+
76
+ /** Matches an imported post-Gloas block to an exact local bid and records the win. */
77
+ export class BidSelector {
78
+ constructor(private readonly modules: BidSelectorModules) {}
79
+
80
+ match(observed: ObservedPostGloasBlock): BidSelectionResult {
81
+ const {block, blockRoot, slot, version} = observed;
82
+ const {builderIndex, config, ledger} = this.modules;
83
+ const blockSlot = block.message.slot;
84
+
85
+ if (blockSlot !== slot) {
86
+ throw new BidSelectorError(
87
+ {code: BidSelectorErrorCode.BLOCK_SLOT_MISMATCH, slot, blockSlot},
88
+ `Observed block slot does not match fetched block slot=${slot} blockSlot=${blockSlot}`
89
+ );
90
+ }
91
+
92
+ const blockFork = config.getForkName(slot);
93
+ if (blockFork !== version) {
94
+ throw new BidSelectorError(
95
+ {code: BidSelectorErrorCode.BLOCK_FORK_MISMATCH, version, blockFork},
96
+ `Observed block fork does not match configured fork version=${version} blockFork=${blockFork}`
97
+ );
98
+ }
99
+
100
+ const computedBlockRoot = toRootHex(config.getForkTypes(slot).BeaconBlock.hashTreeRoot(block.message));
101
+ if (computedBlockRoot !== blockRoot) {
102
+ throw new BidSelectorError(
103
+ {code: BidSelectorErrorCode.BLOCK_ROOT_MISMATCH, blockRoot, computedBlockRoot},
104
+ `Observed block root does not match fetched block blockRoot=${blockRoot} computedBlockRoot=${computedBlockRoot}`
105
+ );
106
+ }
107
+
108
+ const bid = block.message.body.signedExecutionPayloadBid.message;
109
+ if (bid.slot !== slot) {
110
+ throw new BidSelectorError(
111
+ {code: BidSelectorErrorCode.BID_SLOT_MISMATCH, slot, bidSlot: bid.slot},
112
+ `Selected bid slot does not match block slot=${slot} bidSlot=${bid.slot}`
113
+ );
114
+ }
115
+ if (bid.builderIndex !== builderIndex) {
116
+ return {status: "ignored", reason: BidSelectionIgnoreReason.FOREIGN_BUILDER};
117
+ }
118
+
119
+ const identity: BidIdentity = {
120
+ slot,
121
+ parentBlockHash: toRootHex(bid.parentBlockHash),
122
+ parentBlockRoot: toRootHex(bid.parentBlockRoot),
123
+ blockHash: toRootHex(bid.blockHash),
124
+ };
125
+ const signedBidRoot = toRootHex(
126
+ sszTypesFor(version, "SignedExecutionPayloadBid").hashTreeRoot(block.message.body.signedExecutionPayloadBid)
127
+ );
128
+ const localBid = ledger.recordWin({...identity, signedBidRoot}, blockRoot);
129
+ if (localBid === null) {
130
+ throw new BidSelectorError(
131
+ {code: BidSelectorErrorCode.UNKNOWN_BID, ...identity, signedBidRoot},
132
+ `Selected bid is not in the local ledger slot=${slot} blockHash=${identity.blockHash} signedBidRoot=${signedBidRoot}`
133
+ );
134
+ }
135
+
136
+ return {status: "selected", blockRoot, bid: localBid};
137
+ }
138
+ }
@@ -47,55 +47,17 @@ export class BlockObserver {
47
47
  this.retries = retries;
48
48
  this.retryDelay = retryDelay;
49
49
  this.maxSeenBlockRoots = maxSeenBlockRoots;
50
+ this.logger.info("Block observer initialized", {retries, retryDelay, maxSeenBlockRoots});
50
51
  }
51
52
 
52
53
  /**
53
- * Register a block consumer. Consumers that require complete observation must register before {@link start}, because
54
+ * Register a block consumer. Consumers that require complete observation must register before event delivery, because
54
55
  * roots observed before registration remain consumed until normal FIFO eviction.
55
56
  */
56
57
  runOnBlock(fn: RunOnBlockFn): void {
57
58
  this.fns.push(fn);
58
59
  }
59
60
 
60
- start(signal: AbortSignal): void {
61
- this.logger.info("Subscribing to block events", {
62
- retries: this.retries,
63
- retryDelay: this.retryDelay,
64
- maxSeenBlockRoots: this.maxSeenBlockRoots,
65
- });
66
-
67
- this.api.events
68
- .eventstream({
69
- topics: [EventType.block],
70
- signal,
71
- onEvent: (event) => {
72
- if (event.type !== EventType.block) {
73
- this.logger.debug("Ignoring unexpected beacon event", {eventType: event.type});
74
- return;
75
- }
76
-
77
- void this.processBlockEvent(event.message, signal);
78
- },
79
- onError: (error) => {
80
- this.logger.error("Failed to receive block event", {}, error);
81
- },
82
- onClose: () => {
83
- if (signal.aborted) {
84
- this.logger.debug("Closed stream for block events");
85
- } else {
86
- this.logger.error("Block event stream closed unexpectedly", {});
87
- }
88
- },
89
- })
90
- .catch((error: unknown) => {
91
- this.logger.error(
92
- "Failed to subscribe to block events",
93
- {},
94
- error instanceof Error ? error : Error(String(error))
95
- );
96
- });
97
- }
98
-
99
61
  async processBlockEvent(event: BlockEvent, signal: AbortSignal): Promise<void> {
100
62
  try {
101
63
  const {slot, block: blockRoot, executionOptimistic} = event;
@@ -145,7 +107,7 @@ export class BlockObserver {
145
107
  return null;
146
108
  });
147
109
 
148
- if (response === null) {
110
+ if (response === null || signal.aborted) {
149
111
  return;
150
112
  }
151
113
 
@@ -0,0 +1,154 @@
1
+ import {type ApiClient, routes} from "@lodestar/api";
2
+ import {type BuilderIndex, type RootHex, type gloas, ssz} from "@lodestar/types";
3
+ import {LodestarError, defer, toRootHex} from "@lodestar/utils";
4
+ import type {BidIdentity, BidLedger} from "./bidLedger.js";
5
+ import type {BuilderSigner} from "./builderSigner.js";
6
+ import type {ExecutionPayloadEnvelopeContents} from "./executionPayloadEnvelope.js";
7
+
8
+ export type EnvelopeSelectionIdentity = BidIdentity & {blockRoot: RootHex};
9
+
10
+ export type EnvelopePublisherModules = {
11
+ api: ApiClient;
12
+ signer: BuilderSigner;
13
+ ledger: BidLedger;
14
+ builderIndex: BuilderIndex;
15
+ };
16
+
17
+ export enum EnvelopePublisherErrorCode {
18
+ BUILDER_INDEX_MISMATCH = "ENVELOPE_PUBLISHER_ERROR_BUILDER_INDEX_MISMATCH",
19
+ SELECTION_NOT_RECORDED = "ENVELOPE_PUBLISHER_ERROR_SELECTION_NOT_RECORDED",
20
+ }
21
+
22
+ export type EnvelopePublisherErrorType =
23
+ | {
24
+ code: EnvelopePublisherErrorCode.BUILDER_INDEX_MISMATCH;
25
+ builderIndex: BuilderIndex;
26
+ envelopeBuilderIndex: BuilderIndex;
27
+ }
28
+ | ({code: EnvelopePublisherErrorCode.SELECTION_NOT_RECORDED} & EnvelopeSelectionIdentity);
29
+
30
+ export class EnvelopePublisherError extends LodestarError<EnvelopePublisherErrorType> {}
31
+
32
+ export type EnvelopePublicationResult =
33
+ | {status: "published"; signedEnvelope: gloas.SignedExecutionPayloadEnvelope}
34
+ | {status: "duplicate"};
35
+
36
+ type ActivePublication = {
37
+ controller: AbortController;
38
+ promise: Promise<EnvelopePublicationResult>;
39
+ waiters: number;
40
+ };
41
+
42
+ /** Signs and submits an envelope for a recorded local selection. */
43
+ export class EnvelopePublisher {
44
+ private readonly activePublications = new Map<RootHex, ActivePublication>();
45
+
46
+ constructor(private readonly modules: EnvelopePublisherModules) {}
47
+
48
+ async publish(contents: ExecutionPayloadEnvelopeContents, signal: AbortSignal): Promise<EnvelopePublicationResult> {
49
+ signal.throwIfAborted();
50
+
51
+ const {api, builderIndex, ledger, signer} = this.modules;
52
+ const {envelope} = contents;
53
+ if (envelope.builderIndex !== builderIndex) {
54
+ throw new EnvelopePublisherError(
55
+ {
56
+ code: EnvelopePublisherErrorCode.BUILDER_INDEX_MISMATCH,
57
+ builderIndex,
58
+ envelopeBuilderIndex: envelope.builderIndex,
59
+ },
60
+ `Envelope builder index does not match local builder index builderIndex=${builderIndex} envelopeBuilderIndex=${envelope.builderIndex}`
61
+ );
62
+ }
63
+
64
+ const identity: EnvelopeSelectionIdentity = {
65
+ slot: envelope.payload.slotNumber,
66
+ parentBlockHash: toRootHex(envelope.payload.parentHash),
67
+ parentBlockRoot: toRootHex(envelope.parentBeaconBlockRoot),
68
+ blockHash: toRootHex(envelope.payload.blockHash),
69
+ blockRoot: toRootHex(envelope.beaconBlockRoot),
70
+ };
71
+ if (!ledger.hasWon(identity, identity.blockRoot)) {
72
+ throw new EnvelopePublisherError(
73
+ {code: EnvelopePublisherErrorCode.SELECTION_NOT_RECORDED, ...identity},
74
+ `Envelope selection is not recorded slot=${identity.slot} blockRoot=${identity.blockRoot} blockHash=${identity.blockHash}`
75
+ );
76
+ }
77
+
78
+ const envelopeRoot = toRootHex(ssz.gloas.ExecutionPayloadEnvelope.hashTreeRoot(envelope));
79
+ ledger.recordReveal(identity.slot, identity.blockRoot, identity.blockHash, envelopeRoot);
80
+ if (ledger.hasPublishedReveal(identity.blockRoot)) {
81
+ return {status: "duplicate"};
82
+ }
83
+
84
+ let publication = this.activePublications.get(identity.blockRoot);
85
+ if (publication === undefined) {
86
+ const controller = new AbortController();
87
+ publication = {
88
+ controller,
89
+ waiters: 0,
90
+ promise: this.publishEnvelope(contents, identity, envelopeRoot, api, ledger, signer, controller.signal).finally(
91
+ () => {
92
+ if (this.activePublications.get(identity.blockRoot)?.controller === controller) {
93
+ this.activePublications.delete(identity.blockRoot);
94
+ }
95
+ }
96
+ ),
97
+ };
98
+ this.activePublications.set(identity.blockRoot, publication);
99
+ }
100
+ return this.waitForPublication(identity.blockRoot, publication, signal);
101
+ }
102
+
103
+ private async waitForPublication(
104
+ blockRoot: RootHex,
105
+ publication: ActivePublication,
106
+ signal: AbortSignal
107
+ ): Promise<EnvelopePublicationResult> {
108
+ const aborted = defer<never>();
109
+ const onAbort = (): void => aborted.reject(signal.reason);
110
+ publication.waiters++;
111
+ signal.addEventListener("abort", onAbort, {once: true});
112
+ if (signal.aborted) onAbort();
113
+
114
+ try {
115
+ return await Promise.race([publication.promise, aborted.promise]);
116
+ } finally {
117
+ signal.removeEventListener("abort", onAbort);
118
+ publication.waiters--;
119
+ if (publication.waiters === 0 && signal.aborted) {
120
+ if (this.activePublications.get(blockRoot) === publication) {
121
+ this.activePublications.delete(blockRoot);
122
+ }
123
+ publication.controller.abort(signal.reason);
124
+ }
125
+ }
126
+ }
127
+
128
+ private async publishEnvelope(
129
+ contents: ExecutionPayloadEnvelopeContents,
130
+ identity: EnvelopeSelectionIdentity,
131
+ envelopeRoot: RootHex,
132
+ api: ApiClient,
133
+ ledger: BidLedger,
134
+ signer: BuilderSigner,
135
+ signal: AbortSignal
136
+ ): Promise<EnvelopePublicationResult> {
137
+ const signedEnvelope = signer.signExecutionPayloadEnvelope(contents.envelope);
138
+
139
+ const response = await api.beacon.publishExecutionPayloadEnvelope(
140
+ {
141
+ signedEnvelopeOrContents: {
142
+ signedExecutionPayloadEnvelope: signedEnvelope,
143
+ kzgProofs: contents.kzgProofs,
144
+ blobs: contents.blobs,
145
+ },
146
+ broadcastValidation: routes.beacon.BroadcastValidation.gossip,
147
+ },
148
+ {signal}
149
+ );
150
+ response.assertOk();
151
+ ledger.recordRevealPublished(identity.slot, identity.blockRoot, identity.blockHash, envelopeRoot);
152
+ return {status: "published", signedEnvelope};
153
+ }
154
+ }
@@ -0,0 +1,156 @@
1
+ import type {BuilderIndex, RootHex, Slot, deneb, gloas} from "@lodestar/types";
2
+ import {ssz} from "@lodestar/types";
3
+ import {LodestarError, byteArrayEquals, fromHex, toRootHex} from "@lodestar/utils";
4
+ import type {StoredPayload} from "./payloadStore.js";
5
+
6
+ export type ExecutionPayloadEnvelopeInput = {
7
+ blockRoot: RootHex;
8
+ builderIndex: BuilderIndex;
9
+ selectedBid: gloas.ExecutionPayloadBid;
10
+ storedPayload: StoredPayload;
11
+ };
12
+
13
+ export type ExecutionPayloadEnvelopeContents = {
14
+ envelope: gloas.ExecutionPayloadEnvelope;
15
+ kzgProofs: deneb.KZGProofs;
16
+ blobs: deneb.Blobs;
17
+ };
18
+
19
+ export enum ExecutionPayloadEnvelopeErrorCode {
20
+ SLOT_MISMATCH = "EXECUTION_PAYLOAD_ENVELOPE_ERROR_SLOT_MISMATCH",
21
+ PARENT_BLOCK_ROOT_MISMATCH = "EXECUTION_PAYLOAD_ENVELOPE_ERROR_PARENT_BLOCK_ROOT_MISMATCH",
22
+ PARENT_BLOCK_HASH_MISMATCH = "EXECUTION_PAYLOAD_ENVELOPE_ERROR_PARENT_BLOCK_HASH_MISMATCH",
23
+ BLOCK_HASH_MISMATCH = "EXECUTION_PAYLOAD_ENVELOPE_ERROR_BLOCK_HASH_MISMATCH",
24
+ BUILDER_INDEX_MISMATCH = "EXECUTION_PAYLOAD_ENVELOPE_ERROR_BUILDER_INDEX_MISMATCH",
25
+ BLOB_KZG_COMMITMENTS_MISMATCH = "EXECUTION_PAYLOAD_ENVELOPE_ERROR_BLOB_KZG_COMMITMENTS_MISMATCH",
26
+ EXECUTION_REQUESTS_ROOT_MISMATCH = "EXECUTION_PAYLOAD_ENVELOPE_ERROR_EXECUTION_REQUESTS_ROOT_MISMATCH",
27
+ }
28
+
29
+ export type ExecutionPayloadEnvelopeErrorType =
30
+ | {
31
+ code: ExecutionPayloadEnvelopeErrorCode.BUILDER_INDEX_MISMATCH;
32
+ builderIndex: BuilderIndex;
33
+ bidBuilderIndex: BuilderIndex;
34
+ }
35
+ | {code: ExecutionPayloadEnvelopeErrorCode.BLOB_KZG_COMMITMENTS_MISMATCH}
36
+ | {
37
+ code: ExecutionPayloadEnvelopeErrorCode.EXECUTION_REQUESTS_ROOT_MISMATCH;
38
+ bidExecutionRequestsRoot: RootHex;
39
+ payloadExecutionRequestsRoot: RootHex;
40
+ }
41
+ | {
42
+ code: ExecutionPayloadEnvelopeErrorCode.PARENT_BLOCK_ROOT_MISMATCH;
43
+ bidParentBlockRoot: RootHex;
44
+ storedParentBlockRoot: RootHex;
45
+ }
46
+ | {
47
+ code: ExecutionPayloadEnvelopeErrorCode.SLOT_MISMATCH;
48
+ bidSlot: Slot;
49
+ payloadSlot: Slot;
50
+ }
51
+ | {
52
+ code: ExecutionPayloadEnvelopeErrorCode.PARENT_BLOCK_HASH_MISMATCH;
53
+ bidParentBlockHash: RootHex;
54
+ payloadParentBlockHash: RootHex;
55
+ }
56
+ | {
57
+ code: ExecutionPayloadEnvelopeErrorCode.BLOCK_HASH_MISMATCH;
58
+ bidBlockHash: RootHex;
59
+ payloadBlockHash: RootHex;
60
+ };
61
+
62
+ export class ExecutionPayloadEnvelopeError extends LodestarError<ExecutionPayloadEnvelopeErrorType> {}
63
+
64
+ /** The caller must have matched the selected bid to its local ledger record. */
65
+ export function createExecutionPayloadEnvelopeContents({
66
+ blockRoot,
67
+ builderIndex,
68
+ selectedBid,
69
+ storedPayload,
70
+ }: ExecutionPayloadEnvelopeInput): ExecutionPayloadEnvelopeContents {
71
+ if (builderIndex !== selectedBid.builderIndex) {
72
+ throw new ExecutionPayloadEnvelopeError({
73
+ code: ExecutionPayloadEnvelopeErrorCode.BUILDER_INDEX_MISMATCH,
74
+ builderIndex,
75
+ bidBuilderIndex: selectedBid.builderIndex,
76
+ });
77
+ }
78
+
79
+ const bidParentBlockRoot = toRootHex(selectedBid.parentBlockRoot);
80
+ const storedParentBlockRoot = toRootHex(storedPayload.parentBlockRoot);
81
+ if (storedParentBlockRoot !== bidParentBlockRoot) {
82
+ throw new ExecutionPayloadEnvelopeError(
83
+ {
84
+ code: ExecutionPayloadEnvelopeErrorCode.PARENT_BLOCK_ROOT_MISMATCH,
85
+ bidParentBlockRoot,
86
+ storedParentBlockRoot,
87
+ },
88
+ `Selected bid beacon parent does not match retained payload bidParentBlockRoot=${bidParentBlockRoot} storedParentBlockRoot=${storedParentBlockRoot}`
89
+ );
90
+ }
91
+
92
+ const {payload} = storedPayload;
93
+ const payloadSlot = payload.executionPayload.slotNumber;
94
+ if (payloadSlot !== selectedBid.slot) {
95
+ throw new ExecutionPayloadEnvelopeError(
96
+ {code: ExecutionPayloadEnvelopeErrorCode.SLOT_MISMATCH, bidSlot: selectedBid.slot, payloadSlot},
97
+ `Selected bid slot does not match payload slot bidSlot=${selectedBid.slot} payloadSlot=${payloadSlot}`
98
+ );
99
+ }
100
+
101
+ const payloadParentBlockHash = toRootHex(payload.executionPayload.parentHash);
102
+ const bidParentBlockHash = toRootHex(selectedBid.parentBlockHash);
103
+ if (payloadParentBlockHash !== bidParentBlockHash) {
104
+ throw new ExecutionPayloadEnvelopeError(
105
+ {
106
+ code: ExecutionPayloadEnvelopeErrorCode.PARENT_BLOCK_HASH_MISMATCH,
107
+ bidParentBlockHash,
108
+ payloadParentBlockHash,
109
+ },
110
+ `Selected bid parent does not match payload parent bidParentBlockHash=${bidParentBlockHash} payloadParentBlockHash=${payloadParentBlockHash}`
111
+ );
112
+ }
113
+
114
+ const payloadBlockHash = toRootHex(payload.executionPayload.blockHash);
115
+ const bidBlockHash = toRootHex(selectedBid.blockHash);
116
+ if (payloadBlockHash !== bidBlockHash) {
117
+ throw new ExecutionPayloadEnvelopeError(
118
+ {
119
+ code: ExecutionPayloadEnvelopeErrorCode.BLOCK_HASH_MISMATCH,
120
+ bidBlockHash,
121
+ payloadBlockHash,
122
+ },
123
+ `Selected bid block hash does not match payload bidBlockHash=${bidBlockHash} payloadBlockHash=${payloadBlockHash}`
124
+ );
125
+ }
126
+
127
+ if (
128
+ !ssz.gloas.ExecutionPayloadBid.fields.blobKzgCommitments.equals(
129
+ selectedBid.blobKzgCommitments,
130
+ payload.blobsBundle.commitments
131
+ )
132
+ ) {
133
+ throw new ExecutionPayloadEnvelopeError({code: ExecutionPayloadEnvelopeErrorCode.BLOB_KZG_COMMITMENTS_MISMATCH});
134
+ }
135
+
136
+ const executionRequestsRoot = ssz.gloas.ExecutionRequests.hashTreeRoot(payload.executionRequests);
137
+ if (!byteArrayEquals(executionRequestsRoot, selectedBid.executionRequestsRoot)) {
138
+ throw new ExecutionPayloadEnvelopeError({
139
+ code: ExecutionPayloadEnvelopeErrorCode.EXECUTION_REQUESTS_ROOT_MISMATCH,
140
+ bidExecutionRequestsRoot: toRootHex(selectedBid.executionRequestsRoot),
141
+ payloadExecutionRequestsRoot: toRootHex(executionRequestsRoot),
142
+ });
143
+ }
144
+
145
+ return {
146
+ envelope: {
147
+ payload: payload.executionPayload,
148
+ executionRequests: payload.executionRequests,
149
+ builderIndex,
150
+ beaconBlockRoot: fromHex(blockRoot),
151
+ parentBeaconBlockRoot: selectedBid.parentBlockRoot,
152
+ },
153
+ kzgProofs: payload.blobsBundle.proofs,
154
+ blobs: payload.blobsBundle.blobs,
155
+ };
156
+ }
@@ -0,0 +1,107 @@
1
+ import {LodestarError, TimeoutError, retry, sleep, withTimeout} from "@lodestar/utils";
2
+ import {
3
+ type BuildRequest,
4
+ type BuiltPayload,
5
+ type PayloadSource,
6
+ PayloadSourceError,
7
+ PayloadSourceErrorCode,
8
+ } from "./payloadSource.js";
9
+
10
+ const PREPARE_RETRY_DELAY = 100;
11
+
12
+ export type PayloadBuildJob = {
13
+ /** Jobs with the same ID share one build and its result. */
14
+ id: string;
15
+ request: BuildRequest;
16
+ /** Unix timestamp in milliseconds at which the prepared payload should be retrieved. */
17
+ getPayloadAt: number;
18
+ };
19
+
20
+ export type PayloadOrchestratorOptions = {
21
+ /** Maximum time in milliseconds to wait for payload retrieval. */
22
+ getPayloadTimeout: number;
23
+ };
24
+
25
+ export enum PayloadOrchestratorErrorCode {
26
+ PREPARE_DEADLINE_REACHED = "PAYLOAD_ORCHESTRATOR_ERROR_PREPARE_DEADLINE_REACHED",
27
+ PREPARE_TIMEOUT = "PAYLOAD_ORCHESTRATOR_ERROR_PREPARE_TIMEOUT",
28
+ GET_PAYLOAD_TIMEOUT = "PAYLOAD_ORCHESTRATOR_ERROR_GET_PAYLOAD_TIMEOUT",
29
+ }
30
+
31
+ export type PayloadOrchestratorErrorType =
32
+ | {
33
+ code: PayloadOrchestratorErrorCode.PREPARE_DEADLINE_REACHED;
34
+ jobId: string;
35
+ getPayloadAt: number;
36
+ }
37
+ | {
38
+ code: PayloadOrchestratorErrorCode.PREPARE_TIMEOUT | PayloadOrchestratorErrorCode.GET_PAYLOAD_TIMEOUT;
39
+ jobId: string;
40
+ };
41
+
42
+ export class PayloadOrchestratorError extends LodestarError<PayloadOrchestratorErrorType> {}
43
+
44
+ /**
45
+ * Prepares a payload and retrieves it at the requested time. Preparation retries missing payload IDs until the
46
+ * retrieval time. Transport-level retries remain owned by the source.
47
+ */
48
+ export class PayloadOrchestrator {
49
+ private readonly jobs = new Map<string, Promise<BuiltPayload>>();
50
+
51
+ constructor(
52
+ private readonly source: PayloadSource,
53
+ private readonly options: PayloadOrchestratorOptions,
54
+ private readonly signal: AbortSignal
55
+ ) {}
56
+
57
+ run(job: PayloadBuildJob): Promise<BuiltPayload> {
58
+ const {id} = job;
59
+ let promise = this.jobs.get(id);
60
+ if (promise === undefined) {
61
+ promise = this.runJob(job).finally(() => this.jobs.delete(id));
62
+ this.jobs.set(id, promise);
63
+ }
64
+ return promise;
65
+ }
66
+
67
+ private async runJob({id, request, getPayloadAt}: PayloadBuildJob): Promise<BuiltPayload> {
68
+ const prepareTimeout = getPayloadAt - Date.now();
69
+ if (!(prepareTimeout > 0)) {
70
+ throw new PayloadOrchestratorError(
71
+ {code: PayloadOrchestratorErrorCode.PREPARE_DEADLINE_REACHED, jobId: id, getPayloadAt},
72
+ `Payload preparation deadline reached jobId=${id} getPayloadAt=${getPayloadAt}`
73
+ );
74
+ }
75
+
76
+ const handle = await withTimeout(
77
+ (signal = this.signal) =>
78
+ retry(() => this.source.prepare(request, signal), {
79
+ retries: Infinity,
80
+ retryDelay: PREPARE_RETRY_DELAY,
81
+ shouldRetry: (error) =>
82
+ error instanceof PayloadSourceError && error.type.code === PayloadSourceErrorCode.NO_PAYLOAD_ID,
83
+ signal,
84
+ }),
85
+ prepareTimeout,
86
+ this.signal
87
+ ).catch((error: unknown) => {
88
+ if (error instanceof TimeoutError) {
89
+ throw new PayloadOrchestratorError({code: PayloadOrchestratorErrorCode.PREPARE_TIMEOUT, jobId: id});
90
+ }
91
+ throw error;
92
+ });
93
+
94
+ await sleep(getPayloadAt - Date.now(), this.signal);
95
+
96
+ return withTimeout(
97
+ (signal = this.signal) => this.source.getPayload(handle, signal),
98
+ this.options.getPayloadTimeout,
99
+ this.signal
100
+ ).catch((error: unknown) => {
101
+ if (error instanceof TimeoutError) {
102
+ throw new PayloadOrchestratorError({code: PayloadOrchestratorErrorCode.GET_PAYLOAD_TIMEOUT, jobId: id});
103
+ }
104
+ throw error;
105
+ });
106
+ }
107
+ }
@@ -1,6 +1,5 @@
1
- import {ApiClient, routes} from "@lodestar/api";
2
1
  import type {RootHex, Slot, gloas} from "@lodestar/types";
3
- import {Logger, MapDef, toRootHex} from "@lodestar/utils";
2
+ import {MapDef, toRootHex} from "@lodestar/utils";
4
3
 
5
4
  /** Retains validated proposer preferences by the branch-specific identity used for bid validation. */
6
5
  export class ProposerPreferencesTracker {
@@ -8,40 +7,6 @@ export class ProposerPreferencesTracker {
8
7
  () => new Map()
9
8
  );
10
9
 
11
- constructor(
12
- private readonly api: ApiClient,
13
- private readonly logger: Logger
14
- ) {}
15
-
16
- start(signal: AbortSignal): void {
17
- if (signal.aborted) return;
18
-
19
- this.logger.verbose("Subscribing to proposer preferences");
20
- this.api.events
21
- .eventstream({
22
- topics: [routes.events.EventType.proposerPreferences],
23
- signal,
24
- onEvent: (event) => {
25
- if (!signal.aborted && event.type === routes.events.EventType.proposerPreferences) {
26
- this.onProposerPreferences(event.message.data);
27
- }
28
- },
29
- onError: (error) => {
30
- if (!signal.aborted) this.logger.error("Failed to receive proposer preferences", {}, error);
31
- },
32
- onClose: () => {
33
- if (signal.aborted) {
34
- this.logger.verbose("Closed proposer preferences stream");
35
- } else {
36
- this.logger.error("Proposer preferences stream closed unexpectedly", {});
37
- }
38
- },
39
- })
40
- .catch((error: Error) => {
41
- if (!signal.aborted) this.logger.error("Failed to subscribe to proposer preferences", {}, error);
42
- });
43
- }
44
-
45
10
  onProposerPreferences(signedProposerPreferences: gloas.SignedProposerPreferences): boolean {
46
11
  const {proposalSlot, dependentRoot} = signedProposerPreferences.message;
47
12
  const dependentRootHex = toRootHex(dependentRoot);