@aztec/sequencer-client 0.0.0-test.1 → 0.0.1-fake-ceab37513c
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dest/client/sequencer-client.d.ts +25 -25
- package/dest/client/sequencer-client.d.ts.map +1 -1
- package/dest/client/sequencer-client.js +65 -51
- package/dest/config.d.ts +6 -14
- package/dest/config.d.ts.map +1 -1
- package/dest/config.js +46 -54
- package/dest/global_variable_builder/global_builder.d.ts +11 -6
- package/dest/global_variable_builder/global_builder.d.ts.map +1 -1
- package/dest/global_variable_builder/global_builder.js +39 -34
- package/dest/index.d.ts +1 -2
- package/dest/index.d.ts.map +1 -1
- package/dest/index.js +1 -2
- package/dest/publisher/config.d.ts +6 -8
- package/dest/publisher/config.d.ts.map +1 -1
- package/dest/publisher/config.js +19 -17
- package/dest/publisher/index.d.ts +2 -0
- package/dest/publisher/index.d.ts.map +1 -1
- package/dest/publisher/index.js +3 -0
- package/dest/publisher/sequencer-publisher-factory.d.ts +42 -0
- package/dest/publisher/sequencer-publisher-factory.d.ts.map +1 -0
- package/dest/publisher/sequencer-publisher-factory.js +51 -0
- package/dest/publisher/sequencer-publisher-metrics.d.ts +1 -0
- package/dest/publisher/sequencer-publisher-metrics.d.ts.map +1 -1
- package/dest/publisher/sequencer-publisher-metrics.js +36 -1
- package/dest/publisher/sequencer-publisher.d.ts +101 -68
- package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
- package/dest/publisher/sequencer-publisher.js +603 -211
- package/dest/sequencer/block_builder.d.ts +27 -0
- package/dest/sequencer/block_builder.d.ts.map +1 -0
- package/dest/sequencer/block_builder.js +126 -0
- package/dest/sequencer/config.d.ts +5 -0
- package/dest/sequencer/config.d.ts.map +1 -1
- package/dest/sequencer/errors.d.ts +11 -0
- package/dest/sequencer/errors.d.ts.map +1 -0
- package/dest/sequencer/errors.js +15 -0
- package/dest/sequencer/index.d.ts +1 -1
- package/dest/sequencer/index.d.ts.map +1 -1
- package/dest/sequencer/index.js +1 -1
- package/dest/sequencer/metrics.d.ts +18 -11
- package/dest/sequencer/metrics.d.ts.map +1 -1
- package/dest/sequencer/metrics.js +84 -50
- package/dest/sequencer/sequencer.d.ts +118 -79
- package/dest/sequencer/sequencer.d.ts.map +1 -1
- package/dest/sequencer/sequencer.js +588 -359
- package/dest/sequencer/timetable.d.ts +32 -20
- package/dest/sequencer/timetable.d.ts.map +1 -1
- package/dest/sequencer/timetable.js +56 -29
- package/dest/sequencer/utils.d.ts +11 -35
- package/dest/sequencer/utils.d.ts.map +1 -1
- package/dest/sequencer/utils.js +9 -47
- package/dest/test/index.d.ts +7 -0
- package/dest/test/index.d.ts.map +1 -1
- package/dest/test/index.js +0 -4
- package/dest/tx_validator/nullifier_cache.d.ts +0 -2
- package/dest/tx_validator/nullifier_cache.d.ts.map +1 -1
- package/dest/tx_validator/tx_validator_factory.d.ts +9 -10
- package/dest/tx_validator/tx_validator_factory.d.ts.map +1 -1
- package/dest/tx_validator/tx_validator_factory.js +24 -24
- package/package.json +42 -43
- package/src/client/sequencer-client.ts +94 -84
- package/src/config.ts +53 -61
- package/src/global_variable_builder/global_builder.ts +44 -23
- package/src/index.ts +6 -2
- package/src/publisher/config.ts +26 -24
- package/src/publisher/index.ts +4 -0
- package/src/publisher/sequencer-publisher-factory.ts +89 -0
- package/src/publisher/sequencer-publisher-metrics.ts +23 -1
- package/src/publisher/sequencer-publisher.ts +725 -234
- package/src/sequencer/block_builder.ts +216 -0
- package/src/sequencer/config.ts +7 -0
- package/src/sequencer/errors.ts +21 -0
- package/src/sequencer/index.ts +1 -1
- package/src/sequencer/metrics.ts +109 -55
- package/src/sequencer/sequencer.ts +758 -414
- package/src/sequencer/timetable.ts +103 -32
- package/src/sequencer/utils.ts +17 -58
- package/src/test/index.ts +11 -4
- package/src/tx_validator/tx_validator_factory.ts +39 -32
- package/dest/sequencer/allowed.d.ts +0 -3
- package/dest/sequencer/allowed.d.ts.map +0 -1
- package/dest/sequencer/allowed.js +0 -27
- package/dest/slasher/factory.d.ts +0 -7
- package/dest/slasher/factory.d.ts.map +0 -1
- package/dest/slasher/factory.js +0 -8
- package/dest/slasher/index.d.ts +0 -3
- package/dest/slasher/index.d.ts.map +0 -1
- package/dest/slasher/index.js +0 -2
- package/dest/slasher/slasher_client.d.ts +0 -75
- package/dest/slasher/slasher_client.d.ts.map +0 -1
- package/dest/slasher/slasher_client.js +0 -132
- package/dest/tx_validator/archive_cache.d.ts +0 -14
- package/dest/tx_validator/archive_cache.d.ts.map +0 -1
- package/dest/tx_validator/archive_cache.js +0 -22
- package/dest/tx_validator/gas_validator.d.ts +0 -14
- package/dest/tx_validator/gas_validator.d.ts.map +0 -1
- package/dest/tx_validator/gas_validator.js +0 -78
- package/dest/tx_validator/phases_validator.d.ts +0 -12
- package/dest/tx_validator/phases_validator.d.ts.map +0 -1
- package/dest/tx_validator/phases_validator.js +0 -80
- package/dest/tx_validator/test_utils.d.ts +0 -23
- package/dest/tx_validator/test_utils.d.ts.map +0 -1
- package/dest/tx_validator/test_utils.js +0 -26
- package/src/sequencer/allowed.ts +0 -36
- package/src/slasher/factory.ts +0 -15
- package/src/slasher/index.ts +0 -2
- package/src/slasher/slasher_client.ts +0 -193
- package/src/tx_validator/archive_cache.ts +0 -28
- package/src/tx_validator/gas_validator.ts +0 -101
- package/src/tx_validator/phases_validator.ts +0 -98
- package/src/tx_validator/test_utils.ts +0 -48
|
@@ -1,55 +1,77 @@
|
|
|
1
1
|
import type { L2Block } from '@aztec/aztec.js';
|
|
2
|
-
import { INITIAL_L2_BLOCK_NUM } from '@aztec/constants';
|
|
3
|
-
import {
|
|
2
|
+
import { BLOBS_PER_BLOCK, FIELDS_PER_BLOB, INITIAL_L2_BLOCK_NUM } from '@aztec/constants';
|
|
3
|
+
import type { EpochCache } from '@aztec/epoch-cache';
|
|
4
|
+
import { FormattedViemError, NoCommitteeError, type RollupContract } from '@aztec/ethereum';
|
|
5
|
+
import { omit, pick } from '@aztec/foundation/collection';
|
|
6
|
+
import { randomInt } from '@aztec/foundation/crypto';
|
|
4
7
|
import { EthAddress } from '@aztec/foundation/eth-address';
|
|
5
|
-
import
|
|
8
|
+
import { Signature } from '@aztec/foundation/eth-signature';
|
|
6
9
|
import { Fr } from '@aztec/foundation/fields';
|
|
7
10
|
import { createLogger } from '@aztec/foundation/log';
|
|
8
11
|
import { RunningPromise } from '@aztec/foundation/running-promise';
|
|
9
|
-
import { type DateProvider, Timer
|
|
12
|
+
import { type DateProvider, Timer } from '@aztec/foundation/timer';
|
|
13
|
+
import { type TypedEventEmitter, unfreeze } from '@aztec/foundation/types';
|
|
10
14
|
import type { P2P } from '@aztec/p2p';
|
|
11
|
-
import type {
|
|
12
|
-
import
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
15
|
+
import type { SlasherClientInterface } from '@aztec/slasher';
|
|
16
|
+
import {
|
|
17
|
+
CommitteeAttestation,
|
|
18
|
+
CommitteeAttestationsAndSigners,
|
|
19
|
+
type L2BlockSource,
|
|
20
|
+
type ValidateBlockResult,
|
|
21
|
+
} from '@aztec/stdlib/block';
|
|
22
|
+
import { type L1RollupConstants, getSlotAtTimestamp, getSlotStartBuildTimestamp } from '@aztec/stdlib/epoch-helpers';
|
|
17
23
|
import { Gas } from '@aztec/stdlib/gas';
|
|
18
24
|
import {
|
|
19
|
-
type
|
|
25
|
+
type IFullNodeBlockBuilder,
|
|
26
|
+
type PublicProcessorLimits,
|
|
20
27
|
SequencerConfigSchema,
|
|
21
28
|
type WorldStateSynchronizer,
|
|
22
|
-
type WorldStateSynchronizerStatus,
|
|
23
29
|
} from '@aztec/stdlib/interfaces/server';
|
|
24
30
|
import type { L1ToL2MessageSource } from '@aztec/stdlib/messaging';
|
|
31
|
+
import { type BlockProposalOptions, orderAttestations } from '@aztec/stdlib/p2p';
|
|
25
32
|
import { pickFromSchema } from '@aztec/stdlib/schemas';
|
|
26
33
|
import type { L2BlockBuiltStats } from '@aztec/stdlib/stats';
|
|
27
|
-
import {
|
|
28
|
-
import {
|
|
29
|
-
|
|
30
|
-
ContentCommitment,
|
|
31
|
-
type GlobalVariables,
|
|
32
|
-
StateReference,
|
|
33
|
-
Tx,
|
|
34
|
-
type TxHash,
|
|
35
|
-
} from '@aztec/stdlib/tx';
|
|
34
|
+
import { MerkleTreeId } from '@aztec/stdlib/trees';
|
|
35
|
+
import { ContentCommitment, type FailedTx, GlobalVariables, ProposedBlockHeader, Tx } from '@aztec/stdlib/tx';
|
|
36
|
+
import { AttestationTimeoutError } from '@aztec/stdlib/validators';
|
|
36
37
|
import { Attributes, type TelemetryClient, type Tracer, getTelemetryClient, trackSpan } from '@aztec/telemetry-client';
|
|
37
38
|
import type { ValidatorClient } from '@aztec/validator-client';
|
|
38
39
|
|
|
40
|
+
import EventEmitter from 'node:events';
|
|
41
|
+
import type { TypedDataDefinition } from 'viem';
|
|
42
|
+
|
|
39
43
|
import type { GlobalVariableBuilder } from '../global_variable_builder/global_builder.js';
|
|
40
|
-
import
|
|
41
|
-
import type {
|
|
42
|
-
import { createValidatorsForBlockBuilding } from '../tx_validator/tx_validator_factory.js';
|
|
43
|
-
import { getDefaultAllowedSetupFunctions } from './allowed.js';
|
|
44
|
+
import type { SequencerPublisherFactory } from '../publisher/sequencer-publisher-factory.js';
|
|
45
|
+
import type { Action, InvalidateBlockRequest, SequencerPublisher } from '../publisher/sequencer-publisher.js';
|
|
44
46
|
import type { SequencerConfig } from './config.js';
|
|
47
|
+
import { SequencerInterruptedError, SequencerTooSlowError } from './errors.js';
|
|
45
48
|
import { SequencerMetrics } from './metrics.js';
|
|
46
|
-
import { SequencerTimetable
|
|
47
|
-
import { SequencerState,
|
|
49
|
+
import { SequencerTimetable } from './timetable.js';
|
|
50
|
+
import { SequencerState, type SequencerStateWithSlot } from './utils.js';
|
|
48
51
|
|
|
49
52
|
export { SequencerState };
|
|
50
53
|
|
|
51
54
|
type SequencerRollupConstants = Pick<L1RollupConstants, 'ethereumSlotDuration' | 'l1GenesisTime' | 'slotDuration'>;
|
|
52
55
|
|
|
56
|
+
export type SequencerEvents = {
|
|
57
|
+
['state-changed']: (args: {
|
|
58
|
+
oldState: SequencerState;
|
|
59
|
+
newState: SequencerState;
|
|
60
|
+
secondsIntoSlot?: number;
|
|
61
|
+
slotNumber?: bigint;
|
|
62
|
+
}) => void;
|
|
63
|
+
['proposer-rollup-check-failed']: (args: { reason: string }) => void;
|
|
64
|
+
['tx-count-check-failed']: (args: { minTxs: number; availableTxs: number }) => void;
|
|
65
|
+
['block-build-failed']: (args: { reason: string }) => void;
|
|
66
|
+
['block-publish-failed']: (args: {
|
|
67
|
+
successfulActions?: Action[];
|
|
68
|
+
failedActions?: Action[];
|
|
69
|
+
sentActions?: Action[];
|
|
70
|
+
expiredActions?: Action[];
|
|
71
|
+
}) => void;
|
|
72
|
+
['block-published']: (args: { blockNumber: number; slot: number }) => void;
|
|
73
|
+
};
|
|
74
|
+
|
|
53
75
|
/**
|
|
54
76
|
* Sequencer client
|
|
55
77
|
* - Wins a period of time to become the sequencer (depending on finalized protocol).
|
|
@@ -59,64 +81,81 @@ type SequencerRollupConstants = Pick<L1RollupConstants, 'ethereumSlotDuration' |
|
|
|
59
81
|
* - Receives results to those proofs from the network (repeats as necessary) (not for this milestone).
|
|
60
82
|
* - Publishes L1 tx(s) to the rollup contract via RollupPublisher.
|
|
61
83
|
*/
|
|
62
|
-
export class Sequencer {
|
|
84
|
+
export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<SequencerEvents>) {
|
|
63
85
|
private runningPromise?: RunningPromise;
|
|
64
86
|
private pollingIntervalMs: number = 1000;
|
|
65
87
|
private maxTxsPerBlock = 32;
|
|
66
88
|
private minTxsPerBlock = 1;
|
|
67
89
|
private maxL1TxInclusionTimeIntoSlot = 0;
|
|
68
|
-
// TODO: zero values should not be allowed for the following 2 values in PROD
|
|
69
|
-
private _coinbase = EthAddress.ZERO;
|
|
70
|
-
private _feeRecipient = AztecAddress.ZERO;
|
|
71
90
|
private state = SequencerState.STOPPED;
|
|
72
|
-
private allowedInSetup: AllowedElement[] = [];
|
|
73
91
|
private maxBlockSizeInBytes: number = 1024 * 1024;
|
|
74
92
|
private maxBlockGas: Gas = new Gas(100e9, 100e9);
|
|
75
93
|
private metrics: SequencerMetrics;
|
|
76
|
-
|
|
94
|
+
|
|
95
|
+
private lastBlockPublished: L2Block | undefined;
|
|
96
|
+
|
|
97
|
+
private governanceProposerPayload: EthAddress | undefined;
|
|
98
|
+
|
|
99
|
+
/** The last slot for which we attempted to vote when sync failed, to prevent duplicate attempts. */
|
|
100
|
+
private lastSlotForVoteWhenSyncFailed: bigint | undefined;
|
|
77
101
|
|
|
78
102
|
/** The maximum number of seconds that the sequencer can be into a slot to transition to a particular state. */
|
|
79
103
|
protected timetable!: SequencerTimetable;
|
|
80
|
-
|
|
81
104
|
protected enforceTimeTable: boolean = false;
|
|
82
105
|
|
|
106
|
+
// This shouldn't be here as this gets re-created each time we build/propose a block.
|
|
107
|
+
// But we have a number of tests that abuse/rely on this class having a permanent publisher.
|
|
108
|
+
// As long as those tests only configure a single publisher they will continue to work.
|
|
109
|
+
// This will get re-assigned every time the sequencer goes to build a new block to a publisher that is valid
|
|
110
|
+
// for the block proposer.
|
|
111
|
+
protected publisher: SequencerPublisher | undefined;
|
|
112
|
+
|
|
83
113
|
constructor(
|
|
84
|
-
protected
|
|
114
|
+
protected publisherFactory: SequencerPublisherFactory,
|
|
85
115
|
protected validatorClient: ValidatorClient | undefined, // During migration the validator client can be inactive
|
|
86
116
|
protected globalsBuilder: GlobalVariableBuilder,
|
|
87
117
|
protected p2pClient: P2P,
|
|
88
118
|
protected worldState: WorldStateSynchronizer,
|
|
89
|
-
protected slasherClient:
|
|
90
|
-
protected blockBuilderFactory: BlockBuilderFactory,
|
|
119
|
+
protected slasherClient: SlasherClientInterface | undefined,
|
|
91
120
|
protected l2BlockSource: L2BlockSource,
|
|
92
121
|
protected l1ToL2MessageSource: L1ToL2MessageSource,
|
|
93
|
-
protected
|
|
94
|
-
protected contractDataSource: ContractDataSource,
|
|
122
|
+
protected blockBuilder: IFullNodeBlockBuilder,
|
|
95
123
|
protected l1Constants: SequencerRollupConstants,
|
|
96
124
|
protected dateProvider: DateProvider,
|
|
97
|
-
protected
|
|
98
|
-
|
|
125
|
+
protected epochCache: EpochCache,
|
|
126
|
+
protected rollupContract: RollupContract,
|
|
127
|
+
protected config: SequencerConfig,
|
|
128
|
+
protected telemetry: TelemetryClient = getTelemetryClient(),
|
|
99
129
|
protected log = createLogger('sequencer'),
|
|
100
130
|
) {
|
|
101
|
-
|
|
131
|
+
super();
|
|
102
132
|
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
// Register the slasher on the publisher to fetch slashing payloads
|
|
107
|
-
this.publisher.registerSlashPayloadGetter(this.slasherClient.getSlashPayload.bind(this.slasherClient));
|
|
133
|
+
this.metrics = new SequencerMetrics(telemetry, this.rollupContract, 'Sequencer');
|
|
134
|
+
// Initialize config
|
|
135
|
+
this.updateConfig(this.config);
|
|
108
136
|
}
|
|
109
137
|
|
|
110
138
|
get tracer(): Tracer {
|
|
111
139
|
return this.metrics.tracer;
|
|
112
140
|
}
|
|
113
141
|
|
|
142
|
+
public getValidatorAddresses() {
|
|
143
|
+
return this.validatorClient?.getValidatorAddresses();
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
public getConfig() {
|
|
147
|
+
return this.config;
|
|
148
|
+
}
|
|
149
|
+
|
|
114
150
|
/**
|
|
115
|
-
* Updates sequencer config.
|
|
151
|
+
* Updates sequencer config by the defined values in the config on input.
|
|
116
152
|
* @param config - New parameters.
|
|
117
153
|
*/
|
|
118
|
-
public
|
|
119
|
-
this.log.info(
|
|
154
|
+
public updateConfig(config: SequencerConfig) {
|
|
155
|
+
this.log.info(
|
|
156
|
+
`Sequencer config set`,
|
|
157
|
+
omit(pickFromSchema(config, SequencerConfigSchema), 'txPublicSetupAllowList'),
|
|
158
|
+
);
|
|
120
159
|
|
|
121
160
|
if (config.transactionPollingIntervalMS !== undefined) {
|
|
122
161
|
this.pollingIntervalMs = config.transactionPollingIntervalMS;
|
|
@@ -133,22 +172,11 @@ export class Sequencer {
|
|
|
133
172
|
if (config.maxL2BlockGas !== undefined) {
|
|
134
173
|
this.maxBlockGas = new Gas(this.maxBlockGas.daGas, config.maxL2BlockGas);
|
|
135
174
|
}
|
|
136
|
-
if (config.coinbase) {
|
|
137
|
-
this._coinbase = config.coinbase;
|
|
138
|
-
}
|
|
139
|
-
if (config.feeRecipient) {
|
|
140
|
-
this._feeRecipient = config.feeRecipient;
|
|
141
|
-
}
|
|
142
|
-
if (config.allowedInSetup) {
|
|
143
|
-
this.allowedInSetup = config.allowedInSetup;
|
|
144
|
-
} else {
|
|
145
|
-
this.allowedInSetup = await getDefaultAllowedSetupFunctions();
|
|
146
|
-
}
|
|
147
175
|
if (config.maxBlockSizeInBytes !== undefined) {
|
|
148
176
|
this.maxBlockSizeInBytes = config.maxBlockSizeInBytes;
|
|
149
177
|
}
|
|
150
178
|
if (config.governanceProposerPayload) {
|
|
151
|
-
this.
|
|
179
|
+
this.governanceProposerPayload = config.governanceProposerPayload;
|
|
152
180
|
}
|
|
153
181
|
if (config.maxL1TxInclusionTimeIntoSlot !== undefined) {
|
|
154
182
|
this.maxL1TxInclusionTimeIntoSlot = config.maxL1TxInclusionTimeIntoSlot;
|
|
@@ -160,55 +188,51 @@ export class Sequencer {
|
|
|
160
188
|
this.setTimeTable();
|
|
161
189
|
|
|
162
190
|
// TODO: Just read everything from the config object as needed instead of copying everything into local vars.
|
|
163
|
-
|
|
191
|
+
|
|
192
|
+
// Update all values on this.config that are populated in the config object.
|
|
193
|
+
Object.assign(this.config, config);
|
|
164
194
|
}
|
|
165
195
|
|
|
166
196
|
private setTimeTable() {
|
|
167
197
|
this.timetable = new SequencerTimetable(
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
198
|
+
{
|
|
199
|
+
ethereumSlotDuration: this.l1Constants.ethereumSlotDuration,
|
|
200
|
+
aztecSlotDuration: this.aztecSlotDuration,
|
|
201
|
+
maxL1TxInclusionTimeIntoSlot: this.maxL1TxInclusionTimeIntoSlot,
|
|
202
|
+
attestationPropagationTime: this.config.attestationPropagationTime,
|
|
203
|
+
enforce: this.enforceTimeTable,
|
|
204
|
+
},
|
|
172
205
|
this.metrics,
|
|
173
206
|
this.log,
|
|
174
207
|
);
|
|
175
|
-
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
public async init() {
|
|
211
|
+
this.publisher = (await this.publisherFactory.create(undefined)).publisher;
|
|
176
212
|
}
|
|
177
213
|
|
|
178
214
|
/**
|
|
179
215
|
* Starts the sequencer and moves to IDLE state.
|
|
180
216
|
*/
|
|
181
|
-
public
|
|
182
|
-
|
|
183
|
-
this.
|
|
184
|
-
this.setState(SequencerState.IDLE, 0n, true /** force */);
|
|
217
|
+
public start() {
|
|
218
|
+
this.runningPromise = new RunningPromise(this.safeWork.bind(this), this.log, this.pollingIntervalMs);
|
|
219
|
+
this.setState(SequencerState.IDLE, undefined, { force: true });
|
|
185
220
|
this.runningPromise.start();
|
|
186
|
-
this.log.info(
|
|
221
|
+
this.log.info('Started sequencer');
|
|
187
222
|
}
|
|
188
223
|
|
|
189
224
|
/**
|
|
190
225
|
* Stops the sequencer from processing txs and moves to STOPPED state.
|
|
191
226
|
*/
|
|
192
227
|
public async stop(): Promise<void> {
|
|
193
|
-
this.log.
|
|
194
|
-
|
|
228
|
+
this.log.info(`Stopping sequencer`);
|
|
229
|
+
this.setState(SequencerState.STOPPING, undefined, { force: true });
|
|
230
|
+
this.publisher?.interrupt();
|
|
195
231
|
await this.runningPromise?.stop();
|
|
196
|
-
this.
|
|
197
|
-
this.publisher.interrupt();
|
|
198
|
-
this.setState(SequencerState.STOPPED, 0n, true /** force */);
|
|
232
|
+
this.setState(SequencerState.STOPPED, undefined, { force: true });
|
|
199
233
|
this.log.info('Stopped sequencer');
|
|
200
234
|
}
|
|
201
235
|
|
|
202
|
-
/**
|
|
203
|
-
* Starts a previously stopped sequencer.
|
|
204
|
-
*/
|
|
205
|
-
public restart() {
|
|
206
|
-
this.log.info('Restarting sequencer');
|
|
207
|
-
this.publisher.restart();
|
|
208
|
-
this.runningPromise!.start();
|
|
209
|
-
this.setState(SequencerState.IDLE, 0n, true /** force */);
|
|
210
|
-
}
|
|
211
|
-
|
|
212
236
|
/**
|
|
213
237
|
* Returns the current state of the sequencer.
|
|
214
238
|
* @returns An object with a state entry with one of SequencerState.
|
|
@@ -217,11 +241,6 @@ export class Sequencer {
|
|
|
217
241
|
return { state: this.state };
|
|
218
242
|
}
|
|
219
243
|
|
|
220
|
-
/** Forces the sequencer to bypass all time and tx count checks for the next block and build anyway. */
|
|
221
|
-
public flush() {
|
|
222
|
-
this.isFlushing = true;
|
|
223
|
-
}
|
|
224
|
-
|
|
225
244
|
/**
|
|
226
245
|
* @notice Performs most of the sequencer duties:
|
|
227
246
|
* - Checks if we are up to date
|
|
@@ -230,300 +249,304 @@ export class Sequencer {
|
|
|
230
249
|
* - Submit block
|
|
231
250
|
* - If our block for some reason is not included, revert the state
|
|
232
251
|
*/
|
|
233
|
-
protected async
|
|
234
|
-
this.setState(SequencerState.SYNCHRONIZING,
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
//
|
|
238
|
-
if (
|
|
252
|
+
protected async work() {
|
|
253
|
+
this.setState(SequencerState.SYNCHRONIZING, undefined);
|
|
254
|
+
const { slot, ts, now } = this.epochCache.getEpochAndSlotInNextL1Slot();
|
|
255
|
+
|
|
256
|
+
// Check we have not already published a block for this slot (cheapest check)
|
|
257
|
+
if (this.lastBlockPublished && this.lastBlockPublished.header.getSlot() >= slot) {
|
|
258
|
+
this.log.debug(
|
|
259
|
+
`Cannot propose block at next L2 slot ${slot} since that slot was taken by our own block ${this.lastBlockPublished.number}`,
|
|
260
|
+
);
|
|
239
261
|
return;
|
|
240
262
|
}
|
|
241
263
|
|
|
242
|
-
|
|
264
|
+
// Check all components are synced to latest as seen by the archiver (queries all subsystems)
|
|
265
|
+
const syncedTo = await this.checkSync({ ts, slot });
|
|
266
|
+
if (!syncedTo) {
|
|
267
|
+
await this.tryVoteWhenSyncFails({ slot, ts });
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
const chainTipArchive = syncedTo.archive;
|
|
272
|
+
const newBlockNumber = syncedTo.blockNumber + 1;
|
|
273
|
+
|
|
274
|
+
const syncLogData = {
|
|
275
|
+
now,
|
|
276
|
+
syncedToL1Ts: syncedTo.l1Timestamp,
|
|
277
|
+
syncedToL2Slot: getSlotAtTimestamp(syncedTo.l1Timestamp, this.l1Constants),
|
|
278
|
+
nextL2Slot: slot,
|
|
279
|
+
nextL2SlotTs: ts,
|
|
280
|
+
l1SlotDuration: this.l1Constants.ethereumSlotDuration,
|
|
281
|
+
newBlockNumber,
|
|
282
|
+
isPendingChainValid: pick(syncedTo.pendingChainValidationStatus, 'valid', 'reason', 'invalidIndex'),
|
|
283
|
+
};
|
|
284
|
+
|
|
285
|
+
// Check that we are a proposer for the next slot
|
|
286
|
+
this.setState(SequencerState.PROPOSER_CHECK, slot);
|
|
287
|
+
const [canPropose, proposer] = await this.checkCanPropose(slot);
|
|
288
|
+
|
|
289
|
+
// If we are not a proposer, check if we should invalidate a invalid block, and bail
|
|
290
|
+
if (!canPropose) {
|
|
291
|
+
await this.considerInvalidatingBlock(syncedTo, slot);
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
// Check that the slot is not taken by a block already (should never happen, since only us can propose for this slot)
|
|
296
|
+
if (syncedTo.block && syncedTo.block.header.getSlot() >= slot) {
|
|
297
|
+
this.log.warn(
|
|
298
|
+
`Cannot propose block at next L2 slot ${slot} since that slot was taken by block ${syncedTo.blockNumber}`,
|
|
299
|
+
{ ...syncLogData, block: syncedTo.block.header.toInspect() },
|
|
300
|
+
);
|
|
301
|
+
return;
|
|
302
|
+
}
|
|
243
303
|
|
|
244
|
-
|
|
304
|
+
// We now need to get ourselves a publisher.
|
|
305
|
+
// The returned attestor will be the one we provided if we provided one.
|
|
306
|
+
// Otherwise it will be a valid attestor for the returned publisher.
|
|
307
|
+
const { attestorAddress, publisher } = await this.publisherFactory.create(proposer);
|
|
308
|
+
this.log.verbose(`Created publisher at address ${publisher.getSenderAddress()} for attestor ${attestorAddress}`);
|
|
309
|
+
this.publisher = publisher;
|
|
245
310
|
|
|
246
|
-
|
|
247
|
-
const
|
|
311
|
+
const coinbase = this.validatorClient!.getCoinbaseForAttestor(attestorAddress);
|
|
312
|
+
const feeRecipient = this.validatorClient!.getFeeRecipientForAttestor(attestorAddress);
|
|
248
313
|
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
314
|
+
// Prepare invalidation request if the pending chain is invalid (returns undefined if no need)
|
|
315
|
+
const invalidateBlock = await publisher.simulateInvalidateBlock(syncedTo.pendingChainValidationStatus);
|
|
316
|
+
|
|
317
|
+
// Check with the rollup if we can indeed propose at the next L2 slot. This check should not fail
|
|
318
|
+
// if all the previous checks are good, but we do it just in case.
|
|
319
|
+
const canProposeCheck = await publisher.canProposeAtNextEthBlock(
|
|
320
|
+
chainTipArchive,
|
|
321
|
+
proposer ?? EthAddress.ZERO,
|
|
322
|
+
invalidateBlock,
|
|
323
|
+
);
|
|
324
|
+
|
|
325
|
+
if (canProposeCheck === undefined) {
|
|
326
|
+
this.log.warn(
|
|
327
|
+
`Cannot propose block ${newBlockNumber} at slot ${slot} due to failed rollup contract check`,
|
|
328
|
+
syncLogData,
|
|
329
|
+
);
|
|
330
|
+
this.emit('proposer-rollup-check-failed', { reason: 'Rollup contract check failed' });
|
|
331
|
+
return;
|
|
332
|
+
} else if (canProposeCheck.slot !== slot) {
|
|
333
|
+
this.log.warn(
|
|
334
|
+
`Cannot propose block due to slot mismatch with rollup contract (this can be caused by a clock out of sync). Expected slot ${slot} but got ${canProposeCheck.slot}.`,
|
|
335
|
+
{ ...syncLogData, rollup: canProposeCheck, newBlockNumber, expectedSlot: slot },
|
|
336
|
+
);
|
|
337
|
+
this.emit('proposer-rollup-check-failed', { reason: 'Slot mismatch' });
|
|
338
|
+
return;
|
|
339
|
+
} else if (canProposeCheck.blockNumber !== BigInt(newBlockNumber)) {
|
|
340
|
+
this.log.warn(
|
|
341
|
+
`Cannot propose block due to block mismatch with rollup contract (this can be caused by a pending archiver sync). Expected block ${newBlockNumber} but got ${canProposeCheck.blockNumber}.`,
|
|
342
|
+
{ ...syncLogData, rollup: canProposeCheck, newBlockNumber, expectedSlot: slot },
|
|
343
|
+
);
|
|
344
|
+
this.emit('proposer-rollup-check-failed', { reason: 'Block mismatch' });
|
|
252
345
|
return;
|
|
253
346
|
}
|
|
254
347
|
|
|
255
|
-
this.log.debug(`Can propose block ${newBlockNumber} at slot ${slot}
|
|
348
|
+
this.log.debug(`Can propose block ${newBlockNumber} at slot ${slot} as ${proposer}`, { ...syncLogData });
|
|
256
349
|
|
|
257
350
|
const newGlobalVariables = await this.globalsBuilder.buildGlobalVariables(
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
351
|
+
newBlockNumber,
|
|
352
|
+
coinbase,
|
|
353
|
+
feeRecipient,
|
|
261
354
|
slot,
|
|
262
355
|
);
|
|
263
356
|
|
|
264
|
-
|
|
357
|
+
// Enqueue governance and slashing votes (returns promises that will be awaited later)
|
|
358
|
+
const votesPromises = this.enqueueGovernanceAndSlashingVotes(
|
|
359
|
+
publisher,
|
|
360
|
+
attestorAddress,
|
|
265
361
|
slot,
|
|
266
|
-
newGlobalVariables.timestamp
|
|
267
|
-
VoteType.GOVERNANCE,
|
|
362
|
+
newGlobalVariables.timestamp,
|
|
268
363
|
);
|
|
269
|
-
|
|
364
|
+
|
|
365
|
+
// Enqueues block invalidation
|
|
366
|
+
if (invalidateBlock && !this.config.skipInvalidateBlockAsProposer) {
|
|
367
|
+
publisher.enqueueInvalidateBlock(invalidateBlock);
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
// Actual block building
|
|
371
|
+
this.setState(SequencerState.INITIALIZING_PROPOSAL, slot);
|
|
372
|
+
const block: L2Block | undefined = await this.tryBuildBlockAndEnqueuePublish(
|
|
270
373
|
slot,
|
|
271
|
-
|
|
272
|
-
|
|
374
|
+
proposer,
|
|
375
|
+
newBlockNumber,
|
|
376
|
+
publisher,
|
|
377
|
+
newGlobalVariables,
|
|
378
|
+
chainTipArchive,
|
|
379
|
+
invalidateBlock,
|
|
273
380
|
);
|
|
274
381
|
|
|
275
|
-
|
|
382
|
+
// Wait until the voting promises have resolved, so all requests are enqueued
|
|
383
|
+
await Promise.all(votesPromises);
|
|
384
|
+
|
|
385
|
+
// And send the tx to L1
|
|
386
|
+
const l1Response = await publisher.sendRequests();
|
|
387
|
+
const proposedBlock = l1Response?.successfulActions.find(a => a === 'propose');
|
|
388
|
+
if (proposedBlock) {
|
|
389
|
+
this.lastBlockPublished = block;
|
|
390
|
+
this.emit('block-published', { blockNumber: newBlockNumber, slot: Number(slot) });
|
|
391
|
+
await this.metrics.incFilledSlot(publisher.getSenderAddress().toString(), coinbase);
|
|
392
|
+
} else if (block) {
|
|
393
|
+
this.emit('block-publish-failed', l1Response ?? {});
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
this.setState(SequencerState.IDLE, undefined);
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/** Tries building a block proposal, and if successful, enqueues it for publishing. */
|
|
400
|
+
private async tryBuildBlockAndEnqueuePublish(
|
|
401
|
+
slot: bigint,
|
|
402
|
+
proposer: EthAddress | undefined,
|
|
403
|
+
newBlockNumber: number,
|
|
404
|
+
publisher: SequencerPublisher,
|
|
405
|
+
newGlobalVariables: GlobalVariables,
|
|
406
|
+
chainTipArchive: Fr,
|
|
407
|
+
invalidateBlock: InvalidateBlockRequest | undefined,
|
|
408
|
+
) {
|
|
409
|
+
this.metrics.incOpenSlot(slot, (proposer ?? EthAddress.ZERO).toString());
|
|
276
410
|
this.log.verbose(`Preparing proposal for block ${newBlockNumber} at slot ${slot}`, {
|
|
411
|
+
proposer,
|
|
412
|
+
publisher: publisher.getSenderAddress(),
|
|
413
|
+
globalVariables: newGlobalVariables.toInspect(),
|
|
277
414
|
chainTipArchive,
|
|
278
415
|
blockNumber: newBlockNumber,
|
|
279
416
|
slot,
|
|
280
417
|
});
|
|
281
418
|
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
419
|
+
const proposalHeader = ProposedBlockHeader.from({
|
|
420
|
+
...newGlobalVariables,
|
|
421
|
+
timestamp: newGlobalVariables.timestamp,
|
|
422
|
+
lastArchiveRoot: chainTipArchive,
|
|
423
|
+
contentCommitment: ContentCommitment.empty(),
|
|
424
|
+
totalManaUsed: Fr.ZERO,
|
|
425
|
+
});
|
|
426
|
+
|
|
427
|
+
let block: L2Block | undefined;
|
|
291
428
|
|
|
292
|
-
let finishedFlushing = false;
|
|
293
429
|
const pendingTxCount = await this.p2pClient.getPendingTxCount();
|
|
294
|
-
if (pendingTxCount >= this.minTxsPerBlock
|
|
430
|
+
if (pendingTxCount >= this.minTxsPerBlock) {
|
|
295
431
|
// We don't fetch exactly maxTxsPerBlock txs here because we may not need all of them if we hit a limit before,
|
|
296
432
|
// and also we may need to fetch more if we don't have enough valid txs.
|
|
297
433
|
const pendingTxs = this.p2pClient.iteratePendingTxs();
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
434
|
+
try {
|
|
435
|
+
block = await this.buildBlockAndEnqueuePublish(
|
|
436
|
+
pendingTxs,
|
|
437
|
+
proposalHeader,
|
|
438
|
+
newGlobalVariables,
|
|
439
|
+
proposer,
|
|
440
|
+
invalidateBlock,
|
|
441
|
+
publisher,
|
|
442
|
+
);
|
|
443
|
+
} catch (err: any) {
|
|
444
|
+
this.emit('block-build-failed', { reason: err.message });
|
|
445
|
+
if (err instanceof FormattedViemError) {
|
|
446
|
+
this.log.verbose(`Unable to build/enqueue block ${err.message}`);
|
|
447
|
+
} else {
|
|
448
|
+
this.log.error(`Error building/enqueuing block`, err, { blockNumber: newBlockNumber, slot });
|
|
449
|
+
}
|
|
450
|
+
}
|
|
303
451
|
} else {
|
|
304
|
-
this.log.
|
|
305
|
-
`Not enough txs to build block ${newBlockNumber} at slot ${slot}
|
|
452
|
+
this.log.verbose(
|
|
453
|
+
`Not enough txs to build block ${newBlockNumber} at slot ${slot} (got ${pendingTxCount} txs, need ${this.minTxsPerBlock})`,
|
|
454
|
+
{ chainTipArchive, blockNumber: newBlockNumber, slot },
|
|
306
455
|
);
|
|
456
|
+
this.emit('tx-count-check-failed', { minTxs: this.minTxsPerBlock, availableTxs: pendingTxCount });
|
|
307
457
|
}
|
|
308
|
-
|
|
309
|
-
await enqueueGovernanceVotePromise.catch(err => {
|
|
310
|
-
this.log.error(`Error enqueuing governance vote`, err, { blockNumber: newBlockNumber, slot });
|
|
311
|
-
});
|
|
312
|
-
await enqueueSlashingVotePromise.catch(err => {
|
|
313
|
-
this.log.error(`Error enqueuing slashing vote`, err, { blockNumber: newBlockNumber, slot });
|
|
314
|
-
});
|
|
315
|
-
|
|
316
|
-
await this.publisher.sendRequests();
|
|
317
|
-
|
|
318
|
-
if (finishedFlushing) {
|
|
319
|
-
this.isFlushing = false;
|
|
320
|
-
}
|
|
321
|
-
|
|
322
|
-
this.setState(SequencerState.IDLE, 0n);
|
|
458
|
+
return block;
|
|
323
459
|
}
|
|
324
460
|
|
|
325
461
|
@trackSpan('Sequencer.work')
|
|
326
|
-
protected async
|
|
462
|
+
protected async safeWork() {
|
|
327
463
|
try {
|
|
328
|
-
await this.
|
|
464
|
+
await this.work();
|
|
329
465
|
} catch (err) {
|
|
330
466
|
if (err instanceof SequencerTooSlowError) {
|
|
331
|
-
|
|
467
|
+
// Log as warn only if we had to abort halfway through the block proposal
|
|
468
|
+
const logLvl = [SequencerState.INITIALIZING_PROPOSAL, SequencerState.PROPOSER_CHECK].includes(err.proposedState)
|
|
469
|
+
? ('debug' as const)
|
|
470
|
+
: ('warn' as const);
|
|
471
|
+
this.log[logLvl](err.message, { now: this.dateProvider.nowInSeconds() });
|
|
332
472
|
} else {
|
|
333
473
|
// Re-throw other errors
|
|
334
474
|
throw err;
|
|
335
475
|
}
|
|
336
476
|
} finally {
|
|
337
|
-
this.setState(SequencerState.IDLE,
|
|
477
|
+
this.setState(SequencerState.IDLE, undefined);
|
|
338
478
|
}
|
|
339
479
|
}
|
|
340
480
|
|
|
341
|
-
public getForwarderAddress() {
|
|
342
|
-
return this.publisher.getForwarderAddress();
|
|
343
|
-
}
|
|
344
|
-
|
|
345
|
-
/**
|
|
346
|
-
* Checks if we can propose at the next block and returns the slot number if we can.
|
|
347
|
-
* @param tipArchive - The archive of the previous block.
|
|
348
|
-
* @param proposalBlockNumber - The block number of the proposal.
|
|
349
|
-
* @returns The slot number if we can propose at the next block, otherwise undefined.
|
|
350
|
-
*/
|
|
351
|
-
async slotForProposal(tipArchive: Buffer, proposalBlockNumber: bigint): Promise<bigint | undefined> {
|
|
352
|
-
const result = await this.publisher.canProposeAtNextEthBlock(tipArchive);
|
|
353
|
-
|
|
354
|
-
if (!result) {
|
|
355
|
-
return undefined;
|
|
356
|
-
}
|
|
357
|
-
|
|
358
|
-
const [slot, blockNumber] = result;
|
|
359
|
-
|
|
360
|
-
if (proposalBlockNumber !== blockNumber) {
|
|
361
|
-
const msg = `Sequencer block number mismatch. Expected ${proposalBlockNumber} but got ${blockNumber}.`;
|
|
362
|
-
this.log.warn(msg);
|
|
363
|
-
throw new Error(msg);
|
|
364
|
-
}
|
|
365
|
-
return slot;
|
|
366
|
-
}
|
|
367
|
-
|
|
368
481
|
/**
|
|
369
482
|
* Sets the sequencer state and checks if we have enough time left in the slot to transition to the new state.
|
|
370
483
|
* @param proposedState - The new state to transition to.
|
|
371
|
-
* @param
|
|
484
|
+
* @param slotNumber - The current slot number.
|
|
372
485
|
* @param force - Whether to force the transition even if the sequencer is stopped.
|
|
373
|
-
*
|
|
374
|
-
* @dev If the `currentSlotNumber` doesn't matter (e.g. transitioning to IDLE), pass in `0n`;
|
|
375
|
-
* it is only used to check if we have enough time left in the slot to transition to the new state.
|
|
376
486
|
*/
|
|
377
|
-
setState(proposedState:
|
|
378
|
-
|
|
487
|
+
setState(proposedState: SequencerStateWithSlot, slotNumber: bigint, opts?: { force?: boolean }): void;
|
|
488
|
+
setState(
|
|
489
|
+
proposedState: Exclude<SequencerState, SequencerStateWithSlot>,
|
|
490
|
+
slotNumber?: undefined,
|
|
491
|
+
opts?: { force?: boolean },
|
|
492
|
+
): void;
|
|
493
|
+
setState(proposedState: SequencerState, slotNumber: bigint | undefined, opts: { force?: boolean } = {}): void {
|
|
494
|
+
if (this.state === SequencerState.STOPPING && proposedState !== SequencerState.STOPPED && !opts.force) {
|
|
495
|
+
this.log.warn(`Cannot set sequencer to ${proposedState} as it is stopping.`);
|
|
496
|
+
throw new SequencerInterruptedError();
|
|
497
|
+
}
|
|
498
|
+
if (this.state === SequencerState.STOPPED && !opts.force) {
|
|
379
499
|
this.log.warn(`Cannot set sequencer from ${this.state} to ${proposedState} as it is stopped.`);
|
|
380
500
|
return;
|
|
381
501
|
}
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
/**
|
|
389
|
-
* Build a block
|
|
390
|
-
*
|
|
391
|
-
* Shared between the sequencer and the validator for re-execution
|
|
392
|
-
*
|
|
393
|
-
* @param pendingTxs - The pending transactions to construct the block from
|
|
394
|
-
* @param newGlobalVariables - The global variables for the new block
|
|
395
|
-
* @param historicalHeader - The historical header of the parent
|
|
396
|
-
* @param opts - Whether to just validate the block as a validator, as opposed to building it as a proposal
|
|
397
|
-
*/
|
|
398
|
-
protected async buildBlock(
|
|
399
|
-
pendingTxs: Iterable<Tx> | AsyncIterable<Tx>,
|
|
400
|
-
newGlobalVariables: GlobalVariables,
|
|
401
|
-
opts: { validateOnly?: boolean } = {},
|
|
402
|
-
) {
|
|
403
|
-
const blockNumber = newGlobalVariables.blockNumber.toNumber();
|
|
404
|
-
const slot = newGlobalVariables.slotNumber.toBigInt();
|
|
405
|
-
this.log.debug(`Requesting L1 to L2 messages from contract for block ${blockNumber}`);
|
|
406
|
-
const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(BigInt(blockNumber));
|
|
407
|
-
const msgCount = l1ToL2Messages.length;
|
|
502
|
+
let secondsIntoSlot = undefined;
|
|
503
|
+
if (slotNumber !== undefined) {
|
|
504
|
+
secondsIntoSlot = this.getSecondsIntoSlot(slotNumber);
|
|
505
|
+
this.timetable.assertTimeLeft(proposedState, secondsIntoSlot);
|
|
506
|
+
}
|
|
408
507
|
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
508
|
+
const boringStates = [SequencerState.IDLE, SequencerState.SYNCHRONIZING];
|
|
509
|
+
const logLevel =
|
|
510
|
+
boringStates.includes(proposedState) && boringStates.includes(this.state)
|
|
511
|
+
? ('trace' as const)
|
|
512
|
+
: ('debug' as const);
|
|
513
|
+
this.log[logLevel](`Transitioning from ${this.state} to ${proposedState}`, { slotNumber, secondsIntoSlot });
|
|
514
|
+
|
|
515
|
+
this.emit('state-changed', {
|
|
516
|
+
oldState: this.state,
|
|
517
|
+
newState: proposedState,
|
|
518
|
+
secondsIntoSlot,
|
|
519
|
+
slotNumber,
|
|
414
520
|
});
|
|
521
|
+
this.state = proposedState;
|
|
522
|
+
}
|
|
415
523
|
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
// NB: separating the dbs because both should update the state
|
|
421
|
-
const publicProcessorFork = await this.worldState.fork();
|
|
422
|
-
const orchestratorFork = await this.worldState.fork();
|
|
423
|
-
|
|
424
|
-
const previousBlockHeader =
|
|
425
|
-
(await this.l2BlockSource.getBlock(blockNumber - 1))?.header ?? orchestratorFork.getInitialHeader();
|
|
426
|
-
|
|
427
|
-
try {
|
|
428
|
-
const processor = this.publicProcessorFactory.create(publicProcessorFork, newGlobalVariables, true);
|
|
429
|
-
const blockBuildingTimer = new Timer();
|
|
430
|
-
const blockBuilder = this.blockBuilderFactory.create(orchestratorFork);
|
|
431
|
-
await blockBuilder.startNewBlock(newGlobalVariables, l1ToL2Messages, previousBlockHeader);
|
|
432
|
-
|
|
433
|
-
// Deadline for processing depends on whether we're proposing a block
|
|
434
|
-
const secondsIntoSlot = this.getSecondsIntoSlot(slot);
|
|
435
|
-
const processingEndTimeWithinSlot = opts.validateOnly
|
|
436
|
-
? this.timetable.getValidatorReexecTimeEnd(secondsIntoSlot)
|
|
437
|
-
: this.timetable.getBlockProposalExecTimeEnd(secondsIntoSlot);
|
|
438
|
-
|
|
439
|
-
// Deadline is only set if enforceTimeTable is enabled.
|
|
440
|
-
const deadline = this.enforceTimeTable
|
|
441
|
-
? new Date((this.getSlotStartTimestamp(slot) + processingEndTimeWithinSlot) * 1000)
|
|
442
|
-
: undefined;
|
|
443
|
-
|
|
444
|
-
this.log.verbose(`Processing pending txs`, {
|
|
445
|
-
slot,
|
|
446
|
-
slotStart: new Date(this.getSlotStartTimestamp(slot) * 1000),
|
|
447
|
-
now: new Date(this.dateProvider.now()),
|
|
448
|
-
deadline,
|
|
449
|
-
});
|
|
450
|
-
|
|
451
|
-
const validators = createValidatorsForBlockBuilding(
|
|
452
|
-
publicProcessorFork,
|
|
453
|
-
this.contractDataSource,
|
|
454
|
-
newGlobalVariables,
|
|
455
|
-
this.allowedInSetup,
|
|
456
|
-
);
|
|
457
|
-
|
|
458
|
-
// TODO(#11000): Public processor should just handle processing, one tx at a time. It should be responsibility
|
|
459
|
-
// of the sequencer to update world state and iterate over txs. We should refactor this along with unifying the
|
|
460
|
-
// publicProcessorFork and orchestratorFork, to avoid doing tree insertions twice when building the block.
|
|
461
|
-
const proposerLimits = {
|
|
462
|
-
maxTransactions: this.maxTxsPerBlock,
|
|
463
|
-
maxBlockSize: this.maxBlockSizeInBytes,
|
|
464
|
-
maxBlockGas: this.maxBlockGas,
|
|
465
|
-
};
|
|
466
|
-
const limits = opts.validateOnly ? { deadline } : { deadline, ...proposerLimits };
|
|
467
|
-
const [publicProcessorDuration, [processedTxs, failedTxs]] = await elapsed(() =>
|
|
468
|
-
processor.process(pendingTxs, limits, validators),
|
|
469
|
-
);
|
|
470
|
-
|
|
471
|
-
if (!opts.validateOnly && failedTxs.length > 0) {
|
|
472
|
-
const failedTxData = failedTxs.map(fail => fail.tx);
|
|
473
|
-
const failedTxHashes = await Tx.getHashes(failedTxData);
|
|
474
|
-
this.log.verbose(`Dropping failed txs ${failedTxHashes.join(', ')}`);
|
|
475
|
-
await this.p2pClient.deleteTxs(failedTxHashes);
|
|
476
|
-
}
|
|
477
|
-
|
|
478
|
-
if (
|
|
479
|
-
!opts.validateOnly && // We check for minTxCount only if we are proposing a block, not if we are validating it
|
|
480
|
-
!this.isFlushing && // And we skip the check when flushing, since we want all pending txs to go out, no matter if too few
|
|
481
|
-
this.minTxsPerBlock !== undefined &&
|
|
482
|
-
processedTxs.length < this.minTxsPerBlock
|
|
483
|
-
) {
|
|
484
|
-
this.log.warn(
|
|
485
|
-
`Block ${blockNumber} has too few txs to be proposed (got ${processedTxs.length} but required ${this.minTxsPerBlock})`,
|
|
486
|
-
{ slot, blockNumber, processedTxCount: processedTxs.length },
|
|
487
|
-
);
|
|
488
|
-
throw new Error(`Block has too few successful txs to be proposed`);
|
|
489
|
-
}
|
|
490
|
-
|
|
491
|
-
const start = process.hrtime.bigint();
|
|
492
|
-
await blockBuilder.addTxs(processedTxs);
|
|
493
|
-
const end = process.hrtime.bigint();
|
|
494
|
-
const duration = Number(end - start) / 1_000;
|
|
495
|
-
this.metrics.recordBlockBuilderTreeInsertions(duration);
|
|
496
|
-
|
|
497
|
-
// All real transactions have been added, set the block as full and pad if needed
|
|
498
|
-
const block = await blockBuilder.setBlockCompleted();
|
|
499
|
-
|
|
500
|
-
// How much public gas was processed
|
|
501
|
-
const publicGas = processedTxs.reduce((acc, tx) => acc.add(tx.gasUsed.publicGas), Gas.empty());
|
|
502
|
-
|
|
503
|
-
return {
|
|
504
|
-
block,
|
|
505
|
-
publicGas,
|
|
506
|
-
publicProcessorDuration,
|
|
507
|
-
numMsgs: l1ToL2Messages.length,
|
|
508
|
-
numTxs: processedTxs.length,
|
|
509
|
-
numFailedTxs: failedTxs.length,
|
|
510
|
-
blockBuildingTimer,
|
|
511
|
-
};
|
|
512
|
-
} finally {
|
|
513
|
-
// We create a fresh processor each time to reset any cached state (eg storage writes)
|
|
514
|
-
// We wait a bit to close the forks since the processor may still be working on a dangling tx
|
|
515
|
-
// which was interrupted due to the processingDeadline being hit.
|
|
516
|
-
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
|
517
|
-
setTimeout(async () => {
|
|
518
|
-
try {
|
|
519
|
-
await publicProcessorFork.close();
|
|
520
|
-
await orchestratorFork.close();
|
|
521
|
-
} catch (err) {
|
|
522
|
-
// This can happen if the sequencer is stopped before we hit this timeout.
|
|
523
|
-
this.log.warn(`Error closing forks for block processing`, err);
|
|
524
|
-
}
|
|
525
|
-
}, 5000);
|
|
524
|
+
private async dropFailedTxsFromP2P(failedTxs: FailedTx[]) {
|
|
525
|
+
if (failedTxs.length === 0) {
|
|
526
|
+
return;
|
|
526
527
|
}
|
|
528
|
+
const failedTxData = failedTxs.map(fail => fail.tx);
|
|
529
|
+
const failedTxHashes = failedTxData.map(tx => tx.getTxHash());
|
|
530
|
+
this.log.verbose(`Dropping failed txs ${failedTxHashes.join(', ')}`);
|
|
531
|
+
await this.p2pClient.deleteTxs(failedTxHashes);
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
protected getBlockBuilderOptions(slot: number): PublicProcessorLimits {
|
|
535
|
+
// Deadline for processing depends on whether we're proposing a block
|
|
536
|
+
const secondsIntoSlot = this.getSecondsIntoSlot(slot);
|
|
537
|
+
const processingEndTimeWithinSlot = this.timetable.getBlockProposalExecTimeEnd(secondsIntoSlot);
|
|
538
|
+
|
|
539
|
+
// Deadline is only set if enforceTimeTable is enabled.
|
|
540
|
+
const deadline = this.enforceTimeTable
|
|
541
|
+
? new Date((this.getSlotStartBuildTimestamp(slot) + processingEndTimeWithinSlot) * 1000)
|
|
542
|
+
: undefined;
|
|
543
|
+
return {
|
|
544
|
+
maxTransactions: this.maxTxsPerBlock,
|
|
545
|
+
maxBlockSize: this.maxBlockSizeInBytes,
|
|
546
|
+
maxBlockGas: this.maxBlockGas,
|
|
547
|
+
maxBlobFields: BLOBS_PER_BLOCK * FIELDS_PER_BLOB,
|
|
548
|
+
deadline,
|
|
549
|
+
};
|
|
527
550
|
}
|
|
528
551
|
|
|
529
552
|
/**
|
|
@@ -534,36 +557,58 @@ export class Sequencer {
|
|
|
534
557
|
*
|
|
535
558
|
* @param pendingTxs - Iterable of pending transactions to construct the block from
|
|
536
559
|
* @param proposalHeader - The partial header constructed for the proposal
|
|
560
|
+
* @param newGlobalVariables - The global variables for the new block
|
|
561
|
+
* @param proposerAddress - The address of the proposer
|
|
537
562
|
*/
|
|
538
|
-
@trackSpan('Sequencer.buildBlockAndEnqueuePublish', (_validTxs,
|
|
539
|
-
[Attributes.BLOCK_NUMBER]:
|
|
563
|
+
@trackSpan('Sequencer.buildBlockAndEnqueuePublish', (_validTxs, _proposalHeader, newGlobalVariables) => ({
|
|
564
|
+
[Attributes.BLOCK_NUMBER]: newGlobalVariables.blockNumber,
|
|
540
565
|
}))
|
|
541
566
|
private async buildBlockAndEnqueuePublish(
|
|
542
567
|
pendingTxs: Iterable<Tx> | AsyncIterable<Tx>,
|
|
543
|
-
proposalHeader:
|
|
544
|
-
|
|
545
|
-
|
|
568
|
+
proposalHeader: ProposedBlockHeader,
|
|
569
|
+
newGlobalVariables: GlobalVariables,
|
|
570
|
+
proposerAddress: EthAddress | undefined,
|
|
571
|
+
invalidateBlock: InvalidateBlockRequest | undefined,
|
|
572
|
+
publisher: SequencerPublisher,
|
|
573
|
+
): Promise<L2Block> {
|
|
574
|
+
await publisher.validateBlockHeader(proposalHeader, invalidateBlock);
|
|
546
575
|
|
|
547
|
-
const
|
|
548
|
-
const
|
|
549
|
-
const
|
|
576
|
+
const blockNumber = newGlobalVariables.blockNumber;
|
|
577
|
+
const slot = proposalHeader.slotNumber.toBigInt();
|
|
578
|
+
const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(blockNumber);
|
|
550
579
|
|
|
551
|
-
// this.metrics.recordNewBlock(blockNumber, validTxs.length);
|
|
552
580
|
const workTimer = new Timer();
|
|
553
581
|
this.setState(SequencerState.CREATING_BLOCK, slot);
|
|
554
582
|
|
|
555
583
|
try {
|
|
556
|
-
const
|
|
557
|
-
const
|
|
558
|
-
|
|
584
|
+
const blockBuilderOptions = this.getBlockBuilderOptions(Number(slot));
|
|
585
|
+
const buildBlockRes = await this.blockBuilder.buildBlock(
|
|
586
|
+
pendingTxs,
|
|
587
|
+
l1ToL2Messages,
|
|
588
|
+
newGlobalVariables,
|
|
589
|
+
blockBuilderOptions,
|
|
590
|
+
);
|
|
591
|
+
const { publicGas, block, publicProcessorDuration, numTxs, numMsgs, blockBuildingTimer, usedTxs, failedTxs } =
|
|
592
|
+
buildBlockRes;
|
|
593
|
+
const blockBuildDuration = workTimer.ms();
|
|
594
|
+
await this.dropFailedTxsFromP2P(failedTxs);
|
|
595
|
+
|
|
596
|
+
const minTxsPerBlock = this.minTxsPerBlock;
|
|
597
|
+
if (numTxs < minTxsPerBlock) {
|
|
598
|
+
this.log.warn(
|
|
599
|
+
`Block ${blockNumber} has too few txs to be proposed (got ${numTxs} but required ${minTxsPerBlock})`,
|
|
600
|
+
{ slot, blockNumber, numTxs },
|
|
601
|
+
);
|
|
602
|
+
throw new Error(`Block has too few successful txs to be proposed`);
|
|
603
|
+
}
|
|
559
604
|
|
|
560
605
|
// TODO(@PhilWindle) We should probably periodically check for things like another
|
|
561
606
|
// block being published before ours instead of just waiting on our block
|
|
562
|
-
await
|
|
607
|
+
await publisher.validateBlockHeader(block.header.toPropose(), invalidateBlock);
|
|
563
608
|
|
|
564
609
|
const blockStats: L2BlockBuiltStats = {
|
|
565
610
|
eventName: 'l2-block-built',
|
|
566
|
-
creator:
|
|
611
|
+
creator: proposerAddress?.toString() ?? publisher.getSenderAddress().toString(),
|
|
567
612
|
duration: workTimer.ms(),
|
|
568
613
|
publicProcessDuration: publicProcessorDuration,
|
|
569
614
|
rollupCircuitsDuration: blockBuildingTimer.ms(),
|
|
@@ -585,14 +630,25 @@ export class Sequencer {
|
|
|
585
630
|
);
|
|
586
631
|
|
|
587
632
|
this.log.debug('Collecting attestations');
|
|
588
|
-
const
|
|
589
|
-
const attestations = await this.collectAttestations(block, txHashes);
|
|
633
|
+
const attestations = await this.collectAttestations(block, usedTxs, proposerAddress);
|
|
590
634
|
if (attestations !== undefined) {
|
|
591
635
|
this.log.verbose(`Collected ${attestations.length} attestations`, { blockHash, blockNumber });
|
|
592
636
|
}
|
|
593
|
-
stopCollectingAttestationsTimer();
|
|
594
637
|
|
|
595
|
-
|
|
638
|
+
const attestationsAndSigners = new CommitteeAttestationsAndSigners(attestations ?? []);
|
|
639
|
+
const attestationsAndSignersSignature = this.validatorClient
|
|
640
|
+
? await this.validatorClient.signAttestationsAndSigners(attestationsAndSigners, proposerAddress)
|
|
641
|
+
: Signature.empty();
|
|
642
|
+
|
|
643
|
+
await this.enqueuePublishL2Block(
|
|
644
|
+
block,
|
|
645
|
+
attestationsAndSigners,
|
|
646
|
+
attestationsAndSignersSignature,
|
|
647
|
+
invalidateBlock,
|
|
648
|
+
publisher,
|
|
649
|
+
);
|
|
650
|
+
this.metrics.recordBuiltBlock(blockBuildDuration, publicGas.l2Gas);
|
|
651
|
+
return block;
|
|
596
652
|
} catch (err) {
|
|
597
653
|
this.metrics.recordFailedBlock();
|
|
598
654
|
throw err;
|
|
@@ -604,9 +660,17 @@ export class Sequencer {
|
|
|
604
660
|
[Attributes.BLOCK_ARCHIVE]: block.archive.toString(),
|
|
605
661
|
[Attributes.BLOCK_TXS_COUNT]: txHashes.length,
|
|
606
662
|
}))
|
|
607
|
-
protected async collectAttestations(
|
|
608
|
-
|
|
609
|
-
|
|
663
|
+
protected async collectAttestations(
|
|
664
|
+
block: L2Block,
|
|
665
|
+
txs: Tx[],
|
|
666
|
+
proposerAddress: EthAddress | undefined,
|
|
667
|
+
): Promise<CommitteeAttestation[] | undefined> {
|
|
668
|
+
const { committee } = await this.epochCache.getCommittee(block.header.getSlot());
|
|
669
|
+
|
|
670
|
+
// We checked above that the committee is defined, so this should never happen.
|
|
671
|
+
if (!committee) {
|
|
672
|
+
throw new Error('No committee when collecting attestations');
|
|
673
|
+
}
|
|
610
674
|
|
|
611
675
|
if (committee.length === 0) {
|
|
612
676
|
this.log.verbose(`Attesting committee is empty`);
|
|
@@ -622,31 +686,70 @@ export class Sequencer {
|
|
|
622
686
|
}
|
|
623
687
|
|
|
624
688
|
const numberOfRequiredAttestations = Math.floor((committee.length * 2) / 3) + 1;
|
|
689
|
+
|
|
625
690
|
const slotNumber = block.header.globalVariables.slotNumber.toBigInt();
|
|
626
691
|
this.setState(SequencerState.COLLECTING_ATTESTATIONS, slotNumber);
|
|
627
692
|
|
|
628
693
|
this.log.debug('Creating block proposal for validators');
|
|
629
|
-
const
|
|
694
|
+
const blockProposalOptions: BlockProposalOptions = { publishFullTxs: !!this.config.publishTxsWithProposals };
|
|
695
|
+
const proposal = await this.validatorClient.createBlockProposal(
|
|
696
|
+
block.header.globalVariables.blockNumber,
|
|
697
|
+
block.header.toPropose(),
|
|
698
|
+
block.archive.root,
|
|
699
|
+
block.header.state,
|
|
700
|
+
txs,
|
|
701
|
+
proposerAddress,
|
|
702
|
+
blockProposalOptions,
|
|
703
|
+
);
|
|
704
|
+
|
|
630
705
|
if (!proposal) {
|
|
631
|
-
|
|
632
|
-
|
|
706
|
+
throw new Error(`Failed to create block proposal`);
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
if (this.config.skipCollectingAttestations) {
|
|
710
|
+
this.log.warn('Skipping attestation collection as per config (attesting with own keys only)');
|
|
711
|
+
const attestations = await this.validatorClient?.collectOwnAttestations(proposal);
|
|
712
|
+
return orderAttestations(attestations ?? [], committee);
|
|
633
713
|
}
|
|
634
714
|
|
|
635
715
|
this.log.debug('Broadcasting block proposal to validators');
|
|
636
|
-
this.validatorClient.broadcastBlockProposal(proposal);
|
|
716
|
+
await this.validatorClient.broadcastBlockProposal(proposal);
|
|
637
717
|
|
|
638
718
|
const attestationTimeAllowed = this.enforceTimeTable
|
|
639
719
|
? this.timetable.getMaxAllowedTime(SequencerState.PUBLISHING_BLOCK)!
|
|
640
720
|
: this.aztecSlotDuration;
|
|
641
|
-
const attestationDeadline = new Date(this.dateProvider.now() + attestationTimeAllowed * 1000);
|
|
642
|
-
const attestations = await this.validatorClient.collectAttestations(
|
|
643
|
-
proposal,
|
|
644
|
-
numberOfRequiredAttestations,
|
|
645
|
-
attestationDeadline,
|
|
646
|
-
);
|
|
647
721
|
|
|
648
|
-
|
|
649
|
-
|
|
722
|
+
this.metrics.recordRequiredAttestations(numberOfRequiredAttestations, attestationTimeAllowed);
|
|
723
|
+
|
|
724
|
+
const timer = new Timer();
|
|
725
|
+
let collectedAttestationsCount: number = 0;
|
|
726
|
+
try {
|
|
727
|
+
const attestationDeadline = new Date(this.dateProvider.now() + attestationTimeAllowed * 1000);
|
|
728
|
+
const attestations = await this.validatorClient.collectAttestations(
|
|
729
|
+
proposal,
|
|
730
|
+
numberOfRequiredAttestations,
|
|
731
|
+
attestationDeadline,
|
|
732
|
+
);
|
|
733
|
+
|
|
734
|
+
collectedAttestationsCount = attestations.length;
|
|
735
|
+
|
|
736
|
+
// note: the smart contract requires that the signatures are provided in the order of the committee
|
|
737
|
+
const sorted = orderAttestations(attestations, committee);
|
|
738
|
+
if (this.config.injectFakeAttestation) {
|
|
739
|
+
const nonEmpty = sorted.filter(a => !a.signature.isEmpty());
|
|
740
|
+
const randomIndex = randomInt(nonEmpty.length);
|
|
741
|
+
this.log.warn(`Injecting fake attestation in block ${block.number}`);
|
|
742
|
+
unfreeze(nonEmpty[randomIndex]).signature = Signature.random();
|
|
743
|
+
}
|
|
744
|
+
return sorted;
|
|
745
|
+
} catch (err) {
|
|
746
|
+
if (err && err instanceof AttestationTimeoutError) {
|
|
747
|
+
collectedAttestationsCount = err.collectedCount;
|
|
748
|
+
}
|
|
749
|
+
throw err;
|
|
750
|
+
} finally {
|
|
751
|
+
this.metrics.recordCollectedAttestations(collectedAttestationsCount, timer.ms());
|
|
752
|
+
}
|
|
650
753
|
}
|
|
651
754
|
|
|
652
755
|
/**
|
|
@@ -658,19 +761,27 @@ export class Sequencer {
|
|
|
658
761
|
}))
|
|
659
762
|
protected async enqueuePublishL2Block(
|
|
660
763
|
block: L2Block,
|
|
661
|
-
|
|
662
|
-
|
|
764
|
+
attestationsAndSigners: CommitteeAttestationsAndSigners,
|
|
765
|
+
attestationsAndSignersSignature: Signature,
|
|
766
|
+
invalidateBlock: InvalidateBlockRequest | undefined,
|
|
767
|
+
publisher: SequencerPublisher,
|
|
663
768
|
): Promise<void> {
|
|
664
769
|
// Publishes new block to the network and awaits the tx to be mined
|
|
665
770
|
this.setState(SequencerState.PUBLISHING_BLOCK, block.header.globalVariables.slotNumber.toBigInt());
|
|
666
771
|
|
|
667
772
|
// Time out tx at the end of the slot
|
|
668
773
|
const slot = block.header.globalVariables.slotNumber.toNumber();
|
|
669
|
-
const txTimeoutAt = new Date((this.
|
|
670
|
-
|
|
671
|
-
const enqueued = await
|
|
672
|
-
|
|
673
|
-
|
|
774
|
+
const txTimeoutAt = new Date((this.getSlotStartBuildTimestamp(slot) + this.aztecSlotDuration) * 1000);
|
|
775
|
+
|
|
776
|
+
const enqueued = await publisher.enqueueProposeL2Block(
|
|
777
|
+
block,
|
|
778
|
+
attestationsAndSigners,
|
|
779
|
+
attestationsAndSignersSignature,
|
|
780
|
+
{
|
|
781
|
+
txTimeoutAt,
|
|
782
|
+
forcePendingBlockNumber: invalidateBlock?.forcePendingBlockNumber,
|
|
783
|
+
},
|
|
784
|
+
);
|
|
674
785
|
|
|
675
786
|
if (!enqueued) {
|
|
676
787
|
throw new Error(`Failed to enqueue publish of block ${block.number}`);
|
|
@@ -680,68 +791,301 @@ export class Sequencer {
|
|
|
680
791
|
/**
|
|
681
792
|
* Returns whether all dependencies have caught up.
|
|
682
793
|
* We don't check against the previous block submitted since it may have been reorg'd out.
|
|
683
|
-
* @returns Boolean indicating if our dependencies are synced to the latest block.
|
|
684
794
|
*/
|
|
685
|
-
protected async
|
|
795
|
+
protected async checkSync(args: { ts: bigint; slot: bigint }): Promise<
|
|
796
|
+
| {
|
|
797
|
+
block?: L2Block;
|
|
798
|
+
blockNumber: number;
|
|
799
|
+
archive: Fr;
|
|
800
|
+
l1Timestamp: bigint;
|
|
801
|
+
pendingChainValidationStatus: ValidateBlockResult;
|
|
802
|
+
}
|
|
803
|
+
| undefined
|
|
804
|
+
> {
|
|
805
|
+
// Check that the archiver and dependencies have synced to the previous L1 slot at least
|
|
806
|
+
// TODO(#14766): Archiver reports L1 timestamp based on L1 blocks seen, which means that a missed L1 block will
|
|
807
|
+
// cause the archiver L1 timestamp to fall behind, and cause this sequencer to start processing one L1 slot later.
|
|
808
|
+
const l1Timestamp = await this.l2BlockSource.getL1Timestamp();
|
|
809
|
+
const { slot, ts } = args;
|
|
810
|
+
if (l1Timestamp === undefined || l1Timestamp + BigInt(this.l1Constants.ethereumSlotDuration) < ts) {
|
|
811
|
+
this.log.debug(`Cannot propose block at next L2 slot ${slot} due to pending sync from L1`, {
|
|
812
|
+
slot,
|
|
813
|
+
ts,
|
|
814
|
+
l1Timestamp,
|
|
815
|
+
});
|
|
816
|
+
return undefined;
|
|
817
|
+
}
|
|
818
|
+
|
|
686
819
|
const syncedBlocks = await Promise.all([
|
|
687
|
-
this.worldState.status().then((
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
};
|
|
692
|
-
}),
|
|
820
|
+
this.worldState.status().then(({ syncSummary }) => ({
|
|
821
|
+
number: syncSummary.latestBlockNumber,
|
|
822
|
+
hash: syncSummary.latestBlockHash,
|
|
823
|
+
})),
|
|
693
824
|
this.l2BlockSource.getL2Tips().then(t => t.latest),
|
|
694
825
|
this.p2pClient.getStatus().then(p2p => p2p.syncedToL2Block),
|
|
695
|
-
this.l1ToL2MessageSource.
|
|
826
|
+
this.l1ToL2MessageSource.getL2Tips().then(t => t.latest),
|
|
827
|
+
this.l2BlockSource.getPendingChainValidationStatus(),
|
|
696
828
|
] as const);
|
|
697
829
|
|
|
698
|
-
const [worldState, l2BlockSource, p2p, l1ToL2MessageSource] = syncedBlocks;
|
|
830
|
+
const [worldState, l2BlockSource, p2p, l1ToL2MessageSource, pendingChainValidationStatus] = syncedBlocks;
|
|
699
831
|
|
|
832
|
+
// The archiver reports 'undefined' hash for the genesis block
|
|
833
|
+
// because it doesn't have access to world state to compute it (facepalm)
|
|
700
834
|
const result =
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
// this should change to hashes once p2p client handles reorgs
|
|
707
|
-
// and once we stop pretending that the l1tol2message source is not
|
|
708
|
-
// just the archiver under a different name
|
|
709
|
-
(!l2BlockSource.hash || p2p.hash === l2BlockSource.hash) &&
|
|
710
|
-
l1ToL2MessageSource === l2BlockSource.number;
|
|
711
|
-
|
|
712
|
-
this.log.debug(`Sequencer sync check ${result ? 'succeeded' : 'failed'}`, {
|
|
713
|
-
worldStateNumber: worldState.number,
|
|
714
|
-
worldStateHash: worldState.hash,
|
|
715
|
-
l2BlockSourceNumber: l2BlockSource.number,
|
|
716
|
-
l2BlockSourceHash: l2BlockSource.hash,
|
|
717
|
-
p2pNumber: p2p.number,
|
|
718
|
-
p2pHash: p2p.hash,
|
|
719
|
-
l1ToL2MessageSourceNumber: l1ToL2MessageSource,
|
|
720
|
-
});
|
|
835
|
+
l2BlockSource.hash === undefined
|
|
836
|
+
? worldState.number === 0 && p2p.number === 0 && l1ToL2MessageSource.number === 0
|
|
837
|
+
: worldState.hash === l2BlockSource.hash &&
|
|
838
|
+
p2p.hash === l2BlockSource.hash &&
|
|
839
|
+
l1ToL2MessageSource.hash === l2BlockSource.hash;
|
|
721
840
|
|
|
722
841
|
if (!result) {
|
|
842
|
+
this.log.debug(`Sequencer sync check failed`, { worldState, l2BlockSource, p2p, l1ToL2MessageSource });
|
|
723
843
|
return undefined;
|
|
724
844
|
}
|
|
725
|
-
if (worldState.number >= INITIAL_L2_BLOCK_NUM) {
|
|
726
|
-
const block = await this.l2BlockSource.getBlock(worldState.number);
|
|
727
|
-
if (!block) {
|
|
728
|
-
// this shouldn't really happen because a moment ago we checked that all components were in synch
|
|
729
|
-
return undefined;
|
|
730
|
-
}
|
|
731
845
|
|
|
732
|
-
|
|
733
|
-
|
|
846
|
+
// Special case for genesis state
|
|
847
|
+
const blockNumber = worldState.number;
|
|
848
|
+
if (blockNumber < INITIAL_L2_BLOCK_NUM) {
|
|
734
849
|
const archive = new Fr((await this.worldState.getCommitted().getTreeInfo(MerkleTreeId.ARCHIVE)).root);
|
|
735
|
-
return { blockNumber: INITIAL_L2_BLOCK_NUM - 1, archive };
|
|
850
|
+
return { blockNumber: INITIAL_L2_BLOCK_NUM - 1, archive, l1Timestamp, pendingChainValidationStatus };
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
const block = await this.l2BlockSource.getBlock(blockNumber);
|
|
854
|
+
if (!block) {
|
|
855
|
+
// this shouldn't really happen because a moment ago we checked that all components were in sync
|
|
856
|
+
this.log.error(`Failed to get L2 block ${blockNumber} from the archiver with all components in sync`);
|
|
857
|
+
return undefined;
|
|
736
858
|
}
|
|
859
|
+
|
|
860
|
+
return {
|
|
861
|
+
block,
|
|
862
|
+
blockNumber: block.number,
|
|
863
|
+
archive: block.archive.root,
|
|
864
|
+
l1Timestamp,
|
|
865
|
+
pendingChainValidationStatus,
|
|
866
|
+
};
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
/**
|
|
870
|
+
* Enqueues governance and slashing votes with the publisher. Does not block.
|
|
871
|
+
* @param publisher - The publisher to enqueue votes with
|
|
872
|
+
* @param attestorAddress - The attestor address to use for signing
|
|
873
|
+
* @param slot - The slot number
|
|
874
|
+
* @param timestamp - The timestamp for the votes
|
|
875
|
+
* @param context - Optional context for logging (e.g., block number)
|
|
876
|
+
* @returns A tuple of [governanceEnqueued, slashingEnqueued]
|
|
877
|
+
*/
|
|
878
|
+
protected enqueueGovernanceAndSlashingVotes(
|
|
879
|
+
publisher: SequencerPublisher,
|
|
880
|
+
attestorAddress: EthAddress,
|
|
881
|
+
slot: bigint,
|
|
882
|
+
timestamp: bigint,
|
|
883
|
+
): [Promise<boolean> | undefined, Promise<boolean> | undefined] {
|
|
884
|
+
try {
|
|
885
|
+
const signerFn = (msg: TypedDataDefinition) =>
|
|
886
|
+
this.validatorClient!.signWithAddress(attestorAddress, msg).then(s => s.toString());
|
|
887
|
+
|
|
888
|
+
const enqueueGovernancePromise =
|
|
889
|
+
this.governanceProposerPayload && !this.governanceProposerPayload.isZero()
|
|
890
|
+
? publisher
|
|
891
|
+
.enqueueGovernanceCastSignal(this.governanceProposerPayload, slot, timestamp, attestorAddress, signerFn)
|
|
892
|
+
.catch(err => {
|
|
893
|
+
this.log.error(`Error enqueuing governance vote`, err, { slot });
|
|
894
|
+
return false;
|
|
895
|
+
})
|
|
896
|
+
: undefined;
|
|
897
|
+
|
|
898
|
+
const enqueueSlashingPromise = this.slasherClient
|
|
899
|
+
? this.slasherClient
|
|
900
|
+
.getProposerActions(slot)
|
|
901
|
+
.then(actions => publisher.enqueueSlashingActions(actions, slot, timestamp, attestorAddress, signerFn))
|
|
902
|
+
.catch(err => {
|
|
903
|
+
this.log.error(`Error enqueuing slashing actions`, err, { slot });
|
|
904
|
+
return false;
|
|
905
|
+
})
|
|
906
|
+
: undefined;
|
|
907
|
+
|
|
908
|
+
return [enqueueGovernancePromise, enqueueSlashingPromise];
|
|
909
|
+
} catch (err) {
|
|
910
|
+
this.log.error(`Error enqueueing governance and slashing votes`, err);
|
|
911
|
+
return [undefined, undefined];
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
/**
|
|
916
|
+
* Checks if we are the proposer for the next slot.
|
|
917
|
+
* @returns True if we can propose, and the proposer address (undefined if anyone can propose)
|
|
918
|
+
*/
|
|
919
|
+
protected async checkCanPropose(slot: bigint): Promise<[boolean, EthAddress | undefined]> {
|
|
920
|
+
let proposer: EthAddress | undefined;
|
|
921
|
+
try {
|
|
922
|
+
proposer = await this.epochCache.getProposerAttesterAddressInSlot(slot);
|
|
923
|
+
} catch (e) {
|
|
924
|
+
if (e instanceof NoCommitteeError) {
|
|
925
|
+
this.log.warn(`Cannot propose at next L2 slot ${slot} since the committee does not exist on L1`);
|
|
926
|
+
return [false, undefined];
|
|
927
|
+
}
|
|
928
|
+
this.log.error(`Error getting proposer for slot ${slot}`, e);
|
|
929
|
+
return [false, undefined];
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
// If proposer is undefined, then the committee is empty and anyone may propose
|
|
933
|
+
if (proposer === undefined) {
|
|
934
|
+
return [true, undefined];
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
const validatorAddresses = this.validatorClient!.getValidatorAddresses();
|
|
938
|
+
const weAreProposer = validatorAddresses.some(addr => addr.equals(proposer));
|
|
939
|
+
|
|
940
|
+
if (!weAreProposer) {
|
|
941
|
+
this.log.debug(`Cannot propose at slot ${slot} since we are not a proposer`, { validatorAddresses, proposer });
|
|
942
|
+
return [false, proposer];
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
return [true, proposer];
|
|
946
|
+
}
|
|
947
|
+
|
|
948
|
+
/**
|
|
949
|
+
* Tries to vote on slashing actions and governance when the sync check fails but we're past the max time for initializing a proposal.
|
|
950
|
+
* This allows the sequencer to participate in governance/slashing votes even when it cannot build blocks.
|
|
951
|
+
*/
|
|
952
|
+
protected async tryVoteWhenSyncFails(args: { slot: bigint; ts: bigint }): Promise<void> {
|
|
953
|
+
const { slot, ts } = args;
|
|
954
|
+
|
|
955
|
+
// Prevent duplicate attempts in the same slot
|
|
956
|
+
if (this.lastSlotForVoteWhenSyncFailed === slot) {
|
|
957
|
+
this.log.debug(`Already attempted to vote in slot ${slot} (skipping)`);
|
|
958
|
+
return;
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
// Check if we're past the max time for initializing a proposal
|
|
962
|
+
const secondsIntoSlot = this.getSecondsIntoSlot(slot);
|
|
963
|
+
const maxAllowedTime = this.timetable.getMaxAllowedTime(SequencerState.INITIALIZING_PROPOSAL);
|
|
964
|
+
|
|
965
|
+
// If we haven't exceeded the time limit for initializing a proposal, don't proceed with voting
|
|
966
|
+
// We use INITIALIZING_PROPOSAL time limit because if we're past that, we can't build a block anyway
|
|
967
|
+
if (maxAllowedTime === undefined || secondsIntoSlot <= maxAllowedTime) {
|
|
968
|
+
this.log.trace(`Not attempting to vote since there is still for block building`, {
|
|
969
|
+
secondsIntoSlot,
|
|
970
|
+
maxAllowedTime,
|
|
971
|
+
});
|
|
972
|
+
return;
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
this.log.debug(`Sync for slot ${slot} failed, checking for voting opportunities`, {
|
|
976
|
+
secondsIntoSlot,
|
|
977
|
+
maxAllowedTime,
|
|
978
|
+
});
|
|
979
|
+
|
|
980
|
+
// Check if we're a proposer or proposal is open
|
|
981
|
+
const [canPropose, proposer] = await this.checkCanPropose(slot);
|
|
982
|
+
if (!canPropose) {
|
|
983
|
+
this.log.debug(`Cannot vote in slot ${slot} since we are not a proposer`, { slot, proposer });
|
|
984
|
+
return;
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
// Mark this slot as attempted
|
|
988
|
+
this.lastSlotForVoteWhenSyncFailed = slot;
|
|
989
|
+
|
|
990
|
+
// Get a publisher for voting
|
|
991
|
+
const { attestorAddress, publisher } = await this.publisherFactory.create(proposer);
|
|
992
|
+
|
|
993
|
+
this.log.debug(`Attempting to vote despite sync failure at slot ${slot}`, {
|
|
994
|
+
attestorAddress,
|
|
995
|
+
slot,
|
|
996
|
+
});
|
|
997
|
+
|
|
998
|
+
// Enqueue governance and slashing votes using the shared helper method
|
|
999
|
+
const votesPromises = this.enqueueGovernanceAndSlashingVotes(publisher, attestorAddress, slot, ts);
|
|
1000
|
+
await Promise.all(votesPromises);
|
|
1001
|
+
|
|
1002
|
+
if (votesPromises.every(p => !p)) {
|
|
1003
|
+
this.log.debug(`No votes to enqueue for slot ${slot}`);
|
|
1004
|
+
return;
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
this.log.info(`Voting in slot ${slot} despite sync failure`, { slot });
|
|
1008
|
+
await publisher.sendRequests();
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
/**
|
|
1012
|
+
* Considers invalidating a block if the pending chain is invalid. Depends on how long the invalid block
|
|
1013
|
+
* has been there without being invalidated and whether the sequencer is in the committee or not. We always
|
|
1014
|
+
* have the proposer try to invalidate, but if they fail, the sequencers in the committee are expected to try,
|
|
1015
|
+
* and if they fail, any sequencer will try as well.
|
|
1016
|
+
*/
|
|
1017
|
+
protected async considerInvalidatingBlock(
|
|
1018
|
+
syncedTo: NonNullable<Awaited<ReturnType<Sequencer['checkSync']>>>,
|
|
1019
|
+
currentSlot: bigint,
|
|
1020
|
+
): Promise<void> {
|
|
1021
|
+
const { pendingChainValidationStatus, l1Timestamp } = syncedTo;
|
|
1022
|
+
if (pendingChainValidationStatus.valid) {
|
|
1023
|
+
return;
|
|
1024
|
+
}
|
|
1025
|
+
|
|
1026
|
+
const { publisher } = await this.publisherFactory.create(undefined);
|
|
1027
|
+
const invalidBlockNumber = pendingChainValidationStatus.block.blockNumber;
|
|
1028
|
+
const invalidBlockTimestamp = pendingChainValidationStatus.block.timestamp;
|
|
1029
|
+
const timeSinceChainInvalid = this.dateProvider.nowInSeconds() - Number(invalidBlockTimestamp);
|
|
1030
|
+
const ourValidatorAddresses = this.validatorClient!.getValidatorAddresses();
|
|
1031
|
+
|
|
1032
|
+
const { secondsBeforeInvalidatingBlockAsCommitteeMember, secondsBeforeInvalidatingBlockAsNonCommitteeMember } =
|
|
1033
|
+
this.config;
|
|
1034
|
+
|
|
1035
|
+
const logData = {
|
|
1036
|
+
invalidL1Timestamp: invalidBlockTimestamp,
|
|
1037
|
+
l1Timestamp,
|
|
1038
|
+
invalidBlock: pendingChainValidationStatus.block,
|
|
1039
|
+
secondsBeforeInvalidatingBlockAsCommitteeMember,
|
|
1040
|
+
secondsBeforeInvalidatingBlockAsNonCommitteeMember,
|
|
1041
|
+
ourValidatorAddresses,
|
|
1042
|
+
currentSlot,
|
|
1043
|
+
};
|
|
1044
|
+
|
|
1045
|
+
const inCurrentCommittee = () =>
|
|
1046
|
+
this.epochCache
|
|
1047
|
+
.getCommittee(currentSlot)
|
|
1048
|
+
.then(c => c?.committee?.some(member => ourValidatorAddresses.some(addr => addr.equals(member))));
|
|
1049
|
+
|
|
1050
|
+
const invalidateAsCommitteeMember =
|
|
1051
|
+
secondsBeforeInvalidatingBlockAsCommitteeMember !== undefined &&
|
|
1052
|
+
secondsBeforeInvalidatingBlockAsCommitteeMember > 0 &&
|
|
1053
|
+
timeSinceChainInvalid > secondsBeforeInvalidatingBlockAsCommitteeMember &&
|
|
1054
|
+
(await inCurrentCommittee());
|
|
1055
|
+
|
|
1056
|
+
const invalidateAsNonCommitteeMember =
|
|
1057
|
+
secondsBeforeInvalidatingBlockAsNonCommitteeMember !== undefined &&
|
|
1058
|
+
secondsBeforeInvalidatingBlockAsNonCommitteeMember > 0 &&
|
|
1059
|
+
timeSinceChainInvalid > secondsBeforeInvalidatingBlockAsNonCommitteeMember;
|
|
1060
|
+
|
|
1061
|
+
if (!invalidateAsCommitteeMember && !invalidateAsNonCommitteeMember) {
|
|
1062
|
+
this.log.debug(`Not invalidating pending chain`, logData);
|
|
1063
|
+
return;
|
|
1064
|
+
}
|
|
1065
|
+
|
|
1066
|
+
const invalidateBlock = await publisher.simulateInvalidateBlock(pendingChainValidationStatus);
|
|
1067
|
+
if (!invalidateBlock) {
|
|
1068
|
+
this.log.warn(`Failed to simulate invalidate block`, logData);
|
|
1069
|
+
return;
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
this.log.info(
|
|
1073
|
+
invalidateAsCommitteeMember
|
|
1074
|
+
? `Invalidating block ${invalidBlockNumber} as committee member`
|
|
1075
|
+
: `Invalidating block ${invalidBlockNumber} as non-committee member`,
|
|
1076
|
+
logData,
|
|
1077
|
+
);
|
|
1078
|
+
|
|
1079
|
+
publisher.enqueueInvalidateBlock(invalidateBlock);
|
|
1080
|
+
await publisher.sendRequests();
|
|
737
1081
|
}
|
|
738
1082
|
|
|
739
|
-
private
|
|
740
|
-
return
|
|
1083
|
+
private getSlotStartBuildTimestamp(slotNumber: number | bigint): number {
|
|
1084
|
+
return getSlotStartBuildTimestamp(slotNumber, this.l1Constants);
|
|
741
1085
|
}
|
|
742
1086
|
|
|
743
1087
|
private getSecondsIntoSlot(slotNumber: number | bigint): number {
|
|
744
|
-
const slotStartTimestamp = this.
|
|
1088
|
+
const slotStartTimestamp = this.getSlotStartBuildTimestamp(slotNumber);
|
|
745
1089
|
return Number((this.dateProvider.now() / 1000 - slotStartTimestamp).toFixed(3));
|
|
746
1090
|
}
|
|
747
1091
|
|
|
@@ -749,11 +1093,11 @@ export class Sequencer {
|
|
|
749
1093
|
return this.l1Constants.slotDuration;
|
|
750
1094
|
}
|
|
751
1095
|
|
|
752
|
-
get
|
|
753
|
-
return this.
|
|
1096
|
+
get maxL2BlockGas(): number | undefined {
|
|
1097
|
+
return this.config.maxL2BlockGas;
|
|
754
1098
|
}
|
|
755
1099
|
|
|
756
|
-
|
|
757
|
-
return this.
|
|
1100
|
+
public getSlasherClient(): SlasherClientInterface | undefined {
|
|
1101
|
+
return this.slasherClient;
|
|
758
1102
|
}
|
|
759
1103
|
}
|