|
| 1 | +import type { Archiver } from '@aztec/archiver'; |
| 2 | +import type { AztecNodeService } from '@aztec/aztec-node'; |
| 3 | +import { AztecAddress, EthAddress } from '@aztec/aztec.js/addresses'; |
| 4 | +import { NO_WAIT } from '@aztec/aztec.js/contracts'; |
| 5 | +import { Fr } from '@aztec/aztec.js/fields'; |
| 6 | +import type { Logger } from '@aztec/aztec.js/log'; |
| 7 | +import { waitForTx } from '@aztec/aztec.js/node'; |
| 8 | +import { RollupContract } from '@aztec/ethereum/contracts'; |
| 9 | +import type { Operator } from '@aztec/ethereum/deploy-aztec-l1-contracts'; |
| 10 | +import { asyncMap } from '@aztec/foundation/async-map'; |
| 11 | +import { CheckpointNumber } from '@aztec/foundation/branded-types'; |
| 12 | +import { times, timesAsync } from '@aztec/foundation/collection'; |
| 13 | +import { SecretValue } from '@aztec/foundation/config'; |
| 14 | +import { bufferToHex } from '@aztec/foundation/string'; |
| 15 | +import { executeTimeout } from '@aztec/foundation/timer'; |
| 16 | +import { TestContract } from '@aztec/noir-test-contracts.js/Test'; |
| 17 | +import { TxStatus } from '@aztec/stdlib/tx'; |
| 18 | +import { TestWallet, proveInteraction } from '@aztec/test-wallet/server'; |
| 19 | + |
| 20 | +import { jest } from '@jest/globals'; |
| 21 | +import { privateKeyToAccount } from 'viem/accounts'; |
| 22 | + |
| 23 | +import { type EndToEndContext, getPrivateKeyFromIndex } from '../fixtures/utils.js'; |
| 24 | +import { EpochsTestContext } from './epochs_test.js'; |
| 25 | + |
| 26 | +jest.setTimeout(1000 * 60 * 15); |
| 27 | + |
| 28 | +const NODE_COUNT = 4; |
| 29 | +const EXPECTED_BLOCKS_PER_CHECKPOINT = 3; |
| 30 | + |
| 31 | +// Send enough transactions to trigger multiple blocks within a checkpoint assuming 2 txs per block. |
| 32 | +// If we start including txs at the 2nd block of a checkpoint, we can ensure a 3-block checkpoint |
| 33 | +// if we produce 10 txs: |
| 34 | +// - Checkpoint 1: Block 1 (0 txs), Block 2 (2 txs), Block 3 (2 txs) |
| 35 | +// - Checkpoint 2: Block 1 (2 txs), Block 2 (2 txs), Block 3 (2 txs) |
| 36 | +const TX_COUNT = 10; |
| 37 | + |
| 38 | +/** |
| 39 | + * E2E tests for Multiple Blocks Per Slot (MBPS) functionality. |
| 40 | + * Tests that the system correctly builds multiple blocks within a single slot/checkpoint. |
| 41 | + */ |
| 42 | +describe('e2e_epochs/epochs_mbps', () => { |
| 43 | + let context: EndToEndContext; |
| 44 | + let logger: Logger; |
| 45 | + let rollup: RollupContract; |
| 46 | + let archiver: Archiver; |
| 47 | + |
| 48 | + let test: EpochsTestContext; |
| 49 | + let validators: (Operator & { privateKey: `0x${string}` })[]; |
| 50 | + let nodes: AztecNodeService[]; |
| 51 | + let contract: TestContract; |
| 52 | + let wallet: TestWallet; |
| 53 | + let from: AztecAddress; |
| 54 | + |
| 55 | + /** |
| 56 | + * Creates validators and sets up the test context with MBPS configuration. |
| 57 | + */ |
| 58 | + async function setupTest(opts: { |
| 59 | + syncChainTip: 'proposed' | 'checkpointed'; |
| 60 | + minTxsPerBlock?: number; |
| 61 | + maxTxsPerBlock?: number; |
| 62 | + buildCheckpointIfEmpty?: boolean; |
| 63 | + }) { |
| 64 | + const { syncChainTip = 'checkpointed', ...setupOpts } = opts; |
| 65 | + |
| 66 | + validators = times(NODE_COUNT, i => { |
| 67 | + const privateKey = bufferToHex(getPrivateKeyFromIndex(i + 3)!); |
| 68 | + const attester = EthAddress.fromString(privateKeyToAccount(privateKey).address); |
| 69 | + return { attester, withdrawer: attester, privateKey, bn254SecretKey: new SecretValue(Fr.random().toBigInt()) }; |
| 70 | + }); |
| 71 | + |
| 72 | + // Setup context with the given set of validators and MBPS configuration. |
| 73 | + // Timing calculation for 3 blocks per checkpoint with 8s sub-slots: |
| 74 | + // - initializationOffset ≈ 0.5s (test mode with ethereumSlotDuration < 8) |
| 75 | + // - 3 blocks × 8s = 24s |
| 76 | + // - checkpointFinalization = 0.5s (assemble) + 0 (p2p in test) + 2s (L1 publish) = 2.5s |
| 77 | + // - finalBlockDuration = 8s |
| 78 | + // - Total: 0.5 + 24 + 8 + 2.5 = 35s → use 36s for margin |
| 79 | + test = await EpochsTestContext.setup({ |
| 80 | + numberOfAccounts: 1, |
| 81 | + initialValidators: validators, |
| 82 | + mockGossipSubNetwork: true, |
| 83 | + disableAnvilTestWatcher: true, |
| 84 | + aztecProofSubmissionEpochs: 1024, |
| 85 | + startProverNode: false, |
| 86 | + enforceTimeTable: true, |
| 87 | + // L1 slot duration - using < 8 to enable test mode optimizations |
| 88 | + ethereumSlotDuration: 4, |
| 89 | + // L2 slot duration - should fit 3 blocks (8s each) + overhead |
| 90 | + aztecSlotDuration: 36, |
| 91 | + // Block duration of 8s as specified |
| 92 | + blockDurationMs: 8000, |
| 93 | + // L1 publishing time |
| 94 | + l1PublishingTime: 2, |
| 95 | + // Reduce attestation propagation time for tests |
| 96 | + attestationPropagationTime: 0.5, |
| 97 | + // Committee size of 3 |
| 98 | + aztecTargetCommitteeSize: 3, |
| 99 | + // Additional options (minTxsPerBlock, maxTxsPerBlock, etc.) |
| 100 | + ...setupOpts, |
| 101 | + // PXE options for chain tip syncing |
| 102 | + pxeOpts: { syncChainTip }, |
| 103 | + }); |
| 104 | + |
| 105 | + ({ context, logger, rollup } = test); |
| 106 | + wallet = context.wallet; |
| 107 | + archiver = (context.aztecNode as AztecNodeService).getBlockSource() as Archiver; |
| 108 | + from = context.accounts[0]; |
| 109 | + |
| 110 | + // Halt block building in initial aztec node, which was not set up as a validator. |
| 111 | + logger.warn(`Stopping sequencer in initial aztec node.`); |
| 112 | + await context.sequencer!.stop(); |
| 113 | + |
| 114 | + // Start the validator nodes (but don't start sequencers yet) |
| 115 | + logger.warn(`Initial setup complete. Starting ${NODE_COUNT} validator nodes.`); |
| 116 | + nodes = await asyncMap(validators, ({ privateKey }) => |
| 117 | + test.createValidatorNode([privateKey], { dontStartSequencer: true }), |
| 118 | + ); |
| 119 | + logger.warn(`Started ${NODE_COUNT} validator nodes.`, { validators: validators.map(v => v.attester.toString()) }); |
| 120 | + |
| 121 | + // Register contract for sending txs. |
| 122 | + contract = await test.registerTestContract(wallet); |
| 123 | + logger.warn(`Test setup completed.`, { validators: validators.map(v => v.attester.toString()) }); |
| 124 | + } |
| 125 | + |
| 126 | + /** Retrieves all checkpoints from the archiver and checks that one of them at least has the target block count */ |
| 127 | + async function assertMultipleBlocksPerSlot(targetBlockCount: number, logger: Logger) { |
| 128 | + const checkpoints = await archiver.getCheckpoints(CheckpointNumber(1), 50); |
| 129 | + logger.warn(`Retrieved ${checkpoints.length} checkpoints from archiver`, { |
| 130 | + checkpoints: checkpoints.map(pc => pc.checkpoint.getStats()), |
| 131 | + }); |
| 132 | + |
| 133 | + let expectedBlockNumber = checkpoints[0].checkpoint.blocks[0].number; |
| 134 | + let targetFound = false; |
| 135 | + |
| 136 | + for (const checkpoint of checkpoints) { |
| 137 | + const blockCount = checkpoint.checkpoint.blocks.length; |
| 138 | + targetFound = targetFound || blockCount >= targetBlockCount; |
| 139 | + logger.warn(`Checkpoint ${checkpoint.checkpoint.number} has ${blockCount} blocks`, { |
| 140 | + checkpoint: checkpoint.checkpoint.getStats(), |
| 141 | + }); |
| 142 | + |
| 143 | + for (let i = 0; i < blockCount; i++) { |
| 144 | + const block = checkpoint.checkpoint.blocks[i]; |
| 145 | + expect(block.indexWithinCheckpoint).toBe(i); |
| 146 | + expect(block.checkpointNumber).toBe(checkpoint.checkpoint.number); |
| 147 | + expect(block.number).toBe(expectedBlockNumber); |
| 148 | + expectedBlockNumber++; |
| 149 | + } |
| 150 | + } |
| 151 | + |
| 152 | + expect(targetFound).toBe(true); |
| 153 | + } |
| 154 | + |
| 155 | + afterEach(async () => { |
| 156 | + jest.restoreAllMocks(); |
| 157 | + await test?.teardown(); |
| 158 | + }); |
| 159 | + |
| 160 | + it('builds multiple blocks per slot with transactions anchored to checkpointed block', async () => { |
| 161 | + await setupTest({ syncChainTip: 'checkpointed', minTxsPerBlock: 1, maxTxsPerBlock: 2 }); |
| 162 | + |
| 163 | + // Record the current checkpoint number before starting sequencers |
| 164 | + const initialCheckpointNumber = await rollup.getCheckpointNumber(); |
| 165 | + logger.warn(`Initial checkpoint number: ${initialCheckpointNumber}`); |
| 166 | + |
| 167 | + // Pre-prove and send transactions |
| 168 | + const txs = await timesAsync(TX_COUNT, i => |
| 169 | + proveInteraction(context.wallet, contract.methods.emit_nullifier(new Fr(i + 1)), { from }), |
| 170 | + ); |
| 171 | + const txHashes = await Promise.all(txs.map(tx => tx.send({ wait: NO_WAIT }))); |
| 172 | + logger.warn(`Sent ${txHashes.length} transactions`, { txs: txHashes }); |
| 173 | + |
| 174 | + // Start the sequencers |
| 175 | + await Promise.all(nodes.map(n => n.getSequencer()!.start())); |
| 176 | + logger.warn(`Started all sequencers`); |
| 177 | + |
| 178 | + // Wait until all txs are mined |
| 179 | + const timeout = test.L2_SLOT_DURATION_IN_S * 5; |
| 180 | + await executeTimeout( |
| 181 | + () => Promise.all(txHashes.map(txHash => waitForTx(context.aztecNode, txHash, { timeout }))), |
| 182 | + timeout * 1000, |
| 183 | + ); |
| 184 | + logger.warn(`All txs have been mined`); |
| 185 | + |
| 186 | + await assertMultipleBlocksPerSlot(EXPECTED_BLOCKS_PER_CHECKPOINT, logger); |
| 187 | + }); |
| 188 | + |
| 189 | + it('builds multiple blocks per slot with transactions anchored to proposed blocks', async () => { |
| 190 | + await setupTest({ syncChainTip: 'proposed', minTxsPerBlock: 1, maxTxsPerBlock: 1 }); |
| 191 | + |
| 192 | + // Record the current checkpoint number before starting sequencers |
| 193 | + const initialCheckpointNumber = await rollup.getCheckpointNumber(); |
| 194 | + logger.warn(`Initial checkpoint number: ${initialCheckpointNumber}`); |
| 195 | + |
| 196 | + // Start the sequencers |
| 197 | + await Promise.all(nodes.map(n => n.getSequencer()!.start())); |
| 198 | + logger.warn(`Started all sequencers`); |
| 199 | + |
| 200 | + // Now send the txs and wait for them to be mined one at a time |
| 201 | + // If the pxe syncs correctly, every tx should be anchored to the block in which the previous one was mined |
| 202 | + const txReceipts = []; |
| 203 | + let expectedAnchorBlockNumber = undefined; |
| 204 | + |
| 205 | + while (txReceipts.length < TX_COUNT / 2) { |
| 206 | + logger.warn(`Sending transaction ${txReceipts.length}`); |
| 207 | + const nullifier = new Fr(txReceipts.length + 1); |
| 208 | + const tx = await proveInteraction(context.wallet, contract.methods.emit_nullifier(nullifier), { from }); |
| 209 | + const txAnchorBlockNumber = tx.data.constants.anchorBlockHeader.globalVariables.blockNumber; |
| 210 | + expect(txAnchorBlockNumber).toBeGreaterThanOrEqual(expectedAnchorBlockNumber ?? txAnchorBlockNumber); |
| 211 | + |
| 212 | + const txReceipt = await tx.send({ wait: { waitForStatus: TxStatus.PROPOSED } }); |
| 213 | + txReceipts.push(txReceipt); |
| 214 | + expectedAnchorBlockNumber = txReceipt.blockNumber; |
| 215 | + logger.warn(`Transaction ${txReceipts.length} mined on block ${txReceipt.blockNumber}`, { txReceipt }); |
| 216 | + |
| 217 | + await wallet.sync(); |
| 218 | + expect((await wallet.getSyncedBlockHeader()).getBlockNumber()).toBeGreaterThanOrEqual(txReceipt.blockNumber!); |
| 219 | + } |
| 220 | + logger.warn(`All txs have been mined`); |
| 221 | + |
| 222 | + // We are fine with at least 2 blocks per checkpoint, since we may lose one sub-slot if assembling a tx is slow |
| 223 | + await assertMultipleBlocksPerSlot(2, logger); |
| 224 | + }); |
| 225 | +}); |
0 commit comments