@aztec/sequencer-client 0.0.1-commit.d3ec352c → 0.0.1-commit.d58ff9d0
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/README.md +281 -21
- package/dest/client/sequencer-client.d.ts +41 -18
- package/dest/client/sequencer-client.d.ts.map +1 -1
- package/dest/client/sequencer-client.js +88 -43
- package/dest/config.d.ts +41 -8
- package/dest/config.d.ts.map +1 -1
- package/dest/config.js +146 -55
- package/dest/global_variable_builder/fee_predictor.d.ts +37 -0
- package/dest/global_variable_builder/fee_predictor.d.ts.map +1 -0
- package/dest/global_variable_builder/fee_predictor.js +138 -0
- package/dest/global_variable_builder/fee_provider.d.ts +21 -0
- package/dest/global_variable_builder/fee_provider.d.ts.map +1 -0
- package/dest/global_variable_builder/fee_provider.js +80 -0
- package/dest/global_variable_builder/global_builder.d.ts +20 -26
- package/dest/global_variable_builder/global_builder.d.ts.map +1 -1
- package/dest/global_variable_builder/global_builder.js +28 -75
- package/dest/global_variable_builder/index.d.ts +4 -2
- package/dest/global_variable_builder/index.d.ts.map +1 -1
- package/dest/global_variable_builder/index.js +2 -0
- 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 +57 -20
- package/dest/publisher/config.d.ts.map +1 -1
- package/dest/publisher/config.js +134 -39
- package/dest/publisher/index.d.ts +2 -1
- package/dest/publisher/index.d.ts.map +1 -1
- package/dest/publisher/l1_to_l2_messaging.d.ts +21 -0
- package/dest/publisher/l1_to_l2_messaging.d.ts.map +1 -0
- package/dest/publisher/l1_to_l2_messaging.js +70 -0
- package/dest/publisher/l1_tx_failed_store/factory.d.ts +11 -0
- package/dest/publisher/l1_tx_failed_store/factory.d.ts.map +1 -0
- package/dest/publisher/l1_tx_failed_store/factory.js +22 -0
- package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts +98 -0
- package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts.map +1 -0
- package/dest/publisher/l1_tx_failed_store/failed_tx_store.js +68 -0
- package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts +15 -0
- package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts.map +1 -0
- package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.js +36 -0
- package/dest/publisher/l1_tx_failed_store/index.d.ts +4 -0
- package/dest/publisher/l1_tx_failed_store/index.d.ts.map +1 -0
- package/dest/publisher/l1_tx_failed_store/index.js +3 -0
- package/dest/publisher/sequencer-bundle-simulator.d.ts +96 -0
- package/dest/publisher/sequencer-bundle-simulator.d.ts.map +1 -0
- package/dest/publisher/sequencer-bundle-simulator.js +198 -0
- package/dest/publisher/sequencer-publisher-factory.d.ts +15 -8
- package/dest/publisher/sequencer-publisher-factory.d.ts.map +1 -1
- package/dest/publisher/sequencer-publisher-factory.js +28 -4
- 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 +152 -90
- package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
- package/dest/publisher/sequencer-publisher.js +1257 -421
- package/dest/publisher/write_json.d.ts +11 -0
- package/dest/publisher/write_json.d.ts.map +1 -0
- package/dest/publisher/write_json.js +57 -0
- package/dest/sequencer/automine/automine_factory.d.ts +56 -0
- package/dest/sequencer/automine/automine_factory.d.ts.map +1 -0
- package/dest/sequencer/automine/automine_factory.js +85 -0
- package/dest/sequencer/automine/automine_sequencer.d.ts +189 -0
- package/dest/sequencer/automine/automine_sequencer.d.ts.map +1 -0
- package/dest/sequencer/automine/automine_sequencer.js +690 -0
- package/dest/sequencer/automine/index.d.ts +3 -0
- package/dest/sequencer/automine/index.d.ts.map +1 -0
- package/dest/sequencer/automine/index.js +2 -0
- package/dest/sequencer/checkpoint_proposal_job.d.ts +158 -0
- package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -0
- package/dest/sequencer/checkpoint_proposal_job.js +1801 -0
- package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts +34 -0
- package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts.map +1 -0
- package/dest/sequencer/checkpoint_proposal_job_metrics.js +72 -0
- package/dest/sequencer/checkpoint_voter.d.ts +34 -0
- package/dest/sequencer/checkpoint_voter.d.ts.map +1 -0
- package/dest/sequencer/checkpoint_voter.js +106 -0
- package/dest/sequencer/config.d.ts +3 -2
- package/dest/sequencer/config.d.ts.map +1 -1
- package/dest/sequencer/events.d.ts +103 -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 +42 -7
- package/dest/sequencer/metrics.d.ts.map +1 -1
- package/dest/sequencer/metrics.js +241 -72
- package/dest/sequencer/requests_tracker.d.ts +22 -0
- package/dest/sequencer/requests_tracker.d.ts.map +1 -0
- package/dest/sequencer/requests_tracker.js +33 -0
- package/dest/sequencer/sequencer.d.ts +251 -138
- package/dest/sequencer/sequencer.d.ts.map +1 -1
- package/dest/sequencer/sequencer.js +1190 -704
- 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 +8 -9
- 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 +231 -0
- package/dest/test/utils.d.ts +67 -0
- package/dest/test/utils.d.ts.map +1 -0
- package/dest/test/utils.js +122 -0
- package/package.json +32 -29
- package/src/client/sequencer-client.ts +118 -66
- package/src/config.ts +173 -64
- package/src/global_variable_builder/README.md +44 -0
- package/src/global_variable_builder/fee_predictor.ts +182 -0
- package/src/global_variable_builder/fee_provider.ts +97 -0
- package/src/global_variable_builder/global_builder.ts +45 -110
- package/src/global_variable_builder/index.ts +3 -1
- package/src/index.ts +1 -7
- package/src/publisher/config.ts +182 -46
- package/src/publisher/index.ts +3 -0
- package/src/publisher/l1_to_l2_messaging.ts +85 -0
- package/src/publisher/l1_tx_failed_store/factory.ts +32 -0
- package/src/publisher/l1_tx_failed_store/failed_tx_store.ts +164 -0
- package/src/publisher/l1_tx_failed_store/file_store_failed_tx_store.ts +47 -0
- package/src/publisher/l1_tx_failed_store/index.ts +3 -0
- package/src/publisher/sequencer-bundle-simulator.ts +254 -0
- package/src/publisher/sequencer-publisher-factory.ts +43 -13
- package/src/publisher/sequencer-publisher-metrics.ts +19 -71
- package/src/publisher/sequencer-publisher.ts +1042 -542
- package/src/publisher/write_json.ts +78 -0
- package/src/sequencer/README.md +243 -0
- package/src/sequencer/automine/README.md +60 -0
- package/src/sequencer/automine/automine_factory.ts +152 -0
- package/src/sequencer/automine/automine_sequencer.ts +796 -0
- package/src/sequencer/automine/index.ts +6 -0
- package/src/sequencer/checkpoint_proposal_job.ts +1652 -0
- package/src/sequencer/checkpoint_proposal_job_metrics.ts +128 -0
- package/src/sequencer/checkpoint_voter.ts +119 -0
- package/src/sequencer/config.ts +2 -1
- package/src/sequencer/events.ts +88 -0
- package/src/sequencer/index.ts +3 -1
- package/src/sequencer/metrics.ts +302 -83
- package/src/sequencer/requests_tracker.ts +43 -0
- package/src/sequencer/sequencer.ts +1011 -898
- package/src/sequencer/types.ts +6 -0
- package/src/sequencer/utils.ts +18 -9
- package/src/test/index.ts +7 -8
- package/src/test/mock_checkpoint_builder.ts +323 -0
- package/src/test/utils.ts +218 -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/sequencer/timetable.d.ts +0 -50
- package/dest/sequencer/timetable.d.ts.map +0 -1
- package/dest/sequencer/timetable.js +0 -137
- 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/sequencer/timetable.ts +0 -188
- package/src/tx_validator/nullifier_cache.ts +0 -30
- package/src/tx_validator/tx_validator_factory.ts +0 -133
|
@@ -1,566 +1,804 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import type
|
|
4
|
-
import { FormattedViemError, NoCommitteeError, type RollupContract } from '@aztec/ethereum';
|
|
1
|
+
import { getKzg } from '@aztec/blob-lib';
|
|
2
|
+
import { type EpochCache, PROPOSER_PIPELINING_SLOT_OFFSET } from '@aztec/epoch-cache';
|
|
3
|
+
import { NoCommitteeError, type RollupContract } from '@aztec/ethereum/contracts';
|
|
5
4
|
import { BlockNumber, CheckpointNumber, EpochNumber, SlotNumber } from '@aztec/foundation/branded-types';
|
|
6
|
-
import { omit, pick } from '@aztec/foundation/collection';
|
|
7
|
-
import {
|
|
5
|
+
import { merge, omit, pick } from '@aztec/foundation/collection';
|
|
6
|
+
import { Fr } from '@aztec/foundation/curves/bn254';
|
|
8
7
|
import { EthAddress } from '@aztec/foundation/eth-address';
|
|
9
|
-
import {
|
|
10
|
-
import { Fr } from '@aztec/foundation/fields';
|
|
11
|
-
import { createLogger } from '@aztec/foundation/log';
|
|
8
|
+
import { type Logger, createLogger } from '@aztec/foundation/log';
|
|
12
9
|
import { RunningPromise } from '@aztec/foundation/running-promise';
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
10
|
+
import type { DateProvider } from '@aztec/foundation/timer';
|
|
11
|
+
import type { TypedEventEmitter } from '@aztec/foundation/types';
|
|
15
12
|
import type { P2P } from '@aztec/p2p';
|
|
16
13
|
import type { SlasherClientInterface } from '@aztec/slasher';
|
|
17
|
-
import {
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
14
|
+
import type {
|
|
15
|
+
BlockData,
|
|
16
|
+
L2BlockSink,
|
|
17
|
+
L2BlockSource,
|
|
18
|
+
ProposedCheckpointSink,
|
|
19
|
+
ValidateCheckpointResult,
|
|
23
20
|
} from '@aztec/stdlib/block';
|
|
24
|
-
import { type L1RollupConstants, getSlotAtTimestamp, getSlotStartBuildTimestamp } from '@aztec/stdlib/epoch-helpers';
|
|
25
|
-
import { Gas } from '@aztec/stdlib/gas';
|
|
26
21
|
import {
|
|
27
|
-
type
|
|
28
|
-
type
|
|
22
|
+
type Checkpoint,
|
|
23
|
+
type ProposedCheckpointData,
|
|
24
|
+
buildCheckpointSimulationOverridesPlan,
|
|
25
|
+
} from '@aztec/stdlib/checkpoint';
|
|
26
|
+
import type { ChainConfig } from '@aztec/stdlib/config';
|
|
27
|
+
import { getEpochAtSlot } from '@aztec/stdlib/epoch-helpers';
|
|
28
|
+
import {
|
|
29
|
+
MIN_PER_BLOCK_ALLOCATION_MULTIPLIER,
|
|
30
|
+
MIN_PER_BLOCK_DA_ALLOCATION_MULTIPLIER,
|
|
31
|
+
computeNetworkTxGasLimits,
|
|
32
|
+
} from '@aztec/stdlib/gas';
|
|
33
|
+
import {
|
|
34
|
+
type ResolvedSequencerConfig,
|
|
35
|
+
type SequencerConfig,
|
|
29
36
|
SequencerConfigSchema,
|
|
30
37
|
type WorldStateSynchronizer,
|
|
31
38
|
} from '@aztec/stdlib/interfaces/server';
|
|
32
39
|
import type { L1ToL2MessageSource } from '@aztec/stdlib/messaging';
|
|
33
|
-
import type {
|
|
34
|
-
import { orderAttestations } from '@aztec/stdlib/p2p';
|
|
35
|
-
import { CheckpointHeader } from '@aztec/stdlib/rollup';
|
|
40
|
+
import type { CoordinationSignatureContext } from '@aztec/stdlib/p2p';
|
|
36
41
|
import { pickFromSchema } from '@aztec/stdlib/schemas';
|
|
37
|
-
import
|
|
38
|
-
import { MerkleTreeId } from '@aztec/stdlib/trees';
|
|
39
|
-
import { ContentCommitment, type FailedTx, GlobalVariables, Tx } from '@aztec/stdlib/tx';
|
|
40
|
-
import { AttestationTimeoutError } from '@aztec/stdlib/validators';
|
|
42
|
+
import { ProposerTimetable, buildProposerTimetable } from '@aztec/stdlib/timetable';
|
|
41
43
|
import { Attributes, type TelemetryClient, type Tracer, getTelemetryClient, trackSpan } from '@aztec/telemetry-client';
|
|
42
|
-
import type
|
|
44
|
+
import { FullNodeCheckpointsBuilder, NodeKeystoreAdapter, type ValidatorClient } from '@aztec/validator-client';
|
|
43
45
|
|
|
44
46
|
import EventEmitter from 'node:events';
|
|
45
|
-
import type { TypedDataDefinition } from 'viem';
|
|
46
47
|
|
|
48
|
+
import { DefaultSequencerConfig } from '../config.js';
|
|
47
49
|
import type { GlobalVariableBuilder } from '../global_variable_builder/global_builder.js';
|
|
48
50
|
import type { SequencerPublisherFactory } from '../publisher/sequencer-publisher-factory.js';
|
|
49
|
-
import type {
|
|
50
|
-
import
|
|
51
|
-
import {
|
|
51
|
+
import type { InvalidateCheckpointRequest, SequencerPublisher } from '../publisher/sequencer-publisher.js';
|
|
52
|
+
import { CheckpointProposalJob } from './checkpoint_proposal_job.js';
|
|
53
|
+
import { CheckpointProposalJobMetrics } from './checkpoint_proposal_job_metrics.js';
|
|
54
|
+
import { CheckpointVoter } from './checkpoint_voter.js';
|
|
55
|
+
import { SequencerInterruptedError } from './errors.js';
|
|
56
|
+
import type { SequencerEvents } from './events.js';
|
|
52
57
|
import { SequencerMetrics } from './metrics.js';
|
|
53
|
-
import {
|
|
54
|
-
import {
|
|
58
|
+
import { RequestsTracker } from './requests_tracker.js';
|
|
59
|
+
import type { SequencerRollupConstants } from './types.js';
|
|
60
|
+
import { SequencerState } from './utils.js';
|
|
55
61
|
|
|
56
62
|
export { SequencerState };
|
|
57
63
|
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
}) => void;
|
|
67
|
-
['proposer-rollup-check-failed']: (args: { reason: string }) => void;
|
|
68
|
-
['tx-count-check-failed']: (args: { minTxs: number; availableTxs: number }) => void;
|
|
69
|
-
['block-build-failed']: (args: { reason: string }) => void;
|
|
70
|
-
['block-publish-failed']: (args: {
|
|
71
|
-
successfulActions?: Action[];
|
|
72
|
-
failedActions?: Action[];
|
|
73
|
-
sentActions?: Action[];
|
|
74
|
-
expiredActions?: Action[];
|
|
75
|
-
}) => void;
|
|
76
|
-
['block-published']: (args: { blockNumber: BlockNumber; slot: number }) => void;
|
|
64
|
+
/** Slot snapshot used to prepare a checkpoint proposal. */
|
|
65
|
+
type SequencerSlotContext = {
|
|
66
|
+
slot: SlotNumber;
|
|
67
|
+
targetSlot: SlotNumber;
|
|
68
|
+
epoch: EpochNumber;
|
|
69
|
+
targetEpoch: EpochNumber;
|
|
70
|
+
ts: bigint;
|
|
71
|
+
nowSeconds: bigint;
|
|
77
72
|
};
|
|
78
73
|
|
|
79
74
|
/**
|
|
80
75
|
* Sequencer client
|
|
81
|
-
* -
|
|
82
|
-
* -
|
|
83
|
-
* -
|
|
84
|
-
* -
|
|
85
|
-
* -
|
|
86
|
-
* - Publishes L1 tx(s) to the rollup contract via RollupPublisher.
|
|
76
|
+
* - Checks whether it is elected as proposer for the next slot
|
|
77
|
+
* - Builds multiple blocks and broadcasts them
|
|
78
|
+
* - Collects attestations for the checkpoint
|
|
79
|
+
* - Publishes the checkpoint to L1
|
|
80
|
+
* - Votes for proposals and slashes on L1
|
|
87
81
|
*/
|
|
88
82
|
export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<SequencerEvents>) {
|
|
89
|
-
|
|
90
|
-
private pollingIntervalMs: number = 1000;
|
|
91
|
-
private maxTxsPerBlock = 32;
|
|
92
|
-
private minTxsPerBlock = 1;
|
|
93
|
-
private maxL1TxInclusionTimeIntoSlot = 0;
|
|
83
|
+
protected runningPromise?: RunningPromise;
|
|
94
84
|
private state = SequencerState.STOPPED;
|
|
95
|
-
private
|
|
96
|
-
|
|
85
|
+
private stateSlotNumber: SlotNumber | undefined;
|
|
86
|
+
/** Wall-clock time (ms, via the date provider) at which the current state was entered. */
|
|
87
|
+
private stateEnteredAtMs: number;
|
|
97
88
|
private metrics: SequencerMetrics;
|
|
89
|
+
private checkpointProposalJobMetrics: CheckpointProposalJobMetrics;
|
|
90
|
+
private readonly stateLog: Logger;
|
|
91
|
+
|
|
92
|
+
/** The last slot for which we attempted to perform our fallback duties (votes and/or prune) with degraded block production */
|
|
93
|
+
private lastSlotForFallbackAction: SlotNumber | undefined;
|
|
94
|
+
|
|
95
|
+
/** The (checkpoint, slot) of the last invalidation request we successfully simulated, to prevent
|
|
96
|
+
* re-simulating and re-submitting the same invalidation across the many ticks within a single slot. */
|
|
97
|
+
private lastInvalidationAttempt: { slot: SlotNumber; checkpointNumber: CheckpointNumber } | undefined;
|
|
98
|
+
|
|
99
|
+
/** The last slot for which we logged "no committee" warning, to avoid spam */
|
|
100
|
+
private lastSlotForNoCommitteeWarning: SlotNumber | undefined;
|
|
101
|
+
|
|
102
|
+
/** The last slot for which we triggered a checkpoint proposal job, to prevent duplicate attempts. */
|
|
103
|
+
protected lastSlotForCheckpointProposalJob: SlotNumber | undefined;
|
|
98
104
|
|
|
99
|
-
|
|
105
|
+
/** Last successful checkpoint proposed */
|
|
106
|
+
private lastCheckpointProposed: Checkpoint | undefined;
|
|
100
107
|
|
|
101
|
-
|
|
108
|
+
/** The last epoch for which we logged strategy comparison in fisherman mode. */
|
|
109
|
+
private lastEpochForStrategyComparison: EpochNumber | undefined;
|
|
102
110
|
|
|
103
|
-
/** The last
|
|
104
|
-
|
|
111
|
+
/** The last checkpoint proposal job, tracked so we can await its pending L1 submission during shutdown. */
|
|
112
|
+
protected lastCheckpointProposalJob: CheckpointProposalJob | undefined;
|
|
105
113
|
|
|
106
|
-
/**
|
|
107
|
-
|
|
114
|
+
/**
|
|
115
|
+
* In-flight fire-and-forget requests that {@link stop} interrupts and drains, and {@link pause} awaits
|
|
116
|
+
* untouched: the checkpoint proposal jobs' backgrounded L1 submissions (each job is handed this shared
|
|
117
|
+
* tracker) plus the sequencer's own fallback submissions (votes/prune when we cannot build, or
|
|
118
|
+
* escape-hatch votes). Each fallback send is gated by its wrapper publisher's interruptible target-slot
|
|
119
|
+
* sleep; the tracked interrupt wakes that sleep so the send short-circuits without publishing. A wrapper
|
|
120
|
+
* is created for a single send and is never restarted, so once interrupted its sleeper can never publish
|
|
121
|
+
* a stale-slot tx, even after the pooled publishers are restarted by a later {@link start}.
|
|
122
|
+
*/
|
|
123
|
+
protected readonly pendingRequests = new RequestsTracker();
|
|
108
124
|
|
|
109
|
-
/**
|
|
110
|
-
protected timetable!:
|
|
111
|
-
protected enforceTimeTable: boolean = false;
|
|
125
|
+
/** Proposer schedule and block sub-slot timetable for the sequencer, rebuilt on every config update. */
|
|
126
|
+
protected timetable!: ProposerTimetable;
|
|
112
127
|
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
// This will get re-assigned every time the sequencer goes to build a new block to a publisher that is valid
|
|
117
|
-
// for the block proposer.
|
|
118
|
-
protected publisher: SequencerPublisher | undefined;
|
|
128
|
+
/** Config for the sequencer */
|
|
129
|
+
protected config: ResolvedSequencerConfig = DefaultSequencerConfig;
|
|
130
|
+
private readonly signatureContext: CoordinationSignatureContext;
|
|
119
131
|
|
|
120
132
|
constructor(
|
|
121
133
|
protected publisherFactory: SequencerPublisherFactory,
|
|
122
|
-
protected validatorClient: ValidatorClient
|
|
134
|
+
protected validatorClient: ValidatorClient,
|
|
123
135
|
protected globalsBuilder: GlobalVariableBuilder,
|
|
124
136
|
protected p2pClient: P2P,
|
|
125
137
|
protected worldState: WorldStateSynchronizer,
|
|
126
138
|
protected slasherClient: SlasherClientInterface | undefined,
|
|
127
|
-
protected l2BlockSource: L2BlockSource,
|
|
139
|
+
protected l2BlockSource: L2BlockSource & L2BlockSink & ProposedCheckpointSink,
|
|
128
140
|
protected l1ToL2MessageSource: L1ToL2MessageSource,
|
|
129
|
-
protected
|
|
141
|
+
protected checkpointsBuilder: FullNodeCheckpointsBuilder,
|
|
130
142
|
protected l1Constants: SequencerRollupConstants,
|
|
131
143
|
protected dateProvider: DateProvider,
|
|
132
144
|
protected epochCache: EpochCache,
|
|
133
145
|
protected rollupContract: RollupContract,
|
|
134
|
-
|
|
146
|
+
config: SequencerConfig & Pick<ChainConfig, 'l1ChainId' | 'rollupAddress'>,
|
|
135
147
|
protected telemetry: TelemetryClient = getTelemetryClient(),
|
|
136
148
|
protected log = createLogger('sequencer'),
|
|
137
149
|
) {
|
|
138
150
|
super();
|
|
151
|
+
this.stateLog = log.createChild('state');
|
|
152
|
+
this.stateEnteredAtMs = this.dateProvider.now();
|
|
139
153
|
|
|
140
154
|
// Add [FISHERMAN] prefix to logger if in fisherman mode
|
|
141
|
-
if (
|
|
155
|
+
if (config.fishermanMode) {
|
|
142
156
|
this.log = log.createChild('[FISHERMAN]');
|
|
143
157
|
}
|
|
144
158
|
|
|
159
|
+
this.signatureContext = {
|
|
160
|
+
chainId: config.l1ChainId,
|
|
161
|
+
rollupAddress: config.rollupAddress,
|
|
162
|
+
};
|
|
145
163
|
this.metrics = new SequencerMetrics(telemetry, this.rollupContract, 'Sequencer');
|
|
146
|
-
|
|
147
|
-
this.updateConfig(
|
|
164
|
+
this.checkpointProposalJobMetrics = new CheckpointProposalJobMetrics(telemetry);
|
|
165
|
+
this.updateConfig(config);
|
|
148
166
|
}
|
|
149
167
|
|
|
150
|
-
|
|
151
|
-
|
|
168
|
+
/**
|
|
169
|
+
* Updates sequencer config by the defined values and rebuilds the timetable.
|
|
170
|
+
*
|
|
171
|
+
* The merged config is validated against a candidate before being committed: {@link buildTimetable} may
|
|
172
|
+
* reject the candidate (invalid timing geometry, or per-block allocation multipliers below the network
|
|
173
|
+
* minimums). On rejection we leave `this.config` and `this.timetable` untouched and rethrow, so a bad update
|
|
174
|
+
* never leaves the sequencer running with a rejected config and a stale timetable.
|
|
175
|
+
*/
|
|
176
|
+
public updateConfig(config: Partial<SequencerConfig>) {
|
|
177
|
+
const filteredConfig = pickFromSchema(config, SequencerConfigSchema);
|
|
178
|
+
const candidate = merge(this.config, filteredConfig);
|
|
179
|
+
let timetable: ProposerTimetable;
|
|
180
|
+
try {
|
|
181
|
+
timetable = this.buildTimetable(candidate);
|
|
182
|
+
} catch (err) {
|
|
183
|
+
this.log.warn(`Rejecting sequencer config update: ${(err as Error).message}`, {
|
|
184
|
+
rejectedConfig: omit(filteredConfig, 'txPublicSetupAllowListExtend'),
|
|
185
|
+
});
|
|
186
|
+
throw err;
|
|
187
|
+
}
|
|
188
|
+
this.config = candidate;
|
|
189
|
+
this.timetable = timetable;
|
|
190
|
+
this.log.info(`Updated sequencer config`, omit(filteredConfig, 'txPublicSetupAllowListExtend'));
|
|
152
191
|
}
|
|
153
192
|
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
193
|
+
/**
|
|
194
|
+
* Builds the proposer timetable from the given config and L1 constants via the shared
|
|
195
|
+
* {@link buildProposerTimetable} helper, so the sequencer derives the same blocks-per-checkpoint as the p2p
|
|
196
|
+
* layer and `getNodeInfo`. The fast local/e2e profile and budget clamping happen inside
|
|
197
|
+
* {@link ProposerTimetable}.
|
|
198
|
+
*
|
|
199
|
+
* Throws if the timing geometry is invalid or the per-block allocation multipliers are below the network
|
|
200
|
+
* minimums; callers must treat a throw as a rejected config and not commit it.
|
|
201
|
+
*/
|
|
202
|
+
private buildTimetable(config: ResolvedSequencerConfig): ProposerTimetable {
|
|
203
|
+
const timetable = buildProposerTimetable(config, this.l1Constants);
|
|
204
|
+
|
|
205
|
+
const maxNumberOfBlocks = timetable.getMaxBlocksPerCheckpoint();
|
|
206
|
+
this.log.info(`Sequencer timetable initialized with ${maxNumberOfBlocks} blocks per slot`, {
|
|
207
|
+
aztecSlotDuration: timetable.aztecSlotDuration,
|
|
208
|
+
ethereumSlotDuration: timetable.ethereumSlotDuration,
|
|
209
|
+
blockDuration: timetable.blockDuration,
|
|
210
|
+
minBlockDuration: timetable.minBlockDuration,
|
|
211
|
+
p2pPropagationTime: timetable.p2pPropagationTime,
|
|
212
|
+
checkpointProposalPrepareTime: timetable.checkpointProposalPrepareTime,
|
|
213
|
+
maxNumberOfBlocks,
|
|
214
|
+
});
|
|
157
215
|
|
|
158
|
-
|
|
159
|
-
|
|
216
|
+
this.assertConfigMeetsNetworkTxLimits(config, maxNumberOfBlocks);
|
|
217
|
+
|
|
218
|
+
return timetable;
|
|
160
219
|
}
|
|
161
220
|
|
|
162
221
|
/**
|
|
163
|
-
*
|
|
164
|
-
*
|
|
222
|
+
* Checks this node's configured per-block allocation against the network admission limit. A node
|
|
223
|
+
* advertises and admits txs up to the limit derived from the network-minimum multipliers (see
|
|
224
|
+
* {@link computeNetworkTxGasLimits}).
|
|
225
|
+
*
|
|
226
|
+
* Fails startup (and runtime config updates) only when the configured per-block allocation *multipliers*
|
|
227
|
+
* (`perBlockAllocationMultiplier` / `perBlockDAAllocationMultiplier`) are below the network minimums: such
|
|
228
|
+
* a node would accept txs over RPC/gossip that its builder can never pack into a block regardless of block
|
|
229
|
+
* size. Operators may configure a higher (more generous) multiplier, but not a lower one.
|
|
230
|
+
*
|
|
231
|
+
* When the multipliers meet the floor but an absolute per-block gas cap (`maxDABlockGas` / `maxL2BlockGas`)
|
|
232
|
+
* shrinks the builder's effective grant below the network limit, this is legitimate operator
|
|
233
|
+
* restrictiveness — the node simply builds smaller blocks and such txs stay in the pool for other
|
|
234
|
+
* proposers — so we only log a warning rather than failing startup. Restrictive tx-count caps
|
|
235
|
+
* (`maxTxsPerBlock` / `maxTxsPerCheckpoint`) can likewise make the builder skip admitted txs; they are
|
|
236
|
+
* intentionally not modeled here for the same reason.
|
|
165
237
|
*/
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
this.minTxsPerBlock = config.minTxsPerBlock;
|
|
180
|
-
}
|
|
181
|
-
if (config.maxDABlockGas !== undefined) {
|
|
182
|
-
this.maxBlockGas = new Gas(config.maxDABlockGas, this.maxBlockGas.l2Gas);
|
|
183
|
-
}
|
|
184
|
-
if (config.maxL2BlockGas !== undefined) {
|
|
185
|
-
this.maxBlockGas = new Gas(this.maxBlockGas.daGas, config.maxL2BlockGas);
|
|
186
|
-
}
|
|
187
|
-
if (config.maxBlockSizeInBytes !== undefined) {
|
|
188
|
-
this.maxBlockSizeInBytes = config.maxBlockSizeInBytes;
|
|
238
|
+
private assertConfigMeetsNetworkTxLimits(config: ResolvedSequencerConfig, maxBlocksPerCheckpoint: number) {
|
|
239
|
+
// Mirror CheckpointBuilder.capLimitsByCheckpointBudgets: DA falls back to the general multiplier.
|
|
240
|
+
const l2Multiplier = config.perBlockAllocationMultiplier;
|
|
241
|
+
const daMultiplier = config.perBlockDAAllocationMultiplier ?? l2Multiplier;
|
|
242
|
+
|
|
243
|
+
// The allocation is monotonic in the multiplier, so a multiplier at or above the network minimum
|
|
244
|
+
// guarantees the builder grants at least the network admission limit. Checking the multipliers directly
|
|
245
|
+
// is sufficient (and strictly more conservative than modeling the resulting gas grant).
|
|
246
|
+
if (daMultiplier < MIN_PER_BLOCK_DA_ALLOCATION_MULTIPLIER) {
|
|
247
|
+
throw new Error(
|
|
248
|
+
`perBlockDAAllocationMultiplier (${daMultiplier}) is below the network minimum ` +
|
|
249
|
+
`${MIN_PER_BLOCK_DA_ALLOCATION_MULTIPLIER}; the node would admit txs its own builder can never include.`,
|
|
250
|
+
);
|
|
189
251
|
}
|
|
190
|
-
if (
|
|
191
|
-
|
|
252
|
+
if (l2Multiplier < MIN_PER_BLOCK_ALLOCATION_MULTIPLIER) {
|
|
253
|
+
throw new Error(
|
|
254
|
+
`perBlockAllocationMultiplier (${l2Multiplier}) is below the network minimum ` +
|
|
255
|
+
`${MIN_PER_BLOCK_ALLOCATION_MULTIPLIER}; the node would admit txs its own builder can never include.`,
|
|
256
|
+
);
|
|
192
257
|
}
|
|
193
|
-
|
|
194
|
-
|
|
258
|
+
|
|
259
|
+
// Absolute per-block gas caps below the network admission limit are legitimate operator restrictiveness:
|
|
260
|
+
// the node simply builds smaller blocks and such txs stay in the pool for other proposers. Warn only.
|
|
261
|
+
const networkLimit = computeNetworkTxGasLimits({
|
|
262
|
+
maxBlocksPerCheckpoint,
|
|
263
|
+
manaCheckpointBudget: this.l1Constants.rollupManaLimit,
|
|
264
|
+
});
|
|
265
|
+
if (config.maxDABlockGas !== undefined && config.maxDABlockGas < networkLimit.daGas) {
|
|
266
|
+
this.log.warn(
|
|
267
|
+
`Sequencer maxDABlockGas (${config.maxDABlockGas}) is below the network DA admission limit ` +
|
|
268
|
+
`(${networkLimit.daGas}): txs declaring more DA gas are admitted over RPC/gossip but will be skipped ` +
|
|
269
|
+
`by this proposer's own blocks and left in the pool for other proposers.`,
|
|
270
|
+
{ maxDABlockGas: config.maxDABlockGas, networkDaGas: networkLimit.daGas, maxBlocksPerCheckpoint },
|
|
271
|
+
);
|
|
195
272
|
}
|
|
196
|
-
if (config.
|
|
197
|
-
this.
|
|
273
|
+
if (config.maxL2BlockGas !== undefined && config.maxL2BlockGas < networkLimit.l2Gas) {
|
|
274
|
+
this.log.warn(
|
|
275
|
+
`Sequencer maxL2BlockGas (${config.maxL2BlockGas}) is below the network L2 admission limit ` +
|
|
276
|
+
`(${networkLimit.l2Gas}): txs declaring more L2 gas are admitted over RPC/gossip but will be skipped ` +
|
|
277
|
+
`by this proposer's own blocks and left in the pool for other proposers.`,
|
|
278
|
+
{ maxL2BlockGas: config.maxL2BlockGas, networkL2Gas: networkLimit.l2Gas, maxBlocksPerCheckpoint },
|
|
279
|
+
);
|
|
198
280
|
}
|
|
199
|
-
|
|
200
|
-
this.setTimeTable();
|
|
201
|
-
|
|
202
|
-
// TODO: Just read everything from the config object as needed instead of copying everything into local vars.
|
|
203
|
-
|
|
204
|
-
// Update all values on this.config that are populated in the config object.
|
|
205
|
-
Object.assign(this.config, config);
|
|
206
281
|
}
|
|
207
282
|
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
ethereumSlotDuration: this.l1Constants.ethereumSlotDuration,
|
|
212
|
-
aztecSlotDuration: this.aztecSlotDuration,
|
|
213
|
-
maxL1TxInclusionTimeIntoSlot: this.maxL1TxInclusionTimeIntoSlot,
|
|
214
|
-
attestationPropagationTime: this.config.attestationPropagationTime,
|
|
215
|
-
enforce: this.enforceTimeTable,
|
|
216
|
-
},
|
|
217
|
-
this.metrics,
|
|
218
|
-
this.log,
|
|
219
|
-
);
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
public async init() {
|
|
223
|
-
this.publisher = (await this.publisherFactory.create(undefined)).publisher;
|
|
283
|
+
/** Initializes the sequencer (precomputes tables). Takes about 3s. */
|
|
284
|
+
public init() {
|
|
285
|
+
getKzg();
|
|
224
286
|
}
|
|
225
287
|
|
|
226
288
|
/**
|
|
227
|
-
* Starts the sequencer and moves to IDLE state.
|
|
289
|
+
* Starts (or restarts) the sequencer and moves it to the IDLE state. Idempotent: a start while already
|
|
290
|
+
* running is a no-op, so it never orphans the previous poll loop. A start while STOPPING throws, since the
|
|
291
|
+
* in-flight stop would mark the fresh loop's state STOPPED and orphan it — silently doing nothing would
|
|
292
|
+
* leave the caller believing the sequencer is running when it is on its way to STOPPED. Safe to call after
|
|
293
|
+
* a previous {@link stop} has resolved; the caller must also restart the publishers (see
|
|
294
|
+
* {@link SequencerClient.start}) so L1 publishing is re-enabled.
|
|
228
295
|
*/
|
|
229
296
|
public start() {
|
|
230
|
-
|
|
297
|
+
if (this.state === SequencerState.STOPPING) {
|
|
298
|
+
throw new Error('Cannot start sequencer while it is stopping');
|
|
299
|
+
}
|
|
300
|
+
if (this.runningPromise?.isRunning()) {
|
|
301
|
+
this.log.warn('Attempted to start sequencer that is already running');
|
|
302
|
+
return;
|
|
303
|
+
}
|
|
304
|
+
this.runningPromise = new RunningPromise(
|
|
305
|
+
this.safeWork.bind(this),
|
|
306
|
+
this.log,
|
|
307
|
+
this.config.sequencerPollingIntervalMS,
|
|
308
|
+
);
|
|
231
309
|
this.setState(SequencerState.IDLE, undefined, { force: true });
|
|
232
310
|
this.runningPromise.start();
|
|
233
311
|
this.log.info('Started sequencer');
|
|
234
312
|
}
|
|
235
313
|
|
|
314
|
+
/** Triggers an immediate run of the sequencer, bypassing the polling interval. */
|
|
315
|
+
public trigger() {
|
|
316
|
+
return this.runningPromise?.trigger();
|
|
317
|
+
}
|
|
318
|
+
|
|
236
319
|
/**
|
|
237
|
-
* Stops the sequencer from
|
|
320
|
+
* Stops the sequencer from building blocks and moves it to STOPPED state, interrupting the in-flight
|
|
321
|
+
* work() iteration and its pending L1 submissions for a fast shutdown, then draining before returning.
|
|
322
|
+
* Idempotent: a second call while already stopped or stopping is a no-op. Lifecycle calls are expected
|
|
323
|
+
* to be serialized by the caller. For a restartable pause that lets in-flight work finish untouched
|
|
324
|
+
* (e.g. around a test clock warp), use {@link pause} instead.
|
|
238
325
|
*/
|
|
239
326
|
public async stop(): Promise<void> {
|
|
327
|
+
if (this.state === SequencerState.STOPPED || this.state === SequencerState.STOPPING) {
|
|
328
|
+
this.log.debug(`Sequencer already ${this.state.toLowerCase()}, ignoring stop`);
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
240
331
|
this.log.info(`Stopping sequencer`);
|
|
241
332
|
this.setState(SequencerState.STOPPING, undefined, { force: true });
|
|
242
|
-
this.
|
|
333
|
+
this.lastCheckpointProposalJob?.interrupt();
|
|
334
|
+
await this.publisherFactory.stopAll();
|
|
335
|
+
// Stop the poll loop and await the in-flight work() iteration. work() registers its fire-and-forget
|
|
336
|
+
// requests synchronously before returning, so once the loop has stopped, pendingRequests holds every
|
|
337
|
+
// request that will ever exist. Interrupting any earlier could miss a request registered by the last
|
|
338
|
+
// in-flight iteration.
|
|
243
339
|
await this.runningPromise?.stop();
|
|
340
|
+
this.pendingRequests.interruptRequests();
|
|
341
|
+
await this.pendingRequests.awaitRequests();
|
|
244
342
|
this.setState(SequencerState.STOPPED, undefined, { force: true });
|
|
245
343
|
this.log.info('Stopped sequencer');
|
|
246
344
|
}
|
|
247
345
|
|
|
248
346
|
/**
|
|
249
|
-
*
|
|
250
|
-
*
|
|
347
|
+
* Gracefully pauses block production so the sequencer can later be resumed with {@link start}: halts the
|
|
348
|
+
* poll loop and waits for the in-flight work() iteration and every pending L1 submission / fallback send
|
|
349
|
+
* to finish, without interrupting them. No interrupt lands mid-build, so no spurious checkpoint-error is
|
|
350
|
+
* emitted and no enqueued checkpoint is dropped. Deliberately does not stop inner services (validator/HA
|
|
351
|
+
* signer, publishers), so the slashing-protection store stays open and the sequencer stays restartable.
|
|
352
|
+
* Used by tests that pause sequencers around an L1 clock warp. Idempotent.
|
|
251
353
|
*/
|
|
354
|
+
public async pause(): Promise<void> {
|
|
355
|
+
if (!this.runningPromise?.isRunning()) {
|
|
356
|
+
this.log.debug('Sequencer not running, ignoring pause');
|
|
357
|
+
return;
|
|
358
|
+
}
|
|
359
|
+
this.log.info('Pausing sequencer');
|
|
360
|
+
// Halt the poll loop and let the in-flight iteration finish naturally — no interrupt, and no STOPPING
|
|
361
|
+
// state, since entering STOPPING would make the iteration's own setState calls throw and fail it.
|
|
362
|
+
// work() registers its fire-and-forget requests synchronously before returning, so once the loop has
|
|
363
|
+
// stopped pendingRequests holds every request that will ever exist; awaiting it lets them all finish.
|
|
364
|
+
await this.runningPromise.stop();
|
|
365
|
+
await this.pendingRequests.awaitRequests();
|
|
366
|
+
this.log.info('Paused sequencer');
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/** Main sequencer loop with a try/catch */
|
|
370
|
+
protected async safeWork() {
|
|
371
|
+
try {
|
|
372
|
+
await this.work();
|
|
373
|
+
} catch (err) {
|
|
374
|
+
this.emit('checkpoint-error', { error: err as Error });
|
|
375
|
+
throw err;
|
|
376
|
+
} finally {
|
|
377
|
+
this.setState(SequencerState.IDLE, undefined);
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/** Returns the current state of the sequencer. */
|
|
252
382
|
public status() {
|
|
253
383
|
return { state: this.state };
|
|
254
384
|
}
|
|
255
385
|
|
|
256
386
|
/**
|
|
257
|
-
*
|
|
258
|
-
*
|
|
259
|
-
*
|
|
260
|
-
*
|
|
261
|
-
*
|
|
262
|
-
*
|
|
387
|
+
* Main sequencer loop:
|
|
388
|
+
* - Checks if we are up to date
|
|
389
|
+
* - If we are and we are the sequencer, collect txs and build blocks
|
|
390
|
+
* - Build multiple blocks per slot when configured
|
|
391
|
+
* - Collect attestations for the final block
|
|
392
|
+
* - Submit checkpoint
|
|
263
393
|
*/
|
|
394
|
+
@trackSpan('Sequencer.work')
|
|
264
395
|
protected async work() {
|
|
265
396
|
this.setState(SequencerState.SYNCHRONIZING, undefined);
|
|
266
|
-
const { slot, ts,
|
|
397
|
+
const { slot, targetSlot, epoch, targetEpoch, ts, nowSeconds } = this.getSlotContextInNextL1Slot();
|
|
267
398
|
|
|
268
|
-
// Check we
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
399
|
+
// Check if we are synced and it's our slot, grab a publisher, check previous block invalidation, etc
|
|
400
|
+
const checkpointProposalJob = await this.prepareCheckpointProposal(
|
|
401
|
+
slot,
|
|
402
|
+
targetSlot,
|
|
403
|
+
epoch,
|
|
404
|
+
targetEpoch,
|
|
405
|
+
ts,
|
|
406
|
+
nowSeconds,
|
|
407
|
+
);
|
|
408
|
+
if (!checkpointProposalJob) {
|
|
273
409
|
return;
|
|
274
410
|
}
|
|
275
411
|
|
|
276
|
-
//
|
|
412
|
+
// Track the job so we can await its pending L1 submission during shutdown
|
|
413
|
+
this.lastCheckpointProposalJob = checkpointProposalJob;
|
|
414
|
+
|
|
415
|
+
// Execute the checkpoint proposal job
|
|
416
|
+
const checkpoint = await checkpointProposalJob.execute();
|
|
417
|
+
|
|
418
|
+
// Update last checkpoint proposed (currently unused)
|
|
419
|
+
if (checkpoint) {
|
|
420
|
+
this.lastCheckpointProposed = checkpoint;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
// Log fee strategy comparison if on fisherman (uses target epoch since we mirror the proposer's perspective)
|
|
424
|
+
if (
|
|
425
|
+
this.config.fishermanMode &&
|
|
426
|
+
(this.lastEpochForStrategyComparison === undefined || targetEpoch > this.lastEpochForStrategyComparison)
|
|
427
|
+
) {
|
|
428
|
+
this.logStrategyComparison(targetEpoch, checkpointProposalJob.getPublisher());
|
|
429
|
+
this.lastEpochForStrategyComparison = targetEpoch;
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
return checkpoint;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/** Returns slot and target slot from a single clock snapshot. */
|
|
436
|
+
protected getSlotContextInNextL1Slot(): SequencerSlotContext {
|
|
437
|
+
const { slot, ts, nowSeconds, epoch } = this.epochCache.getEpochAndSlotInNextL1Slot();
|
|
438
|
+
const targetSlot = SlotNumber(slot + PROPOSER_PIPELINING_SLOT_OFFSET);
|
|
439
|
+
return { slot, targetSlot, epoch, targetEpoch: getEpochAtSlot(targetSlot, this.l1Constants), ts, nowSeconds };
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/**
|
|
443
|
+
* Prepares the checkpoint proposal by performing all necessary checks and setup.
|
|
444
|
+
* This is the initial step in the main loop.
|
|
445
|
+
* @returns CheckpointProposalJob if successful, undefined if we are not yet synced or are not the proposer.
|
|
446
|
+
*/
|
|
447
|
+
@trackSpan('Sequencer.prepareCheckpointProposal')
|
|
448
|
+
protected async prepareCheckpointProposal(
|
|
449
|
+
slot: SlotNumber,
|
|
450
|
+
targetSlot: SlotNumber,
|
|
451
|
+
epoch: EpochNumber,
|
|
452
|
+
targetEpoch: EpochNumber,
|
|
453
|
+
ts: bigint,
|
|
454
|
+
nowSeconds: bigint,
|
|
455
|
+
): Promise<CheckpointProposalJob | undefined> {
|
|
456
|
+
// Check we have not already processed this target slot (cheapest check).
|
|
457
|
+
if (this.lastSlotForCheckpointProposalJob && this.lastSlotForCheckpointProposalJob >= targetSlot) {
|
|
458
|
+
this.log.trace(`Target slot ${targetSlot} has already been processed`);
|
|
459
|
+
return undefined;
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
// But if we have already proposed for this slot, then we definitely have to skip it, automining or not
|
|
463
|
+
if (this.lastCheckpointProposed && this.lastCheckpointProposed.header.slotNumber >= targetSlot) {
|
|
464
|
+
this.log.trace(
|
|
465
|
+
`Slot ${targetSlot} has already been published as checkpoint ${this.lastCheckpointProposed.number}`,
|
|
466
|
+
);
|
|
467
|
+
return undefined;
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
// Test-only: skip proposing for explicitly paused slots. Attestation paths run in the validator
|
|
471
|
+
// client and are not gated by this hook, so paused proposers still attest to others' proposals.
|
|
472
|
+
if (this.config.pauseProposingForSlots?.some(s => s === targetSlot)) {
|
|
473
|
+
this.log.warn(`Skipping proposal for paused slot ${targetSlot} (test-only pauseProposingForSlots hook)`, {
|
|
474
|
+
targetSlot,
|
|
475
|
+
});
|
|
476
|
+
return undefined;
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
// Cheap proposer check first: most nodes are not the proposer for most slots, so gate the
|
|
480
|
+
// expensive multi-subsystem checkSync (and the rest of the build path) behind it. Computed once
|
|
481
|
+
// here and reused for the escape-hatch voting path below. No setState/timing gate on this path:
|
|
482
|
+
// the build-start deadline gate runs only on the proposer build path after a successful checkSync.
|
|
483
|
+
const [canPropose, proposer] = await this.checkCanPropose(targetSlot);
|
|
484
|
+
|
|
485
|
+
// If escape hatch is open for the target epoch, do not start checkpoint proposal work and do not attempt invalidations.
|
|
486
|
+
// Still perform governance/slashing voting (as proposer) once per slot.
|
|
487
|
+
// When pipelining, we check the target epoch (slot+1's epoch) since that's the epoch we're building for.
|
|
488
|
+
const isEscapeHatchOpen = await this.epochCache.isEscapeHatchOpen(targetEpoch);
|
|
489
|
+
|
|
490
|
+
if (isEscapeHatchOpen) {
|
|
491
|
+
if (canPropose) {
|
|
492
|
+
await this.tryVoteWhenEscapeHatchOpen({ slot, targetSlot, proposer });
|
|
493
|
+
} else {
|
|
494
|
+
this.log.trace(`Escape hatch open but we are not proposer, skipping vote-only actions`, {
|
|
495
|
+
slot,
|
|
496
|
+
epoch,
|
|
497
|
+
proposer,
|
|
498
|
+
});
|
|
499
|
+
}
|
|
500
|
+
return undefined;
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
// If we are not the proposer, check whether we should invalidate an invalid pending chain (a
|
|
504
|
+
// liveness backstop) and bail before any sync work or build-timing gate. This reads only the
|
|
505
|
+
// archiver's pending-chain validation status, which is authoritative on its own, instead of
|
|
506
|
+
// running the full sync check. Wrapped in try/catch because this leaner path skips the broader
|
|
507
|
+
// proposed-checkpoint/tip coherence screen that checkSync applied, so transient archiver
|
|
508
|
+
// incoherence surfaces as a quiet skip rather than a work-loop error.
|
|
509
|
+
if (!canPropose) {
|
|
510
|
+
try {
|
|
511
|
+
const pendingChainValidationStatus = await this.l2BlockSource.getPendingChainValidationStatus();
|
|
512
|
+
await this.considerInvalidatingCheckpoint(pendingChainValidationStatus, slot);
|
|
513
|
+
} catch (err) {
|
|
514
|
+
this.log.warn(`Failed to consider invalidating checkpoint`, { err, slot, targetSlot });
|
|
515
|
+
}
|
|
516
|
+
return undefined;
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
// Explicit build-loop entry gate: if we are past the latest useful block-building start for the
|
|
520
|
+
// target slot, abandon building for this slot. The proposer prioritizes the ideal L1-publish path
|
|
521
|
+
// and does not plan around the late consensus-handoff path. This is the proposer build path's
|
|
522
|
+
// timing gate; it runs only after we know we are the synced proposer, so non-proposer invalidation
|
|
523
|
+
// and escape-hatch voting (which returned above) are never gated by build timing. Vote-only paths
|
|
524
|
+
// still run when block building is abandoned.
|
|
525
|
+
const startDeadline = this.timetable.getBuildStartDeadline(targetSlot);
|
|
526
|
+
const nowForStartGate = this.dateProvider.now() / 1000;
|
|
527
|
+
if (nowForStartGate > startDeadline) {
|
|
528
|
+
this.log.debug(`Past start deadline for slot ${targetSlot}, abandoning block building`, {
|
|
529
|
+
targetSlot,
|
|
530
|
+
nowForStartGate,
|
|
531
|
+
startDeadline,
|
|
532
|
+
});
|
|
533
|
+
// Mark the slot as attempted so a deadline abort is not retried within the same slot. Vote-only actions
|
|
534
|
+
// still need to run because sync can succeed even when it is too late to start building a checkpoint.
|
|
535
|
+
await this.tryVoteAndPruneWhenCannotBuild({ slot, targetSlot });
|
|
536
|
+
this.lastSlotForCheckpointProposalJob = targetSlot;
|
|
537
|
+
return undefined;
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
// We are the proposer, the escape hatch is closed, and we have time before the build start deadline.
|
|
541
|
+
// Now run the full sync check before building.
|
|
277
542
|
const syncedTo = await this.checkSync({ ts, slot });
|
|
278
543
|
if (!syncedTo) {
|
|
279
|
-
|
|
280
|
-
return;
|
|
544
|
+
return undefined;
|
|
281
545
|
}
|
|
282
546
|
|
|
283
|
-
|
|
284
|
-
const
|
|
285
|
-
|
|
286
|
-
const
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
newBlockNumber,
|
|
547
|
+
// Next checkpoint follows from the last synced one
|
|
548
|
+
const checkpointNumber = CheckpointNumber(syncedTo.checkpointNumber + 1);
|
|
549
|
+
|
|
550
|
+
const logCtx = {
|
|
551
|
+
nowSeconds,
|
|
552
|
+
syncedToL2Slot: syncedTo.syncedL2Slot,
|
|
553
|
+
slot,
|
|
554
|
+
targetSlot,
|
|
555
|
+
slotTs: ts,
|
|
556
|
+
checkpointNumber,
|
|
294
557
|
isPendingChainValid: pick(syncedTo.pendingChainValidationStatus, 'valid', 'reason', 'invalidIndex'),
|
|
295
558
|
};
|
|
296
559
|
|
|
297
|
-
//
|
|
298
|
-
this.setState(SequencerState.PROPOSER_CHECK,
|
|
299
|
-
const [canPropose, proposer] = await this.checkCanPropose(slot);
|
|
300
|
-
|
|
301
|
-
// If we are not a proposer check if we should invalidate a invalid block, and bail
|
|
302
|
-
if (!canPropose) {
|
|
303
|
-
await this.considerInvalidatingBlock(syncedTo, slot);
|
|
304
|
-
return;
|
|
305
|
-
}
|
|
560
|
+
// We are the synced proposer within the build window; enter the proposer-check state and build.
|
|
561
|
+
this.setState(SequencerState.PROPOSER_CHECK, targetSlot);
|
|
306
562
|
|
|
307
|
-
//
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
this.log.debug(
|
|
314
|
-
`Building validation block for slot ${slot} (actual proposer: ${proposer?.toString() ?? 'none'})`,
|
|
315
|
-
{ slot, proposer: proposer?.toString() },
|
|
563
|
+
// Guard: don't exceed 1-deep pipeline. Without a proposed checkpoint, we can only build
|
|
564
|
+
// confirmed + 1. With a proposed checkpoint, we can build confirmed + 2.
|
|
565
|
+
const confirmedCkpt = syncedTo.checkpointedCheckpointNumber;
|
|
566
|
+
if (checkpointNumber > confirmedCkpt + 2) {
|
|
567
|
+
this.log.verbose(
|
|
568
|
+
`Skipping slot ${targetSlot}: checkpoint ${checkpointNumber} exceeds max pipeline depth (confirmed=${confirmedCkpt})`,
|
|
316
569
|
);
|
|
317
|
-
|
|
318
|
-
this.lastSlotForValidationBlock = slot;
|
|
570
|
+
return undefined;
|
|
319
571
|
}
|
|
320
572
|
|
|
321
|
-
// Check that the slot is not taken by a block already (should never happen, since only us can propose for this slot)
|
|
322
|
-
if (syncedTo.
|
|
573
|
+
// Check that the target slot is not taken by a block already (should never happen, since only us can propose for this slot)
|
|
574
|
+
if (syncedTo.blockData && syncedTo.blockData.header.getSlot() >= targetSlot) {
|
|
323
575
|
this.log.warn(
|
|
324
|
-
`Cannot propose block at
|
|
325
|
-
{ ...
|
|
576
|
+
`Cannot propose block at target slot ${targetSlot} since that slot was taken by block ${syncedTo.blockNumber}`,
|
|
577
|
+
{ ...logCtx, block: syncedTo.blockData.header.toInspect() },
|
|
326
578
|
);
|
|
327
|
-
this.metrics.
|
|
328
|
-
return;
|
|
579
|
+
this.metrics.recordCheckpointPrecheckFailed('slot_already_taken');
|
|
580
|
+
return undefined;
|
|
329
581
|
}
|
|
330
582
|
|
|
331
583
|
// We now need to get ourselves a publisher.
|
|
332
584
|
// The returned attestor will be the one we provided if we provided one.
|
|
333
585
|
// Otherwise it will be a valid attestor for the returned publisher.
|
|
334
586
|
// In fisherman mode, pass undefined to use the fisherman's own keystore instead of the actual proposer's
|
|
335
|
-
const
|
|
336
|
-
|
|
337
|
-
);
|
|
587
|
+
const proposerForPublisher = this.config.fishermanMode ? undefined : proposer;
|
|
588
|
+
const { attestorAddress, publisher } = await this.publisherFactory.create(proposerForPublisher);
|
|
338
589
|
this.log.verbose(`Created publisher at address ${publisher.getSenderAddress()} for attestor ${attestorAddress}`);
|
|
339
|
-
this.publisher = publisher;
|
|
340
590
|
|
|
341
|
-
//
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
591
|
+
// Prepare invalidation request if the pending chain is invalid (returns undefined if no need).
|
|
592
|
+
// Only simulate invalidation when there's no proposed parent, since we assume the proposed parent
|
|
593
|
+
// will invalidate the currently invalid checkpoint on L1.
|
|
594
|
+
const invalidateCheckpoint =
|
|
595
|
+
syncedTo.hasProposedCheckpoint || syncedTo.pendingChainValidationStatus.valid
|
|
596
|
+
? undefined
|
|
597
|
+
: await publisher.simulateInvalidateCheckpoint(syncedTo.pendingChainValidationStatus);
|
|
598
|
+
|
|
599
|
+
// Determine the correct archive and L1 state overrides for the canProposeAt check.
|
|
600
|
+
// The L1 contract reads archives[proposedCheckpointNumber] and compares it with the provided archive.
|
|
601
|
+
// When invalidating or pipelining, the local archive may differ from L1's, so we adjust accordingly.
|
|
602
|
+
let archiveForCheck = syncedTo.archive;
|
|
603
|
+
|
|
604
|
+
if (syncedTo.hasProposedCheckpoint) {
|
|
605
|
+
this.metrics.recordPipelineDepth(syncedTo.checkpointNumber - syncedTo.checkpointedCheckpointNumber);
|
|
606
|
+
this.log.verbose(
|
|
607
|
+
`Building on top of proposed checkpoint (pending=${syncedTo.proposedCheckpointData?.checkpointNumber}) for target slot ${targetSlot}`,
|
|
608
|
+
{ targetSlot, parentCheckpointNumber: CheckpointNumber(checkpointNumber - 1) },
|
|
609
|
+
);
|
|
610
|
+
// Match what L1 will see at archives[pending] once the proposed parent lands: the parent's
|
|
611
|
+
// own archive root from the gossiped proposal. `syncedTo.archive` is the world-state-local
|
|
612
|
+
// view and can transiently diverge from the proposed parent (e.g. before the proposed
|
|
613
|
+
// parent's blocks have been applied locally); diverging here would cause the canProposeAt
|
|
614
|
+
// override to set archives[pending] to one value while we present another for comparison.
|
|
615
|
+
archiveForCheck = syncedTo.proposedCheckpointData!.archive.root;
|
|
616
|
+
} else if (invalidateCheckpoint) {
|
|
617
|
+
// After invalidation, L1 will roll back to checkpoint N-1. The archive at N-1 already
|
|
618
|
+
// exists on L1, so we just pass the matching archive (the lastArchive of the invalid checkpoint).
|
|
619
|
+
archiveForCheck = invalidateCheckpoint.lastArchive;
|
|
620
|
+
this.metrics.recordPipelineDepth(0);
|
|
621
|
+
} else {
|
|
622
|
+
this.metrics.recordPipelineDepth(0);
|
|
347
623
|
}
|
|
348
624
|
|
|
349
|
-
//
|
|
350
|
-
|
|
351
|
-
|
|
625
|
+
// Build the simulation plan: pending/proven override from pipelining or invalidation (or the
|
|
626
|
+
// current snapshot when neither applies, to short-circuit any pending prune in simulation),
|
|
627
|
+
// plus the parent checkpoint cell and fee header when pipelining.
|
|
628
|
+
const simulationOverridesPlan = await buildCheckpointSimulationOverridesPlan({
|
|
629
|
+
checkpointNumber,
|
|
630
|
+
proposedCheckpointData: syncedTo.hasProposedCheckpoint ? syncedTo.proposedCheckpointData : undefined,
|
|
631
|
+
invalidateToPendingCheckpointNumber: invalidateCheckpoint?.forcePendingCheckpointNumber,
|
|
632
|
+
checkpointedCheckpointNumber: syncedTo.checkpointedCheckpointNumber,
|
|
633
|
+
rollup: this.rollupContract,
|
|
634
|
+
signatureContext: this.signatureContext,
|
|
635
|
+
log: this.log,
|
|
636
|
+
});
|
|
352
637
|
|
|
353
|
-
//
|
|
354
|
-
|
|
638
|
+
// The plan always pins both pending/proven (to short-circuit `canPruneAtTime` in simulation),
|
|
639
|
+
// so `provenOverride` always reflects the assumed proven checkpoint we are pinning the
|
|
640
|
+
// simulation to. We additionally warn when the pin is load-bearing — i.e. when a prune would
|
|
641
|
+
// actually fire at the target slot without it — so observers can spot "we are building
|
|
642
|
+
// optimistically across a pruning boundary" in the logs.
|
|
643
|
+
const provenOverride = simulationOverridesPlan?.chainTipsOverride?.proven;
|
|
644
|
+
if (provenOverride !== undefined && (await this.l2BlockSource.isPruneDueAtSlot(targetSlot))) {
|
|
645
|
+
this.log.warn(
|
|
646
|
+
`Assuming proof for epoch ending at checkpoint ${provenOverride} lands by target slot ${targetSlot}`,
|
|
647
|
+
{ checkpointNumber, slot, targetSlot, provenOverride },
|
|
648
|
+
);
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
this.emit('preparing-checkpoint', {
|
|
652
|
+
targetSlot,
|
|
653
|
+
checkpointNumber,
|
|
654
|
+
hadProposedParent: syncedTo.hasProposedCheckpoint,
|
|
655
|
+
provenOverride,
|
|
656
|
+
simulatedPending: simulationOverridesPlan?.chainTipsOverride?.pending,
|
|
657
|
+
});
|
|
355
658
|
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
const canProposeCheck = await publisher.canProposeAtNextEthBlock(
|
|
359
|
-
chainTipArchive,
|
|
659
|
+
const canProposeCheck = await publisher.canProposeAt(
|
|
660
|
+
archiveForCheck,
|
|
360
661
|
proposer ?? EthAddress.ZERO,
|
|
361
|
-
|
|
662
|
+
simulationOverridesPlan,
|
|
362
663
|
);
|
|
363
664
|
|
|
665
|
+
const proposeContext = {
|
|
666
|
+
hasProposedCheckpoint: syncedTo.hasProposedCheckpoint,
|
|
667
|
+
proposedCheckpointNumber: syncedTo.proposedCheckpointData?.checkpointNumber,
|
|
668
|
+
checkpointedCheckpointNumber: syncedTo.checkpointedCheckpointNumber,
|
|
669
|
+
isInvalidating: !!invalidateCheckpoint,
|
|
670
|
+
invalidatingCheckpointNumber: invalidateCheckpoint?.checkpointNumber,
|
|
671
|
+
archiveForCheck: archiveForCheck.toString(),
|
|
672
|
+
overridePendingCheckpointNumber: simulationOverridesPlan?.chainTipsOverride?.pending,
|
|
673
|
+
overrideArchive: simulationOverridesPlan?.pendingCheckpointState?.archive,
|
|
674
|
+
overrideFeeHeader: simulationOverridesPlan?.pendingCheckpointState?.feeHeader,
|
|
675
|
+
};
|
|
676
|
+
|
|
364
677
|
if (canProposeCheck === undefined) {
|
|
365
678
|
this.log.warn(
|
|
366
|
-
`Cannot propose
|
|
367
|
-
|
|
679
|
+
`Cannot propose checkpoint ${checkpointNumber} at slot ${slot} due to failed rollup contract check`,
|
|
680
|
+
{ ...logCtx, ...proposeContext },
|
|
368
681
|
);
|
|
369
|
-
this.emit('proposer-rollup-check-failed', { reason: 'Rollup contract check failed' });
|
|
370
|
-
this.metrics.
|
|
371
|
-
return;
|
|
372
|
-
}
|
|
682
|
+
this.emit('proposer-rollup-check-failed', { reason: 'Rollup contract check failed', slot });
|
|
683
|
+
this.metrics.recordCheckpointPrecheckFailed('rollup_contract_check_failed');
|
|
684
|
+
return undefined;
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
if (canProposeCheck.slot !== targetSlot) {
|
|
373
688
|
this.log.warn(
|
|
374
|
-
`Cannot propose block due to slot mismatch with rollup contract (this can be caused by a clock out of sync). Expected slot ${
|
|
375
|
-
{ ...
|
|
689
|
+
`Cannot propose block due to slot mismatch with rollup contract (this can be caused by a clock out of sync). Expected slot ${targetSlot} but got ${canProposeCheck.slot}.`,
|
|
690
|
+
{ ...logCtx, ...proposeContext, rollup: canProposeCheck, expectedSlot: targetSlot },
|
|
376
691
|
);
|
|
377
|
-
this.emit('proposer-rollup-check-failed', { reason: 'Slot mismatch' });
|
|
378
|
-
this.metrics.
|
|
379
|
-
return;
|
|
380
|
-
}
|
|
692
|
+
this.emit('proposer-rollup-check-failed', { reason: 'Slot mismatch', slot });
|
|
693
|
+
this.metrics.recordCheckpointPrecheckFailed('slot_mismatch');
|
|
694
|
+
return undefined;
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
if (canProposeCheck.checkpointNumber !== checkpointNumber) {
|
|
381
698
|
this.log.warn(
|
|
382
|
-
`Cannot propose
|
|
383
|
-
{ ...
|
|
699
|
+
`Cannot propose due to block mismatch with rollup contract (this can be caused by a pending archiver sync). Expected checkpoint ${checkpointNumber} but got ${canProposeCheck.checkpointNumber}.`,
|
|
700
|
+
{ ...logCtx, ...proposeContext, rollup: canProposeCheck, expectedSlot: slot },
|
|
384
701
|
);
|
|
385
|
-
this.emit('proposer-rollup-check-failed', { reason: 'Block mismatch' });
|
|
386
|
-
this.metrics.
|
|
387
|
-
return;
|
|
702
|
+
this.emit('proposer-rollup-check-failed', { reason: 'Block mismatch', slot });
|
|
703
|
+
this.metrics.recordCheckpointPrecheckFailed('block_number_mismatch');
|
|
704
|
+
return undefined;
|
|
388
705
|
}
|
|
389
706
|
|
|
390
|
-
this.
|
|
707
|
+
this.lastSlotForCheckpointProposalJob = targetSlot;
|
|
391
708
|
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
// In fisherman mode, we simulate slashing but don't actually publish to L1
|
|
401
|
-
const votesPromises = this.enqueueGovernanceAndSlashingVotes(
|
|
402
|
-
publisher,
|
|
403
|
-
attestorAddress,
|
|
404
|
-
slot,
|
|
405
|
-
newGlobalVariables.timestamp,
|
|
709
|
+
await this.p2pClient.prepareForSlot(targetSlot);
|
|
710
|
+
this.log.info(
|
|
711
|
+
`Preparing checkpoint proposal ${checkpointNumber} for target slot ${targetSlot} during wall-clock slot ${slot}`,
|
|
712
|
+
{
|
|
713
|
+
...logCtx,
|
|
714
|
+
...proposeContext,
|
|
715
|
+
proposer,
|
|
716
|
+
},
|
|
406
717
|
);
|
|
407
718
|
|
|
408
|
-
//
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
this.metrics.incOpenSlot(slot, proposer?.toString() ?? 'unknown');
|
|
416
|
-
const block: L2Block | undefined = await this.tryBuildBlockAndEnqueuePublish(
|
|
417
|
-
slot,
|
|
719
|
+
// Create and return the checkpoint proposal job
|
|
720
|
+
return this.createCheckpointProposalJob(
|
|
721
|
+
targetSlot,
|
|
722
|
+
targetEpoch,
|
|
723
|
+
checkpointNumber,
|
|
724
|
+
syncedTo.blockNumber,
|
|
725
|
+
syncedTo.checkpointedCheckpointNumber,
|
|
418
726
|
proposer,
|
|
419
|
-
newBlockNumber,
|
|
420
727
|
publisher,
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
728
|
+
attestorAddress,
|
|
729
|
+
invalidateCheckpoint,
|
|
730
|
+
syncedTo.proposedCheckpointData,
|
|
424
731
|
);
|
|
425
|
-
|
|
426
|
-
// Wait until the voting promises have resolved, so all requests are enqueued
|
|
427
|
-
await Promise.all(votesPromises);
|
|
428
|
-
|
|
429
|
-
// In fisherman mode, we don't publish to L1
|
|
430
|
-
if (this.config.fishermanMode) {
|
|
431
|
-
// Clear pending requests
|
|
432
|
-
publisher.clearPendingRequests();
|
|
433
|
-
|
|
434
|
-
if (block) {
|
|
435
|
-
this.log.info(`Validation block building SUCCEEDED for slot ${slot}`, {
|
|
436
|
-
blockNumber: newBlockNumber,
|
|
437
|
-
slot: Number(slot),
|
|
438
|
-
archive: block.archive.toString(),
|
|
439
|
-
txCount: block.body.txEffects.length,
|
|
440
|
-
});
|
|
441
|
-
this.lastBlockPublished = block;
|
|
442
|
-
this.metrics.recordBlockProposalSuccess();
|
|
443
|
-
} else {
|
|
444
|
-
// Block building failed in fisherman mode
|
|
445
|
-
this.log.warn(`Validation block building FAILED for slot ${slot}`, {
|
|
446
|
-
blockNumber: newBlockNumber,
|
|
447
|
-
slot: Number(slot),
|
|
448
|
-
});
|
|
449
|
-
this.metrics.recordBlockProposalFailed('block_build_failed');
|
|
450
|
-
}
|
|
451
|
-
} else {
|
|
452
|
-
// Normal mode: send the tx to L1
|
|
453
|
-
const l1Response = await publisher.sendRequests();
|
|
454
|
-
const proposedBlock = l1Response?.successfulActions.find(a => a === 'propose');
|
|
455
|
-
if (proposedBlock) {
|
|
456
|
-
this.lastBlockPublished = block;
|
|
457
|
-
this.emit('block-published', { blockNumber: newBlockNumber, slot: Number(slot) });
|
|
458
|
-
await this.metrics.incFilledSlot(publisher.getSenderAddress().toString(), coinbase);
|
|
459
|
-
} else if (block) {
|
|
460
|
-
this.emit('block-publish-failed', l1Response ?? {});
|
|
461
|
-
}
|
|
462
|
-
}
|
|
463
|
-
|
|
464
|
-
this.setState(SequencerState.IDLE, undefined);
|
|
465
732
|
}
|
|
466
733
|
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
734
|
+
protected createCheckpointProposalJob(
|
|
735
|
+
targetSlot: SlotNumber,
|
|
736
|
+
targetEpoch: EpochNumber,
|
|
737
|
+
checkpointNumber: CheckpointNumber,
|
|
738
|
+
syncedToBlockNumber: BlockNumber,
|
|
739
|
+
checkpointedCheckpointNumber: CheckpointNumber,
|
|
470
740
|
proposer: EthAddress | undefined,
|
|
471
|
-
newBlockNumber: BlockNumber,
|
|
472
741
|
publisher: SequencerPublisher,
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
) {
|
|
477
|
-
|
|
742
|
+
attestorAddress: EthAddress,
|
|
743
|
+
invalidateCheckpoint: InvalidateCheckpointRequest | undefined,
|
|
744
|
+
proposedCheckpointData?: ProposedCheckpointData,
|
|
745
|
+
): CheckpointProposalJob {
|
|
746
|
+
return new CheckpointProposalJob(
|
|
747
|
+
targetSlot,
|
|
748
|
+
targetEpoch,
|
|
749
|
+
checkpointNumber,
|
|
750
|
+
syncedToBlockNumber,
|
|
751
|
+
checkpointedCheckpointNumber,
|
|
478
752
|
proposer,
|
|
479
|
-
publisher
|
|
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
|
-
newGlobalVariables,
|
|
507
|
-
proposer,
|
|
508
|
-
invalidateBlock,
|
|
509
|
-
publisher,
|
|
510
|
-
);
|
|
511
|
-
} catch (err: any) {
|
|
512
|
-
this.emit('block-build-failed', { reason: err.message });
|
|
513
|
-
if (err instanceof FormattedViemError) {
|
|
514
|
-
this.log.verbose(`Unable to build/enqueue block ${err.message}`);
|
|
515
|
-
} else {
|
|
516
|
-
this.log.error(`Error building/enqueuing block`, err, { blockNumber: newBlockNumber, slot });
|
|
517
|
-
}
|
|
518
|
-
this.metrics.recordBlockProposalFailed(err.name || 'unknown_error');
|
|
519
|
-
}
|
|
520
|
-
} else {
|
|
521
|
-
this.log.verbose(
|
|
522
|
-
`Not enough txs to build block ${newBlockNumber} at slot ${slot} (got ${pendingTxCount} txs, need ${this.minTxsPerBlock})`,
|
|
523
|
-
{ chainTipArchive, blockNumber: newBlockNumber, slot },
|
|
524
|
-
);
|
|
525
|
-
this.emit('tx-count-check-failed', { minTxs: this.minTxsPerBlock, availableTxs: pendingTxCount });
|
|
526
|
-
this.metrics.recordBlockProposalFailed('insufficient_txs');
|
|
527
|
-
}
|
|
528
|
-
return block;
|
|
753
|
+
publisher,
|
|
754
|
+
attestorAddress,
|
|
755
|
+
invalidateCheckpoint,
|
|
756
|
+
this.validatorClient,
|
|
757
|
+
this.globalsBuilder,
|
|
758
|
+
this.p2pClient,
|
|
759
|
+
this.worldState,
|
|
760
|
+
this.l1ToL2MessageSource,
|
|
761
|
+
this.l2BlockSource,
|
|
762
|
+
this.checkpointsBuilder,
|
|
763
|
+
this.l2BlockSource,
|
|
764
|
+
this.l1Constants,
|
|
765
|
+
this.signatureContext,
|
|
766
|
+
this.config,
|
|
767
|
+
this.timetable,
|
|
768
|
+
this.slasherClient,
|
|
769
|
+
this.epochCache,
|
|
770
|
+
this.dateProvider,
|
|
771
|
+
this.metrics,
|
|
772
|
+
this.checkpointProposalJobMetrics.createRecorder(),
|
|
773
|
+
this,
|
|
774
|
+
this.pendingRequests,
|
|
775
|
+
this.setState.bind(this),
|
|
776
|
+
this.tracer,
|
|
777
|
+
this.log.getBindings(),
|
|
778
|
+
proposedCheckpointData,
|
|
779
|
+
);
|
|
529
780
|
}
|
|
530
781
|
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
if (err instanceof SequencerTooSlowError) {
|
|
537
|
-
// Log as warn only if we had to abort halfway through the block proposal
|
|
538
|
-
const logLvl = [SequencerState.INITIALIZING_PROPOSAL, SequencerState.PROPOSER_CHECK].includes(err.proposedState)
|
|
539
|
-
? ('debug' as const)
|
|
540
|
-
: ('warn' as const);
|
|
541
|
-
this.log[logLvl](err.message, { now: this.dateProvider.nowInSeconds() });
|
|
542
|
-
} else {
|
|
543
|
-
// Re-throw other errors
|
|
544
|
-
throw err;
|
|
545
|
-
}
|
|
546
|
-
} finally {
|
|
547
|
-
this.setState(SequencerState.IDLE, undefined);
|
|
548
|
-
}
|
|
782
|
+
/**
|
|
783
|
+
* Returns the current sequencer state.
|
|
784
|
+
*/
|
|
785
|
+
public getState(): SequencerState {
|
|
786
|
+
return this.state;
|
|
549
787
|
}
|
|
550
788
|
|
|
551
789
|
/**
|
|
552
|
-
*
|
|
790
|
+
* Internal helper for setting the sequencer state. Pure: sets the state, emits `state-changed`, and
|
|
791
|
+
* records metrics. Timing deadlines are queried explicitly at the relevant call sites, not gated here.
|
|
553
792
|
* @param proposedState - The new state to transition to.
|
|
554
|
-
* @param slotNumber - The
|
|
793
|
+
* @param slotNumber - The target slot being proposed for, emitted as `targetSlot` on the event payload
|
|
794
|
+
* and used to anchor `secondsIntoBuildFrame`. Undefined for lifecycle states with no associated slot.
|
|
555
795
|
* @param force - Whether to force the transition even if the sequencer is stopped.
|
|
556
796
|
*/
|
|
557
|
-
setState(
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
): void;
|
|
563
|
-
setState(proposedState: SequencerState, slotNumber: SlotNumber | undefined, opts: { force?: boolean } = {}): void {
|
|
797
|
+
protected setState(
|
|
798
|
+
proposedState: SequencerState,
|
|
799
|
+
slotNumber: SlotNumber | undefined,
|
|
800
|
+
opts: { force?: boolean } = {},
|
|
801
|
+
): void {
|
|
564
802
|
if (this.state === SequencerState.STOPPING && proposedState !== SequencerState.STOPPED && !opts.force) {
|
|
565
803
|
this.log.warn(`Cannot set sequencer to ${proposedState} as it is stopping.`);
|
|
566
804
|
throw new SequencerInterruptedError();
|
|
@@ -569,378 +807,56 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
|
|
|
569
807
|
this.log.warn(`Cannot set sequencer from ${this.state} to ${proposedState} as it is stopped.`);
|
|
570
808
|
return;
|
|
571
809
|
}
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
810
|
+
const secondsIntoBuildFrame = slotNumber !== undefined ? this.getSecondsIntoBuildFrame(slotNumber) : undefined;
|
|
811
|
+
|
|
812
|
+
const oldState = this.state;
|
|
813
|
+
const oldStateSlotNumber = this.stateSlotNumber;
|
|
814
|
+
const stateChanged = proposedState !== oldState;
|
|
815
|
+
// Wall-clock time spent in the previous state: the delta between consecutive state-changing setState
|
|
816
|
+
// calls, read from the date provider so it tracks simulated time under a test/manual clock.
|
|
817
|
+
const transitionAtMs = this.dateProvider.now();
|
|
818
|
+
const stateDurationMs = transitionAtMs - this.stateEnteredAtMs;
|
|
577
819
|
|
|
578
820
|
const boringStates = [SequencerState.IDLE, SequencerState.SYNCHRONIZING];
|
|
579
821
|
const logLevel =
|
|
580
|
-
boringStates.includes(proposedState) && boringStates.includes(
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
this.log[logLevel](`Transitioning from ${this.state} to ${proposedState}`, { slotNumber, secondsIntoSlot });
|
|
584
|
-
|
|
585
|
-
this.emit('state-changed', {
|
|
586
|
-
oldState: this.state,
|
|
822
|
+
boringStates.includes(proposedState) && boringStates.includes(oldState) ? ('trace' as const) : ('debug' as const);
|
|
823
|
+
this.stateLog[logLevel](`Transitioning from ${oldState} to ${proposedState}`, {
|
|
824
|
+
oldState,
|
|
587
825
|
newState: proposedState,
|
|
588
|
-
secondsIntoSlot,
|
|
589
826
|
slotNumber,
|
|
827
|
+
stateSlotNumber: oldStateSlotNumber,
|
|
828
|
+
secondsIntoBuildFrame,
|
|
829
|
+
...(stateChanged && { stateDurationMs: Math.ceil(stateDurationMs) }),
|
|
590
830
|
});
|
|
591
|
-
this.state = proposedState;
|
|
592
|
-
}
|
|
593
|
-
|
|
594
|
-
private async dropFailedTxsFromP2P(failedTxs: FailedTx[]) {
|
|
595
|
-
if (failedTxs.length === 0) {
|
|
596
|
-
return;
|
|
597
|
-
}
|
|
598
|
-
const failedTxData = failedTxs.map(fail => fail.tx);
|
|
599
|
-
const failedTxHashes = failedTxData.map(tx => tx.getTxHash());
|
|
600
|
-
this.log.verbose(`Dropping failed txs ${failedTxHashes.join(', ')}`);
|
|
601
|
-
await this.p2pClient.deleteTxs(failedTxHashes);
|
|
602
|
-
}
|
|
603
|
-
|
|
604
|
-
protected getBlockBuilderOptions(slot: SlotNumber): PublicProcessorLimits {
|
|
605
|
-
// Deadline for processing depends on whether we're proposing a block
|
|
606
|
-
const secondsIntoSlot = this.getSecondsIntoSlot(slot);
|
|
607
|
-
const processingEndTimeWithinSlot = this.timetable.getBlockProposalExecTimeEnd(secondsIntoSlot);
|
|
608
|
-
|
|
609
|
-
// Deadline is only set if enforceTimeTable is enabled.
|
|
610
|
-
const deadline = this.enforceTimeTable
|
|
611
|
-
? new Date((this.getSlotStartBuildTimestamp(slot) + processingEndTimeWithinSlot) * 1000)
|
|
612
|
-
: undefined;
|
|
613
|
-
return {
|
|
614
|
-
maxTransactions: this.maxTxsPerBlock,
|
|
615
|
-
maxBlockSize: this.maxBlockSizeInBytes,
|
|
616
|
-
maxBlockGas: this.maxBlockGas,
|
|
617
|
-
maxBlobFields: BLOBS_PER_CHECKPOINT * FIELDS_PER_BLOB,
|
|
618
|
-
deadline,
|
|
619
|
-
};
|
|
620
|
-
}
|
|
621
|
-
|
|
622
|
-
/**
|
|
623
|
-
* @notice Build and propose a block to the chain
|
|
624
|
-
*
|
|
625
|
-
* @dev MUST throw instead of exiting early to ensure that world-state
|
|
626
|
-
* is being rolled back if the block is dropped.
|
|
627
|
-
*
|
|
628
|
-
* @param pendingTxs - Iterable of pending transactions to construct the block from
|
|
629
|
-
* @param proposalHeader - The partial header constructed for the proposal
|
|
630
|
-
* @param newGlobalVariables - The global variables for the new block
|
|
631
|
-
* @param proposerAddress - The address of the proposer
|
|
632
|
-
*/
|
|
633
|
-
@trackSpan('Sequencer.buildBlockAndEnqueuePublish', (_validTxs, _proposalHeader, newGlobalVariables) => ({
|
|
634
|
-
[Attributes.BLOCK_NUMBER]: newGlobalVariables.blockNumber,
|
|
635
|
-
}))
|
|
636
|
-
private async buildBlockAndEnqueuePublish(
|
|
637
|
-
pendingTxs: Iterable<Tx> | AsyncIterable<Tx>,
|
|
638
|
-
proposalHeader: CheckpointHeader,
|
|
639
|
-
newGlobalVariables: GlobalVariables,
|
|
640
|
-
proposerAddress: EthAddress | undefined,
|
|
641
|
-
invalidateBlock: InvalidateBlockRequest | undefined,
|
|
642
|
-
publisher: SequencerPublisher,
|
|
643
|
-
): Promise<L2Block> {
|
|
644
|
-
await publisher.validateBlockHeader(proposalHeader, invalidateBlock);
|
|
645
|
-
|
|
646
|
-
const blockNumber = newGlobalVariables.blockNumber;
|
|
647
|
-
const slot = proposalHeader.slotNumber;
|
|
648
|
-
const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(blockNumber);
|
|
649
|
-
|
|
650
|
-
const workTimer = new Timer();
|
|
651
|
-
this.setState(SequencerState.CREATING_BLOCK, slot);
|
|
652
|
-
|
|
653
|
-
try {
|
|
654
|
-
const blockBuilderOptions = this.getBlockBuilderOptions(slot);
|
|
655
|
-
const buildBlockRes = await this.blockBuilder.buildBlock(
|
|
656
|
-
pendingTxs,
|
|
657
|
-
l1ToL2Messages,
|
|
658
|
-
newGlobalVariables,
|
|
659
|
-
blockBuilderOptions,
|
|
660
|
-
);
|
|
661
|
-
const { publicGas, block, publicProcessorDuration, numTxs, numMsgs, blockBuildingTimer, usedTxs, failedTxs } =
|
|
662
|
-
buildBlockRes;
|
|
663
|
-
const blockBuildDuration = workTimer.ms();
|
|
664
|
-
await this.dropFailedTxsFromP2P(failedTxs);
|
|
665
|
-
|
|
666
|
-
const minTxsPerBlock = this.minTxsPerBlock;
|
|
667
|
-
if (numTxs < minTxsPerBlock) {
|
|
668
|
-
this.log.warn(
|
|
669
|
-
`Block ${blockNumber} has too few txs to be proposed (got ${numTxs} but required ${minTxsPerBlock})`,
|
|
670
|
-
{ slot, blockNumber, numTxs },
|
|
671
|
-
);
|
|
672
|
-
throw new Error(`Block has too few successful txs to be proposed`);
|
|
673
|
-
}
|
|
674
|
-
|
|
675
|
-
// TODO(@PhilWindle) We should probably periodically check for things like another
|
|
676
|
-
// block being published before ours instead of just waiting on our block
|
|
677
|
-
await publisher.validateBlockHeader(block.getCheckpointHeader(), invalidateBlock);
|
|
678
|
-
|
|
679
|
-
const blockStats: L2BlockBuiltStats = {
|
|
680
|
-
eventName: 'l2-block-built',
|
|
681
|
-
creator: proposerAddress?.toString() ?? publisher.getSenderAddress().toString(),
|
|
682
|
-
duration: workTimer.ms(),
|
|
683
|
-
publicProcessDuration: publicProcessorDuration,
|
|
684
|
-
rollupCircuitsDuration: blockBuildingTimer.ms(),
|
|
685
|
-
...block.getStats(),
|
|
686
|
-
};
|
|
687
|
-
|
|
688
|
-
const blockHash = await block.hash();
|
|
689
|
-
const txHashes = block.body.txEffects.map(tx => tx.txHash);
|
|
690
|
-
this.log.info(
|
|
691
|
-
`Built block ${block.number} for slot ${slot} with ${numTxs} txs and ${numMsgs} messages. ${
|
|
692
|
-
publicGas.l2Gas / workTimer.s()
|
|
693
|
-
} mana/s`,
|
|
694
|
-
{
|
|
695
|
-
blockHash,
|
|
696
|
-
globalVariables: block.header.globalVariables.toInspect(),
|
|
697
|
-
txHashes,
|
|
698
|
-
...blockStats,
|
|
699
|
-
},
|
|
700
|
-
);
|
|
701
|
-
|
|
702
|
-
// In fisherman mode, skip attestation collection
|
|
703
|
-
let attestationsAndSigners: CommitteeAttestationsAndSigners;
|
|
704
|
-
if (this.config.fishermanMode) {
|
|
705
|
-
this.log.debug('Skipping attestation collection');
|
|
706
|
-
attestationsAndSigners = CommitteeAttestationsAndSigners.empty();
|
|
707
|
-
} else {
|
|
708
|
-
this.log.debug('Collecting attestations');
|
|
709
|
-
attestationsAndSigners = await this.collectAttestations(block, usedTxs, proposerAddress);
|
|
710
|
-
this.log.verbose(
|
|
711
|
-
`Collected ${attestationsAndSigners.attestations.length} attestations for block ${blockNumber} at slot ${slot}`,
|
|
712
|
-
{ blockHash, blockNumber, slot },
|
|
713
|
-
);
|
|
714
|
-
}
|
|
715
|
-
|
|
716
|
-
// In fisherman mode, skip attestation signing
|
|
717
|
-
const attestationsAndSignersSignature =
|
|
718
|
-
this.config.fishermanMode || !this.validatorClient
|
|
719
|
-
? Signature.empty()
|
|
720
|
-
: await this.validatorClient.signAttestationsAndSigners(
|
|
721
|
-
attestationsAndSigners,
|
|
722
|
-
proposerAddress ?? publisher.getSenderAddress(),
|
|
723
|
-
);
|
|
724
|
-
|
|
725
|
-
await this.enqueuePublishL2Block(
|
|
726
|
-
block,
|
|
727
|
-
attestationsAndSigners,
|
|
728
|
-
attestationsAndSignersSignature,
|
|
729
|
-
invalidateBlock,
|
|
730
|
-
publisher,
|
|
731
|
-
);
|
|
732
|
-
this.metrics.recordBuiltBlock(blockBuildDuration, publicGas.l2Gas);
|
|
733
|
-
return block;
|
|
734
|
-
} catch (err) {
|
|
735
|
-
this.metrics.recordFailedBlock();
|
|
736
|
-
throw err;
|
|
737
|
-
}
|
|
738
|
-
}
|
|
739
|
-
|
|
740
|
-
@trackSpan('Sequencer.collectAttestations', (block, txHashes) => ({
|
|
741
|
-
[Attributes.BLOCK_NUMBER]: block.number,
|
|
742
|
-
[Attributes.BLOCK_ARCHIVE]: block.archive.toString(),
|
|
743
|
-
[Attributes.BLOCK_TXS_COUNT]: txHashes.length,
|
|
744
|
-
}))
|
|
745
|
-
protected async collectAttestations(
|
|
746
|
-
block: L2Block,
|
|
747
|
-
txs: Tx[],
|
|
748
|
-
proposerAddress: EthAddress | undefined,
|
|
749
|
-
): Promise<CommitteeAttestationsAndSigners> {
|
|
750
|
-
const { committee, seed, epoch } = await this.epochCache.getCommittee(block.slot);
|
|
751
|
-
|
|
752
|
-
// We checked above that the committee is defined, so this should never happen.
|
|
753
|
-
if (!committee) {
|
|
754
|
-
throw new Error('No committee when collecting attestations');
|
|
755
|
-
}
|
|
756
|
-
|
|
757
|
-
if (committee.length === 0) {
|
|
758
|
-
this.log.verbose(`Attesting committee is empty`);
|
|
759
|
-
return CommitteeAttestationsAndSigners.empty();
|
|
760
|
-
} else {
|
|
761
|
-
this.log.debug(`Attesting committee length is ${committee.length}`);
|
|
762
|
-
}
|
|
763
|
-
|
|
764
|
-
if (!this.validatorClient) {
|
|
765
|
-
throw new Error('Missing validator client: Cannot collect attestations');
|
|
766
|
-
}
|
|
767
831
|
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
const proposal = await this.validatorClient.createBlockProposal(
|
|
779
|
-
block.header.globalVariables.blockNumber,
|
|
780
|
-
block.getCheckpointHeader(),
|
|
781
|
-
block.archive.root,
|
|
782
|
-
txs,
|
|
783
|
-
proposerAddress,
|
|
784
|
-
blockProposalOptions,
|
|
785
|
-
);
|
|
786
|
-
|
|
787
|
-
if (!proposal) {
|
|
788
|
-
throw new Error(`Failed to create block proposal`);
|
|
789
|
-
}
|
|
790
|
-
|
|
791
|
-
if (this.config.skipCollectingAttestations) {
|
|
792
|
-
this.log.warn('Skipping attestation collection as per config (attesting with own keys only)');
|
|
793
|
-
const attestations = await this.validatorClient?.collectOwnAttestations(proposal);
|
|
794
|
-
return new CommitteeAttestationsAndSigners(orderAttestations(attestations ?? [], committee));
|
|
795
|
-
}
|
|
796
|
-
|
|
797
|
-
this.log.debug('Broadcasting block proposal to validators');
|
|
798
|
-
await this.validatorClient.broadcastBlockProposal(proposal);
|
|
799
|
-
|
|
800
|
-
const attestationTimeAllowed = this.enforceTimeTable
|
|
801
|
-
? this.timetable.getMaxAllowedTime(SequencerState.PUBLISHING_BLOCK)!
|
|
802
|
-
: this.aztecSlotDuration;
|
|
803
|
-
|
|
804
|
-
this.metrics.recordRequiredAttestations(numberOfRequiredAttestations, attestationTimeAllowed);
|
|
805
|
-
|
|
806
|
-
const timer = new Timer();
|
|
807
|
-
let collectedAttestationsCount: number = 0;
|
|
808
|
-
try {
|
|
809
|
-
const attestationDeadline = new Date(this.dateProvider.now() + attestationTimeAllowed * 1000);
|
|
810
|
-
const attestations = await this.validatorClient.collectAttestations(
|
|
811
|
-
proposal,
|
|
812
|
-
numberOfRequiredAttestations,
|
|
813
|
-
attestationDeadline,
|
|
814
|
-
);
|
|
815
|
-
|
|
816
|
-
collectedAttestationsCount = attestations.length;
|
|
817
|
-
|
|
818
|
-
// note: the smart contract requires that the signatures are provided in the order of the committee
|
|
819
|
-
const sorted = orderAttestations(attestations, committee);
|
|
820
|
-
|
|
821
|
-
// manipulate the attestations if we've been configured to do so
|
|
822
|
-
if (this.config.injectFakeAttestation || this.config.shuffleAttestationOrdering) {
|
|
823
|
-
return this.manipulateAttestations(block, epoch, seed, committee, sorted);
|
|
824
|
-
}
|
|
825
|
-
|
|
826
|
-
return new CommitteeAttestationsAndSigners(sorted);
|
|
827
|
-
} catch (err) {
|
|
828
|
-
if (err && err instanceof AttestationTimeoutError) {
|
|
829
|
-
collectedAttestationsCount = err.collectedCount;
|
|
830
|
-
}
|
|
831
|
-
throw err;
|
|
832
|
-
} finally {
|
|
833
|
-
this.metrics.recordCollectedAttestations(collectedAttestationsCount, timer.ms());
|
|
834
|
-
}
|
|
835
|
-
}
|
|
836
|
-
|
|
837
|
-
/** Breaks the attestations before publishing based on attack configs */
|
|
838
|
-
private manipulateAttestations(
|
|
839
|
-
block: L2Block,
|
|
840
|
-
epoch: EpochNumber,
|
|
841
|
-
seed: bigint,
|
|
842
|
-
committee: EthAddress[],
|
|
843
|
-
attestations: CommitteeAttestation[],
|
|
844
|
-
) {
|
|
845
|
-
// Compute the proposer index in the committee, since we dont want to tweak it.
|
|
846
|
-
// Otherwise, the L1 rollup contract will reject the block outright.
|
|
847
|
-
const proposerIndex = Number(
|
|
848
|
-
this.epochCache.computeProposerIndex(block.slot, epoch, seed, BigInt(committee.length)),
|
|
849
|
-
);
|
|
850
|
-
|
|
851
|
-
if (this.config.injectFakeAttestation) {
|
|
852
|
-
// Find non-empty attestations that are not from the proposer
|
|
853
|
-
const nonProposerIndices: number[] = [];
|
|
854
|
-
for (let i = 0; i < attestations.length; i++) {
|
|
855
|
-
if (!attestations[i].signature.isEmpty() && i !== proposerIndex) {
|
|
856
|
-
nonProposerIndices.push(i);
|
|
857
|
-
}
|
|
858
|
-
}
|
|
859
|
-
if (nonProposerIndices.length > 0) {
|
|
860
|
-
const targetIndex = nonProposerIndices[randomInt(nonProposerIndices.length)];
|
|
861
|
-
this.log.warn(`Injecting fake attestation in block ${block.number} at index ${targetIndex}`);
|
|
862
|
-
unfreeze(attestations[targetIndex]).signature = Signature.random();
|
|
863
|
-
}
|
|
864
|
-
return new CommitteeAttestationsAndSigners(attestations);
|
|
865
|
-
}
|
|
866
|
-
|
|
867
|
-
if (this.config.shuffleAttestationOrdering) {
|
|
868
|
-
this.log.warn(`Shuffling attestation ordering in block ${block.number} (proposer index ${proposerIndex})`);
|
|
869
|
-
|
|
870
|
-
const shuffled = [...attestations];
|
|
871
|
-
const [i, j] = [(proposerIndex + 1) % shuffled.length, (proposerIndex + 2) % shuffled.length];
|
|
872
|
-
const valueI = shuffled[i];
|
|
873
|
-
const valueJ = shuffled[j];
|
|
874
|
-
shuffled[i] = valueJ;
|
|
875
|
-
shuffled[j] = valueI;
|
|
876
|
-
|
|
877
|
-
const signers = new CommitteeAttestationsAndSigners(attestations).getSigners();
|
|
878
|
-
return new MaliciousCommitteeAttestationsAndSigners(shuffled, signers);
|
|
879
|
-
}
|
|
880
|
-
|
|
881
|
-
return new CommitteeAttestationsAndSigners(attestations);
|
|
882
|
-
}
|
|
883
|
-
|
|
884
|
-
/**
|
|
885
|
-
* Publishes the L2Block to the rollup contract.
|
|
886
|
-
* @param block - The L2Block to be published.
|
|
887
|
-
*/
|
|
888
|
-
@trackSpan('Sequencer.enqueuePublishL2Block', block => ({
|
|
889
|
-
[Attributes.BLOCK_NUMBER]: block.number,
|
|
890
|
-
}))
|
|
891
|
-
protected async enqueuePublishL2Block(
|
|
892
|
-
block: L2Block,
|
|
893
|
-
attestationsAndSigners: CommitteeAttestationsAndSigners,
|
|
894
|
-
attestationsAndSignersSignature: Signature,
|
|
895
|
-
invalidateBlock: InvalidateBlockRequest | undefined,
|
|
896
|
-
publisher: SequencerPublisher,
|
|
897
|
-
): Promise<void> {
|
|
898
|
-
// Publishes new block to the network and awaits the tx to be mined
|
|
899
|
-
this.setState(SequencerState.PUBLISHING_BLOCK, block.header.globalVariables.slotNumber);
|
|
900
|
-
|
|
901
|
-
// Time out tx at the end of the slot
|
|
902
|
-
const slot = block.header.globalVariables.slotNumber;
|
|
903
|
-
const txTimeoutAt = new Date((this.getSlotStartBuildTimestamp(slot) + this.aztecSlotDuration) * 1000);
|
|
904
|
-
|
|
905
|
-
const enqueued = await publisher.enqueueProposeL2Block(
|
|
906
|
-
block,
|
|
907
|
-
attestationsAndSigners,
|
|
908
|
-
attestationsAndSignersSignature,
|
|
909
|
-
{
|
|
910
|
-
txTimeoutAt,
|
|
911
|
-
forcePendingBlockNumber: invalidateBlock?.forcePendingBlockNumber,
|
|
912
|
-
},
|
|
913
|
-
);
|
|
914
|
-
|
|
915
|
-
if (!enqueued) {
|
|
916
|
-
throw new Error(`Failed to enqueue publish of block ${block.number}`);
|
|
832
|
+
this.emit('state-changed', {
|
|
833
|
+
oldState,
|
|
834
|
+
newState: proposedState,
|
|
835
|
+
secondsIntoBuildFrame,
|
|
836
|
+
targetSlot: slotNumber,
|
|
837
|
+
});
|
|
838
|
+
if (stateChanged) {
|
|
839
|
+
this.metrics.recordStateDuration(stateDurationMs, oldState);
|
|
840
|
+
this.stateEnteredAtMs = transitionAtMs;
|
|
841
|
+
this.stateSlotNumber = slotNumber;
|
|
917
842
|
}
|
|
843
|
+
this.state = proposedState;
|
|
918
844
|
}
|
|
919
845
|
|
|
920
846
|
/**
|
|
921
847
|
* Returns whether all dependencies have caught up.
|
|
922
848
|
* We don't check against the previous block submitted since it may have been reorg'd out.
|
|
923
849
|
*/
|
|
924
|
-
protected async checkSync(args: { ts: bigint; slot: SlotNumber }): Promise<
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
}
|
|
932
|
-
| undefined
|
|
933
|
-
> {
|
|
934
|
-
// Check that the archiver and dependencies have synced to the previous L1 slot at least
|
|
935
|
-
// TODO(#14766): Archiver reports L1 timestamp based on L1 blocks seen, which means that a missed L1 block will
|
|
936
|
-
// cause the archiver L1 timestamp to fall behind, and cause this sequencer to start processing one L1 slot later.
|
|
937
|
-
const l1Timestamp = await this.l2BlockSource.getL1Timestamp();
|
|
938
|
-
const { slot, ts } = args;
|
|
939
|
-
if (l1Timestamp === undefined || l1Timestamp + BigInt(this.l1Constants.ethereumSlotDuration) < ts) {
|
|
850
|
+
protected async checkSync(args: { ts: bigint; slot: SlotNumber }): Promise<SequencerSyncCheckResult | undefined> {
|
|
851
|
+
// Check that the archiver has fully synced the L2 slot before the one we want to propose in.
|
|
852
|
+
// The archiver reports sync progress via L1 block timestamps and synced checkpoint slots.
|
|
853
|
+
// See getSyncedL2SlotNumber for how missed L1 blocks are handled.
|
|
854
|
+
const syncedL2Slot = await this.l2BlockSource.getSyncedL2SlotNumber();
|
|
855
|
+
const { slot } = args;
|
|
856
|
+
if (syncedL2Slot === undefined || syncedL2Slot + 1 < slot) {
|
|
940
857
|
this.log.debug(`Cannot propose block at next L2 slot ${slot} due to pending sync from L1`, {
|
|
941
858
|
slot,
|
|
942
|
-
|
|
943
|
-
l1Timestamp,
|
|
859
|
+
syncedL2Slot,
|
|
944
860
|
});
|
|
945
861
|
return undefined;
|
|
946
862
|
}
|
|
@@ -950,122 +866,117 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
|
|
|
950
866
|
number: syncSummary.latestBlockNumber,
|
|
951
867
|
hash: syncSummary.latestBlockHash,
|
|
952
868
|
})),
|
|
953
|
-
this.l2BlockSource.getL2Tips().then(t => t.
|
|
869
|
+
this.l2BlockSource.getL2Tips().then(t => ({ proposed: t.proposed, checkpointed: t.checkpointed })),
|
|
954
870
|
this.p2pClient.getStatus().then(p2p => p2p.syncedToL2Block),
|
|
955
|
-
this.l1ToL2MessageSource.getL2Tips().then(t => t.
|
|
871
|
+
this.l1ToL2MessageSource.getL2Tips().then(t => ({ proposed: t.proposed, checkpointed: t.checkpointed })),
|
|
956
872
|
this.l2BlockSource.getPendingChainValidationStatus(),
|
|
873
|
+
this.l2BlockSource.getProposedCheckpointData(),
|
|
957
874
|
] as const);
|
|
958
875
|
|
|
959
|
-
const [worldState,
|
|
876
|
+
const [worldState, l2Tips, p2p, l1ToL2MessageSourceTips, pendingChainValidationStatus, proposedCheckpointData] =
|
|
877
|
+
syncedBlocks;
|
|
960
878
|
|
|
961
|
-
// Handle zero as a special case, since the block hash won't match across services if we're changing the prefilled data for the genesis block,
|
|
962
|
-
// as the world state can compute the new genesis block hash, but other components use the hardcoded constant.
|
|
963
879
|
const result =
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
880
|
+
worldState.hash === l2Tips.proposed.hash &&
|
|
881
|
+
p2p.hash === l2Tips.proposed.hash &&
|
|
882
|
+
l1ToL2MessageSourceTips.proposed.hash === l2Tips.proposed.hash &&
|
|
883
|
+
l1ToL2MessageSourceTips.checkpointed.block.hash === l2Tips.checkpointed.block.hash &&
|
|
884
|
+
l1ToL2MessageSourceTips.checkpointed.checkpoint.hash === l2Tips.checkpointed.checkpoint.hash;
|
|
968
885
|
|
|
969
886
|
if (!result) {
|
|
970
|
-
this.log.debug(`Sequencer sync check failed`, {
|
|
887
|
+
this.log.debug(`Sequencer sync check failed`, {
|
|
888
|
+
worldState,
|
|
889
|
+
l2BlockSource: l2Tips.proposed,
|
|
890
|
+
p2p,
|
|
891
|
+
l1ToL2MessageSourceTips,
|
|
892
|
+
});
|
|
971
893
|
return undefined;
|
|
972
894
|
}
|
|
973
895
|
|
|
974
|
-
// Special case for genesis state
|
|
975
896
|
const blockNumber = worldState.number;
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
897
|
+
const blockData = await this.l2BlockSource.getBlockData({ number: blockNumber });
|
|
898
|
+
if (!blockData) {
|
|
899
|
+
this.log.warn(`Sequencer sync check failed: failed to get L2 block data ${blockNumber} from the archiver`, {
|
|
900
|
+
blockNumber,
|
|
901
|
+
l2Tips,
|
|
902
|
+
syncedL2Slot,
|
|
903
|
+
...args,
|
|
904
|
+
});
|
|
905
|
+
return undefined;
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
// Refuse to build a checkpoint on top of a proposed block whose enclosing checkpoint was never
|
|
909
|
+
// proposed. Under pipelining we may have received and reexecuted such a block locally — advancing
|
|
910
|
+
// our world-state tip past the checkpointed tip — while the proposing node never published the
|
|
911
|
+
// matching proposed checkpoint (e.g. it crashed before assembling it). Building on this orphan block
|
|
912
|
+
// would fork the chain off a tip no other node can follow. The archiver prunes these orphan blocks
|
|
913
|
+
// once their build slot ends; this guard is the correctness barrier during the grace window before.
|
|
914
|
+
// `getProposedCheckpointData()` returns the latest proposed checkpoint payload, which is always
|
|
915
|
+
// the leading one (a proposed entry is only stored beyond the confirmed frontier and is deleted
|
|
916
|
+
// on confirmation). It carries no tip, so there is no tip-vs-payload split read to reconcile.
|
|
917
|
+
if (
|
|
918
|
+
blockData.checkpointNumber > l2Tips.checkpointed.checkpoint.number &&
|
|
919
|
+
proposedCheckpointData?.checkpointNumber !== blockData.checkpointNumber
|
|
920
|
+
) {
|
|
921
|
+
const logCtx = {
|
|
922
|
+
blockCheckpointNumber: blockData.checkpointNumber,
|
|
923
|
+
checkpointedCheckpointNumber: l2Tips.checkpointed.checkpoint.number,
|
|
924
|
+
proposedCheckpointTipNumber: proposedCheckpointData?.checkpointNumber,
|
|
925
|
+
blockNumber: blockData.header.getBlockNumber(),
|
|
926
|
+
blockSlot: blockData.header.getSlot(),
|
|
927
|
+
syncedL2Slot,
|
|
928
|
+
...args,
|
|
929
|
+
};
|
|
930
|
+
|
|
931
|
+
this.log.debug(`Waiting for proposed checkpoint to catch up with reexecuted block`, logCtx);
|
|
932
|
+
return undefined;
|
|
979
933
|
}
|
|
980
934
|
|
|
981
|
-
const
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
935
|
+
const hasProposedCheckpoint = proposedCheckpointData !== undefined;
|
|
936
|
+
|
|
937
|
+
// Check that the proposed checkpoint is indeed the parent of the checkpoint we'll be building
|
|
938
|
+
// The checkpoint number to build is derived as blockData.checkpointNumber + 1
|
|
939
|
+
if (proposedCheckpointData && proposedCheckpointData.checkpointNumber !== blockData.checkpointNumber) {
|
|
940
|
+
this.log.warn(`Sequencer sync check failed: proposed checkpoint number mismatch`, {
|
|
941
|
+
proposedCheckpointNumber: proposedCheckpointData.checkpointNumber,
|
|
942
|
+
blockCheckpointNumber: blockData.checkpointNumber,
|
|
943
|
+
syncedL2Slot,
|
|
944
|
+
...args,
|
|
945
|
+
});
|
|
985
946
|
return undefined;
|
|
986
947
|
}
|
|
987
948
|
|
|
988
949
|
return {
|
|
989
|
-
|
|
990
|
-
blockNumber:
|
|
991
|
-
|
|
992
|
-
|
|
950
|
+
blockData,
|
|
951
|
+
blockNumber: blockData.header.getBlockNumber(),
|
|
952
|
+
checkpointNumber: blockData.checkpointNumber,
|
|
953
|
+
checkpointedCheckpointNumber: l2Tips.checkpointed.checkpoint.number,
|
|
954
|
+
archive: blockData.archive.root,
|
|
955
|
+
hasProposedCheckpoint,
|
|
956
|
+
proposedCheckpointData,
|
|
957
|
+
syncedL2Slot,
|
|
993
958
|
pendingChainValidationStatus,
|
|
994
959
|
};
|
|
995
960
|
}
|
|
996
961
|
|
|
997
|
-
/**
|
|
998
|
-
* Enqueues governance and slashing votes with the publisher. Does not block.
|
|
999
|
-
* @param publisher - The publisher to enqueue votes with
|
|
1000
|
-
* @param attestorAddress - The attestor address to use for signing
|
|
1001
|
-
* @param slot - The slot number
|
|
1002
|
-
* @param timestamp - The timestamp for the votes
|
|
1003
|
-
* @param context - Optional context for logging (e.g., block number)
|
|
1004
|
-
* @returns A tuple of [governanceEnqueued, slashingEnqueued]
|
|
1005
|
-
*/
|
|
1006
|
-
protected enqueueGovernanceAndSlashingVotes(
|
|
1007
|
-
publisher: SequencerPublisher,
|
|
1008
|
-
attestorAddress: EthAddress,
|
|
1009
|
-
slot: SlotNumber,
|
|
1010
|
-
timestamp: bigint,
|
|
1011
|
-
): [Promise<boolean> | undefined, Promise<boolean> | undefined] {
|
|
1012
|
-
try {
|
|
1013
|
-
const signerFn = (msg: TypedDataDefinition) =>
|
|
1014
|
-
this.validatorClient!.signWithAddress(attestorAddress, msg).then(s => s.toString());
|
|
1015
|
-
|
|
1016
|
-
const enqueueGovernancePromise =
|
|
1017
|
-
this.governanceProposerPayload && !this.governanceProposerPayload.isZero()
|
|
1018
|
-
? publisher
|
|
1019
|
-
.enqueueGovernanceCastSignal(this.governanceProposerPayload, slot, timestamp, attestorAddress, signerFn)
|
|
1020
|
-
.catch(err => {
|
|
1021
|
-
this.log.error(`Error enqueuing governance vote`, err, { slot });
|
|
1022
|
-
return false;
|
|
1023
|
-
})
|
|
1024
|
-
: undefined;
|
|
1025
|
-
|
|
1026
|
-
const enqueueSlashingPromise = this.slasherClient
|
|
1027
|
-
? this.slasherClient
|
|
1028
|
-
.getProposerActions(slot)
|
|
1029
|
-
.then(actions => {
|
|
1030
|
-
// Record metrics for fisherman mode
|
|
1031
|
-
if (this.config.fishermanMode && actions.length > 0) {
|
|
1032
|
-
this.log.debug(`Fisherman mode: simulating ${actions.length} slashing action(s) for slot ${slot}`, {
|
|
1033
|
-
slot,
|
|
1034
|
-
actionCount: actions.length,
|
|
1035
|
-
});
|
|
1036
|
-
this.metrics.recordSlashingAttempt(actions.length);
|
|
1037
|
-
}
|
|
1038
|
-
// Enqueue the actions to fully simulate L1 tx building (they won't be sent in fisherman mode)
|
|
1039
|
-
return publisher.enqueueSlashingActions(actions, slot, timestamp, attestorAddress, signerFn);
|
|
1040
|
-
})
|
|
1041
|
-
.catch(err => {
|
|
1042
|
-
this.log.error(`Error enqueuing slashing actions`, err, { slot });
|
|
1043
|
-
return false;
|
|
1044
|
-
})
|
|
1045
|
-
: undefined;
|
|
1046
|
-
|
|
1047
|
-
return [enqueueGovernancePromise, enqueueSlashingPromise];
|
|
1048
|
-
} catch (err) {
|
|
1049
|
-
this.log.error(`Error enqueueing governance and slashing votes`, err);
|
|
1050
|
-
return [undefined, undefined];
|
|
1051
|
-
}
|
|
1052
|
-
}
|
|
1053
|
-
|
|
1054
962
|
/**
|
|
1055
963
|
* Checks if we are the proposer for the next slot.
|
|
1056
964
|
* @returns True if we can propose, and the proposer address (undefined if anyone can propose)
|
|
1057
965
|
*/
|
|
1058
|
-
protected async checkCanPropose(
|
|
966
|
+
protected async checkCanPropose(targetSlot: SlotNumber): Promise<[boolean, EthAddress | undefined]> {
|
|
1059
967
|
let proposer: EthAddress | undefined;
|
|
1060
968
|
|
|
1061
969
|
try {
|
|
1062
|
-
proposer = await this.epochCache.getProposerAttesterAddressInSlot(
|
|
970
|
+
proposer = await this.epochCache.getProposerAttesterAddressInSlot(targetSlot);
|
|
1063
971
|
} catch (e) {
|
|
1064
972
|
if (e instanceof NoCommitteeError) {
|
|
1065
|
-
this.
|
|
973
|
+
if (this.lastSlotForNoCommitteeWarning !== targetSlot) {
|
|
974
|
+
this.lastSlotForNoCommitteeWarning = targetSlot;
|
|
975
|
+
this.log.warn(`Cannot propose at target slot ${targetSlot} since the committee does not exist on L1`);
|
|
976
|
+
}
|
|
1066
977
|
return [false, undefined];
|
|
1067
978
|
}
|
|
1068
|
-
this.log.error(`Error getting proposer for slot ${
|
|
979
|
+
this.log.error(`Error getting proposer for target slot ${targetSlot}`, e);
|
|
1069
980
|
return [false, undefined];
|
|
1070
981
|
}
|
|
1071
982
|
|
|
@@ -1078,58 +989,60 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
|
|
|
1078
989
|
return [true, proposer];
|
|
1079
990
|
}
|
|
1080
991
|
|
|
1081
|
-
const validatorAddresses = this.validatorClient
|
|
992
|
+
const validatorAddresses = this.validatorClient.getValidatorAddresses();
|
|
1082
993
|
const weAreProposer = validatorAddresses.some(addr => addr.equals(proposer));
|
|
1083
994
|
|
|
1084
995
|
if (!weAreProposer) {
|
|
1085
|
-
this.log.debug(`Cannot propose at slot ${
|
|
996
|
+
this.log.debug(`Cannot propose at target slot ${targetSlot} since we are not a proposer`, {
|
|
997
|
+
targetSlot,
|
|
998
|
+
validatorAddresses,
|
|
999
|
+
proposer,
|
|
1000
|
+
});
|
|
1086
1001
|
return [false, proposer];
|
|
1087
1002
|
}
|
|
1088
1003
|
|
|
1004
|
+
this.log.info(`We are the proposer for pipeline slot ${targetSlot}`, {
|
|
1005
|
+
targetSlot,
|
|
1006
|
+
proposer,
|
|
1007
|
+
});
|
|
1089
1008
|
return [true, proposer];
|
|
1090
1009
|
}
|
|
1091
1010
|
|
|
1092
1011
|
/**
|
|
1093
|
-
* Tries to vote on slashing actions and governance
|
|
1094
|
-
* This allows the sequencer to participate in governance/slashing votes even when it
|
|
1012
|
+
* Tries to vote on slashing actions and governance and to prune when we cannot build and are past the
|
|
1013
|
+
* block-building window. This allows the sequencer to participate in governance/slashing votes even when it
|
|
1014
|
+
* cannot build blocks, and to prune the pending chain so it can recover from bad data that is blocking sync.
|
|
1095
1015
|
*/
|
|
1096
|
-
|
|
1097
|
-
|
|
1016
|
+
@trackSpan('Sequencer.tryVoteAndPruneWhenCannotBuild', ({ slot }) => ({ [Attributes.SLOT_NUMBER]: slot }))
|
|
1017
|
+
protected async tryVoteAndPruneWhenCannotBuild(args: { slot: SlotNumber; targetSlot: SlotNumber }): Promise<void> {
|
|
1018
|
+
const { slot, targetSlot } = args;
|
|
1098
1019
|
|
|
1099
1020
|
// Prevent duplicate attempts in the same slot
|
|
1100
|
-
if (this.
|
|
1101
|
-
this.log.
|
|
1021
|
+
if (this.lastSlotForFallbackAction === slot) {
|
|
1022
|
+
this.log.trace(`Already attempted fallback actions in slot ${slot} (skipping)`);
|
|
1102
1023
|
return;
|
|
1103
1024
|
}
|
|
1104
1025
|
|
|
1105
|
-
//
|
|
1106
|
-
|
|
1107
|
-
|
|
1026
|
+
// Vote-only actions do not give up the slot: if sync recovers, a later work-loop iteration can still build.
|
|
1027
|
+
// Under proposer pipelining the work loop reasons about the next L1 slot, so waiting for the target slot's
|
|
1028
|
+
// build-start deadline can miss the whole fallback window when the target advances with the clock.
|
|
1029
|
+
const nowSeconds = this.dateProvider.now() / 1000;
|
|
1030
|
+
const startDeadline = this.timetable.getBuildStartDeadline(targetSlot);
|
|
1108
1031
|
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
this.log.trace(`Not attempting to vote since there is still for block building`, {
|
|
1113
|
-
secondsIntoSlot,
|
|
1114
|
-
maxAllowedTime,
|
|
1115
|
-
});
|
|
1116
|
-
return;
|
|
1117
|
-
}
|
|
1118
|
-
|
|
1119
|
-
this.log.debug(`Sync for slot ${slot} failed, checking for voting opportunities`, {
|
|
1120
|
-
secondsIntoSlot,
|
|
1121
|
-
maxAllowedTime,
|
|
1032
|
+
this.log.trace(`Cannot build for slot ${slot}, checking for voting opportunities`, {
|
|
1033
|
+
nowSeconds,
|
|
1034
|
+
startDeadline,
|
|
1122
1035
|
});
|
|
1123
1036
|
|
|
1124
1037
|
// Check if we're a proposer or proposal is open
|
|
1125
|
-
const [canPropose, proposer] = await this.checkCanPropose(
|
|
1038
|
+
const [canPropose, proposer] = await this.checkCanPropose(targetSlot);
|
|
1126
1039
|
if (!canPropose) {
|
|
1127
|
-
this.log.
|
|
1040
|
+
this.log.trace(`Cannot vote in slot ${slot} since we are not a proposer`, { slot, proposer });
|
|
1128
1041
|
return;
|
|
1129
1042
|
}
|
|
1130
1043
|
|
|
1131
1044
|
// Mark this slot as attempted
|
|
1132
|
-
this.
|
|
1045
|
+
this.lastSlotForFallbackAction = slot;
|
|
1133
1046
|
|
|
1134
1047
|
// Get a publisher for voting
|
|
1135
1048
|
const { attestorAddress, publisher } = await this.publisherFactory.create(proposer);
|
|
@@ -1139,17 +1052,122 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
|
|
|
1139
1052
|
slot,
|
|
1140
1053
|
});
|
|
1141
1054
|
|
|
1142
|
-
// Enqueue governance and slashing votes
|
|
1143
|
-
const
|
|
1144
|
-
|
|
1055
|
+
// Enqueue governance and slashing votes (voter uses the target slot for L1 submission)
|
|
1056
|
+
const voter = new CheckpointVoter(
|
|
1057
|
+
targetSlot,
|
|
1058
|
+
publisher,
|
|
1059
|
+
attestorAddress,
|
|
1060
|
+
this.validatorClient,
|
|
1061
|
+
this.slasherClient,
|
|
1062
|
+
this.l1Constants,
|
|
1063
|
+
this.config,
|
|
1064
|
+
this.metrics,
|
|
1065
|
+
this.log,
|
|
1066
|
+
);
|
|
1067
|
+
const votesPromises = voter.enqueueVotes();
|
|
1068
|
+
const votes = await Promise.all(votesPromises);
|
|
1069
|
+
|
|
1070
|
+
// Even if we cannot build, try to prune so a stuck pending chain (e.g. bad data blocking sync) can
|
|
1071
|
+
// recover. prune() is permissionless, so it rides the same fallback multicall as the votes.
|
|
1072
|
+
const pruneEnqueued = await this.tryEnqueuePruneIfPrunable(targetSlot, publisher);
|
|
1145
1073
|
|
|
1146
|
-
if
|
|
1147
|
-
|
|
1074
|
+
// Bail if nothing to do
|
|
1075
|
+
if (votes.every(p => !p) && !pruneEnqueued) {
|
|
1076
|
+
this.log.debug(`Nothing to enqueue for slot ${slot} (no votes, not prunable)`);
|
|
1148
1077
|
return;
|
|
1149
1078
|
}
|
|
1150
1079
|
|
|
1151
|
-
|
|
1152
|
-
|
|
1080
|
+
const [governanceVoteEnqueued, slashingVoteEnqueued] = votes;
|
|
1081
|
+
this.log.info(`Submitting fallback requests in slot ${slot} despite sync failure`, {
|
|
1082
|
+
slot,
|
|
1083
|
+
pruneEnqueued,
|
|
1084
|
+
governanceVoteEnqueued: !!governanceVoteEnqueued,
|
|
1085
|
+
slashingVoteEnqueued: !!slashingVoteEnqueued,
|
|
1086
|
+
});
|
|
1087
|
+
|
|
1088
|
+
// Votes are EIP-712-signed for `targetSlot` (the pipelined slot in which the multicall is
|
|
1089
|
+
// expected to mine). Delay submission to the start of `targetSlot` so the tx mines in the
|
|
1090
|
+
// slot the votes were signed for. We fire-and-forget so we don't block the sequencer's
|
|
1091
|
+
// work loop while waiting for the target slot to start, but track it so stop() can drain it.
|
|
1092
|
+
const send = publisher.sendRequestsAt(targetSlot).catch(err => {
|
|
1093
|
+
this.log.error(`Failed to publish fallback requests despite sync failure for slot ${slot}`, err, { slot });
|
|
1094
|
+
});
|
|
1095
|
+
this.pendingRequests.trackRequest(send, () => publisher.interrupt());
|
|
1096
|
+
}
|
|
1097
|
+
|
|
1098
|
+
private async tryEnqueuePruneIfPrunable(targetSlot: SlotNumber, publisher: SequencerPublisher): Promise<boolean> {
|
|
1099
|
+
try {
|
|
1100
|
+
return await publisher.enqueuePruneIfPrunable(targetSlot);
|
|
1101
|
+
} catch (err) {
|
|
1102
|
+
this.log.error(`Failed to enqueue rollup prune for slot ${targetSlot}`, err, { targetSlot });
|
|
1103
|
+
return false;
|
|
1104
|
+
}
|
|
1105
|
+
}
|
|
1106
|
+
|
|
1107
|
+
/**
|
|
1108
|
+
* Tries to vote on slashing actions and governance proposals when escape hatch is open.
|
|
1109
|
+
* This allows the sequencer to participate in voting without performing checkpoint proposal work.
|
|
1110
|
+
*/
|
|
1111
|
+
@trackSpan('Sequencer.tryVoteWhenEscapeHatchOpen', ({ slot }) => ({ [Attributes.SLOT_NUMBER]: slot }))
|
|
1112
|
+
protected async tryVoteWhenEscapeHatchOpen(args: {
|
|
1113
|
+
slot: SlotNumber;
|
|
1114
|
+
targetSlot: SlotNumber;
|
|
1115
|
+
proposer: EthAddress | undefined;
|
|
1116
|
+
}): Promise<void> {
|
|
1117
|
+
const { slot, targetSlot, proposer } = args;
|
|
1118
|
+
|
|
1119
|
+
// Prevent duplicate attempts in the same slot
|
|
1120
|
+
if (this.lastSlotForFallbackAction === slot) {
|
|
1121
|
+
this.log.trace(`Already attempted to vote in slot ${slot} (escape hatch open, skipping)`);
|
|
1122
|
+
return;
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
// Mark this slot as attempted
|
|
1126
|
+
this.lastSlotForFallbackAction = slot;
|
|
1127
|
+
|
|
1128
|
+
const { attestorAddress, publisher } = await this.publisherFactory.create(proposer);
|
|
1129
|
+
|
|
1130
|
+
this.log.debug(`Escape hatch open for slot ${slot}, attempting vote-only actions`, {
|
|
1131
|
+
slot,
|
|
1132
|
+
targetSlot,
|
|
1133
|
+
attestorAddress,
|
|
1134
|
+
});
|
|
1135
|
+
|
|
1136
|
+
// Under proposer pipelining, the multicall is expected to mine in `targetSlot` (slot + 1).
|
|
1137
|
+
// Governance and slashing votes are EIP-712-signed against the slot they will mine in, and the
|
|
1138
|
+
// L1 contract checks `msg.sender == getCurrentProposer()` using the mining slot. So we must
|
|
1139
|
+
// sign for `targetSlot` and delay submission to the start of `targetSlot`.
|
|
1140
|
+
const voter = new CheckpointVoter(
|
|
1141
|
+
targetSlot,
|
|
1142
|
+
publisher,
|
|
1143
|
+
attestorAddress,
|
|
1144
|
+
this.validatorClient,
|
|
1145
|
+
this.slasherClient,
|
|
1146
|
+
this.l1Constants,
|
|
1147
|
+
this.config,
|
|
1148
|
+
this.metrics,
|
|
1149
|
+
this.log,
|
|
1150
|
+
);
|
|
1151
|
+
|
|
1152
|
+
const votesPromises = voter.enqueueVotes();
|
|
1153
|
+
const votes = await Promise.all(votesPromises);
|
|
1154
|
+
|
|
1155
|
+
if (votes.every(p => !p)) {
|
|
1156
|
+
this.log.debug(`No votes to enqueue for slot ${slot} (escape hatch open)`);
|
|
1157
|
+
return;
|
|
1158
|
+
}
|
|
1159
|
+
|
|
1160
|
+
this.log.info(`Voting in slot ${slot} (escape hatch open)`, { slot, targetSlot });
|
|
1161
|
+
// Votes are EIP-712-signed for `targetSlot`. Delay submission to the start of `targetSlot` so
|
|
1162
|
+
// the multicall mines in the slot the votes were signed for; otherwise the L1 contract reads
|
|
1163
|
+
// `signaler = getCurrentProposer()` against the wrong slot and signature verification fails
|
|
1164
|
+
// silently inside Multicall3. Fire-and-forget so we don't block the sequencer's work loop while
|
|
1165
|
+
// waiting for the target slot to start, mirroring tryVoteAndPruneWhenCannotBuild, but tracked so
|
|
1166
|
+
// stop() can drain it.
|
|
1167
|
+
const send = publisher.sendRequestsAt(targetSlot).catch(err => {
|
|
1168
|
+
this.log.error(`Failed to publish escape-hatch votes for slot ${slot}`, err, { slot, targetSlot });
|
|
1169
|
+
});
|
|
1170
|
+
this.pendingRequests.trackRequest(send, () => publisher.interrupt());
|
|
1153
1171
|
}
|
|
1154
1172
|
|
|
1155
1173
|
/**
|
|
@@ -1157,29 +1175,44 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
|
|
|
1157
1175
|
* has been there without being invalidated and whether the sequencer is in the committee or not. We always
|
|
1158
1176
|
* have the proposer try to invalidate, but if they fail, the sequencers in the committee are expected to try,
|
|
1159
1177
|
* and if they fail, any sequencer will try as well.
|
|
1178
|
+
* @param pendingChainValidationStatus - The archiver's pending-chain validation status, authoritative on its own.
|
|
1179
|
+
* @param currentSlot - The wall-clock slot, used for committee lookup, the per-(checkpoint, slot) dedup guard, and logging.
|
|
1160
1180
|
*/
|
|
1161
|
-
protected async
|
|
1162
|
-
|
|
1181
|
+
protected async considerInvalidatingCheckpoint(
|
|
1182
|
+
pendingChainValidationStatus: ValidateCheckpointResult,
|
|
1163
1183
|
currentSlot: SlotNumber,
|
|
1164
1184
|
): Promise<void> {
|
|
1165
|
-
const { pendingChainValidationStatus, l1Timestamp } = syncedTo;
|
|
1166
1185
|
if (pendingChainValidationStatus.valid) {
|
|
1167
1186
|
return;
|
|
1168
1187
|
}
|
|
1169
1188
|
|
|
1170
|
-
const
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1189
|
+
const invalidCheckpointNumber = pendingChainValidationStatus.checkpoint.checkpointNumber;
|
|
1190
|
+
|
|
1191
|
+
// Avoid re-running the committee lookup, simulation, and submission on every tick within a slot.
|
|
1192
|
+
// The guard is keyed by (checkpoint, slot) — so a different invalid checkpoint surfacing later in
|
|
1193
|
+
// the same slot is not suppressed — and is set only after a request is successfully simulated below,
|
|
1194
|
+
// so a transient simulation failure (or thresholds not yet met) still retries on the next tick.
|
|
1195
|
+
if (
|
|
1196
|
+
this.lastInvalidationAttempt?.slot === currentSlot &&
|
|
1197
|
+
this.lastInvalidationAttempt.checkpointNumber === invalidCheckpointNumber
|
|
1198
|
+
) {
|
|
1199
|
+
this.log.trace(`Already attempted to invalidate checkpoint ${invalidCheckpointNumber} in slot ${currentSlot}`, {
|
|
1200
|
+
currentSlot,
|
|
1201
|
+
invalidCheckpointNumber,
|
|
1202
|
+
});
|
|
1203
|
+
return;
|
|
1204
|
+
}
|
|
1205
|
+
|
|
1206
|
+
const invalidCheckpointTimestamp = pendingChainValidationStatus.checkpoint.timestamp;
|
|
1207
|
+
const timeSinceChainInvalid = this.dateProvider.nowInSeconds() - Number(invalidCheckpointTimestamp);
|
|
1208
|
+
const ourValidatorAddresses = this.validatorClient.getValidatorAddresses();
|
|
1175
1209
|
|
|
1176
1210
|
const { secondsBeforeInvalidatingBlockAsCommitteeMember, secondsBeforeInvalidatingBlockAsNonCommitteeMember } =
|
|
1177
1211
|
this.config;
|
|
1178
1212
|
|
|
1179
1213
|
const logData = {
|
|
1180
|
-
invalidL1Timestamp:
|
|
1181
|
-
|
|
1182
|
-
invalidBlock: pendingChainValidationStatus.block,
|
|
1214
|
+
invalidL1Timestamp: invalidCheckpointTimestamp,
|
|
1215
|
+
invalidCheckpoint: pendingChainValidationStatus.checkpoint,
|
|
1183
1216
|
secondsBeforeInvalidatingBlockAsCommitteeMember,
|
|
1184
1217
|
secondsBeforeInvalidatingBlockAsNonCommitteeMember,
|
|
1185
1218
|
ourValidatorAddresses,
|
|
@@ -1207,47 +1240,127 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
|
|
|
1207
1240
|
return;
|
|
1208
1241
|
}
|
|
1209
1242
|
|
|
1210
|
-
|
|
1211
|
-
if (
|
|
1212
|
-
|
|
1243
|
+
let validatorToUse: EthAddress;
|
|
1244
|
+
if (invalidateAsCommitteeMember) {
|
|
1245
|
+
// When invalidating as a committee member, use first validator that's actually in the committee
|
|
1246
|
+
const { committee } = await this.epochCache.getCommittee(currentSlot);
|
|
1247
|
+
if (committee) {
|
|
1248
|
+
const committeeSet = new Set(committee.map(addr => addr.toString()));
|
|
1249
|
+
validatorToUse =
|
|
1250
|
+
ourValidatorAddresses.find(addr => committeeSet.has(addr.toString())) ?? ourValidatorAddresses[0];
|
|
1251
|
+
} else {
|
|
1252
|
+
validatorToUse = ourValidatorAddresses[0];
|
|
1253
|
+
}
|
|
1254
|
+
} else {
|
|
1255
|
+
// When invalidating as a non-committee member, use the first validator
|
|
1256
|
+
validatorToUse = ourValidatorAddresses[0];
|
|
1257
|
+
}
|
|
1258
|
+
|
|
1259
|
+
const { publisher } = await this.publisherFactory.create(validatorToUse);
|
|
1260
|
+
|
|
1261
|
+
const invalidateCheckpoint = await publisher.simulateInvalidateCheckpoint(pendingChainValidationStatus);
|
|
1262
|
+
if (!invalidateCheckpoint) {
|
|
1263
|
+
this.log.warn(`Failed to simulate invalidate checkpoint`, logData);
|
|
1213
1264
|
return;
|
|
1214
1265
|
}
|
|
1215
1266
|
|
|
1267
|
+
// We produced a valid invalidation request; record it so further ticks within this slot skip the
|
|
1268
|
+
// committee lookup, simulation, and submission above for this same invalid checkpoint.
|
|
1269
|
+
this.lastInvalidationAttempt = { slot: currentSlot, checkpointNumber: invalidCheckpointNumber };
|
|
1270
|
+
|
|
1216
1271
|
this.log.info(
|
|
1217
1272
|
invalidateAsCommitteeMember
|
|
1218
|
-
? `Invalidating
|
|
1219
|
-
: `Invalidating
|
|
1273
|
+
? `Invalidating checkpoint ${invalidCheckpointNumber} as committee member`
|
|
1274
|
+
: `Invalidating checkpoint ${invalidCheckpointNumber} as non-committee member`,
|
|
1220
1275
|
logData,
|
|
1221
1276
|
);
|
|
1222
1277
|
|
|
1223
|
-
publisher.
|
|
1278
|
+
publisher.enqueueInvalidateCheckpoint(invalidateCheckpoint);
|
|
1224
1279
|
|
|
1225
1280
|
if (!this.config.fishermanMode) {
|
|
1226
1281
|
await publisher.sendRequests();
|
|
1227
1282
|
} else {
|
|
1228
|
-
this.log.info('Invalidating
|
|
1283
|
+
this.log.info('Invalidating checkpoint in fisherman mode, clearing pending requests');
|
|
1229
1284
|
publisher.clearPendingRequests();
|
|
1230
1285
|
}
|
|
1231
1286
|
}
|
|
1232
1287
|
|
|
1233
|
-
private
|
|
1234
|
-
|
|
1288
|
+
private logStrategyComparison(epoch: EpochNumber, publisher: SequencerPublisher): void {
|
|
1289
|
+
const feeAnalyzer = publisher.getL1FeeAnalyzer();
|
|
1290
|
+
if (!feeAnalyzer) {
|
|
1291
|
+
return;
|
|
1292
|
+
}
|
|
1293
|
+
|
|
1294
|
+
const comparison = feeAnalyzer.getStrategyComparison();
|
|
1295
|
+
if (comparison.length === 0) {
|
|
1296
|
+
this.log.debug(`No strategy data available yet for epoch ${epoch}`);
|
|
1297
|
+
return;
|
|
1298
|
+
}
|
|
1299
|
+
|
|
1300
|
+
this.log.info(`L1 Fee Strategy Performance Report - End of Epoch ${epoch}`, {
|
|
1301
|
+
epoch: Number(epoch),
|
|
1302
|
+
totalAnalyses: comparison[0]?.totalAnalyses,
|
|
1303
|
+
strategies: comparison.map(s => ({
|
|
1304
|
+
id: s.strategyId,
|
|
1305
|
+
name: s.strategyName,
|
|
1306
|
+
inclusionRate: `${(s.inclusionRate * 100).toFixed(1)}%`,
|
|
1307
|
+
inclusionCount: `${s.inclusionCount}/${s.totalAnalyses}`,
|
|
1308
|
+
avgCostEth: s.avgEstimatedCostEth.toFixed(6),
|
|
1309
|
+
totalCostEth: s.totalEstimatedCostEth.toFixed(6),
|
|
1310
|
+
avgOverpaymentEth: s.avgOverpaymentEth.toFixed(6),
|
|
1311
|
+
totalOverpaymentEth: s.totalOverpaymentEth.toFixed(6),
|
|
1312
|
+
avgPriorityFeeDeltaGwei: s.avgPriorityFeeDeltaGwei.toFixed(2),
|
|
1313
|
+
})),
|
|
1314
|
+
});
|
|
1235
1315
|
}
|
|
1236
1316
|
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1317
|
+
/**
|
|
1318
|
+
* Wall-clock seconds elapsed since the build-frame start of the given target slot
|
|
1319
|
+
* (`now − getBuildFrameStart(targetSlot)`). May be negative if called before the build frame opens.
|
|
1320
|
+
*/
|
|
1321
|
+
private getSecondsIntoBuildFrame(targetSlot: SlotNumber): number {
|
|
1322
|
+
const buildFrameStart = this.timetable.getBuildFrameStart(targetSlot);
|
|
1323
|
+
return Number((this.dateProvider.now() / 1000 - buildFrameStart).toFixed(3));
|
|
1240
1324
|
}
|
|
1241
1325
|
|
|
1242
|
-
get aztecSlotDuration() {
|
|
1326
|
+
public get aztecSlotDuration() {
|
|
1243
1327
|
return this.l1Constants.slotDuration;
|
|
1244
1328
|
}
|
|
1245
1329
|
|
|
1246
|
-
get maxL2BlockGas(): number | undefined {
|
|
1330
|
+
public get maxL2BlockGas(): number | undefined {
|
|
1247
1331
|
return this.config.maxL2BlockGas;
|
|
1248
1332
|
}
|
|
1249
1333
|
|
|
1250
1334
|
public getSlasherClient(): SlasherClientInterface | undefined {
|
|
1251
1335
|
return this.slasherClient;
|
|
1252
1336
|
}
|
|
1337
|
+
|
|
1338
|
+
public get tracer(): Tracer {
|
|
1339
|
+
return this.metrics.tracer;
|
|
1340
|
+
}
|
|
1341
|
+
|
|
1342
|
+
public getValidatorAddresses() {
|
|
1343
|
+
return this.validatorClient?.getValidatorAddresses();
|
|
1344
|
+
}
|
|
1345
|
+
|
|
1346
|
+
/** Updates the publisher factory's node keystore adapter after a keystore reload. */
|
|
1347
|
+
public updatePublisherNodeKeyStore(adapter: NodeKeystoreAdapter): void {
|
|
1348
|
+
this.publisherFactory.updateNodeKeyStore(adapter);
|
|
1349
|
+
}
|
|
1350
|
+
|
|
1351
|
+
public getConfig() {
|
|
1352
|
+
return this.config;
|
|
1353
|
+
}
|
|
1253
1354
|
}
|
|
1355
|
+
|
|
1356
|
+
type SequencerSyncCheckResult = {
|
|
1357
|
+
blockData?: BlockData;
|
|
1358
|
+
checkpointNumber: CheckpointNumber;
|
|
1359
|
+
checkpointedCheckpointNumber: CheckpointNumber;
|
|
1360
|
+
blockNumber: BlockNumber;
|
|
1361
|
+
archive: Fr;
|
|
1362
|
+
hasProposedCheckpoint: boolean;
|
|
1363
|
+
proposedCheckpointData?: ProposedCheckpointData;
|
|
1364
|
+
syncedL2Slot: SlotNumber;
|
|
1365
|
+
pendingChainValidationStatus: ValidateCheckpointResult;
|
|
1366
|
+
};
|