-
-
Notifications
You must be signed in to change notification settings - Fork 317
/
Copy pathproduceBlockBody.ts
668 lines (599 loc) Β· 23.2 KB
/
produceBlockBody.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
import {ChainForkConfig} from "@lodestar/config";
import {ForkExecution, ForkSeq, isForkExecution} from "@lodestar/params";
import {
CachedBeaconStateAllForks,
CachedBeaconStateBellatrix,
CachedBeaconStateCapella,
CachedBeaconStateExecutions,
computeEpochAtSlot,
computeTimeAtSlot,
getCurrentEpoch,
getExpectedWithdrawals,
getRandaoMix,
isMergeTransitionComplete,
} from "@lodestar/state-transition";
import {
BLSPubkey,
BLSSignature,
BeaconBlock,
BeaconBlockBody,
BlindedBeaconBlock,
BlindedBeaconBlockBody,
Bytes32,
ExecutionPayloadHeader,
Root,
RootHex,
SSEPayloadAttributes,
Slot,
ValidatorIndex,
Wei,
capella,
deneb,
electra,
ssz,
sszTypesFor,
} from "@lodestar/types";
import {Logger, sleep, toHex, toRootHex} from "@lodestar/utils";
import {ZERO_HASH, ZERO_HASH_HEX} from "../../constants/index.js";
import {IEth1ForBlockProduction} from "../../eth1/index.js";
import {numToQuantity} from "../../eth1/provider/utils.js";
import {IExecutionBuilder, IExecutionEngine, PayloadAttributes, PayloadId} from "../../execution/index.js";
import type {BeaconChain} from "../chain.js";
import {CommonBlockBody} from "../interface.js";
import {validateBlobsAndKzgCommitments} from "./validateBlobsAndKzgCommitments.js";
// Time to provide the EL to generate a payload from new payload id
const PAYLOAD_GENERATION_TIME_MS = 500;
export enum PayloadPreparationType {
Fresh = "Fresh",
Cached = "Cached",
Reorged = "Reorged",
Blinded = "Blinded",
}
/**
* Block production steps tracked in metrics
*/
export enum BlockProductionStep {
proposerSlashing = "proposerSlashing",
attesterSlashings = "attesterSlashings",
voluntaryExits = "voluntaryExits",
blsToExecutionChanges = "blsToExecutionChanges",
attestations = "attestations",
eth1DataAndDeposits = "eth1DataAndDeposits",
syncAggregate = "syncAggregate",
executionPayload = "executionPayload",
}
export type BlockAttributes = {
randaoReveal: BLSSignature;
graffiti: Bytes32;
slot: Slot;
parentBlockRoot: Root;
feeRecipient?: string;
};
export enum BlockType {
Full = "Full",
Blinded = "Blinded",
}
export type AssembledBodyType<T extends BlockType> = T extends BlockType.Full
? BeaconBlockBody
: BlindedBeaconBlockBody;
export type AssembledBlockType<T extends BlockType> = T extends BlockType.Full ? BeaconBlock : BlindedBeaconBlock;
export enum BlobsResultType {
preDeneb,
produced,
blinded,
}
export type BlobsResult =
| {type: BlobsResultType.preDeneb}
| {type: BlobsResultType.produced; contents: deneb.Contents; blockHash: RootHex}
| {type: BlobsResultType.blinded};
export async function produceBlockBody<T extends BlockType>(
this: BeaconChain,
blockType: T,
currentState: CachedBeaconStateAllForks,
blockAttr: BlockAttributes & {
parentSlot: Slot;
proposerIndex: ValidatorIndex;
proposerPubKey: BLSPubkey;
commonBlockBody?: CommonBlockBody;
}
): Promise<{
body: AssembledBodyType<T>;
blobs: BlobsResult;
executionPayloadValue: Wei;
shouldOverrideBuilder?: boolean;
}> {
const {
slot: blockSlot,
feeRecipient: requestedFeeRecipient,
parentBlockRoot,
proposerIndex,
proposerPubKey,
commonBlockBody,
} = blockAttr;
// Type-safe for blobs variable. Translate 'null' value into 'preDeneb' enum
// TODO: Not ideal, but better than just using null.
// TODO: Does not guarantee that preDeneb enum goes with a preDeneb block
let blobsResult: BlobsResult;
let executionPayloadValue: Wei;
// even though shouldOverrideBuilder is relevant for the engine response, for simplicity of typing
// we just return it undefined for the builder which anyway doesn't get consumed downstream
let shouldOverrideBuilder: boolean | undefined;
const fork = currentState.config.getForkName(blockSlot);
const logMeta: Record<string, string | number | bigint> = {
fork,
blockType,
slot: blockSlot,
};
this.logger.verbose("Producing beacon block body", logMeta);
const stepsMetrics =
blockType === BlockType.Full
? this.metrics?.executionBlockProductionTimeSteps
: this.metrics?.builderBlockProductionTimeSteps;
const blockBody = commonBlockBody
? Object.assign({}, commonBlockBody)
: await produceCommonBlockBody.call(this, blockType, currentState, blockAttr);
const {attestations, deposits, voluntaryExits, attesterSlashings, proposerSlashings, blsToExecutionChanges} =
blockBody;
Object.assign(logMeta, {
attestations: attestations.length,
deposits: deposits.length,
voluntaryExits: voluntaryExits.length,
attesterSlashings: attesterSlashings.length,
proposerSlashings: proposerSlashings.length,
});
const endExecutionPayload = stepsMetrics?.startTimer();
if (isForkExecution(fork)) {
const safeBlockHash = this.forkChoice.getJustifiedBlock().executionPayloadBlockHash ?? ZERO_HASH_HEX;
const finalizedBlockHash = this.forkChoice.getFinalizedBlock().executionPayloadBlockHash ?? ZERO_HASH_HEX;
const feeRecipient = requestedFeeRecipient ?? this.beaconProposerCache.getOrDefault(proposerIndex);
const feeRecipientType = requestedFeeRecipient
? "requested"
: this.beaconProposerCache.get(proposerIndex)
? "cached"
: "default";
Object.assign(logMeta, {feeRecipientType, feeRecipient});
if (blockType === BlockType.Blinded) {
if (!this.executionBuilder) throw Error("Execution Builder not available");
// This path will not be used in the production, but is here just for merge mock
// tests because merge-mock requires an fcU to be issued prior to fetch payload
// header.
if (this.executionBuilder.issueLocalFcUWithFeeRecipient !== undefined) {
await prepareExecutionPayload(
this,
this.logger,
fork,
parentBlockRoot,
safeBlockHash,
finalizedBlockHash ?? ZERO_HASH_HEX,
currentState as CachedBeaconStateBellatrix,
this.executionBuilder.issueLocalFcUWithFeeRecipient
);
}
// For MeV boost integration, this is where the execution header will be
// fetched from the payload id and a blinded block will be produced instead of
// fullblock for the validator to sign
const builderRes = await prepareExecutionPayloadHeader(
this,
fork,
currentState as CachedBeaconStateBellatrix,
proposerPubKey
);
(blockBody as BlindedBeaconBlockBody).executionPayloadHeader = builderRes.header;
executionPayloadValue = builderRes.executionPayloadValue;
const fetchedTime = Date.now() / 1000 - computeTimeAtSlot(this.config, blockSlot, this.genesisTime);
const prepType = PayloadPreparationType.Blinded;
this.metrics?.blockPayload.payloadFetchedTime.observe({prepType}, fetchedTime);
this.logger.verbose("Fetched execution payload header from builder", {
slot: blockSlot,
executionPayloadValue,
prepType,
fetchedTime,
});
if (ForkSeq[fork] >= ForkSeq.deneb) {
const {blobKzgCommitments} = builderRes;
if (blobKzgCommitments === undefined) {
throw Error(`Invalid builder getHeader response for fork=${fork}, missing blobKzgCommitments`);
}
(blockBody as deneb.BlindedBeaconBlockBody).blobKzgCommitments = blobKzgCommitments;
blobsResult = {type: BlobsResultType.blinded};
Object.assign(logMeta, {blobs: blobKzgCommitments.length});
} else {
blobsResult = {type: BlobsResultType.preDeneb};
}
if (ForkSeq[fork] >= ForkSeq.electra) {
const {executionRequests} = builderRes;
if (executionRequests === undefined) {
throw Error(`Invalid builder getHeader response for fork=${fork}, missing executionRequests`);
}
(blockBody as electra.BlindedBeaconBlockBody).executionRequests = executionRequests;
}
}
// blockType === BlockType.Full
else {
// try catch payload fetch here, because there is still a recovery path possible if we
// are pre-merge. We don't care the same for builder segment as the execution block
// will takeover if the builder flow was activated and errors
try {
// https://github.com/ethereum/consensus-specs/blob/dev/specs/eip4844/validator.md#constructing-the-beaconblockbody
const prepareRes = await prepareExecutionPayload(
this,
this.logger,
fork,
parentBlockRoot,
safeBlockHash,
finalizedBlockHash ?? ZERO_HASH_HEX,
currentState as CachedBeaconStateExecutions,
feeRecipient
);
if (prepareRes.isPremerge) {
(blockBody as BeaconBlockBody<ForkExecution>).executionPayload =
sszTypesFor(fork).ExecutionPayload.defaultValue();
blobsResult = {type: BlobsResultType.preDeneb};
executionPayloadValue = BigInt(0);
} else {
const {prepType, payloadId} = prepareRes;
Object.assign(logMeta, {executionPayloadPrepType: prepType});
if (prepType !== PayloadPreparationType.Cached) {
// Wait for 500ms to allow EL to add some txs to the payload
// the pitfalls of this have been put forward here, but 500ms delay for block proposal
// seems marginal even with unhealthy network
//
// See: https://discord.com/channels/595666850260713488/892088344438255616/1009882079632314469
await sleep(PAYLOAD_GENERATION_TIME_MS);
}
const engineRes = await this.executionEngine.getPayload(fork, payloadId);
const {executionPayload, blobsBundle, executionRequests} = engineRes;
shouldOverrideBuilder = engineRes.shouldOverrideBuilder;
(blockBody as BeaconBlockBody<ForkExecution>).executionPayload = executionPayload;
executionPayloadValue = engineRes.executionPayloadValue;
Object.assign(logMeta, {transactions: executionPayload.transactions.length, shouldOverrideBuilder});
const fetchedTime = Date.now() / 1000 - computeTimeAtSlot(this.config, blockSlot, this.genesisTime);
this.metrics?.blockPayload.payloadFetchedTime.observe({prepType}, fetchedTime);
this.logger.verbose("Fetched execution payload from engine", {
slot: blockSlot,
executionPayloadValue,
prepType,
payloadId,
fetchedTime,
executionHeadBlockHash: toRootHex(engineRes.executionPayload.blockHash),
});
if (executionPayload.transactions.length === 0) {
this.metrics?.blockPayload.emptyPayloads.inc({prepType});
}
if (ForkSeq[fork] >= ForkSeq.deneb) {
if (blobsBundle === undefined) {
throw Error(`Missing blobsBundle response from getPayload at fork=${fork}`);
}
if (this.opts.sanityCheckExecutionEngineBlobs) {
validateBlobsAndKzgCommitments(executionPayload, blobsBundle);
}
(blockBody as deneb.BeaconBlockBody).blobKzgCommitments = blobsBundle.commitments;
const blockHash = toRootHex(executionPayload.blockHash);
const contents = {kzgProofs: blobsBundle.proofs, blobs: blobsBundle.blobs};
blobsResult = {type: BlobsResultType.produced, contents, blockHash};
Object.assign(logMeta, {blobs: blobsBundle.commitments.length});
} else {
blobsResult = {type: BlobsResultType.preDeneb};
}
if (ForkSeq[fork] >= ForkSeq.electra) {
if (executionRequests === undefined) {
throw Error(`Missing executionRequests response from getPayload at fork=${fork}`);
}
(blockBody as electra.BeaconBlockBody).executionRequests = executionRequests;
}
}
} catch (e) {
this.metrics?.blockPayload.payloadFetchErrors.inc();
// ok we don't have an execution payload here, so we can assign an empty one
// if pre-merge
if (!isMergeTransitionComplete(currentState as CachedBeaconStateBellatrix)) {
this.logger?.warn(
"Fetch payload from the execution failed, however since we are still pre-merge proceeding with an empty one.",
{},
e as Error
);
(blockBody as BeaconBlockBody<ForkExecution>).executionPayload =
sszTypesFor(fork).ExecutionPayload.defaultValue();
blobsResult = {type: BlobsResultType.preDeneb};
executionPayloadValue = BigInt(0);
} else {
// since merge transition is complete, we need a valid payload even if with an
// empty (transactions) one. defaultValue isn't gonna cut it!
throw e;
}
}
}
} else {
blobsResult = {type: BlobsResultType.preDeneb};
executionPayloadValue = BigInt(0);
}
endExecutionPayload?.({
step: BlockProductionStep.executionPayload,
});
if (ForkSeq[fork] >= ForkSeq.capella) {
Object.assign(logMeta, {
blsToExecutionChanges: blsToExecutionChanges.length,
});
// withdrawals are only available in full body
if (blockType === BlockType.Full) {
Object.assign(logMeta, {
withdrawals: (blockBody as capella.BeaconBlockBody).executionPayload.withdrawals.length,
});
}
}
Object.assign(logMeta, {executionPayloadValue});
this.logger.verbose("Produced beacon block body", logMeta);
return {body: blockBody as AssembledBodyType<T>, blobs: blobsResult, executionPayloadValue, shouldOverrideBuilder};
}
/**
* Produce ExecutionPayload for pre-merge, merge, and post-merge.
*
* Expects `eth1MergeBlockFinder` to be actively searching for blocks well in advance to being called.
*
* @returns PayloadId = pow block found, null = pow NOT found
*/
export async function prepareExecutionPayload(
chain: {
eth1: IEth1ForBlockProduction;
executionEngine: IExecutionEngine;
config: ChainForkConfig;
},
logger: Logger,
fork: ForkExecution,
parentBlockRoot: Root,
safeBlockHash: RootHex,
finalizedBlockHash: RootHex,
state: CachedBeaconStateExecutions,
suggestedFeeRecipient: string
): Promise<{isPremerge: true} | {isPremerge: false; prepType: PayloadPreparationType; payloadId: PayloadId}> {
const parentHashRes = await getExecutionPayloadParentHash(chain, state);
if (parentHashRes.isPremerge) {
// Return null only if the execution is pre-merge
return {isPremerge: true};
}
const {parentHash} = parentHashRes;
const timestamp = computeTimeAtSlot(chain.config, state.slot, state.genesisTime);
const prevRandao = getRandaoMix(state, state.epochCtx.epoch);
const payloadIdCached = chain.executionEngine.payloadIdCache.get({
headBlockHash: toRootHex(parentHash),
finalizedBlockHash,
timestamp: numToQuantity(timestamp),
prevRandao: toHex(prevRandao),
suggestedFeeRecipient,
});
// prepareExecutionPayload will throw error via notifyForkchoiceUpdate if
// the EL returns Syncing on this request to prepare a payload
// TODO: Handle only this case, DO NOT put a generic try / catch that discards all errors
let payloadId: PayloadId | null;
let prepType: PayloadPreparationType;
if (payloadIdCached) {
payloadId = payloadIdCached;
prepType = PayloadPreparationType.Cached;
} else {
// If there was a payload assigned to this timestamp, it would imply that there some sort
// of payload reorg, i.e. head, fee recipient or any other fcu param changed
if (chain.executionEngine.payloadIdCache.hasPayload({timestamp: numToQuantity(timestamp)})) {
prepType = PayloadPreparationType.Reorged;
} else {
prepType = PayloadPreparationType.Fresh;
}
const attributes: PayloadAttributes = preparePayloadAttributes(fork, chain, {
prepareState: state,
prepareSlot: state.slot,
parentBlockRoot,
feeRecipient: suggestedFeeRecipient,
});
payloadId = await chain.executionEngine.notifyForkchoiceUpdate(
fork,
toRootHex(parentHash),
safeBlockHash,
finalizedBlockHash,
attributes
);
logger.verbose("Prepared payload id from execution engine", {payloadId});
}
// Should never happen, notifyForkchoiceUpdate() with payload attributes always
// returns payloadId
if (payloadId === null) {
throw Error("notifyForkchoiceUpdate returned payloadId null");
}
// We are only returning payloadId here because prepareExecutionPayload is also called from
// prepareNextSlot, which is an advance call to execution engine to start building payload
// Actual payload isn't produced till getPayload is called.
return {isPremerge: false, payloadId, prepType};
}
async function prepareExecutionPayloadHeader(
chain: {
eth1: IEth1ForBlockProduction;
executionBuilder?: IExecutionBuilder;
config: ChainForkConfig;
},
fork: ForkExecution,
state: CachedBeaconStateBellatrix,
proposerPubKey: BLSPubkey
): Promise<{
header: ExecutionPayloadHeader;
executionPayloadValue: Wei;
blobKzgCommitments?: deneb.BlobKzgCommitments;
executionRequests?: electra.ExecutionRequests;
}> {
if (!chain.executionBuilder) {
throw Error("executionBuilder required");
}
const parentHashRes = await getExecutionPayloadParentHash(chain, state);
if (parentHashRes.isPremerge) {
throw Error("Execution builder disabled pre-merge");
}
const {parentHash} = parentHashRes;
return chain.executionBuilder.getHeader(fork, state.slot, parentHash, proposerPubKey);
}
export async function getExecutionPayloadParentHash(
chain: {
eth1: IEth1ForBlockProduction;
config: ChainForkConfig;
},
state: CachedBeaconStateExecutions
): Promise<{isPremerge: true} | {isPremerge: false; parentHash: Root}> {
// Use different POW block hash parent for block production based on merge status.
// Returned value of null == using an empty ExecutionPayload value
if (isMergeTransitionComplete(state)) {
// Post-merge, normal payload
return {isPremerge: false, parentHash: state.latestExecutionPayloadHeader.blockHash};
}
if (
!ssz.Root.equals(chain.config.TERMINAL_BLOCK_HASH, ZERO_HASH) &&
getCurrentEpoch(state) < chain.config.TERMINAL_BLOCK_HASH_ACTIVATION_EPOCH
) {
throw new Error(
`InvalidMergeTBH epoch: expected >= ${
chain.config.TERMINAL_BLOCK_HASH_ACTIVATION_EPOCH
}, actual: ${getCurrentEpoch(state)}`
);
}
const terminalPowBlockHash = await chain.eth1.getTerminalPowBlock();
if (terminalPowBlockHash === null) {
// Pre-merge, no prepare payload call is needed
return {isPremerge: true};
}
// Signify merge via producing on top of the last PoW block
return {isPremerge: false, parentHash: terminalPowBlockHash};
}
export async function getPayloadAttributesForSSE(
fork: ForkExecution,
chain: {
eth1: IEth1ForBlockProduction;
config: ChainForkConfig;
},
{
prepareState,
prepareSlot,
parentBlockRoot,
feeRecipient,
}: {prepareState: CachedBeaconStateExecutions; prepareSlot: Slot; parentBlockRoot: Root; feeRecipient: string}
): Promise<SSEPayloadAttributes> {
const parentHashRes = await getExecutionPayloadParentHash(chain, prepareState);
if (!parentHashRes.isPremerge) {
const {parentHash} = parentHashRes;
const payloadAttributes = preparePayloadAttributes(fork, chain, {
prepareState,
prepareSlot,
parentBlockRoot,
feeRecipient,
});
const ssePayloadAttributes: SSEPayloadAttributes = {
proposerIndex: prepareState.epochCtx.getBeaconProposer(prepareSlot),
proposalSlot: prepareSlot,
parentBlockNumber: prepareState.latestExecutionPayloadHeader.blockNumber,
parentBlockRoot,
parentBlockHash: parentHash,
payloadAttributes,
};
return ssePayloadAttributes;
}
throw Error("The execution is still pre-merge");
}
function preparePayloadAttributes(
fork: ForkExecution,
chain: {
config: ChainForkConfig;
},
{
prepareState,
prepareSlot,
parentBlockRoot,
feeRecipient,
}: {
prepareState: CachedBeaconStateExecutions;
prepareSlot: Slot;
parentBlockRoot: Root;
feeRecipient: string;
}
): SSEPayloadAttributes["payloadAttributes"] {
const timestamp = computeTimeAtSlot(chain.config, prepareSlot, prepareState.genesisTime);
const prevRandao = getRandaoMix(prepareState, prepareState.epochCtx.epoch);
const payloadAttributes = {
timestamp,
prevRandao,
suggestedFeeRecipient: feeRecipient,
};
if (ForkSeq[fork] >= ForkSeq.capella) {
// withdrawals logic is now fork aware as it changes on electra fork post capella
(payloadAttributes as capella.SSEPayloadAttributes["payloadAttributes"]).withdrawals = getExpectedWithdrawals(
ForkSeq[fork],
prepareState as CachedBeaconStateCapella
).withdrawals;
}
if (ForkSeq[fork] >= ForkSeq.deneb) {
(payloadAttributes as deneb.SSEPayloadAttributes["payloadAttributes"]).parentBeaconBlockRoot = parentBlockRoot;
}
return payloadAttributes;
}
export async function produceCommonBlockBody<T extends BlockType>(
this: BeaconChain,
blockType: T,
currentState: CachedBeaconStateAllForks,
{
randaoReveal,
graffiti,
slot,
parentSlot,
parentBlockRoot,
}: BlockAttributes & {
parentSlot: Slot;
}
): Promise<CommonBlockBody> {
const stepsMetrics =
blockType === BlockType.Full
? this.metrics?.executionBlockProductionTimeSteps
: this.metrics?.builderBlockProductionTimeSteps;
const blockEpoch = computeEpochAtSlot(slot);
const fork = currentState.config.getForkName(slot);
// TODO:
// Iterate through the naive aggregation pool and ensure all the attestations from there
// are included in the operation pool.
// for (const attestation of db.attestationPool.getAll()) {
// try {
// opPool.insertAttestation(attestation);
// } catch (e) {
// // Don't stop block production if there's an error, just create a log.
// logger.error("Attestation did not transfer to op pool", {}, e);
// }
// }
const [attesterSlashings, proposerSlashings, voluntaryExits, blsToExecutionChanges] =
this.opPool.getSlashingsAndExits(currentState, blockType, this.metrics);
const endAttestations = stepsMetrics?.startTimer();
const attestations = this.aggregatedAttestationPool.getAttestationsForBlock(fork, this.forkChoice, currentState);
endAttestations?.({
step: BlockProductionStep.attestations,
});
const endEth1DataAndDeposits = stepsMetrics?.startTimer();
const {eth1Data, deposits} = await this.eth1.getEth1DataAndDeposits(currentState);
endEth1DataAndDeposits?.({
step: BlockProductionStep.eth1DataAndDeposits,
});
const blockBody: Omit<CommonBlockBody, "blsToExecutionChanges" | "syncAggregate"> = {
randaoReveal,
graffiti,
eth1Data,
proposerSlashings,
attesterSlashings,
attestations,
deposits,
voluntaryExits,
};
if (ForkSeq[fork] >= ForkSeq.capella) {
(blockBody as CommonBlockBody).blsToExecutionChanges = blsToExecutionChanges;
}
const endSyncAggregate = stepsMetrics?.startTimer();
if (blockEpoch >= this.config.ALTAIR_FORK_EPOCH) {
const syncAggregate = this.syncContributionAndProofPool.getAggregate(parentSlot, parentBlockRoot);
this.metrics?.production.producedSyncAggregateParticipants.observe(
syncAggregate.syncCommitteeBits.getTrueBitIndexes().length
);
(blockBody as CommonBlockBody).syncAggregate = syncAggregate;
}
endSyncAggregate?.({
step: BlockProductionStep.syncAggregate,
});
return blockBody as CommonBlockBody;
}