-
Notifications
You must be signed in to change notification settings - Fork 596
Expand file tree
/
Copy pathsequencer.test.ts
More file actions
638 lines (535 loc) · 23.8 KB
/
sequencer.test.ts
File metadata and controls
638 lines (535 loc) · 23.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
import { Body, L2Block } from '@aztec/aztec.js';
import { NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP } from '@aztec/constants';
import type { EpochCache, EpochCommitteeInfo } from '@aztec/epoch-cache';
import type { RollupContract } from '@aztec/ethereum';
import { timesParallel } from '@aztec/foundation/collection';
import { Secp256k1Signer } from '@aztec/foundation/crypto';
import { EthAddress } from '@aztec/foundation/eth-address';
import { Signature } from '@aztec/foundation/eth-signature';
import { Fr } from '@aztec/foundation/fields';
import { TestDateProvider, Timer } from '@aztec/foundation/timer';
import { type P2P, P2PClientState } from '@aztec/p2p';
import type { SlasherClientInterface } from '@aztec/slasher';
import { PublicDataWrite } from '@aztec/stdlib/avm';
import { AztecAddress } from '@aztec/stdlib/aztec-address';
import { CommitteeAttestation, type L2BlockSource } from '@aztec/stdlib/block';
import type { L1RollupConstants } from '@aztec/stdlib/epoch-helpers';
import { Gas, GasFees } from '@aztec/stdlib/gas';
import {
type IFullNodeBlockBuilder,
type MerkleTreeReadOperations,
type MerkleTreeWriteOperations,
type PublicProcessorLimits,
type SequencerConfig,
WorldStateRunningState,
type WorldStateSyncStatus,
type WorldStateSynchronizer,
type WorldStateSynchronizerStatus,
} from '@aztec/stdlib/interfaces/server';
import type { L1ToL2MessageSource } from '@aztec/stdlib/messaging';
import { BlockAttestation, BlockProposal, ConsensusPayload } from '@aztec/stdlib/p2p';
import { makeAppendOnlyTreeSnapshot, mockTxForRollup } from '@aztec/stdlib/testing';
import type { MerkleTreeId } from '@aztec/stdlib/trees';
import { BlockHeader, GlobalVariables, type Tx, TxHash, makeProcessedTxFromPrivateOnlyTx } from '@aztec/stdlib/tx';
import type { ValidatorClient } from '@aztec/validator-client';
import { expect } from '@jest/globals';
import { type MockProxy, mock, mockDeep, mockFn } from 'jest-mock-extended';
import type { GlobalVariableBuilder } from '../global_variable_builder/global_builder.js';
import type { AttestorPublisherPair, SequencerPublisherFactory } from '../publisher/sequencer-publisher-factory.js';
import type { SequencerPublisher } from '../publisher/sequencer-publisher.js';
import { Sequencer } from './sequencer.js';
import { SequencerState } from './utils.js';
describe('sequencer', () => {
let publisher: MockProxy<SequencerPublisher>;
let epochCache: MockProxy<EpochCache>;
let validatorClient: MockProxy<ValidatorClient>;
let globalVariableBuilder: MockProxy<GlobalVariableBuilder>;
let p2p: MockProxy<P2P>;
let worldState: MockProxy<WorldStateSynchronizer>;
let fork: MockProxy<MerkleTreeWriteOperations>;
let blockBuilder: MockProxy<IFullNodeBlockBuilder>;
let merkleTreeOps: MockProxy<MerkleTreeReadOperations>;
let l2BlockSource: MockProxy<L2BlockSource>;
let l1ToL2MessageSource: MockProxy<L1ToL2MessageSource>;
let slasherClient: MockProxy<SlasherClientInterface>;
let publisherFactory: MockProxy<SequencerPublisherFactory>;
let rollupContract: MockProxy<RollupContract>;
let dateProvider: TestDateProvider;
let initialBlockHeader: BlockHeader;
let lastBlockNumber: number;
let newBlockNumber: number;
let newSlotNumber: number;
let hash: string;
let block: L2Block;
let globalVariables: GlobalVariables;
let l1Constants: Pick<L1RollupConstants, 'l1GenesisTime' | 'slotDuration' | 'ethereumSlotDuration'>;
// Note: Removed unused l1Contracts declaration
let sequencer: TestSubject;
const slotDuration = 8;
const ethereumSlotDuration = 4;
const chainId = new Fr(12345);
const version = Fr.ZERO;
const coinbase = EthAddress.random();
const gasFees = GasFees.empty();
let feeRecipient: AztecAddress;
const signer = Secp256k1Signer.random();
const mockedSig = Signature.random();
const mockedAttestation = new CommitteeAttestation(signer.address, mockedSig);
const committee = [signer.address];
const getSignatures = () => [mockedAttestation];
const getAttestations = () => {
const consensusPayload = ConsensusPayload.fromBlock(block);
const attestation = new BlockAttestation(block.header.globalVariables.blockNumber, consensusPayload, mockedSig);
(attestation as any).sender = committee[0];
return [attestation];
};
const createBlockProposal = () => {
const consensusPayload = ConsensusPayload.fromBlock(block);
const txHashes = block.body.txEffects.map(tx => tx.txHash);
return new BlockProposal(block.header.globalVariables.blockNumber, consensusPayload, mockedSig, txHashes);
};
const processTxs = async (txs: Tx[]) => {
return await Promise.all(
txs.map(tx =>
makeProcessedTxFromPrivateOnlyTx(tx, Fr.ZERO, new PublicDataWrite(Fr.random(), Fr.random()), globalVariables),
),
);
};
const mockTxIterator = async function* (txs: Promise<Tx[]>): AsyncIterableIterator<Tx> {
for (const tx of await txs) {
yield tx;
}
};
const mockPendingTxs = (txs: Tx[]) => {
p2p.getPendingTxCount.mockResolvedValue(txs.length);
// make sure a new iterator is created for every invocation of iteratePendingTxs
// otherwise we risk iterating over the same iterator more than once (yielding no more values)
p2p.iteratePendingTxs.mockImplementation(() => mockTxIterator(Promise.resolve(txs)));
};
const makeBlock = async (txs: Tx[]) => {
const processedTxs = await processTxs(txs);
const body = new Body(processedTxs.map(tx => tx.txEffect));
const header = BlockHeader.empty({ globalVariables: globalVariables });
const archive = makeAppendOnlyTreeSnapshot(newBlockNumber + 1);
block = new L2Block(archive, header, body);
return block;
};
const makeTx = async (seed?: number) => {
const tx = await mockTxForRollup(seed);
tx.data.constants.txContext.chainId = chainId;
return tx;
};
const expectPublisherProposeL2Block = (txHashes: TxHash[]) => {
expect(publisher.enqueueProposeL2Block).toHaveBeenCalledTimes(1);
expect(publisher.enqueueProposeL2Block).toHaveBeenCalledWith(block, getSignatures(), txHashes, {
txTimeoutAt: expect.any(Date),
});
};
beforeEach(async () => {
feeRecipient = await AztecAddress.random();
initialBlockHeader = BlockHeader.empty();
lastBlockNumber = 0;
newBlockNumber = lastBlockNumber + 1;
newSlotNumber = newBlockNumber;
hash = Fr.ZERO.toString();
globalVariables = new GlobalVariables(
chainId,
version,
newBlockNumber,
new Fr(newSlotNumber),
/*timestamp=*/ 0n,
coinbase,
feeRecipient,
gasFees,
);
const l1GenesisTime = BigInt(Math.floor(Date.now() / 1000));
l1Constants = { l1GenesisTime, slotDuration, ethereumSlotDuration };
epochCache = mockDeep<EpochCache>();
epochCache.getEpochAndSlotInNextL1Slot.mockImplementation(() => ({ epoch: 1n, slot: 1n, ts: 1000n, now: 1000n }));
epochCache.getCommittee.mockResolvedValue({ committee } as EpochCommitteeInfo);
publisher = mockDeep<SequencerPublisher>();
publisher.epochCache = epochCache;
publisher.getSenderAddress.mockImplementation(() => EthAddress.random());
publisher.validateBlockHeader.mockResolvedValue();
publisher.enqueueProposeL2Block.mockResolvedValue(true);
publisher.enqueueGovernanceCastSignal.mockResolvedValue(true);
publisher.enqueueSlashingActions.mockResolvedValue(true);
publisher.canProposeAtNextEthBlock.mockResolvedValue({
slot: BigInt(newSlotNumber),
blockNumber: BigInt(newBlockNumber),
timeOfNextL1Slot: 1000n,
});
publisherFactory = mockDeep<SequencerPublisherFactory>();
publisherFactory.create.mockResolvedValue({
attestorAddress: publisher.getSenderAddress(),
publisher,
} satisfies AttestorPublisherPair);
rollupContract = mockDeep<RollupContract>();
globalVariableBuilder = mock<GlobalVariableBuilder>();
globalVariableBuilder.buildGlobalVariables.mockResolvedValue(globalVariables);
merkleTreeOps = mock<MerkleTreeReadOperations>();
merkleTreeOps.findLeafIndices.mockImplementation((_treeId: MerkleTreeId, _value: any[]) => {
return Promise.resolve([undefined]);
});
merkleTreeOps.getTreeInfo.mockImplementation((treeId: MerkleTreeId) => {
return Promise.resolve({ treeId, root: Fr.random().toBuffer(), size: 99n, depth: 5 });
});
p2p = mock<P2P>({
getStatus: mockFn().mockResolvedValue({
state: P2PClientState.IDLE,
syncedToL2Block: { number: lastBlockNumber, hash },
}),
});
fork = mock<MerkleTreeWriteOperations>({
getInitialHeader: () => initialBlockHeader,
});
worldState = mock<WorldStateSynchronizer>({
fork: () => Promise.resolve(fork),
syncImmediate: () => Promise.resolve(lastBlockNumber),
getCommitted: () => merkleTreeOps,
status: mockFn().mockResolvedValue({
state: WorldStateRunningState.IDLE,
syncSummary: {
latestBlockNumber: lastBlockNumber,
latestBlockHash: hash,
finalizedBlockNumber: 0,
oldestHistoricBlockNumber: 0,
treesAreSynched: true,
},
} satisfies WorldStateSynchronizerStatus),
});
blockBuilder = mock<IFullNodeBlockBuilder>();
blockBuilder.buildBlock.mockImplementation(() =>
Promise.resolve({
block,
publicGas: Gas.empty(),
publicProcessorDuration: 0,
numMsgs: 0,
numTxs: block.body.txEffects.length,
blockBuildingTimer: new Timer(),
usedTxs: [],
failedTxs: [],
}),
);
l2BlockSource = mock<L2BlockSource>({
getBlock: mockFn().mockResolvedValue(L2Block.empty()),
getBlockNumber: mockFn().mockResolvedValue(lastBlockNumber),
getL2Tips: mockFn().mockResolvedValue({ latest: { number: lastBlockNumber, hash } }),
getL1Timestamp: mockFn().mockResolvedValue(1000n),
isPendingChainInvalid: mockFn().mockResolvedValue(false),
getPendingChainValidationStatus: mockFn().mockResolvedValue({ valid: true }),
});
l1ToL2MessageSource = mock<L1ToL2MessageSource>({
getL1ToL2Messages: () => Promise.resolve(Array(NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP).fill(Fr.ZERO)),
getBlockNumber: mockFn().mockResolvedValue(lastBlockNumber),
getL2Tips: mockFn().mockResolvedValue({ latest: { number: lastBlockNumber, hash } }),
});
validatorClient = mock<ValidatorClient>();
validatorClient.collectAttestations.mockImplementation(() => Promise.resolve(getAttestations()));
validatorClient.createBlockProposal.mockImplementation(() => Promise.resolve(createBlockProposal()));
slasherClient = mock<SlasherClientInterface>();
slasherClient.getProposerActions.mockResolvedValue([]);
dateProvider = new TestDateProvider();
const config: SequencerConfig = { enforceTimeTable: true, maxTxsPerBlock: 4 };
sequencer = new TestSubject(
publisherFactory,
// TODO(md): add the relevant methods to the validator client that will prevent it stalling when waiting for attestations
validatorClient,
globalVariableBuilder,
p2p,
worldState,
slasherClient,
l2BlockSource,
l1ToL2MessageSource,
blockBuilder,
l1Constants,
dateProvider,
epochCache,
rollupContract,
config,
);
sequencer.updateConfig(config);
});
describe('block building', () => {
it('builds a block out of a single tx', async () => {
const tx = await makeTx();
const txHash = tx.getTxHash();
block = await makeBlock([tx]);
mockPendingTxs([tx]);
await sequencer.doRealWork();
expectPublisherProposeL2Block([txHash]);
});
it('does not build a block if it does not have enough time left in the slot', async () => {
const tx = await makeTx();
mockPendingTxs([tx]);
block = await makeBlock([tx]);
// deadline for initializing proposal is 1s, so we go 2s past it
expect(sequencer.getTimeTable().initializeDeadline).toEqual(1);
const l1TsForL2Slot1 = Number(l1Constants.l1GenesisTime) + slotDuration;
dateProvider.setTime((l1TsForL2Slot1 + 2) * 1000);
await expect(sequencer.doRealWork()).rejects.toThrow(
expect.objectContaining({
name: 'SequencerTooSlowError',
message: expect.stringContaining(`Too far into slot`),
}),
);
expect(blockBuilder.buildBlock).not.toHaveBeenCalled();
expect(publisher.enqueueProposeL2Block).not.toHaveBeenCalled();
expect(publisher.canProposeAtNextEthBlock).not.toHaveBeenCalled();
});
it('does not publish a block if it does not have enough time left in the slot after collecting attestations', async () => {
expect(sequencer.getTimeTable().l1PublishingTime).toEqual(ethereumSlotDuration);
const l1TsForL2Slot1 = Number(l1Constants.l1GenesisTime) + slotDuration;
const tx = await makeTx();
mockPendingTxs([tx]);
block = await makeBlock([tx]);
validatorClient.collectAttestations.mockImplementation(() => {
// after collecting attestations, "warp" to 1s before the last L1 slot of the L2 slot is mined,
// meaning that we have lost our chance to get mined given our l1PublishingTime is a full L1 slot
dateProvider.setTime((l1TsForL2Slot1 + ethereumSlotDuration - 1) * 1000);
return Promise.resolve(getAttestations());
});
// we begin immediately after the last L1 block for the previous slot has been mined
dateProvider.setTime((l1TsForL2Slot1 - ethereumSlotDuration + 0.1) * 1000);
await sequencer.doRealWork();
expect(blockBuilder.buildBlock).toHaveBeenCalled();
expect(validatorClient.collectAttestations).toHaveBeenCalled();
expect(publisher.enqueueProposeL2Block).not.toHaveBeenCalled();
});
it('builds a block when it is their turn', async () => {
const tx = await makeTx();
const txHash = tx.getTxHash();
mockPendingTxs([tx]);
block = await makeBlock([tx]);
// Not your turn!
publisher.canProposeAtNextEthBlock.mockReturnValue(Promise.resolve(undefined));
publisher.validateBlockHeader.mockRejectedValue(new Error());
await sequencer.doRealWork();
expect(blockBuilder.buildBlock).not.toHaveBeenCalled();
// Now we can propose, but lets assume that the content is still "bad" (missing sigs etc)
publisher.canProposeAtNextEthBlock.mockResolvedValue({
slot: block.header.globalVariables.slotNumber.toBigInt(),
blockNumber: BigInt(block.header.globalVariables.blockNumber),
timeOfNextL1Slot: 1000n,
});
await sequencer.doRealWork();
expect(blockBuilder.buildBlock).not.toHaveBeenCalled();
// Now it is!
publisher.validateBlockHeader.mockClear();
publisher.validateBlockHeader.mockResolvedValue();
await sequencer.doRealWork();
expect(blockBuilder.buildBlock).toHaveBeenCalledWith(
expect.anything(),
expect.anything(),
globalVariables,
expect.anything(),
);
expectPublisherProposeL2Block([txHash]);
});
it('builds a block once it reaches the minimum number of transactions', async () => {
const txs: Tx[] = await timesParallel(8, i => makeTx(i * 0x10000));
sequencer.updateConfig({ minTxsPerBlock: 4 });
// block is not built with 0 txs
mockPendingTxs([]);
await sequencer.doRealWork();
expect(blockBuilder.buildBlock).toHaveBeenCalledTimes(0);
// block is not built with 3 txs
mockPendingTxs(txs.slice(0, 3));
await sequencer.doRealWork();
expect(blockBuilder.buildBlock).toHaveBeenCalledTimes(0);
// block is built with 4 txs
const neededTxs = txs.slice(0, 4);
mockPendingTxs(neededTxs);
block = await makeBlock(neededTxs);
await sequencer.doRealWork();
expect(blockBuilder.buildBlock).toHaveBeenCalledWith(
expect.anything(),
expect.anything(),
globalVariables,
expect.anything(),
);
expectPublisherProposeL2Block(await Promise.all(neededTxs.map(tx => tx.getTxHash())));
});
it('settles on the chain tip before it starts building a block', async () => {
// this test simulates a synch happening right after the sequencer starts building a block
// simulate every component being synched
const firstBlock = await L2Block.random(1);
const currentTip = firstBlock;
const syncedToL2Block = { number: currentTip.number, hash: (await currentTip.hash()).toString() };
worldState.status.mockImplementation(() =>
Promise.resolve({
state: WorldStateRunningState.IDLE,
syncSummary: {
latestBlockNumber: syncedToL2Block.number,
latestBlockHash: syncedToL2Block.hash,
} as WorldStateSyncStatus,
}),
);
p2p.getStatus.mockImplementation(() => Promise.resolve({ state: P2PClientState.IDLE, syncedToL2Block }));
l2BlockSource.getL2Tips.mockImplementation(() =>
Promise.resolve({
latest: syncedToL2Block,
proven: { number: 0, hash: undefined },
finalized: { number: 0, hash: undefined },
}),
);
l1ToL2MessageSource.getL2Tips.mockImplementation(() =>
Promise.resolve({
latest: syncedToL2Block,
proven: { number: 0, hash: undefined },
finalized: { number: 0, hash: undefined },
}),
);
// simulate a synch happening right after
l2BlockSource.getBlockNumber.mockResolvedValueOnce(currentTip.number);
l2BlockSource.getBlockNumber.mockResolvedValueOnce(currentTip.number + 1);
// now the new tip is actually block 2
l2BlockSource.getBlock.mockImplementation(n =>
n === -1
? L2Block.random(currentTip.number + 1)
: n === currentTip.number
? Promise.resolve(currentTip)
: Promise.resolve(undefined),
);
publisher.canProposeAtNextEthBlock.mockResolvedValueOnce(undefined);
await sequencer.doRealWork();
expect(publisher.enqueueProposeL2Block).not.toHaveBeenCalled();
});
it('builds a block only when synced to previous L1 slot', async () => {
const tx = await makeTx();
mockPendingTxs([tx]);
block = await makeBlock([tx]);
l2BlockSource.getL1Timestamp.mockResolvedValue(1000n - BigInt(ethereumSlotDuration) - 1n);
await sequencer.doRealWork();
expect(publisher.enqueueProposeL2Block).not.toHaveBeenCalled();
l2BlockSource.getL1Timestamp.mockResolvedValue(1000n - BigInt(ethereumSlotDuration));
await sequencer.doRealWork();
expect(publisher.enqueueProposeL2Block).toHaveBeenCalled();
});
it('aborts building a block if the chain moves underneath it', async () => {
const tx = await makeTx();
mockPendingTxs([tx]);
block = await makeBlock([tx]);
// This could practically be for any reason, e.g., could also be that we have entered a new slot.
publisher.validateBlockHeader.mockResolvedValueOnce().mockRejectedValueOnce(new Error('No block for you'));
await sequencer.doRealWork();
expect(publisher.enqueueProposeL2Block).not.toHaveBeenCalled();
});
it('does not publish a block if the block proposal failed', async () => {
const tx = await makeTx();
mockPendingTxs([tx]);
block = await makeBlock([tx]);
validatorClient.createBlockProposal.mockResolvedValue(undefined);
await sequencer.doRealWork();
expect(publisher.enqueueProposeL2Block).not.toHaveBeenCalled();
});
it('handles when enqueueProposeL2Block throws', async () => {
const tx = await makeTx();
mockPendingTxs([tx]);
block = await makeBlock([tx]);
publisher.enqueueProposeL2Block.mockRejectedValueOnce(new Error('Failed to enqueue propose L2 block'));
await sequencer.doRealWork();
expectPublisherProposeL2Block([tx.getTxHash()]);
// Even though the block publish was not enqueued, we still send any requests
expect(publisher.sendRequests).toHaveBeenCalledTimes(1);
});
it('should proceed with block proposal when there is no proposer yet', async () => {
// Mock that there is no official proposer yet
epochCache.getProposerAttesterAddressInNextSlot.mockResolvedValueOnce(undefined);
epochCache.getCommittee.mockResolvedValueOnce({ committee: [] as EthAddress[] } as EpochCommitteeInfo);
// Mock that we have some pending transactions
const txs = [await makeTx(1), await makeTx(2)];
mockPendingTxs(txs);
block = await makeBlock(txs);
await sequencer.doRealWork();
// Verify that the sequencer attempted to create and broadcast a block proposal
expect(publisher.enqueueProposeL2Block).toHaveBeenCalled();
// Verify that the sequencer did not broadcast for attestations since there's no committee
expect(validatorClient.createBlockProposal).not.toHaveBeenCalled();
expect(validatorClient.broadcastBlockProposal).not.toHaveBeenCalled();
});
});
describe('multi-eoa publishing', () => {
let publishers: SequencerPublisher[];
beforeEach(() => {
publishers = Array.from({ length: 3 }, () => {
const publisher = mockDeep<SequencerPublisher>();
publisher.epochCache = epochCache;
publisher.getSenderAddress.mockImplementation(() => EthAddress.random());
publisher.validateBlockHeader.mockResolvedValue();
publisher.enqueueProposeL2Block.mockResolvedValue(true);
publisher.enqueueGovernanceCastSignal.mockResolvedValue(true);
publisher.enqueueSlashingActions.mockResolvedValue(true);
publisher.canProposeAtNextEthBlock.mockResolvedValue({
slot: BigInt(newSlotNumber),
blockNumber: BigInt(newBlockNumber),
timeOfNextL1Slot: 1000n,
});
return publisher;
});
publisherFactory = mockDeep<SequencerPublisherFactory>();
publisherFactory.create.mockResolvedValueOnce({
attestorAddress: publishers[0].getSenderAddress(),
publisher: publishers[0],
});
publisherFactory.create.mockResolvedValueOnce({
attestorAddress: publishers[1].getSenderAddress(),
publisher: publishers[1],
});
const config: SequencerConfig = { enforceTimeTable: true, maxTxsPerBlock: 4 };
sequencer = new TestSubject(
publisherFactory,
// TODO(md): add the relevant methods to the validator client that will prevent it stalling when waiting for attestations
validatorClient,
globalVariableBuilder,
p2p,
worldState,
slasherClient,
l2BlockSource,
l1ToL2MessageSource,
blockBuilder,
l1Constants,
dateProvider,
epochCache,
rollupContract,
config,
);
sequencer.updateConfig(config);
});
it('Requests a publisher for each block', async () => {
// Build and publish 2 blocks, the sequencer should request a new publisher each time
for (let i = 0; i < 2; i++) {
const tx = await makeTx();
const txHash = tx.getTxHash();
mockPendingTxs([tx]);
block = await makeBlock([tx]);
await sequencer.doRealWork();
expect(blockBuilder.buildBlock).toHaveBeenCalledWith(
expect.anything(),
expect.anything(),
globalVariables,
expect.anything(),
);
expect(publishers[i].enqueueProposeL2Block).toHaveBeenCalledTimes(1);
expect(publishers[i].enqueueProposeL2Block).toHaveBeenCalledWith(block, getSignatures(), [txHash], {
txTimeoutAt: expect.any(Date),
});
}
});
});
});
class TestSubject extends Sequencer {
public getTimeTable() {
return this.timetable;
}
public setL1GenesisTime(l1GenesisTime: number) {
this.l1Constants.l1GenesisTime = BigInt(l1GenesisTime);
}
public override doRealWork() {
this.setState(SequencerState.IDLE, undefined, { force: true });
return super.doRealWork();
}
public override getBlockBuilderOptions(slot: number): PublicProcessorLimits {
return super.getBlockBuilderOptions(slot);
}
}