-
Notifications
You must be signed in to change notification settings - Fork 327
/
Copy pathsequencer.test.ts
816 lines (654 loc) · 28.9 KB
/
sequencer.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
import {
BlockAttestation,
type BlockBuilder,
BlockProposal,
Body,
ConsensusPayload,
type L1ToL2MessageSource,
L2Block,
type L2BlockSource,
type MerkleTreeId,
type MerkleTreeReadOperations,
type MerkleTreeWriteOperations,
type Tx,
TxHash,
WorldStateRunningState,
type WorldStateSynchronizer,
mockEpochProofQuote as baseMockEpochProofQuote,
makeProcessedTxFromPrivateOnlyTx,
mockTxForRollup,
} from '@aztec/circuit-types';
import {
AztecAddress,
BlockHeader,
type ContractDataSource,
EthAddress,
Fr,
type Gas,
GasFees,
GlobalVariables,
NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP,
} from '@aztec/circuits.js';
import { makeAppendOnlyTreeSnapshot } from '@aztec/circuits.js/testing';
import { DefaultL1ContractsConfig } from '@aztec/ethereum';
import { Buffer32 } from '@aztec/foundation/buffer';
import { times, timesParallel } from '@aztec/foundation/collection';
import { Signature } from '@aztec/foundation/eth-signature';
import { toArray } from '@aztec/foundation/iterable';
import { type Logger, createLogger } from '@aztec/foundation/log';
import { TestDateProvider, type Timer } from '@aztec/foundation/timer';
import { type P2P, P2PClientState } from '@aztec/p2p';
import { type BlockBuilderFactory } from '@aztec/prover-client/block-builder';
import { type PublicProcessor, type PublicProcessorFactory } from '@aztec/simulator/server';
import { type ValidatorClient } from '@aztec/validator-client';
import { expect } from '@jest/globals';
import { type MockProxy, mock, mockFn } from 'jest-mock-extended';
import { type GlobalVariableBuilder } from '../global_variable_builder/global_builder.js';
import { type SequencerPublisher } from '../publisher/sequencer-publisher.js';
import { type SlasherClient } from '../slasher/index.js';
import { Sequencer } from './sequencer.js';
import { SequencerState } from './utils.js';
describe('sequencer', () => {
let publisher: MockProxy<SequencerPublisher>;
let validatorClient: MockProxy<ValidatorClient>;
let globalVariableBuilder: MockProxy<GlobalVariableBuilder>;
let p2p: MockProxy<P2P>;
let worldState: MockProxy<WorldStateSynchronizer>;
let fork: MockProxy<MerkleTreeWriteOperations>;
let blockBuilder: MockProxy<BlockBuilder>;
let merkleTreeOps: MockProxy<MerkleTreeReadOperations>;
let publicProcessor: MockProxy<PublicProcessor>;
let l2BlockSource: MockProxy<L2BlockSource>;
let l1ToL2MessageSource: MockProxy<L1ToL2MessageSource>;
let publicProcessorFactory: MockProxy<PublicProcessorFactory>;
let initialBlockHeader: BlockHeader;
let lastBlockNumber: number;
let newBlockNumber: number;
let newSlotNumber: number;
let hash: string;
let logger: Logger;
let block: L2Block;
let globalVariables: GlobalVariables;
let sequencer: TestSubject;
const {
aztecEpochDuration: epochDuration,
aztecSlotDuration: slotDuration,
ethereumSlotDuration,
} = DefaultL1ContractsConfig;
const chainId = new Fr(12345);
const version = Fr.ZERO;
const coinbase = EthAddress.random();
let feeRecipient: AztecAddress;
const gasFees = GasFees.empty();
const archive = Fr.random();
const mockedSig = new Signature(Buffer32.fromField(Fr.random()), Buffer32.fromField(Fr.random()), 27);
const committee = [EthAddress.random()];
const getSignatures = () => [mockedSig];
const getAttestations = () => {
const attestation = new BlockAttestation(new ConsensusPayload(block.header, archive, []), mockedSig);
(attestation as any).sender = committee[0];
return [attestation];
};
const createBlockProposal = () => {
return new BlockProposal(new ConsensusPayload(block.header, archive, [TxHash.random()]), mockedSig);
};
const processTxs = async (txs: Tx[]) => {
return await Promise.all(txs.map(tx => makeProcessedTxFromPrivateOnlyTx(tx, Fr.ZERO, undefined, 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();
logger = createLogger('sequencer:test');
globalVariables = new GlobalVariables(
chainId,
version,
new Fr(newBlockNumber),
new Fr(newSlotNumber),
Fr.ZERO,
coinbase,
feeRecipient,
gasFees,
);
publisher = mock<SequencerPublisher>();
publisher.getSenderAddress.mockImplementation(() => EthAddress.random());
publisher.getForwarderAddress.mockImplementation(() => EthAddress.random());
publisher.getCurrentEpochCommittee.mockResolvedValue(committee);
publisher.validateBlockForSubmission.mockResolvedValue(1n);
publisher.enqueueProposeL2Block.mockResolvedValue(true);
publisher.enqueueCastVote.mockResolvedValue(true);
publisher.enqueueClaimEpochProofRight.mockReturnValue(true);
publisher.canProposeAtNextEthBlock.mockResolvedValue([BigInt(newSlotNumber), BigInt(newBlockNumber)]);
globalVariableBuilder = mock<GlobalVariableBuilder>();
globalVariableBuilder.buildGlobalVariables.mockResolvedValue(globalVariables);
blockBuilder = mock<BlockBuilder>();
blockBuilder.setBlockCompleted.mockImplementation(() => Promise.resolve(block));
merkleTreeOps = mock<MerkleTreeReadOperations>();
merkleTreeOps.findLeafIndices.mockImplementation((_treeId: MerkleTreeId, _value: any[]) => {
return Promise.resolve([undefined]);
});
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),
getCommitted: () => merkleTreeOps,
status: mockFn().mockResolvedValue({
state: WorldStateRunningState.IDLE,
syncedToL2Block: { number: lastBlockNumber, hash },
}),
});
publicProcessor = mock<PublicProcessor>();
publicProcessor.process.mockImplementation(async txsIter => {
const txs = await toArray(txsIter);
const processed = await processTxs(txs);
logger.verbose(`Processed ${txs.length} txs`, { txHashes: txs.map(tx => tx.getTxHash()) });
return [processed, [], []];
});
publicProcessorFactory = mock<PublicProcessorFactory>({
create: (_a, _b) => publicProcessor,
});
l2BlockSource = mock<L2BlockSource>({
getBlock: mockFn().mockResolvedValue(L2Block.empty()),
getBlockNumber: mockFn().mockResolvedValue(lastBlockNumber),
getL2Tips: mockFn().mockResolvedValue({ latest: { number: lastBlockNumber, hash } }),
});
l1ToL2MessageSource = mock<L1ToL2MessageSource>({
getL1ToL2Messages: () => Promise.resolve(Array(NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP).fill(Fr.ZERO)),
getBlockNumber: mockFn().mockResolvedValue(lastBlockNumber),
});
// all txs use the same allowed FPC class
const fpcClassId = Fr.random();
const contractSource = mock<ContractDataSource>({
getContractClass: mockFn().mockResolvedValue(fpcClassId),
});
const blockBuilderFactory = mock<BlockBuilderFactory>({
create: () => blockBuilder,
});
validatorClient = mock<ValidatorClient>();
validatorClient.collectAttestations.mockImplementation(() => Promise.resolve(getAttestations()));
validatorClient.createBlockProposal.mockImplementation(() => Promise.resolve(createBlockProposal()));
const l1GenesisTime = BigInt(Math.floor(Date.now() / 1000));
const l1Constants = { l1GenesisTime, slotDuration, ethereumSlotDuration };
const slasherClient = mock<SlasherClient>();
const config = { enforceTimeTable: true, maxTxsPerBlock: 4 };
sequencer = new TestSubject(
publisher,
// TODO(md): add the relevant methods to the validator client that will prevent it stalling when waiting for attestations
validatorClient,
globalVariableBuilder,
p2p,
worldState,
slasherClient,
blockBuilderFactory,
l2BlockSource,
l1ToL2MessageSource,
publicProcessorFactory,
contractSource,
l1Constants,
new TestDateProvider(),
);
await sequencer.updateConfig(config);
});
it('builds a block out of a single tx', async () => {
const tx = await makeTx();
const txHash = await tx.getTxHash();
block = await makeBlock([tx]);
mockPendingTxs([tx]);
await sequencer.doRealWork();
expect(blockBuilder.startNewBlock).toHaveBeenCalledWith(
globalVariables,
Array(NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP).fill(new Fr(0n)),
initialBlockHeader,
);
expectPublisherProposeL2Block([txHash]);
});
it('builds a block for proposal setting limits', async () => {
const txs = await timesParallel(5, i => makeTx(i * 0x10000));
await sequencer.buildBlock(txs, globalVariables, { validateOnly: false });
expect(publicProcessor.process).toHaveBeenCalledWith(
txs,
{
deadline: expect.any(Date),
maxTransactions: 4,
maxBlockSize: expect.any(Number),
maxBlockGas: expect.anything(),
},
expect.anything(),
);
});
it('builds a block for validation ignoring limits', async () => {
const txs = await timesParallel(5, i => makeTx(i * 0x10000));
await sequencer.buildBlock(txs, globalVariables, { validateOnly: true });
expect(publicProcessor.process).toHaveBeenCalledWith(txs, { deadline: expect.any(Date) }, expect.anything());
});
it('does not build a block if it does not have enough time left in the slot', async () => {
// Trick the sequencer into thinking that we are just too far into slot 1
sequencer.setL1GenesisTime(
Math.floor(Date.now() / 1000) - slotDuration * 1 - (sequencer.getTimeTable().initialTime + 1),
);
const tx = await makeTx();
mockPendingTxs([tx]);
block = await makeBlock([tx]);
await expect(sequencer.doRealWork()).rejects.toThrow(
expect.objectContaining({
name: 'SequencerTooSlowError',
message: expect.stringContaining(`Too far into slot`),
}),
);
expect(blockBuilder.startNewBlock).not.toHaveBeenCalled();
expect(publisher.enqueueProposeL2Block).not.toHaveBeenCalled();
});
it('builds a block when it is their turn', async () => {
const tx = await makeTx();
const txHash = await tx.getTxHash();
mockPendingTxs([tx]);
block = await makeBlock([tx]);
// Not your turn!
publisher.canProposeAtNextEthBlock.mockReturnValue(Promise.resolve(undefined));
publisher.validateBlockForSubmission.mockRejectedValue(new Error());
await sequencer.doRealWork();
expect(blockBuilder.startNewBlock).not.toHaveBeenCalled();
// Now we can propose, but lets assume that the content is still "bad" (missing sigs etc)
publisher.canProposeAtNextEthBlock.mockResolvedValue([
block.header.globalVariables.slotNumber.toBigInt(),
block.header.globalVariables.blockNumber.toBigInt(),
]);
await sequencer.doRealWork();
expect(blockBuilder.startNewBlock).not.toHaveBeenCalled();
// Now it is!
publisher.validateBlockForSubmission.mockClear();
publisher.validateBlockForSubmission.mockResolvedValue(1n);
await sequencer.doRealWork();
expect(blockBuilder.startNewBlock).toHaveBeenCalledWith(
globalVariables,
Array(NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP).fill(new Fr(0n)),
initialBlockHeader,
);
expectPublisherProposeL2Block([txHash]);
});
it('builds a block out of several txs rejecting invalid txs', async () => {
const txs = await Promise.all([makeTx(0x10000), makeTx(0x20000), makeTx(0x30000)]);
const validTxs = [txs[0], txs[2]];
const invalidTx = txs[1];
const validTxHashes = await Promise.all(validTxs.map(tx => tx.getTxHash()));
mockPendingTxs(txs);
block = await makeBlock([txs[0], txs[2]]);
publicProcessor.process.mockResolvedValue([
await processTxs(validTxs),
[{ tx: invalidTx, error: new Error() }],
[],
]);
await sequencer.doRealWork();
expect(blockBuilder.startNewBlock).toHaveBeenCalledWith(
globalVariables,
Array(NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP).fill(new Fr(0n)),
initialBlockHeader,
);
expectPublisherProposeL2Block(validTxHashes);
expect(p2p.deleteTxs).toHaveBeenCalledWith([await invalidTx.getTxHash()]);
});
it('builds a block once it reaches the minimum number of transactions', async () => {
const txs: Tx[] = await timesParallel(8, i => makeTx(i * 0x10000));
await sequencer.updateConfig({ minTxsPerBlock: 4 });
// block is not built with 0 txs
mockPendingTxs([]);
await sequencer.doRealWork();
expect(blockBuilder.startNewBlock).toHaveBeenCalledTimes(0);
// block is not built with 3 txs
mockPendingTxs(txs.slice(0, 3));
await sequencer.doRealWork();
expect(blockBuilder.startNewBlock).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.startNewBlock).toHaveBeenCalledWith(
globalVariables,
times(NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP, Fr.zero),
initialBlockHeader,
);
expectPublisherProposeL2Block(await Promise.all(neededTxs.map(tx => tx.getTxHash())));
});
it('builds a block that contains zero real transactions once flushed', async () => {
const txs = await timesParallel(8, i => makeTx(i * 0x10000));
await sequencer.updateConfig({ minTxsPerBlock: 4 });
// block is not built with 0 txs
mockPendingTxs([]);
await sequencer.doRealWork();
expect(blockBuilder.startNewBlock).toHaveBeenCalledTimes(0);
// block is not built with 3 txs
mockPendingTxs(txs.slice(0, 3));
await sequencer.doRealWork();
expect(blockBuilder.startNewBlock).toHaveBeenCalledTimes(0);
// flush the sequencer and it should build a block
sequencer.flush();
// block is built with 0 txs
mockPendingTxs([]);
block = await makeBlock([]);
await sequencer.doRealWork();
expect(blockBuilder.startNewBlock).toHaveBeenCalledTimes(1);
expect(blockBuilder.startNewBlock).toHaveBeenCalledWith(
globalVariables,
times(NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP, Fr.zero),
initialBlockHeader,
);
expect(blockBuilder.addTxs).toHaveBeenCalledWith([]);
expectPublisherProposeL2Block([]);
});
it('builds a block that contains less than the minimum number of transactions once flushed', async () => {
const txs = await timesParallel(8, i => makeTx(i * 0x10000));
await sequencer.updateConfig({ minTxsPerBlock: 4 });
// block is not built with 0 txs
mockPendingTxs([]);
await sequencer.doRealWork();
expect(blockBuilder.startNewBlock).toHaveBeenCalledTimes(0);
// block is not built with 3 txs
mockPendingTxs(txs.slice(0, 3));
await sequencer.doRealWork();
expect(blockBuilder.startNewBlock).toHaveBeenCalledTimes(0);
// flush the sequencer and it should build a block
sequencer.flush();
// block is built with 3 txs
const postFlushTxs = txs.slice(0, 3);
mockPendingTxs(postFlushTxs);
block = await makeBlock(postFlushTxs);
const postFlushTxHashes = await Promise.all(postFlushTxs.map(tx => tx.getTxHash()));
await sequencer.doRealWork();
expect(blockBuilder.startNewBlock).toHaveBeenCalledTimes(1);
expect(blockBuilder.startNewBlock).toHaveBeenCalledWith(
globalVariables,
Array(NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP).fill(new Fr(0n)),
initialBlockHeader,
);
expectPublisherProposeL2Block(postFlushTxHashes);
});
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 bloxk
// 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, syncedToL2Block }),
);
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.getBlockNumber.mockImplementation(() => Promise.resolve(currentTip.number));
// 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();
// even though the chain tip moved, the sequencer should still have tried to build a block against the old archive
// this should get caught by the rollup
expect(publisher.canProposeAtNextEthBlock).toHaveBeenCalledWith(currentTip.archive.root.toBuffer());
});
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.validateBlockForSubmission.mockResolvedValueOnce(1n).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([await tx.getTxHash()]);
// Even though the block publish was not enqueued, we still send any requests
expect(publisher.sendRequests).toHaveBeenCalledTimes(1);
});
describe('proof quotes', () => {
let tx: Tx;
let txHash: TxHash;
let currentEpoch = 0n;
const setupForBlockNumber = async (blockNumber: number) => {
newBlockNumber = blockNumber;
newSlotNumber = blockNumber;
currentEpoch = BigInt(blockNumber) / BigInt(epochDuration);
globalVariables = new GlobalVariables(
chainId,
version,
new Fr(blockNumber),
new Fr(blockNumber),
Fr.ZERO,
coinbase,
feeRecipient,
gasFees,
);
worldState.status.mockResolvedValue({
state: WorldStateRunningState.IDLE,
syncedToL2Block: { number: blockNumber - 1, hash },
});
p2p.getStatus.mockResolvedValue({
state: P2PClientState.IDLE,
syncedToL2Block: { number: blockNumber - 1, hash },
});
l2BlockSource.getBlock.mockResolvedValue(L2Block.random(blockNumber - 1));
l2BlockSource.getBlockNumber.mockResolvedValue(blockNumber - 1);
l2BlockSource.getL2Tips.mockResolvedValue({
latest: { number: blockNumber - 1, hash },
proven: { number: 0, hash: undefined },
finalized: { number: 0, hash: undefined },
});
l1ToL2MessageSource.getBlockNumber.mockResolvedValue(blockNumber - 1);
globalVariableBuilder.buildGlobalVariables.mockResolvedValue(globalVariables);
publisher.enqueueClaimEpochProofRight.mockReturnValueOnce(true);
publisher.canProposeAtNextEthBlock.mockResolvedValue([BigInt(newSlotNumber), BigInt(blockNumber)]);
tx = await makeTx();
txHash = await tx.getTxHash();
mockPendingTxs([tx]);
block = await makeBlock([tx]);
};
const mockEpochProofQuote = (opts: { epoch?: bigint; validUntilSlot?: bigint; fee?: number } = {}) =>
baseMockEpochProofQuote(
opts.epoch ?? currentEpoch - 1n,
opts.validUntilSlot ?? block.header.globalVariables.slotNumber.toBigInt() + 1n,
10000n,
EthAddress.random(),
opts.fee ?? 1,
);
it('submits a valid proof quote with a block', async () => {
const blockNumber = epochDuration + 1;
await setupForBlockNumber(blockNumber);
const proofQuote = mockEpochProofQuote();
p2p.getEpochProofQuotes.mockResolvedValue([proofQuote]);
publisher.filterValidQuotes.mockImplementation(() => Promise.resolve([proofQuote]));
// The previous epoch can be claimed
publisher.getClaimableEpoch.mockImplementation(() => Promise.resolve(currentEpoch - 1n));
await sequencer.doRealWork();
expect(publisher.enqueueClaimEpochProofRight).toHaveBeenCalledWith(proofQuote);
expectPublisherProposeL2Block([txHash]);
});
it('submits a valid proof quote even without a block', async () => {
const blockNumber = epochDuration + 1;
await setupForBlockNumber(blockNumber);
// There are no txs!
mockPendingTxs([]);
const proofQuote = mockEpochProofQuote();
p2p.getEpochProofQuotes.mockResolvedValue([proofQuote]);
publisher.filterValidQuotes.mockImplementation(() => Promise.resolve([proofQuote]));
// The previous epoch can be claimed
publisher.getClaimableEpoch.mockImplementation(() => Promise.resolve(currentEpoch - 1n));
await sequencer.doRealWork();
expect(publisher.enqueueClaimEpochProofRight).toHaveBeenCalledWith(proofQuote);
expect(publisher.enqueueProposeL2Block).not.toHaveBeenCalled();
});
it('submits a valid proof quote if building a block proposal fails', async () => {
const blockNumber = epochDuration + 1;
await setupForBlockNumber(blockNumber);
const proofQuote = mockEpochProofQuote();
p2p.getEpochProofQuotes.mockResolvedValue([proofQuote]);
publisher.filterValidQuotes.mockImplementation(() => Promise.resolve([proofQuote]));
// The previous epoch can be claimed
publisher.getClaimableEpoch.mockImplementation(() => Promise.resolve(currentEpoch - 1n));
validatorClient.createBlockProposal.mockResolvedValue(undefined);
await sequencer.doRealWork();
expect(publisher.enqueueClaimEpochProofRight).toHaveBeenCalledWith(proofQuote);
expect(publisher.enqueueProposeL2Block).not.toHaveBeenCalled();
});
it('does not claim the epoch previous to the first', async () => {
const blockNumber = 1;
await setupForBlockNumber(blockNumber);
const proofQuote = mockEpochProofQuote({ epoch: 0n });
p2p.getEpochProofQuotes.mockResolvedValue([proofQuote]);
publisher.filterValidQuotes.mockImplementation(() => Promise.resolve([proofQuote]));
publisher.getClaimableEpoch.mockImplementation(() => Promise.resolve(undefined));
await sequencer.doRealWork();
expectPublisherProposeL2Block([txHash]);
});
it('does not submit a quote with an expired slot number', async () => {
const blockNumber = epochDuration + 1;
await setupForBlockNumber(blockNumber);
const expiredSlotNumber = block.header.globalVariables.slotNumber.toBigInt() - 1n;
const proofQuote = mockEpochProofQuote({ validUntilSlot: expiredSlotNumber });
p2p.getEpochProofQuotes.mockResolvedValue([proofQuote]);
publisher.filterValidQuotes.mockImplementation(() => Promise.resolve([proofQuote]));
// The previous epoch can be claimed
publisher.getClaimableEpoch.mockImplementation(() => Promise.resolve(currentEpoch - 1n));
await sequencer.doRealWork();
expectPublisherProposeL2Block([txHash]);
});
it('does not submit a valid quote if unable to claim epoch', async () => {
const blockNumber = epochDuration + 1;
await setupForBlockNumber(blockNumber);
const proofQuote = mockEpochProofQuote();
p2p.getEpochProofQuotes.mockResolvedValue([proofQuote]);
publisher.filterValidQuotes.mockImplementation(() => Promise.resolve([proofQuote]));
publisher.getClaimableEpoch.mockImplementation(() => Promise.resolve(undefined));
await sequencer.doRealWork();
expectPublisherProposeL2Block([txHash]);
});
it('does not submit an invalid quote', async () => {
const blockNumber = epochDuration + 1;
await setupForBlockNumber(blockNumber);
const proofQuote = mockEpochProofQuote();
p2p.getEpochProofQuotes.mockResolvedValue([proofQuote]);
publisher.enqueueProposeL2Block.mockResolvedValueOnce(true);
// Quote is reported as invalid
publisher.filterValidQuotes.mockImplementation(() => Promise.reject(new Error('Invalid proof quote')));
// The previous epoch can be claimed
publisher.getClaimableEpoch.mockImplementation(() => Promise.resolve(currentEpoch - 1n));
await sequencer.doRealWork();
expectPublisherProposeL2Block([txHash]);
});
it('selects the lowest cost valid quote', async () => {
const blockNumber = epochDuration + 1;
await setupForBlockNumber(blockNumber);
// Create 3 valid quotes with different fees.
// And 3 invalid quotes with lower fees
// We should select the lowest cost valid quote
const validQuotes = times(3, (i: number) => mockEpochProofQuote({ fee: 10 + i }));
const expiredSlot = block.header.globalVariables.slotNumber.toBigInt() - 1n;
const proofQuoteInvalidSlot = mockEpochProofQuote({ validUntilSlot: expiredSlot, fee: 1 });
const proofQuoteInvalidEpoch = mockEpochProofQuote({ epoch: currentEpoch, fee: 2 });
// This is deemed invalid by the contract, we identify it by its fee
const proofQuoteInvalid = mockEpochProofQuote({ fee: 3 });
const allQuotes = [proofQuoteInvalidSlot, proofQuoteInvalidEpoch, ...validQuotes, proofQuoteInvalid];
p2p.getEpochProofQuotes.mockResolvedValue(allQuotes);
publisher.enqueueProposeL2Block.mockResolvedValueOnce(true);
// Quote is reported as invalid
publisher.filterValidQuotes.mockImplementation(() => Promise.resolve(validQuotes));
// The previous epoch can be claimed
publisher.getClaimableEpoch.mockImplementation(() => Promise.resolve(currentEpoch - 1n));
await sequencer.doRealWork();
expect(publisher.enqueueClaimEpochProofRight).toHaveBeenCalledWith(validQuotes[0]);
expectPublisherProposeL2Block([txHash]);
});
});
});
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, 0n, true /** force */);
return super.doRealWork();
}
public override buildBlock(
pendingTxs: Iterable<Tx> | AsyncIterableIterator<Tx>,
newGlobalVariables: GlobalVariables,
opts?: { validateOnly?: boolean | undefined },
): Promise<{
block: L2Block;
publicGas: Gas;
publicProcessorDuration: number;
numMsgs: number;
numTxs: number;
numFailedTxs: number;
blockBuildingTimer: Timer;
}> {
return super.buildBlock(pendingTxs, newGlobalVariables, opts);
}
}