@aztec/world-state 0.0.1-commit.d3ec352c → 0.0.1-commit.fcb71a6

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.
Files changed (32) hide show
  1. package/dest/native/merkle_trees_facade.d.ts +8 -3
  2. package/dest/native/merkle_trees_facade.d.ts.map +1 -1
  3. package/dest/native/merkle_trees_facade.js +21 -3
  4. package/dest/native/message.d.ts +2 -2
  5. package/dest/native/message.d.ts.map +1 -1
  6. package/dest/native/message.js +1 -1
  7. package/dest/native/native_world_state.d.ts +6 -4
  8. package/dest/native/native_world_state.d.ts.map +1 -1
  9. package/dest/native/native_world_state.js +5 -4
  10. package/dest/synchronizer/server_world_state_synchronizer.d.ts +4 -2
  11. package/dest/synchronizer/server_world_state_synchronizer.d.ts.map +1 -1
  12. package/dest/synchronizer/server_world_state_synchronizer.js +17 -16
  13. package/dest/test/utils.d.ts +7 -13
  14. package/dest/test/utils.d.ts.map +1 -1
  15. package/dest/test/utils.js +42 -79
  16. package/dest/testing.d.ts +2 -2
  17. package/dest/testing.d.ts.map +1 -1
  18. package/dest/testing.js +1 -1
  19. package/dest/world-state-db/merkle_tree_db.d.ts +6 -8
  20. package/dest/world-state-db/merkle_tree_db.d.ts.map +1 -1
  21. package/package.json +10 -10
  22. package/src/native/merkle_trees_facade.ts +26 -2
  23. package/src/native/message.ts +1 -1
  24. package/src/native/native_world_state.ts +8 -7
  25. package/src/synchronizer/server_world_state_synchronizer.ts +24 -21
  26. package/src/test/utils.ts +68 -126
  27. package/src/testing.ts +1 -1
  28. package/src/world-state-db/merkle_tree_db.ts +9 -11
  29. package/dest/synchronizer/utils.d.ts +0 -11
  30. package/dest/synchronizer/utils.d.ts.map +0 -1
  31. package/dest/synchronizer/utils.js +0 -59
  32. package/src/synchronizer/utils.ts +0 -83
package/src/test/utils.ts CHANGED
@@ -4,81 +4,89 @@ import {
4
4
  NULLIFIER_SUBTREE_HEIGHT,
5
5
  NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP,
6
6
  } from '@aztec/constants';
7
- import { BlockNumber, type CheckpointNumber, SlotNumber } from '@aztec/foundation/branded-types';
7
+ import { asyncMap } from '@aztec/foundation/async-map';
8
+ import { BlockNumber, type CheckpointNumber } from '@aztec/foundation/branded-types';
8
9
  import { padArrayEnd } from '@aztec/foundation/collection';
9
- import { Fr } from '@aztec/foundation/fields';
10
+ import { Fr } from '@aztec/foundation/curves/bn254';
10
11
  import { L2BlockNew } from '@aztec/stdlib/block';
11
- import { Checkpoint } from '@aztec/stdlib/checkpoint';
12
12
  import type {
13
13
  IndexedTreeId,
14
14
  MerkleTreeReadOperations,
15
15
  MerkleTreeWriteOperations,
16
16
  } from '@aztec/stdlib/interfaces/server';
17
- import { computeInHashFromL1ToL2Messages } from '@aztec/stdlib/messaging';
17
+ import { mockCheckpointAndMessages, mockL1ToL2Messages } from '@aztec/stdlib/testing';
18
18
  import { AppendOnlyTreeSnapshot, MerkleTreeId } from '@aztec/stdlib/trees';
19
+ import { BlockHeader } from '@aztec/stdlib/tx';
19
20
 
20
21
  import type { NativeWorldStateService } from '../native/native_world_state.js';
21
22
 
22
- export async function mockBlock(
23
- blockNum: BlockNumber,
24
- size: number,
25
- fork: MerkleTreeWriteOperations,
26
- maxEffects: number | undefined = 1000, // Defaults to the maximum tx effects.
27
- numL1ToL2Messages: number = NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP,
28
- isFirstBlock: boolean = true,
29
- ) {
30
- const l2Block = await L2BlockNew.random(blockNum, { txsPerBlock: size, txOptions: { maxEffects } });
31
- const l1ToL2Messages = mockL1ToL2Messages(numL1ToL2Messages);
23
+ export async function updateBlockState(block: L2BlockNew, l1ToL2Messages: Fr[], fork: MerkleTreeWriteOperations) {
24
+ const insertData = async (
25
+ treeId: IndexedTreeId,
26
+ data: Buffer[][],
27
+ subTreeHeight: number,
28
+ fork: MerkleTreeWriteOperations,
29
+ ) => {
30
+ for (const dataBatch of data) {
31
+ await fork.batchInsert(treeId, dataBatch, subTreeHeight);
32
+ }
33
+ };
32
34
 
33
- {
34
- const insertData = async (
35
- treeId: IndexedTreeId,
36
- data: Buffer[][],
37
- subTreeHeight: number,
38
- fork: MerkleTreeWriteOperations,
39
- ) => {
40
- for (const dataBatch of data) {
41
- await fork.batchInsert(treeId, dataBatch, subTreeHeight);
42
- }
43
- };
44
-
45
- const publicDataInsert = insertData(
46
- MerkleTreeId.PUBLIC_DATA_TREE,
47
- l2Block.body.txEffects.map(txEffect => txEffect.publicDataWrites.map(write => write.toBuffer())),
48
- 0,
49
- fork,
50
- );
51
- const nullifierInsert = insertData(
52
- MerkleTreeId.NULLIFIER_TREE,
53
- l2Block.body.txEffects.map(txEffect =>
54
- padArrayEnd(txEffect.nullifiers, Fr.ZERO, MAX_NULLIFIERS_PER_TX).map(nullifier => nullifier.toBuffer()),
55
- ),
56
- NULLIFIER_SUBTREE_HEIGHT,
57
- fork,
58
- );
59
- const noteHashesPadded = l2Block.body.txEffects.flatMap(txEffect =>
60
- padArrayEnd(txEffect.noteHashes, Fr.ZERO, MAX_NOTE_HASHES_PER_TX),
61
- );
62
-
63
- const l1ToL2MessagesPadded = isFirstBlock
35
+ const publicDataInsert = insertData(
36
+ MerkleTreeId.PUBLIC_DATA_TREE,
37
+ block.body.txEffects.map(txEffect => txEffect.publicDataWrites.map(write => write.toBuffer())),
38
+ 0,
39
+ fork,
40
+ );
41
+ const nullifierInsert = insertData(
42
+ MerkleTreeId.NULLIFIER_TREE,
43
+ block.body.txEffects.map(txEffect =>
44
+ padArrayEnd(txEffect.nullifiers, Fr.ZERO, MAX_NULLIFIERS_PER_TX).map(nullifier => nullifier.toBuffer()),
45
+ ),
46
+ NULLIFIER_SUBTREE_HEIGHT,
47
+ fork,
48
+ );
49
+ const noteHashesPadded = block.body.txEffects.flatMap(txEffect =>
50
+ padArrayEnd(txEffect.noteHashes, Fr.ZERO, MAX_NOTE_HASHES_PER_TX),
51
+ );
52
+
53
+ const l1ToL2MessagesPadded =
54
+ block.indexWithinCheckpoint === 0
64
55
  ? padArrayEnd<Fr, number>(l1ToL2Messages, Fr.ZERO, NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP)
65
56
  : l1ToL2Messages;
66
57
 
67
- const noteHashInsert = fork.appendLeaves(MerkleTreeId.NOTE_HASH_TREE, noteHashesPadded);
68
- const messageInsert = fork.appendLeaves(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, l1ToL2MessagesPadded);
69
- await Promise.all([publicDataInsert, nullifierInsert, noteHashInsert, messageInsert]);
70
- }
58
+ const noteHashInsert = fork.appendLeaves(MerkleTreeId.NOTE_HASH_TREE, noteHashesPadded);
59
+ const messageInsert = fork.appendLeaves(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, l1ToL2MessagesPadded);
60
+ await Promise.all([publicDataInsert, nullifierInsert, noteHashInsert, messageInsert]);
71
61
 
72
62
  const state = await fork.getStateReference();
73
- l2Block.header.state = state;
74
- await fork.updateArchive(l2Block.header);
63
+ block.header = BlockHeader.from({ ...block.header, state });
64
+ await fork.updateArchive(block.header);
75
65
 
76
66
  const archiveState = await fork.getTreeInfo(MerkleTreeId.ARCHIVE);
77
67
 
78
- l2Block.archive = new AppendOnlyTreeSnapshot(Fr.fromBuffer(archiveState.root), Number(archiveState.size));
68
+ block.archive = new AppendOnlyTreeSnapshot(Fr.fromBuffer(archiveState.root), Number(archiveState.size));
69
+ }
70
+
71
+ export async function mockBlock(
72
+ blockNum: BlockNumber,
73
+ size: number,
74
+ fork: MerkleTreeWriteOperations,
75
+ maxEffects: number | undefined = 1000, // Defaults to the maximum tx effects.
76
+ numL1ToL2Messages: number = NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP,
77
+ isFirstBlockInCheckpoint: boolean = true,
78
+ ) {
79
+ const block = await L2BlockNew.random(blockNum, {
80
+ indexWithinCheckpoint: isFirstBlockInCheckpoint ? 0 : 1,
81
+ txsPerBlock: size,
82
+ txOptions: { maxEffects },
83
+ });
84
+ const l1ToL2Messages = mockL1ToL2Messages(numL1ToL2Messages);
85
+
86
+ await updateBlockState(block, l1ToL2Messages, fork);
79
87
 
80
88
  return {
81
- block: l2Block,
89
+ block,
82
90
  messages: l1ToL2Messages,
83
91
  };
84
92
  }
@@ -89,44 +97,7 @@ export async function mockEmptyBlock(blockNum: BlockNumber, fork: MerkleTreeWrit
89
97
 
90
98
  l2Block.header.globalVariables.blockNumber = blockNum;
91
99
 
92
- // Sync the append only trees
93
- {
94
- const noteHashesPadded = l2Block.body.txEffects.flatMap(txEffect =>
95
- padArrayEnd(txEffect.noteHashes, Fr.ZERO, MAX_NOTE_HASHES_PER_TX),
96
- );
97
- await fork.appendLeaves(MerkleTreeId.NOTE_HASH_TREE, noteHashesPadded);
98
-
99
- const l1ToL2MessagesPadded = padArrayEnd<Fr, number>(l1ToL2Messages, Fr.ZERO, NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP);
100
- await fork.appendLeaves(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, l1ToL2MessagesPadded);
101
- }
102
-
103
- // Sync the indexed trees
104
- {
105
- // We insert the public data tree leaves with one batch per tx to avoid updating the same key twice
106
- for (const txEffect of l2Block.body.txEffects) {
107
- await fork.batchInsert(
108
- MerkleTreeId.PUBLIC_DATA_TREE,
109
- txEffect.publicDataWrites.map(write => write.toBuffer()),
110
- 0,
111
- );
112
-
113
- const nullifiersPadded = padArrayEnd(txEffect.nullifiers, Fr.ZERO, MAX_NULLIFIERS_PER_TX);
114
-
115
- await fork.batchInsert(
116
- MerkleTreeId.NULLIFIER_TREE,
117
- nullifiersPadded.map(nullifier => nullifier.toBuffer()),
118
- NULLIFIER_SUBTREE_HEIGHT,
119
- );
120
- }
121
- }
122
-
123
- const state = await fork.getStateReference();
124
- l2Block.header.state = state;
125
- await fork.updateArchive(l2Block.header);
126
-
127
- const archiveState = await fork.getTreeInfo(MerkleTreeId.ARCHIVE);
128
-
129
- l2Block.archive = new AppendOnlyTreeSnapshot(Fr.fromBuffer(archiveState.root), Number(archiveState.size));
100
+ await updateBlockState(l2Block, l1ToL2Messages, fork);
130
101
 
131
102
  return {
132
103
  block: l2Block,
@@ -155,44 +126,15 @@ export async function mockBlocks(
155
126
  return { blocks, messages: messagesArray };
156
127
  }
157
128
 
158
- export function mockL1ToL2Messages(numL1ToL2Messages: number) {
159
- return Array(numL1ToL2Messages).fill(0).map(Fr.random);
160
- }
161
-
162
129
  export async function mockCheckpoint(
163
130
  checkpointNumber: CheckpointNumber,
164
- {
165
- startBlockNumber = BlockNumber(1),
166
- numBlocks = 1,
167
- numTxsPerBlock = 1,
168
- numL1ToL2Messages = 1,
169
- fork,
170
- }: {
171
- startBlockNumber?: BlockNumber;
172
- numBlocks?: number;
173
- numTxsPerBlock?: number;
174
- numL1ToL2Messages?: number;
175
- fork?: MerkleTreeWriteOperations;
176
- } = {},
131
+ fork: MerkleTreeWriteOperations,
132
+ options: Partial<Parameters<typeof mockCheckpointAndMessages>[1]> = {},
177
133
  ) {
178
- const slotNumber = SlotNumber(checkpointNumber * 10);
179
- const blocksAndMessages = [];
180
- for (let i = 0; i < numBlocks; i++) {
181
- const blockNumber = BlockNumber(startBlockNumber + i);
182
- const { block, messages } = fork
183
- ? await mockBlock(blockNumber, numTxsPerBlock, fork, blockNumber === startBlockNumber ? numL1ToL2Messages : 0)
184
- : {
185
- block: await L2BlockNew.random(blockNumber, { txsPerBlock: numTxsPerBlock, slotNumber }),
186
- messages: mockL1ToL2Messages(numL1ToL2Messages),
187
- };
188
- blocksAndMessages.push({ block, messages });
189
- }
190
-
191
- const messages = blocksAndMessages[0].messages;
192
- const inHash = computeInHashFromL1ToL2Messages(messages);
193
- const checkpoint = await Checkpoint.random(checkpointNumber, { numBlocks: 0, slotNumber, inHash });
194
- checkpoint.blocks = blocksAndMessages.map(({ block }) => block);
195
-
134
+ const { checkpoint, messages } = await mockCheckpointAndMessages(checkpointNumber, options);
135
+ await asyncMap(checkpoint.blocks, async (block, i) => {
136
+ await updateBlockState(block, i === 0 ? messages : [], fork);
137
+ });
196
138
  return { checkpoint, messages };
197
139
  }
198
140
 
package/src/testing.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { GENESIS_ARCHIVE_ROOT } from '@aztec/constants';
2
- import { Fr } from '@aztec/foundation/fields';
2
+ import { Fr } from '@aztec/foundation/curves/bn254';
3
3
  import { computeFeePayerBalanceLeafSlot } from '@aztec/protocol-contracts/fee-juice';
4
4
  import type { AztecAddress } from '@aztec/stdlib/aztec-address';
5
5
  import { MerkleTreeId, PublicDataTreeLeaf } from '@aztec/stdlib/trees';
@@ -1,9 +1,13 @@
1
1
  import { MAX_NULLIFIERS_PER_TX, MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX } from '@aztec/constants';
2
- import { BlockNumber } from '@aztec/foundation/branded-types';
3
- import type { Fr } from '@aztec/foundation/fields';
2
+ import type { BlockNumber } from '@aztec/foundation/branded-types';
3
+ import type { Fr } from '@aztec/foundation/curves/bn254';
4
4
  import type { IndexedTreeSnapshot, TreeSnapshot } from '@aztec/merkle-tree';
5
5
  import type { L2BlockNew } from '@aztec/stdlib/block';
6
- import type { ForkMerkleTreeOperations, MerkleTreeReadOperations } from '@aztec/stdlib/interfaces/server';
6
+ import type {
7
+ ForkMerkleTreeOperations,
8
+ MerkleTreeReadOperations,
9
+ ReadonlyWorldStateAccess,
10
+ } from '@aztec/stdlib/interfaces/server';
7
11
  import type { MerkleTreeId } from '@aztec/stdlib/trees';
8
12
 
9
13
  import type { WorldStateStatusFull, WorldStateStatusSummary } from '../native/message.js';
@@ -35,19 +39,13 @@ export type TreeSnapshots = {
35
39
  [MerkleTreeId.ARCHIVE]: TreeSnapshot<Fr>;
36
40
  };
37
41
 
38
- export interface MerkleTreeAdminDatabase extends ForkMerkleTreeOperations {
42
+ export interface MerkleTreeAdminDatabase extends ForkMerkleTreeOperations, ReadonlyWorldStateAccess {
39
43
  /**
40
44
  * Handles a single L2 block (i.e. Inserts the new note hashes into the merkle tree).
41
45
  * @param block - The L2 block to handle.
42
46
  * @param l1ToL2Messages - The L1 to L2 messages for the block.
43
- * @param isFirstBlock - Whether the block is the first block in a checkpoint. The messages are padded and inserted
44
- * to the tree for the first block in a checkpoint.
45
47
  */
46
- handleL2BlockAndMessages(
47
- block: L2BlockNew,
48
- l1ToL2Messages: Fr[],
49
- isFirstBlock: boolean,
50
- ): Promise<WorldStateStatusFull>;
48
+ handleL2BlockAndMessages(block: L2BlockNew, l1ToL2Messages: Fr[]): Promise<WorldStateStatusFull>;
51
49
 
52
50
  /**
53
51
  * Gets a handle that allows reading the latest committed state
@@ -1,11 +0,0 @@
1
- import type { Fr } from '@aztec/foundation/fields';
2
- import type { L2BlockNew, L2BlockSource } from '@aztec/stdlib/block';
3
- import { type L1ToL2MessageSource } from '@aztec/stdlib/messaging';
4
- /**
5
- * Determine which blocks in the given array are the first block in a checkpoint.
6
- * @param blocks - The candidate blocks, sorted by block number in ascending order.
7
- * @param l2BlockSource - The L2 block source to use to fetch the checkpoints, block headers and L1->L2 messages.
8
- * @returns A map of block numbers that begin a checkpoint to the L1->L2 messages for that checkpoint.
9
- */
10
- export declare function findFirstBlocksInCheckpoints(blocks: L2BlockNew[], l2BlockSource: L2BlockSource & L1ToL2MessageSource): Promise<Map<number, Fr[]>>;
11
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidXRpbHMuZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9zeW5jaHJvbml6ZXIvdXRpbHMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQ0EsT0FBTyxLQUFLLEVBQUUsRUFBRSxFQUFFLE1BQU0sMEJBQTBCLENBQUM7QUFDbkQsT0FBTyxLQUFLLEVBQUUsVUFBVSxFQUFFLGFBQWEsRUFBRSxNQUFNLHFCQUFxQixDQUFDO0FBRXJFLE9BQU8sRUFBRSxLQUFLLG1CQUFtQixFQUFtQyxNQUFNLHlCQUF5QixDQUFDO0FBRXBHOzs7OztHQUtHO0FBQ0gsd0JBQXNCLDRCQUE0QixDQUNoRCxNQUFNLEVBQUUsVUFBVSxFQUFFLEVBQ3BCLGFBQWEsRUFBRSxhQUFhLEdBQUcsbUJBQW1CLEdBQ2pELE9BQU8sQ0FBQyxHQUFHLENBQUMsTUFBTSxFQUFFLEVBQUUsRUFBRSxDQUFDLENBQUMsQ0FtRTVCIn0=
@@ -1 +0,0 @@
1
- {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/synchronizer/utils.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,0BAA0B,CAAC;AACnD,OAAO,KAAK,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAErE,OAAO,EAAE,KAAK,mBAAmB,EAAmC,MAAM,yBAAyB,CAAC;AAEpG;;;;;GAKG;AACH,wBAAsB,4BAA4B,CAChD,MAAM,EAAE,UAAU,EAAE,EACpB,aAAa,EAAE,aAAa,GAAG,mBAAmB,GACjD,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,EAAE,EAAE,CAAC,CAAC,CAmE5B"}
@@ -1,59 +0,0 @@
1
- import { BlockNumber } from '@aztec/foundation/branded-types';
2
- import { computeInHashFromL1ToL2Messages } from '@aztec/stdlib/messaging';
3
- /**
4
- * Determine which blocks in the given array are the first block in a checkpoint.
5
- * @param blocks - The candidate blocks, sorted by block number in ascending order.
6
- * @param l2BlockSource - The L2 block source to use to fetch the checkpoints, block headers and L1->L2 messages.
7
- * @returns A map of block numbers that begin a checkpoint to the L1->L2 messages for that checkpoint.
8
- */ export async function findFirstBlocksInCheckpoints(blocks, l2BlockSource) {
9
- // Select the blocks that are the final block within each group of identical slot numbers.
10
- let seenSlot;
11
- const maybeLastBlocks = [
12
- ...blocks
13
- ].reverse().filter((b)=>{
14
- if (b.header.globalVariables.slotNumber !== seenSlot) {
15
- seenSlot = b.header.globalVariables.slotNumber;
16
- return true;
17
- }
18
- return false;
19
- }).reverse();
20
- // Try to fetch the checkpoints for those blocks. If undefined (which should only occur for blocks.at(-1)),
21
- // then the block is not the last one in a checkpoint.
22
- // If we are not checking the inHashes below, only blocks.at(-1) would need its checkpoint header fetched.
23
- const checkpointedBlocks = (await Promise.all(maybeLastBlocks.map(async (b)=>({
24
- blockNumber: b.number,
25
- // A checkpoint's archive root is the archive root of its last block.
26
- checkpoint: await l2BlockSource.getCheckpointByArchive(b.archive.root)
27
- })))).filter((b)=>b.checkpoint !== undefined);
28
- // Verify that the L1->L2 messages hash to the checkpoint's inHash.
29
- const checkpointedL1ToL2Messages = await Promise.all(checkpointedBlocks.map((b)=>l2BlockSource.getL1ToL2MessagesForCheckpoint(b.checkpoint.number)));
30
- checkpointedBlocks.forEach((b, i)=>{
31
- const computedInHash = computeInHashFromL1ToL2Messages(checkpointedL1ToL2Messages[i]);
32
- const inHash = b.checkpoint.header.contentCommitment.inHash;
33
- if (!computedInHash.equals(inHash)) {
34
- throw new Error('Obtained L1 to L2 messages failed to be hashed to the checkpoint inHash');
35
- }
36
- });
37
- // Compute the first block numbers, which should be right after each checkpointed block. Exclude blocks that haven't
38
- // been added yet.
39
- const firstBlockNumbers = checkpointedBlocks.map((b)=>BlockNumber(b.blockNumber + 1)).filter((n)=>n <= blocks.at(-1).number);
40
- // Check if blocks[0] is the first block in a checkpoint.
41
- if (blocks[0].number === 1) {
42
- firstBlockNumbers.push(blocks[0].number);
43
- } else {
44
- const lastBlockHeader = await l2BlockSource.getBlockHeader(BlockNumber(blocks[0].number - 1));
45
- if (!lastBlockHeader) {
46
- throw new Error(`Failed to get block ${blocks[0].number - 1}`);
47
- }
48
- if (lastBlockHeader.globalVariables.slotNumber !== blocks[0].header.globalVariables.slotNumber) {
49
- firstBlockNumbers.push(blocks[0].number);
50
- }
51
- }
52
- // Fetch the L1->L2 messages for the first blocks and assign them to the map.
53
- const messagesByBlockNumber = new Map();
54
- await Promise.all(firstBlockNumbers.map(async (blockNumber)=>{
55
- const l1ToL2Messages = await l2BlockSource.getL1ToL2Messages(blockNumber);
56
- messagesByBlockNumber.set(blockNumber, l1ToL2Messages);
57
- }));
58
- return messagesByBlockNumber;
59
- }
@@ -1,83 +0,0 @@
1
- import { BlockNumber, type SlotNumber } from '@aztec/foundation/branded-types';
2
- import type { Fr } from '@aztec/foundation/fields';
3
- import type { L2BlockNew, L2BlockSource } from '@aztec/stdlib/block';
4
- import type { Checkpoint } from '@aztec/stdlib/checkpoint';
5
- import { type L1ToL2MessageSource, computeInHashFromL1ToL2Messages } from '@aztec/stdlib/messaging';
6
-
7
- /**
8
- * Determine which blocks in the given array are the first block in a checkpoint.
9
- * @param blocks - The candidate blocks, sorted by block number in ascending order.
10
- * @param l2BlockSource - The L2 block source to use to fetch the checkpoints, block headers and L1->L2 messages.
11
- * @returns A map of block numbers that begin a checkpoint to the L1->L2 messages for that checkpoint.
12
- */
13
- export async function findFirstBlocksInCheckpoints(
14
- blocks: L2BlockNew[],
15
- l2BlockSource: L2BlockSource & L1ToL2MessageSource,
16
- ): Promise<Map<number, Fr[]>> {
17
- // Select the blocks that are the final block within each group of identical slot numbers.
18
- let seenSlot: SlotNumber | undefined;
19
- const maybeLastBlocks = [...blocks]
20
- .reverse()
21
- .filter(b => {
22
- if (b.header.globalVariables.slotNumber !== seenSlot) {
23
- seenSlot = b.header.globalVariables.slotNumber;
24
- return true;
25
- }
26
- return false;
27
- })
28
- .reverse();
29
-
30
- // Try to fetch the checkpoints for those blocks. If undefined (which should only occur for blocks.at(-1)),
31
- // then the block is not the last one in a checkpoint.
32
- // If we are not checking the inHashes below, only blocks.at(-1) would need its checkpoint header fetched.
33
- const checkpointedBlocks = (
34
- await Promise.all(
35
- maybeLastBlocks.map(async b => ({
36
- blockNumber: b.number,
37
- // A checkpoint's archive root is the archive root of its last block.
38
- checkpoint: await l2BlockSource.getCheckpointByArchive(b.archive.root),
39
- })),
40
- )
41
- ).filter(b => b.checkpoint !== undefined) as { blockNumber: BlockNumber; checkpoint: Checkpoint }[];
42
-
43
- // Verify that the L1->L2 messages hash to the checkpoint's inHash.
44
- const checkpointedL1ToL2Messages: Fr[][] = await Promise.all(
45
- checkpointedBlocks.map(b => l2BlockSource.getL1ToL2MessagesForCheckpoint(b.checkpoint!.number)),
46
- );
47
- checkpointedBlocks.forEach((b, i) => {
48
- const computedInHash = computeInHashFromL1ToL2Messages(checkpointedL1ToL2Messages[i]);
49
- const inHash = b.checkpoint.header.contentCommitment.inHash;
50
- if (!computedInHash.equals(inHash)) {
51
- throw new Error('Obtained L1 to L2 messages failed to be hashed to the checkpoint inHash');
52
- }
53
- });
54
-
55
- // Compute the first block numbers, which should be right after each checkpointed block. Exclude blocks that haven't
56
- // been added yet.
57
- const firstBlockNumbers = checkpointedBlocks
58
- .map(b => BlockNumber(b.blockNumber + 1))
59
- .filter(n => n <= blocks.at(-1)!.number);
60
- // Check if blocks[0] is the first block in a checkpoint.
61
- if (blocks[0].number === 1) {
62
- firstBlockNumbers.push(blocks[0].number);
63
- } else {
64
- const lastBlockHeader = await l2BlockSource.getBlockHeader(BlockNumber(blocks[0].number - 1));
65
- if (!lastBlockHeader) {
66
- throw new Error(`Failed to get block ${blocks[0].number - 1}`);
67
- }
68
- if (lastBlockHeader.globalVariables.slotNumber !== blocks[0].header.globalVariables.slotNumber) {
69
- firstBlockNumbers.push(blocks[0].number);
70
- }
71
- }
72
-
73
- // Fetch the L1->L2 messages for the first blocks and assign them to the map.
74
- const messagesByBlockNumber = new Map<BlockNumber, Fr[]>();
75
- await Promise.all(
76
- firstBlockNumbers.map(async blockNumber => {
77
- const l1ToL2Messages = await l2BlockSource.getL1ToL2Messages(blockNumber);
78
- messagesByBlockNumber.set(blockNumber, l1ToL2Messages);
79
- }),
80
- );
81
-
82
- return messagesByBlockNumber;
83
- }