@aztec/sequencer-client 0.0.1-commit.d3ec352c → 0.0.1-commit.e310a4c8
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.
- package/dest/client/sequencer-client.d.ts +12 -12
- package/dest/client/sequencer-client.d.ts.map +1 -1
- package/dest/client/sequencer-client.js +33 -26
- package/dest/config.d.ts +12 -5
- package/dest/config.d.ts.map +1 -1
- package/dest/config.js +73 -30
- package/dest/global_variable_builder/global_builder.d.ts +21 -12
- package/dest/global_variable_builder/global_builder.d.ts.map +1 -1
- package/dest/global_variable_builder/global_builder.js +51 -41
- package/dest/index.d.ts +2 -3
- package/dest/index.d.ts.map +1 -1
- package/dest/index.js +1 -2
- package/dest/publisher/config.d.ts +7 -4
- package/dest/publisher/config.d.ts.map +1 -1
- package/dest/publisher/config.js +9 -3
- package/dest/publisher/sequencer-publisher-factory.d.ts +5 -4
- package/dest/publisher/sequencer-publisher-factory.d.ts.map +1 -1
- package/dest/publisher/sequencer-publisher-factory.js +1 -1
- package/dest/publisher/sequencer-publisher-metrics.d.ts +3 -3
- package/dest/publisher/sequencer-publisher-metrics.d.ts.map +1 -1
- package/dest/publisher/sequencer-publisher-metrics.js +23 -86
- package/dest/publisher/sequencer-publisher.d.ts +48 -41
- package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
- package/dest/publisher/sequencer-publisher.js +600 -129
- package/dest/sequencer/checkpoint_proposal_job.d.ts +96 -0
- package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -0
- package/dest/sequencer/checkpoint_proposal_job.js +1192 -0
- package/dest/sequencer/checkpoint_voter.d.ts +35 -0
- package/dest/sequencer/checkpoint_voter.d.ts.map +1 -0
- package/dest/sequencer/checkpoint_voter.js +109 -0
- package/dest/sequencer/config.d.ts +3 -2
- package/dest/sequencer/config.d.ts.map +1 -1
- package/dest/sequencer/events.d.ts +46 -0
- package/dest/sequencer/events.d.ts.map +1 -0
- package/dest/sequencer/events.js +1 -0
- package/dest/sequencer/index.d.ts +4 -2
- package/dest/sequencer/index.d.ts.map +1 -1
- package/dest/sequencer/index.js +3 -1
- package/dest/sequencer/metrics.d.ts +23 -3
- package/dest/sequencer/metrics.d.ts.map +1 -1
- package/dest/sequencer/metrics.js +143 -70
- package/dest/sequencer/sequencer.d.ts +107 -131
- package/dest/sequencer/sequencer.d.ts.map +1 -1
- package/dest/sequencer/sequencer.js +690 -602
- package/dest/sequencer/timetable.d.ts +54 -14
- package/dest/sequencer/timetable.d.ts.map +1 -1
- package/dest/sequencer/timetable.js +148 -59
- package/dest/sequencer/types.d.ts +3 -0
- package/dest/sequencer/types.d.ts.map +1 -0
- package/dest/sequencer/types.js +1 -0
- package/dest/sequencer/utils.d.ts +14 -8
- package/dest/sequencer/utils.d.ts.map +1 -1
- package/dest/sequencer/utils.js +7 -4
- package/dest/test/index.d.ts +4 -3
- package/dest/test/index.d.ts.map +1 -1
- package/dest/test/mock_checkpoint_builder.d.ts +95 -0
- package/dest/test/mock_checkpoint_builder.d.ts.map +1 -0
- package/dest/test/mock_checkpoint_builder.js +220 -0
- package/dest/test/utils.d.ts +53 -0
- package/dest/test/utils.d.ts.map +1 -0
- package/dest/test/utils.js +103 -0
- package/package.json +30 -28
- package/src/client/sequencer-client.ts +31 -42
- package/src/config.ts +78 -34
- package/src/global_variable_builder/global_builder.ts +63 -59
- package/src/index.ts +1 -7
- package/src/publisher/config.ts +12 -9
- package/src/publisher/sequencer-publisher-factory.ts +5 -4
- package/src/publisher/sequencer-publisher-metrics.ts +19 -71
- package/src/publisher/sequencer-publisher.ts +293 -170
- package/src/sequencer/README.md +531 -0
- package/src/sequencer/checkpoint_proposal_job.ts +874 -0
- package/src/sequencer/checkpoint_voter.ts +130 -0
- package/src/sequencer/config.ts +2 -1
- package/src/sequencer/events.ts +27 -0
- package/src/sequencer/index.ts +3 -1
- package/src/sequencer/metrics.ts +190 -78
- package/src/sequencer/sequencer.ts +430 -804
- package/src/sequencer/timetable.ts +173 -79
- package/src/sequencer/types.ts +6 -0
- package/src/sequencer/utils.ts +18 -9
- package/src/test/index.ts +3 -2
- package/src/test/mock_checkpoint_builder.ts +309 -0
- package/src/test/utils.ts +164 -0
- package/dest/sequencer/block_builder.d.ts +0 -28
- package/dest/sequencer/block_builder.d.ts.map +0 -1
- package/dest/sequencer/block_builder.js +0 -134
- package/dest/tx_validator/nullifier_cache.d.ts +0 -14
- package/dest/tx_validator/nullifier_cache.d.ts.map +0 -1
- package/dest/tx_validator/nullifier_cache.js +0 -24
- package/dest/tx_validator/tx_validator_factory.d.ts +0 -18
- package/dest/tx_validator/tx_validator_factory.d.ts.map +0 -1
- package/dest/tx_validator/tx_validator_factory.js +0 -53
- package/src/sequencer/block_builder.ts +0 -222
- package/src/tx_validator/nullifier_cache.ts +0 -30
- package/src/tx_validator/tx_validator_factory.ts +0 -133
|
@@ -0,0 +1,874 @@
|
|
|
1
|
+
import { NUM_CHECKPOINT_END_MARKER_FIELDS, getNumBlockEndBlobFields } from '@aztec/blob-lib/encoding';
|
|
2
|
+
import { BLOBS_PER_CHECKPOINT, FIELDS_PER_BLOB } from '@aztec/constants';
|
|
3
|
+
import type { EpochCache } from '@aztec/epoch-cache';
|
|
4
|
+
import {
|
|
5
|
+
BlockNumber,
|
|
6
|
+
CheckpointNumber,
|
|
7
|
+
EpochNumber,
|
|
8
|
+
IndexWithinCheckpoint,
|
|
9
|
+
SlotNumber,
|
|
10
|
+
} from '@aztec/foundation/branded-types';
|
|
11
|
+
import { randomInt } from '@aztec/foundation/crypto/random';
|
|
12
|
+
import { Fr } from '@aztec/foundation/curves/bn254';
|
|
13
|
+
import { EthAddress } from '@aztec/foundation/eth-address';
|
|
14
|
+
import { Signature } from '@aztec/foundation/eth-signature';
|
|
15
|
+
import { filter } from '@aztec/foundation/iterator';
|
|
16
|
+
import { type Logger, type LoggerBindings, createLogger } from '@aztec/foundation/log';
|
|
17
|
+
import { sleep, sleepUntil } from '@aztec/foundation/sleep';
|
|
18
|
+
import { type DateProvider, Timer } from '@aztec/foundation/timer';
|
|
19
|
+
import { type TypedEventEmitter, isErrorClass, unfreeze } from '@aztec/foundation/types';
|
|
20
|
+
import type { P2P } from '@aztec/p2p';
|
|
21
|
+
import type { SlasherClientInterface } from '@aztec/slasher';
|
|
22
|
+
import {
|
|
23
|
+
CommitteeAttestation,
|
|
24
|
+
CommitteeAttestationsAndSigners,
|
|
25
|
+
L2Block,
|
|
26
|
+
type L2BlockSink,
|
|
27
|
+
type L2BlockSource,
|
|
28
|
+
MaliciousCommitteeAttestationsAndSigners,
|
|
29
|
+
} from '@aztec/stdlib/block';
|
|
30
|
+
import type { Checkpoint } from '@aztec/stdlib/checkpoint';
|
|
31
|
+
import { getSlotStartBuildTimestamp } from '@aztec/stdlib/epoch-helpers';
|
|
32
|
+
import { Gas } from '@aztec/stdlib/gas';
|
|
33
|
+
import {
|
|
34
|
+
NoValidTxsError,
|
|
35
|
+
type PublicProcessorLimits,
|
|
36
|
+
type ResolvedSequencerConfig,
|
|
37
|
+
type WorldStateSynchronizer,
|
|
38
|
+
} from '@aztec/stdlib/interfaces/server';
|
|
39
|
+
import { type L1ToL2MessageSource, computeInHashFromL1ToL2Messages } from '@aztec/stdlib/messaging';
|
|
40
|
+
import type { BlockProposalOptions, CheckpointProposal, CheckpointProposalOptions } from '@aztec/stdlib/p2p';
|
|
41
|
+
import { orderAttestations } from '@aztec/stdlib/p2p';
|
|
42
|
+
import type { L2BlockBuiltStats } from '@aztec/stdlib/stats';
|
|
43
|
+
import { type FailedTx, Tx } from '@aztec/stdlib/tx';
|
|
44
|
+
import { AttestationTimeoutError } from '@aztec/stdlib/validators';
|
|
45
|
+
import { Attributes, type Traceable, type Tracer, trackSpan } from '@aztec/telemetry-client';
|
|
46
|
+
import { CheckpointBuilder, type FullNodeCheckpointsBuilder, type ValidatorClient } from '@aztec/validator-client';
|
|
47
|
+
import { DutyAlreadySignedError, SlashingProtectionError } from '@aztec/validator-ha-signer/errors';
|
|
48
|
+
|
|
49
|
+
import type { GlobalVariableBuilder } from '../global_variable_builder/global_builder.js';
|
|
50
|
+
import type { InvalidateCheckpointRequest, SequencerPublisher } from '../publisher/sequencer-publisher.js';
|
|
51
|
+
import { CheckpointVoter } from './checkpoint_voter.js';
|
|
52
|
+
import { SequencerInterruptedError } from './errors.js';
|
|
53
|
+
import type { SequencerEvents } from './events.js';
|
|
54
|
+
import type { SequencerMetrics } from './metrics.js';
|
|
55
|
+
import type { SequencerTimetable } from './timetable.js';
|
|
56
|
+
import type { SequencerRollupConstants } from './types.js';
|
|
57
|
+
import { SequencerState } from './utils.js';
|
|
58
|
+
|
|
59
|
+
/** How much time to sleep while waiting for min transactions to accumulate for a block */
|
|
60
|
+
const TXS_POLLING_MS = 500;
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Handles the execution of a checkpoint proposal after the initial preparation phase.
|
|
64
|
+
* This includes building blocks, collecting attestations, and publishing the checkpoint to L1,
|
|
65
|
+
* as well as enqueueing votes for slashing and governance proposals. This class is created from
|
|
66
|
+
* the Sequencer once the check for being the proposer for the slot has succeeded.
|
|
67
|
+
*/
|
|
68
|
+
export class CheckpointProposalJob implements Traceable {
|
|
69
|
+
protected readonly log: Logger;
|
|
70
|
+
|
|
71
|
+
constructor(
|
|
72
|
+
private readonly epoch: EpochNumber,
|
|
73
|
+
private readonly slot: SlotNumber,
|
|
74
|
+
private readonly checkpointNumber: CheckpointNumber,
|
|
75
|
+
private readonly syncedToBlockNumber: BlockNumber,
|
|
76
|
+
// TODO(palla/mbps): Can we remove the proposer in favor of attestorAddress? Need to check fisherman-node flows.
|
|
77
|
+
private readonly proposer: EthAddress | undefined,
|
|
78
|
+
private readonly publisher: SequencerPublisher,
|
|
79
|
+
private readonly attestorAddress: EthAddress,
|
|
80
|
+
private readonly invalidateCheckpoint: InvalidateCheckpointRequest | undefined,
|
|
81
|
+
private readonly validatorClient: ValidatorClient,
|
|
82
|
+
private readonly globalsBuilder: GlobalVariableBuilder,
|
|
83
|
+
private readonly p2pClient: P2P,
|
|
84
|
+
private readonly worldState: WorldStateSynchronizer,
|
|
85
|
+
private readonly l1ToL2MessageSource: L1ToL2MessageSource,
|
|
86
|
+
private readonly l2BlockSource: L2BlockSource,
|
|
87
|
+
private readonly checkpointsBuilder: FullNodeCheckpointsBuilder,
|
|
88
|
+
private readonly blockSink: L2BlockSink,
|
|
89
|
+
private readonly l1Constants: SequencerRollupConstants,
|
|
90
|
+
protected config: ResolvedSequencerConfig,
|
|
91
|
+
protected timetable: SequencerTimetable,
|
|
92
|
+
private readonly slasherClient: SlasherClientInterface | undefined,
|
|
93
|
+
private readonly epochCache: EpochCache,
|
|
94
|
+
private readonly dateProvider: DateProvider,
|
|
95
|
+
private readonly metrics: SequencerMetrics,
|
|
96
|
+
private readonly eventEmitter: TypedEventEmitter<SequencerEvents>,
|
|
97
|
+
private readonly setStateFn: (state: SequencerState, slot?: SlotNumber) => void,
|
|
98
|
+
public readonly tracer: Tracer,
|
|
99
|
+
bindings?: LoggerBindings,
|
|
100
|
+
) {
|
|
101
|
+
this.log = createLogger('sequencer:checkpoint-proposal', { ...bindings, instanceId: `slot-${slot}` });
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Executes the checkpoint proposal job.
|
|
106
|
+
* Returns the published checkpoint if successful, undefined otherwise.
|
|
107
|
+
*/
|
|
108
|
+
@trackSpan('CheckpointProposalJob.execute')
|
|
109
|
+
public async execute(): Promise<Checkpoint | undefined> {
|
|
110
|
+
// Enqueue governance and slashing votes (returns promises that will be awaited later)
|
|
111
|
+
// In fisherman mode, we simulate slashing but don't actually publish to L1
|
|
112
|
+
// These are constant for the whole slot, so we only enqueue them once
|
|
113
|
+
const votesPromises = new CheckpointVoter(
|
|
114
|
+
this.slot,
|
|
115
|
+
this.publisher,
|
|
116
|
+
this.attestorAddress,
|
|
117
|
+
this.validatorClient,
|
|
118
|
+
this.slasherClient,
|
|
119
|
+
this.l1Constants,
|
|
120
|
+
this.config,
|
|
121
|
+
this.metrics,
|
|
122
|
+
this.log,
|
|
123
|
+
).enqueueVotes();
|
|
124
|
+
|
|
125
|
+
// Build and propose the checkpoint. This will enqueue the request on the publisher if a checkpoint is built.
|
|
126
|
+
const checkpoint = await this.proposeCheckpoint();
|
|
127
|
+
|
|
128
|
+
// Wait until the voting promises have resolved, so all requests are enqueued (not sent)
|
|
129
|
+
await Promise.all(votesPromises);
|
|
130
|
+
|
|
131
|
+
if (checkpoint) {
|
|
132
|
+
this.metrics.recordBlockProposalSuccess();
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// Do not post anything to L1 if we are fishermen, but do perform L1 fee analysis
|
|
136
|
+
if (this.config.fishermanMode) {
|
|
137
|
+
await this.handleCheckpointEndAsFisherman(checkpoint);
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// Then send everything to L1
|
|
142
|
+
const l1Response = await this.publisher.sendRequests();
|
|
143
|
+
const proposedAction = l1Response?.successfulActions.find(a => a === 'propose');
|
|
144
|
+
if (proposedAction) {
|
|
145
|
+
this.eventEmitter.emit('checkpoint-published', { checkpoint: this.checkpointNumber, slot: this.slot });
|
|
146
|
+
const coinbase = checkpoint?.header.coinbase;
|
|
147
|
+
await this.metrics.incFilledSlot(this.publisher.getSenderAddress().toString(), coinbase);
|
|
148
|
+
return checkpoint;
|
|
149
|
+
} else if (checkpoint) {
|
|
150
|
+
this.eventEmitter.emit('checkpoint-publish-failed', { ...l1Response, slot: this.slot });
|
|
151
|
+
return undefined;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
@trackSpan('CheckpointProposalJob.proposeCheckpoint', function () {
|
|
156
|
+
return {
|
|
157
|
+
// nullish operator needed for tests
|
|
158
|
+
[Attributes.COINBASE]: this.validatorClient.getCoinbaseForAttestor(this.attestorAddress)?.toString(),
|
|
159
|
+
[Attributes.SLOT_NUMBER]: this.slot,
|
|
160
|
+
};
|
|
161
|
+
})
|
|
162
|
+
private async proposeCheckpoint(): Promise<Checkpoint | undefined> {
|
|
163
|
+
try {
|
|
164
|
+
// Get operator configured coinbase and fee recipient for this attestor
|
|
165
|
+
const coinbase = this.validatorClient.getCoinbaseForAttestor(this.attestorAddress);
|
|
166
|
+
const feeRecipient = this.validatorClient.getFeeRecipientForAttestor(this.attestorAddress);
|
|
167
|
+
|
|
168
|
+
// Start the checkpoint
|
|
169
|
+
this.setStateFn(SequencerState.INITIALIZING_CHECKPOINT, this.slot);
|
|
170
|
+
this.metrics.incOpenSlot(this.slot, this.proposer?.toString() ?? 'unknown');
|
|
171
|
+
|
|
172
|
+
// Enqueues checkpoint invalidation (constant for the whole slot)
|
|
173
|
+
if (this.invalidateCheckpoint && !this.config.skipInvalidateBlockAsProposer) {
|
|
174
|
+
this.publisher.enqueueInvalidateCheckpoint(this.invalidateCheckpoint);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// Create checkpoint builder for the slot
|
|
178
|
+
const checkpointGlobalVariables = await this.globalsBuilder.buildCheckpointGlobalVariables(
|
|
179
|
+
coinbase,
|
|
180
|
+
feeRecipient,
|
|
181
|
+
this.slot,
|
|
182
|
+
);
|
|
183
|
+
|
|
184
|
+
// Collect L1 to L2 messages for the checkpoint and compute their hash
|
|
185
|
+
const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(this.checkpointNumber);
|
|
186
|
+
const inHash = computeInHashFromL1ToL2Messages(l1ToL2Messages);
|
|
187
|
+
|
|
188
|
+
// Collect the out hashes of all the checkpoints before this one in the same epoch
|
|
189
|
+
const previousCheckpoints = (await this.l2BlockSource.getCheckpointsForEpoch(this.epoch)).filter(
|
|
190
|
+
c => c.number < this.checkpointNumber,
|
|
191
|
+
);
|
|
192
|
+
const previousCheckpointOutHashes = previousCheckpoints.map(c => c.getCheckpointOutHash());
|
|
193
|
+
|
|
194
|
+
// Create a long-lived forked world state for the checkpoint builder
|
|
195
|
+
using fork = await this.worldState.fork(this.syncedToBlockNumber, { closeDelayMs: 12_000 });
|
|
196
|
+
|
|
197
|
+
// Create checkpoint builder for the entire slot
|
|
198
|
+
const checkpointBuilder = await this.checkpointsBuilder.startCheckpoint(
|
|
199
|
+
this.checkpointNumber,
|
|
200
|
+
checkpointGlobalVariables,
|
|
201
|
+
l1ToL2Messages,
|
|
202
|
+
previousCheckpointOutHashes,
|
|
203
|
+
fork,
|
|
204
|
+
this.log.getBindings(),
|
|
205
|
+
);
|
|
206
|
+
|
|
207
|
+
// Options for the validator client when creating block and checkpoint proposals
|
|
208
|
+
const blockProposalOptions: BlockProposalOptions = {
|
|
209
|
+
publishFullTxs: !!this.config.publishTxsWithProposals,
|
|
210
|
+
broadcastInvalidBlockProposal: this.config.broadcastInvalidBlockProposal,
|
|
211
|
+
};
|
|
212
|
+
|
|
213
|
+
const checkpointProposalOptions: CheckpointProposalOptions = {
|
|
214
|
+
publishFullTxs: !!this.config.publishTxsWithProposals,
|
|
215
|
+
broadcastInvalidCheckpointProposal: this.config.broadcastInvalidBlockProposal,
|
|
216
|
+
};
|
|
217
|
+
|
|
218
|
+
let blocksInCheckpoint: L2Block[] = [];
|
|
219
|
+
let blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined = undefined;
|
|
220
|
+
|
|
221
|
+
try {
|
|
222
|
+
// Main loop: build blocks for the checkpoint
|
|
223
|
+
const result = await this.buildBlocksForCheckpoint(
|
|
224
|
+
checkpointBuilder,
|
|
225
|
+
checkpointGlobalVariables.timestamp,
|
|
226
|
+
inHash,
|
|
227
|
+
blockProposalOptions,
|
|
228
|
+
);
|
|
229
|
+
blocksInCheckpoint = result.blocksInCheckpoint;
|
|
230
|
+
blockPendingBroadcast = result.blockPendingBroadcast;
|
|
231
|
+
} catch (err) {
|
|
232
|
+
// These errors are expected in HA mode, so we yield and let another HA node handle the slot
|
|
233
|
+
// The only distinction between the 2 errors is SlashingProtectionError throws when the payload is different,
|
|
234
|
+
// which is normal for block building (may have picked different txs)
|
|
235
|
+
if (err instanceof DutyAlreadySignedError) {
|
|
236
|
+
this.log.info(`Checkpoint proposal for slot ${this.slot} already signed by another HA node, yielding`, {
|
|
237
|
+
slot: this.slot,
|
|
238
|
+
signedByNode: err.signedByNode,
|
|
239
|
+
});
|
|
240
|
+
return undefined;
|
|
241
|
+
}
|
|
242
|
+
if (err instanceof SlashingProtectionError) {
|
|
243
|
+
this.log.info(`Checkpoint proposal for slot ${this.slot} blocked by slashing protection, yielding`, {
|
|
244
|
+
slot: this.slot,
|
|
245
|
+
existingMessageHash: err.existingMessageHash,
|
|
246
|
+
attemptedMessageHash: err.attemptedMessageHash,
|
|
247
|
+
});
|
|
248
|
+
return undefined;
|
|
249
|
+
}
|
|
250
|
+
throw err;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
if (blocksInCheckpoint.length === 0) {
|
|
254
|
+
this.log.warn(`No blocks were built for slot ${this.slot}`, { slot: this.slot });
|
|
255
|
+
this.eventEmitter.emit('checkpoint-empty', { slot: this.slot });
|
|
256
|
+
return undefined;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// Assemble and broadcast the checkpoint proposal, including the last block that was not
|
|
260
|
+
// broadcasted yet, and wait to collect the committee attestations.
|
|
261
|
+
this.setStateFn(SequencerState.ASSEMBLING_CHECKPOINT, this.slot);
|
|
262
|
+
const checkpoint = await checkpointBuilder.completeCheckpoint();
|
|
263
|
+
|
|
264
|
+
// Do not collect attestations nor publish to L1 in fisherman mode
|
|
265
|
+
if (this.config.fishermanMode) {
|
|
266
|
+
this.log.info(
|
|
267
|
+
`Built checkpoint for slot ${this.slot} with ${blocksInCheckpoint.length} blocks. ` +
|
|
268
|
+
`Skipping proposal in fisherman mode.`,
|
|
269
|
+
{
|
|
270
|
+
slot: this.slot,
|
|
271
|
+
checkpoint: checkpoint.header.toInspect(),
|
|
272
|
+
blocksBuilt: blocksInCheckpoint.length,
|
|
273
|
+
},
|
|
274
|
+
);
|
|
275
|
+
this.metrics.recordCheckpointSuccess();
|
|
276
|
+
return checkpoint;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
// Include the block pending broadcast in the checkpoint proposal if any
|
|
280
|
+
const lastBlock = blockPendingBroadcast && {
|
|
281
|
+
blockHeader: blockPendingBroadcast.block.header,
|
|
282
|
+
indexWithinCheckpoint: blockPendingBroadcast.block.indexWithinCheckpoint,
|
|
283
|
+
txs: blockPendingBroadcast.txs,
|
|
284
|
+
};
|
|
285
|
+
|
|
286
|
+
// Create the checkpoint proposal and broadcast it
|
|
287
|
+
const proposal = await this.validatorClient.createCheckpointProposal(
|
|
288
|
+
checkpoint.header,
|
|
289
|
+
checkpoint.archive.root,
|
|
290
|
+
lastBlock,
|
|
291
|
+
this.proposer,
|
|
292
|
+
checkpointProposalOptions,
|
|
293
|
+
);
|
|
294
|
+
|
|
295
|
+
const blockProposedAt = this.dateProvider.now();
|
|
296
|
+
await this.p2pClient.broadcastCheckpointProposal(proposal);
|
|
297
|
+
|
|
298
|
+
this.setStateFn(SequencerState.COLLECTING_ATTESTATIONS, this.slot);
|
|
299
|
+
const attestations = await this.waitForAttestations(proposal);
|
|
300
|
+
const blockAttestedAt = this.dateProvider.now();
|
|
301
|
+
|
|
302
|
+
this.metrics.recordCheckpointAttestationDelay(blockAttestedAt - blockProposedAt);
|
|
303
|
+
|
|
304
|
+
// Proposer must sign over the attestations before pushing them to L1
|
|
305
|
+
const signer = this.proposer ?? this.publisher.getSenderAddress();
|
|
306
|
+
let attestationsSignature: Signature;
|
|
307
|
+
try {
|
|
308
|
+
attestationsSignature = await this.validatorClient.signAttestationsAndSigners(
|
|
309
|
+
attestations,
|
|
310
|
+
signer,
|
|
311
|
+
this.slot,
|
|
312
|
+
this.checkpointNumber,
|
|
313
|
+
);
|
|
314
|
+
} catch (err) {
|
|
315
|
+
// We shouldn't really get here since we yield to another HA node
|
|
316
|
+
// as soon as we see these errors when creating block proposals.
|
|
317
|
+
if (err instanceof DutyAlreadySignedError) {
|
|
318
|
+
this.log.info(`Attestations signature for slot ${this.slot} already signed by another HA node, yielding`, {
|
|
319
|
+
slot: this.slot,
|
|
320
|
+
signedByNode: err.signedByNode,
|
|
321
|
+
});
|
|
322
|
+
return undefined;
|
|
323
|
+
}
|
|
324
|
+
if (err instanceof SlashingProtectionError) {
|
|
325
|
+
this.log.info(`Attestations signature for slot ${this.slot} blocked by slashing protection, yielding`, {
|
|
326
|
+
slot: this.slot,
|
|
327
|
+
existingMessageHash: err.existingMessageHash,
|
|
328
|
+
attemptedMessageHash: err.attemptedMessageHash,
|
|
329
|
+
});
|
|
330
|
+
return undefined;
|
|
331
|
+
}
|
|
332
|
+
throw err;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// Enqueue publishing the checkpoint to L1
|
|
336
|
+
this.setStateFn(SequencerState.PUBLISHING_CHECKPOINT, this.slot);
|
|
337
|
+
const aztecSlotDuration = this.l1Constants.slotDuration;
|
|
338
|
+
const slotStartBuildTimestamp = this.getSlotStartBuildTimestamp();
|
|
339
|
+
const txTimeoutAt = new Date((slotStartBuildTimestamp + aztecSlotDuration) * 1000);
|
|
340
|
+
await this.publisher.enqueueProposeCheckpoint(checkpoint, attestations, attestationsSignature, {
|
|
341
|
+
txTimeoutAt,
|
|
342
|
+
forcePendingCheckpointNumber: this.invalidateCheckpoint?.forcePendingCheckpointNumber,
|
|
343
|
+
});
|
|
344
|
+
|
|
345
|
+
return checkpoint;
|
|
346
|
+
} catch (err) {
|
|
347
|
+
if (err && (err instanceof DutyAlreadySignedError || err instanceof SlashingProtectionError)) {
|
|
348
|
+
// swallow this error. It's already been logged by a function deeper in the stack
|
|
349
|
+
return undefined;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
this.log.error(`Error building checkpoint at slot ${this.slot}`, err);
|
|
353
|
+
return undefined;
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/**
|
|
358
|
+
* Builds blocks for a checkpoint within the current slot.
|
|
359
|
+
*/
|
|
360
|
+
@trackSpan('CheckpointProposalJob.buildBlocksForCheckpoint')
|
|
361
|
+
private async buildBlocksForCheckpoint(
|
|
362
|
+
checkpointBuilder: CheckpointBuilder,
|
|
363
|
+
timestamp: bigint,
|
|
364
|
+
inHash: Fr,
|
|
365
|
+
blockProposalOptions: BlockProposalOptions,
|
|
366
|
+
): Promise<{
|
|
367
|
+
blocksInCheckpoint: L2Block[];
|
|
368
|
+
blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined;
|
|
369
|
+
}> {
|
|
370
|
+
const blocksInCheckpoint: L2Block[] = [];
|
|
371
|
+
const txHashesAlreadyIncluded = new Set<string>();
|
|
372
|
+
const initialBlockNumber = BlockNumber(this.syncedToBlockNumber + 1);
|
|
373
|
+
|
|
374
|
+
// Remaining blob fields available for blocks (checkpoint end marker already subtracted)
|
|
375
|
+
let remainingBlobFields = BLOBS_PER_CHECKPOINT * FIELDS_PER_BLOB - NUM_CHECKPOINT_END_MARKER_FIELDS;
|
|
376
|
+
|
|
377
|
+
// Last block in the checkpoint will usually be flagged as pending broadcast, so we send it along with the checkpoint proposal
|
|
378
|
+
let blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined = undefined;
|
|
379
|
+
|
|
380
|
+
while (true) {
|
|
381
|
+
const blocksBuilt = blocksInCheckpoint.length;
|
|
382
|
+
const indexWithinCheckpoint = IndexWithinCheckpoint(blocksBuilt);
|
|
383
|
+
const blockNumber = BlockNumber(initialBlockNumber + blocksBuilt);
|
|
384
|
+
|
|
385
|
+
const secondsIntoSlot = this.getSecondsIntoSlot();
|
|
386
|
+
const timingInfo = this.timetable.canStartNextBlock(secondsIntoSlot);
|
|
387
|
+
|
|
388
|
+
if (!timingInfo.canStart) {
|
|
389
|
+
this.log.debug(`Not enough time left in slot to start another block`, {
|
|
390
|
+
slot: this.slot,
|
|
391
|
+
blocksBuilt,
|
|
392
|
+
secondsIntoSlot,
|
|
393
|
+
});
|
|
394
|
+
break;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
const buildResult = await this.buildSingleBlock(checkpointBuilder, {
|
|
398
|
+
// Create all blocks with the same timestamp
|
|
399
|
+
blockTimestamp: timestamp,
|
|
400
|
+
// Create an empty block if we haven't already and this is the last one
|
|
401
|
+
forceCreate: timingInfo.isLastBlock && blocksBuilt === 0 && this.config.buildCheckpointIfEmpty,
|
|
402
|
+
// Build deadline is only set if we are enforcing the timetable
|
|
403
|
+
buildDeadline: timingInfo.deadline
|
|
404
|
+
? new Date((this.getSlotStartBuildTimestamp() + timingInfo.deadline) * 1000)
|
|
405
|
+
: undefined,
|
|
406
|
+
blockNumber,
|
|
407
|
+
indexWithinCheckpoint,
|
|
408
|
+
txHashesAlreadyIncluded,
|
|
409
|
+
remainingBlobFields,
|
|
410
|
+
});
|
|
411
|
+
|
|
412
|
+
// TODO(palla/mbps): Review these conditions. We may want to keep trying in some scenarios.
|
|
413
|
+
if (!buildResult && timingInfo.isLastBlock) {
|
|
414
|
+
// If no block was produced due to not enough txs and this was the last subslot, exit
|
|
415
|
+
break;
|
|
416
|
+
} else if (!buildResult && timingInfo.deadline !== undefined) {
|
|
417
|
+
// But if there is still time for more blocks, wait until the next subslot and try again
|
|
418
|
+
await this.waitUntilNextSubslot(timingInfo.deadline);
|
|
419
|
+
continue;
|
|
420
|
+
} else if (!buildResult) {
|
|
421
|
+
// Exit if there is no possibility of building more blocks
|
|
422
|
+
break;
|
|
423
|
+
} else if ('error' in buildResult) {
|
|
424
|
+
// If there was an error building the block, just exit the loop and give up the rest of the slot
|
|
425
|
+
if (!(buildResult.error instanceof SequencerInterruptedError)) {
|
|
426
|
+
this.log.warn(`Halting block building for slot ${this.slot}`, {
|
|
427
|
+
slot: this.slot,
|
|
428
|
+
blocksBuilt,
|
|
429
|
+
error: buildResult.error,
|
|
430
|
+
});
|
|
431
|
+
}
|
|
432
|
+
break;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
const { block, usedTxs, remainingBlobFields: newRemainingBlobFields } = buildResult;
|
|
436
|
+
blocksInCheckpoint.push(block);
|
|
437
|
+
|
|
438
|
+
// Update remaining blob fields for the next block
|
|
439
|
+
remainingBlobFields = newRemainingBlobFields;
|
|
440
|
+
|
|
441
|
+
// Sync the proposed block to the archiver to make it available
|
|
442
|
+
// Note that the checkpoint builder uses its own fork so it should not need to wait for this syncing
|
|
443
|
+
// Eventually we should refactor the checkpoint builder to not need a separate long-lived fork
|
|
444
|
+
// Fire and forget - don't block the critical path, but log errors
|
|
445
|
+
this.syncProposedBlockToArchiver(block).catch(err => {
|
|
446
|
+
this.log.error(`Failed to sync proposed block ${block.number} to archiver`, { blockNumber: block.number, err });
|
|
447
|
+
});
|
|
448
|
+
|
|
449
|
+
usedTxs.forEach(tx => txHashesAlreadyIncluded.add(tx.txHash.toString()));
|
|
450
|
+
|
|
451
|
+
// If this is the last block, exit the loop now so we start collecting attestations
|
|
452
|
+
if (timingInfo.isLastBlock) {
|
|
453
|
+
this.log.verbose(`Completed final block ${blockNumber} for slot ${this.slot}`, {
|
|
454
|
+
slot: this.slot,
|
|
455
|
+
blockNumber,
|
|
456
|
+
blocksBuilt,
|
|
457
|
+
});
|
|
458
|
+
blockPendingBroadcast = { block, txs: usedTxs };
|
|
459
|
+
break;
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
// For non-last blocks, broadcast the block proposal (unless we're in fisherman mode)
|
|
463
|
+
// If the block is the last one, we'll broadcast it along with the checkpoint at the end of the loop
|
|
464
|
+
if (!this.config.fishermanMode) {
|
|
465
|
+
const proposal = await this.validatorClient.createBlockProposal(
|
|
466
|
+
block.header,
|
|
467
|
+
block.indexWithinCheckpoint,
|
|
468
|
+
inHash,
|
|
469
|
+
block.archive.root,
|
|
470
|
+
usedTxs,
|
|
471
|
+
this.proposer,
|
|
472
|
+
blockProposalOptions,
|
|
473
|
+
);
|
|
474
|
+
await this.p2pClient.broadcastProposal(proposal);
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
// Wait until the next block's start time
|
|
478
|
+
await this.waitUntilNextSubslot(timingInfo.deadline);
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
this.log.verbose(`Block building loop completed for slot ${this.slot}`, {
|
|
482
|
+
slot: this.slot,
|
|
483
|
+
blocksBuilt: blocksInCheckpoint.length,
|
|
484
|
+
});
|
|
485
|
+
|
|
486
|
+
return { blocksInCheckpoint, blockPendingBroadcast };
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
/** Sleeps until it is time to produce the next block in the slot */
|
|
490
|
+
@trackSpan('CheckpointProposalJob.waitUntilNextSubslot')
|
|
491
|
+
private async waitUntilNextSubslot(nextSubslotStart: number) {
|
|
492
|
+
this.setStateFn(SequencerState.WAITING_UNTIL_NEXT_BLOCK, this.slot);
|
|
493
|
+
this.log.verbose(`Waiting until time for the next block at ${nextSubslotStart}s into slot`, { slot: this.slot });
|
|
494
|
+
await this.waitUntilTimeInSlot(nextSubslotStart);
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
/** Builds a single block. Called from the main block building loop. */
|
|
498
|
+
@trackSpan('CheckpointProposalJob.buildSingleBlock')
|
|
499
|
+
protected async buildSingleBlock(
|
|
500
|
+
checkpointBuilder: CheckpointBuilder,
|
|
501
|
+
opts: {
|
|
502
|
+
forceCreate?: boolean;
|
|
503
|
+
blockTimestamp: bigint;
|
|
504
|
+
blockNumber: BlockNumber;
|
|
505
|
+
indexWithinCheckpoint: IndexWithinCheckpoint;
|
|
506
|
+
buildDeadline: Date | undefined;
|
|
507
|
+
txHashesAlreadyIncluded: Set<string>;
|
|
508
|
+
remainingBlobFields: number;
|
|
509
|
+
},
|
|
510
|
+
): Promise<{ block: L2Block; usedTxs: Tx[]; remainingBlobFields: number } | { error: Error } | undefined> {
|
|
511
|
+
const {
|
|
512
|
+
blockTimestamp,
|
|
513
|
+
forceCreate,
|
|
514
|
+
blockNumber,
|
|
515
|
+
indexWithinCheckpoint,
|
|
516
|
+
buildDeadline,
|
|
517
|
+
txHashesAlreadyIncluded,
|
|
518
|
+
remainingBlobFields,
|
|
519
|
+
} = opts;
|
|
520
|
+
|
|
521
|
+
this.log.verbose(
|
|
522
|
+
`Preparing block ${blockNumber} index ${indexWithinCheckpoint} at checkpoint ${this.checkpointNumber} for slot ${this.slot}`,
|
|
523
|
+
{ ...checkpointBuilder.getConstantData(), ...opts },
|
|
524
|
+
);
|
|
525
|
+
|
|
526
|
+
try {
|
|
527
|
+
// Wait until we have enough txs to build the block
|
|
528
|
+
const minTxs = this.config.minTxsPerBlock;
|
|
529
|
+
const { availableTxs, canStartBuilding } = await this.waitForMinTxs(opts);
|
|
530
|
+
if (!canStartBuilding) {
|
|
531
|
+
this.log.warn(
|
|
532
|
+
`Not enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.slot} (got ${availableTxs} txs but needs ${minTxs})`,
|
|
533
|
+
{ blockNumber, slot: this.slot, indexWithinCheckpoint },
|
|
534
|
+
);
|
|
535
|
+
this.eventEmitter.emit('block-tx-count-check-failed', { minTxs, availableTxs, slot: this.slot });
|
|
536
|
+
this.metrics.recordBlockProposalFailed('insufficient_txs');
|
|
537
|
+
return undefined;
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
// Create iterator to pending txs. We filter out txs already included in previous blocks in the checkpoint
|
|
541
|
+
// just in case p2p failed to sync the provisional block and didn't get to remove those txs from the mempool yet.
|
|
542
|
+
const pendingTxs = filter(
|
|
543
|
+
this.p2pClient.iteratePendingTxs(),
|
|
544
|
+
tx => !txHashesAlreadyIncluded.has(tx.txHash.toString()),
|
|
545
|
+
);
|
|
546
|
+
|
|
547
|
+
this.log.debug(
|
|
548
|
+
`Building block ${blockNumber} at index ${indexWithinCheckpoint} for slot ${this.slot} with ${availableTxs} available txs`,
|
|
549
|
+
{ slot: this.slot, blockNumber, indexWithinCheckpoint },
|
|
550
|
+
);
|
|
551
|
+
this.setStateFn(SequencerState.CREATING_BLOCK, this.slot);
|
|
552
|
+
|
|
553
|
+
// Calculate blob fields limit for txs (remaining capacity - this block's end overhead)
|
|
554
|
+
const blockEndOverhead = getNumBlockEndBlobFields(indexWithinCheckpoint === 0);
|
|
555
|
+
const maxBlobFieldsForTxs = remainingBlobFields - blockEndOverhead;
|
|
556
|
+
|
|
557
|
+
const blockBuilderOptions: PublicProcessorLimits = {
|
|
558
|
+
maxTransactions: this.config.maxTxsPerBlock,
|
|
559
|
+
maxBlockSize: this.config.maxBlockSizeInBytes,
|
|
560
|
+
maxBlockGas: new Gas(this.config.maxDABlockGas, this.config.maxL2BlockGas),
|
|
561
|
+
maxBlobFields: maxBlobFieldsForTxs,
|
|
562
|
+
deadline: buildDeadline,
|
|
563
|
+
};
|
|
564
|
+
|
|
565
|
+
// Actually build the block by executing txs
|
|
566
|
+
const buildResult = await this.buildSingleBlockWithCheckpointBuilder(
|
|
567
|
+
checkpointBuilder,
|
|
568
|
+
pendingTxs,
|
|
569
|
+
blockNumber,
|
|
570
|
+
blockTimestamp,
|
|
571
|
+
blockBuilderOptions,
|
|
572
|
+
);
|
|
573
|
+
|
|
574
|
+
// If any txs failed during execution, drop them from the mempool so we don't pick them up again
|
|
575
|
+
await this.dropFailedTxsFromP2P(buildResult.failedTxs);
|
|
576
|
+
|
|
577
|
+
// Check if we have created a block with enough txs. If there were invalid txs in the pool, or if execution took
|
|
578
|
+
// too long, then we may not get to minTxsPerBlock after executing public functions.
|
|
579
|
+
const minValidTxs = this.config.minValidTxsPerBlock ?? minTxs;
|
|
580
|
+
const numTxs = buildResult.status === 'no-valid-txs' ? 0 : buildResult.numTxs;
|
|
581
|
+
if (buildResult.status === 'no-valid-txs' || (!forceCreate && numTxs < minValidTxs)) {
|
|
582
|
+
this.log.warn(
|
|
583
|
+
`Block ${blockNumber} at index ${indexWithinCheckpoint} on slot ${this.slot} has too few valid txs to be proposed`,
|
|
584
|
+
{ slot: this.slot, blockNumber, numTxs, indexWithinCheckpoint, minValidTxs, buildResult: buildResult.status },
|
|
585
|
+
);
|
|
586
|
+
this.eventEmitter.emit('block-build-failed', { reason: `Insufficient valid txs`, slot: this.slot });
|
|
587
|
+
this.metrics.recordBlockProposalFailed('insufficient_valid_txs');
|
|
588
|
+
return undefined;
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
// Block creation succeeded, emit stats and metrics
|
|
592
|
+
const { publicGas, block, publicProcessorDuration, usedTxs, usedTxBlobFields, blockBuildDuration } = buildResult;
|
|
593
|
+
|
|
594
|
+
const blockStats = {
|
|
595
|
+
eventName: 'l2-block-built',
|
|
596
|
+
duration: blockBuildDuration,
|
|
597
|
+
publicProcessDuration: publicProcessorDuration,
|
|
598
|
+
...block.getStats(),
|
|
599
|
+
} satisfies L2BlockBuiltStats;
|
|
600
|
+
|
|
601
|
+
const blockHash = await block.hash();
|
|
602
|
+
const txHashes = block.body.txEffects.map(tx => tx.txHash);
|
|
603
|
+
const manaPerSec = publicGas.l2Gas / (blockBuildDuration / 1000);
|
|
604
|
+
|
|
605
|
+
this.log.info(
|
|
606
|
+
`Built block ${block.number} at checkpoint ${this.checkpointNumber} for slot ${this.slot} with ${numTxs} txs`,
|
|
607
|
+
{ blockHash, txHashes, manaPerSec, ...blockStats },
|
|
608
|
+
);
|
|
609
|
+
|
|
610
|
+
this.eventEmitter.emit('block-proposed', { blockNumber: block.number, slot: this.slot });
|
|
611
|
+
this.metrics.recordBuiltBlock(blockBuildDuration, publicGas.l2Gas);
|
|
612
|
+
|
|
613
|
+
return { block, usedTxs, remainingBlobFields: maxBlobFieldsForTxs - usedTxBlobFields };
|
|
614
|
+
} catch (err: any) {
|
|
615
|
+
this.eventEmitter.emit('block-build-failed', { reason: err.message, slot: this.slot });
|
|
616
|
+
this.log.error(`Error building block`, err, { blockNumber, slot: this.slot });
|
|
617
|
+
this.metrics.recordBlockProposalFailed(err.name || 'unknown_error');
|
|
618
|
+
this.metrics.recordFailedBlock();
|
|
619
|
+
return { error: err };
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
/** Uses the checkpoint builder to build a block, catching specific txs */
|
|
624
|
+
private async buildSingleBlockWithCheckpointBuilder(
|
|
625
|
+
checkpointBuilder: CheckpointBuilder,
|
|
626
|
+
pendingTxs: AsyncIterable<Tx>,
|
|
627
|
+
blockNumber: BlockNumber,
|
|
628
|
+
blockTimestamp: bigint,
|
|
629
|
+
blockBuilderOptions: PublicProcessorLimits,
|
|
630
|
+
) {
|
|
631
|
+
try {
|
|
632
|
+
const workTimer = new Timer();
|
|
633
|
+
const result = await checkpointBuilder.buildBlock(pendingTxs, blockNumber, blockTimestamp, blockBuilderOptions);
|
|
634
|
+
const blockBuildDuration = workTimer.ms();
|
|
635
|
+
return { ...result, blockBuildDuration, status: 'success' as const };
|
|
636
|
+
} catch (err: unknown) {
|
|
637
|
+
if (isErrorClass(err, NoValidTxsError)) {
|
|
638
|
+
return { failedTxs: err.failedTxs, status: 'no-valid-txs' as const };
|
|
639
|
+
}
|
|
640
|
+
throw err;
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
/** Waits until minTxs are available on the pool for building a block. */
|
|
645
|
+
@trackSpan('CheckpointProposalJob.waitForMinTxs')
|
|
646
|
+
private async waitForMinTxs(opts: {
|
|
647
|
+
forceCreate?: boolean;
|
|
648
|
+
blockNumber: BlockNumber;
|
|
649
|
+
indexWithinCheckpoint: IndexWithinCheckpoint;
|
|
650
|
+
buildDeadline: Date | undefined;
|
|
651
|
+
}): Promise<{ canStartBuilding: boolean; availableTxs: number }> {
|
|
652
|
+
const { indexWithinCheckpoint, blockNumber, buildDeadline, forceCreate } = opts;
|
|
653
|
+
|
|
654
|
+
// We only allow a block with 0 txs in the first block of the checkpoint
|
|
655
|
+
const minTxs = indexWithinCheckpoint > 0 && this.config.minTxsPerBlock === 0 ? 1 : this.config.minTxsPerBlock;
|
|
656
|
+
|
|
657
|
+
// Deadline is undefined if we are not enforcing the timetable, meaning we'll exit immediately when out of time
|
|
658
|
+
const startBuildingDeadline = buildDeadline
|
|
659
|
+
? new Date(buildDeadline.getTime() - this.timetable.minExecutionTime * 1000)
|
|
660
|
+
: undefined;
|
|
661
|
+
|
|
662
|
+
let availableTxs = await this.p2pClient.getPendingTxCount();
|
|
663
|
+
|
|
664
|
+
while (!forceCreate && availableTxs < minTxs) {
|
|
665
|
+
// If we're past deadline, or we have no deadline, give up
|
|
666
|
+
const now = this.dateProvider.nowAsDate();
|
|
667
|
+
if (startBuildingDeadline === undefined || now >= startBuildingDeadline) {
|
|
668
|
+
return { canStartBuilding: false, availableTxs: availableTxs };
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
// Wait a bit before checking again
|
|
672
|
+
this.setStateFn(SequencerState.WAITING_FOR_TXS, this.slot);
|
|
673
|
+
this.log.verbose(
|
|
674
|
+
`Waiting for enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.slot} (have ${availableTxs} but need ${minTxs})`,
|
|
675
|
+
{ blockNumber, slot: this.slot, indexWithinCheckpoint },
|
|
676
|
+
);
|
|
677
|
+
await sleep(TXS_POLLING_MS);
|
|
678
|
+
availableTxs = await this.p2pClient.getPendingTxCount();
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
return { canStartBuilding: true, availableTxs };
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
/**
|
|
685
|
+
* Waits for enough attestations to be collected via p2p.
|
|
686
|
+
* This is run after all blocks for the checkpoint have been built.
|
|
687
|
+
*/
|
|
688
|
+
@trackSpan('CheckpointProposalJob.waitForAttestations')
|
|
689
|
+
private async waitForAttestations(proposal: CheckpointProposal): Promise<CommitteeAttestationsAndSigners> {
|
|
690
|
+
if (this.config.fishermanMode) {
|
|
691
|
+
this.log.debug('Skipping attestation collection in fisherman mode');
|
|
692
|
+
return CommitteeAttestationsAndSigners.empty();
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
const slotNumber = proposal.slotNumber;
|
|
696
|
+
const { committee, seed, epoch } = await this.epochCache.getCommittee(slotNumber);
|
|
697
|
+
|
|
698
|
+
if (!committee) {
|
|
699
|
+
throw new Error('No committee when collecting attestations');
|
|
700
|
+
} else if (committee.length === 0) {
|
|
701
|
+
this.log.verbose(`Attesting committee is empty`);
|
|
702
|
+
return CommitteeAttestationsAndSigners.empty();
|
|
703
|
+
} else {
|
|
704
|
+
this.log.debug(`Attesting committee length is ${committee.length}`, { committee });
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
const numberOfRequiredAttestations = Math.floor((committee.length * 2) / 3) + 1;
|
|
708
|
+
|
|
709
|
+
if (this.config.skipCollectingAttestations) {
|
|
710
|
+
this.log.warn('Skipping attestation collection as per config (attesting with own keys only)');
|
|
711
|
+
const attestations = await this.validatorClient?.collectOwnAttestations(proposal);
|
|
712
|
+
return new CommitteeAttestationsAndSigners(orderAttestations(attestations ?? [], committee));
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
const attestationTimeAllowed = this.config.enforceTimeTable
|
|
716
|
+
? this.timetable.getMaxAllowedTime(SequencerState.PUBLISHING_CHECKPOINT)!
|
|
717
|
+
: this.l1Constants.slotDuration;
|
|
718
|
+
const attestationDeadline = new Date((this.getSlotStartBuildTimestamp() + attestationTimeAllowed) * 1000);
|
|
719
|
+
|
|
720
|
+
this.metrics.recordRequiredAttestations(numberOfRequiredAttestations, attestationTimeAllowed);
|
|
721
|
+
|
|
722
|
+
const collectAttestationsTimer = new Timer();
|
|
723
|
+
let collectedAttestationsCount: number = 0;
|
|
724
|
+
try {
|
|
725
|
+
const attestations = await this.validatorClient.collectAttestations(
|
|
726
|
+
proposal,
|
|
727
|
+
numberOfRequiredAttestations,
|
|
728
|
+
attestationDeadline,
|
|
729
|
+
);
|
|
730
|
+
|
|
731
|
+
collectedAttestationsCount = attestations.length;
|
|
732
|
+
|
|
733
|
+
// Rollup contract requires that the signatures are provided in the order of the committee
|
|
734
|
+
const sorted = orderAttestations(attestations, committee);
|
|
735
|
+
|
|
736
|
+
// Manipulate the attestations if we've been configured to do so
|
|
737
|
+
if (this.config.injectFakeAttestation || this.config.shuffleAttestationOrdering) {
|
|
738
|
+
return this.manipulateAttestations(proposal.slotNumber, epoch, seed, committee, sorted);
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
return new CommitteeAttestationsAndSigners(sorted);
|
|
742
|
+
} catch (err) {
|
|
743
|
+
if (err && err instanceof AttestationTimeoutError) {
|
|
744
|
+
collectedAttestationsCount = err.collectedCount;
|
|
745
|
+
}
|
|
746
|
+
throw err;
|
|
747
|
+
} finally {
|
|
748
|
+
this.metrics.recordCollectedAttestations(collectedAttestationsCount, collectAttestationsTimer.ms());
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
/** Breaks the attestations before publishing based on attack configs */
|
|
753
|
+
private manipulateAttestations(
|
|
754
|
+
slotNumber: SlotNumber,
|
|
755
|
+
epoch: EpochNumber,
|
|
756
|
+
seed: bigint,
|
|
757
|
+
committee: EthAddress[],
|
|
758
|
+
attestations: CommitteeAttestation[],
|
|
759
|
+
) {
|
|
760
|
+
// Compute the proposer index in the committee, since we dont want to tweak it.
|
|
761
|
+
// Otherwise, the L1 rollup contract will reject the block outright.
|
|
762
|
+
const proposerIndex = Number(
|
|
763
|
+
this.epochCache.computeProposerIndex(slotNumber, epoch, seed, BigInt(committee.length)),
|
|
764
|
+
);
|
|
765
|
+
|
|
766
|
+
if (this.config.injectFakeAttestation) {
|
|
767
|
+
// Find non-empty attestations that are not from the proposer
|
|
768
|
+
const nonProposerIndices: number[] = [];
|
|
769
|
+
for (let i = 0; i < attestations.length; i++) {
|
|
770
|
+
if (!attestations[i].signature.isEmpty() && i !== proposerIndex) {
|
|
771
|
+
nonProposerIndices.push(i);
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
if (nonProposerIndices.length > 0) {
|
|
775
|
+
const targetIndex = nonProposerIndices[randomInt(nonProposerIndices.length)];
|
|
776
|
+
this.log.warn(`Injecting fake attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`);
|
|
777
|
+
unfreeze(attestations[targetIndex]).signature = Signature.random();
|
|
778
|
+
}
|
|
779
|
+
return new CommitteeAttestationsAndSigners(attestations);
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
if (this.config.shuffleAttestationOrdering) {
|
|
783
|
+
this.log.warn(`Shuffling attestation ordering in checkpoint for slot ${slotNumber} (proposer #${proposerIndex})`);
|
|
784
|
+
|
|
785
|
+
const shuffled = [...attestations];
|
|
786
|
+
const [i, j] = [(proposerIndex + 1) % shuffled.length, (proposerIndex + 2) % shuffled.length];
|
|
787
|
+
const valueI = shuffled[i];
|
|
788
|
+
const valueJ = shuffled[j];
|
|
789
|
+
shuffled[i] = valueJ;
|
|
790
|
+
shuffled[j] = valueI;
|
|
791
|
+
|
|
792
|
+
const signers = new CommitteeAttestationsAndSigners(attestations).getSigners();
|
|
793
|
+
return new MaliciousCommitteeAttestationsAndSigners(shuffled, signers);
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
return new CommitteeAttestationsAndSigners(attestations);
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
private async dropFailedTxsFromP2P(failedTxs: FailedTx[]) {
|
|
800
|
+
if (failedTxs.length === 0) {
|
|
801
|
+
return;
|
|
802
|
+
}
|
|
803
|
+
const failedTxData = failedTxs.map(fail => fail.tx);
|
|
804
|
+
const failedTxHashes = failedTxData.map(tx => tx.getTxHash());
|
|
805
|
+
this.log.verbose(`Dropping failed txs ${failedTxHashes.join(', ')}`);
|
|
806
|
+
await this.p2pClient.deleteTxs(failedTxHashes);
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
/**
|
|
810
|
+
* Adds the proposed block to the archiver so it's available via P2P.
|
|
811
|
+
* Gossip doesn't echo messages back to the sender, so the proposer's archiver/world-state
|
|
812
|
+
* would never receive its own block without this explicit sync.
|
|
813
|
+
*/
|
|
814
|
+
private async syncProposedBlockToArchiver(block: L2Block): Promise<void> {
|
|
815
|
+
if (this.config.skipPushProposedBlocksToArchiver !== false) {
|
|
816
|
+
this.log.warn(`Skipping push of proposed block ${block.number} to archiver`, {
|
|
817
|
+
blockNumber: block.number,
|
|
818
|
+
slot: block.header.globalVariables.slotNumber,
|
|
819
|
+
});
|
|
820
|
+
return;
|
|
821
|
+
}
|
|
822
|
+
this.log.debug(`Syncing proposed block ${block.number} to archiver`, {
|
|
823
|
+
blockNumber: block.number,
|
|
824
|
+
slot: block.header.globalVariables.slotNumber,
|
|
825
|
+
});
|
|
826
|
+
await this.blockSink.addBlock(block);
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
/** Runs fee analysis and logs checkpoint outcome as fisherman */
|
|
830
|
+
private async handleCheckpointEndAsFisherman(checkpoint: Checkpoint | undefined) {
|
|
831
|
+
// Perform L1 fee analysis before clearing requests
|
|
832
|
+
// The callback is invoked asynchronously after the next block is mined
|
|
833
|
+
const feeAnalysis = await this.publisher.analyzeL1Fees(this.slot, analysis =>
|
|
834
|
+
this.metrics.recordFishermanFeeAnalysis(analysis),
|
|
835
|
+
);
|
|
836
|
+
|
|
837
|
+
if (checkpoint) {
|
|
838
|
+
this.log.info(`Validation checkpoint building SUCCEEDED for slot ${this.slot}`, {
|
|
839
|
+
...checkpoint.toCheckpointInfo(),
|
|
840
|
+
...checkpoint.getStats(),
|
|
841
|
+
feeAnalysisId: feeAnalysis?.id,
|
|
842
|
+
});
|
|
843
|
+
} else {
|
|
844
|
+
this.log.warn(`Validation block building FAILED for slot ${this.slot}`, {
|
|
845
|
+
slot: this.slot,
|
|
846
|
+
feeAnalysisId: feeAnalysis?.id,
|
|
847
|
+
});
|
|
848
|
+
this.metrics.recordBlockProposalFailed('block_build_failed');
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
this.publisher.clearPendingRequests();
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
/** Waits until a specific time within the current slot */
|
|
855
|
+
@trackSpan('CheckpointProposalJob.waitUntilTimeInSlot')
|
|
856
|
+
protected async waitUntilTimeInSlot(targetSecondsIntoSlot: number): Promise<void> {
|
|
857
|
+
const slotStartTimestamp = this.getSlotStartBuildTimestamp();
|
|
858
|
+
const targetTimestamp = slotStartTimestamp + targetSecondsIntoSlot;
|
|
859
|
+
await sleepUntil(new Date(targetTimestamp * 1000), this.dateProvider.nowAsDate());
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
private getSlotStartBuildTimestamp(): number {
|
|
863
|
+
return getSlotStartBuildTimestamp(this.slot, this.l1Constants);
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
private getSecondsIntoSlot(): number {
|
|
867
|
+
const slotStartTimestamp = this.getSlotStartBuildTimestamp();
|
|
868
|
+
return Number((this.dateProvider.now() / 1000 - slotStartTimestamp).toFixed(3));
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
public getPublisher() {
|
|
872
|
+
return this.publisher;
|
|
873
|
+
}
|
|
874
|
+
}
|