@aztec/world-state 0.0.1-commit.9b94fc1 → 0.0.1-commit.9badcec54

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 (50) hide show
  1. package/dest/instrumentation/instrumentation.d.ts +1 -1
  2. package/dest/instrumentation/instrumentation.d.ts.map +1 -1
  3. package/dest/instrumentation/instrumentation.js +17 -41
  4. package/dest/native/fork_checkpoint.d.ts +7 -1
  5. package/dest/native/fork_checkpoint.d.ts.map +1 -1
  6. package/dest/native/fork_checkpoint.js +15 -3
  7. package/dest/native/merkle_trees_facade.d.ts +15 -8
  8. package/dest/native/merkle_trees_facade.d.ts.map +1 -1
  9. package/dest/native/merkle_trees_facade.js +53 -15
  10. package/dest/native/message.d.ts +24 -15
  11. package/dest/native/message.d.ts.map +1 -1
  12. package/dest/native/message.js +14 -13
  13. package/dest/native/native_world_state.d.ts +19 -14
  14. package/dest/native/native_world_state.d.ts.map +1 -1
  15. package/dest/native/native_world_state.js +31 -21
  16. package/dest/native/native_world_state_instance.d.ts +5 -5
  17. package/dest/native/native_world_state_instance.d.ts.map +1 -1
  18. package/dest/native/native_world_state_instance.js +8 -7
  19. package/dest/native/world_state_ops_queue.js +5 -5
  20. package/dest/synchronizer/config.d.ts +3 -5
  21. package/dest/synchronizer/config.d.ts.map +1 -1
  22. package/dest/synchronizer/config.js +14 -16
  23. package/dest/synchronizer/factory.d.ts +6 -5
  24. package/dest/synchronizer/factory.d.ts.map +1 -1
  25. package/dest/synchronizer/factory.js +6 -5
  26. package/dest/synchronizer/server_world_state_synchronizer.d.ts +11 -17
  27. package/dest/synchronizer/server_world_state_synchronizer.d.ts.map +1 -1
  28. package/dest/synchronizer/server_world_state_synchronizer.js +162 -81
  29. package/dest/test/utils.d.ts +12 -5
  30. package/dest/test/utils.d.ts.map +1 -1
  31. package/dest/test/utils.js +54 -50
  32. package/dest/testing.d.ts +5 -4
  33. package/dest/testing.d.ts.map +1 -1
  34. package/dest/testing.js +11 -7
  35. package/dest/world-state-db/merkle_tree_db.d.ts +10 -20
  36. package/dest/world-state-db/merkle_tree_db.d.ts.map +1 -1
  37. package/package.json +12 -13
  38. package/src/instrumentation/instrumentation.ts +17 -41
  39. package/src/native/fork_checkpoint.ts +19 -3
  40. package/src/native/merkle_trees_facade.ts +62 -16
  41. package/src/native/message.ts +37 -26
  42. package/src/native/native_world_state.ts +52 -34
  43. package/src/native/native_world_state_instance.ts +14 -8
  44. package/src/native/world_state_ops_queue.ts +5 -5
  45. package/src/synchronizer/config.ts +15 -26
  46. package/src/synchronizer/factory.ts +13 -7
  47. package/src/synchronizer/server_world_state_synchronizer.ts +184 -106
  48. package/src/test/utils.ts +86 -91
  49. package/src/testing.ts +9 -10
  50. package/src/world-state-db/merkle_tree_db.ts +13 -24
@@ -1,37 +1,51 @@
1
1
  import { MAX_NOTE_HASHES_PER_TX, MAX_NULLIFIERS_PER_TX, NULLIFIER_SUBTREE_HEIGHT, NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP } from '@aztec/constants';
2
+ import { asyncMap } from '@aztec/foundation/async-map';
3
+ import { BlockNumber, IndexWithinCheckpoint } from '@aztec/foundation/branded-types';
2
4
  import { padArrayEnd } from '@aztec/foundation/collection';
3
- import { Fr } from '@aztec/foundation/fields';
5
+ import { Fr } from '@aztec/foundation/curves/bn254';
4
6
  import { L2Block } from '@aztec/stdlib/block';
7
+ import { mockCheckpointAndMessages, mockL1ToL2Messages } from '@aztec/stdlib/testing';
5
8
  import { AppendOnlyTreeSnapshot, MerkleTreeId } from '@aztec/stdlib/trees';
6
- export async function mockBlock(blockNum, size, fork, maxEffects = 1000) {
7
- const l2Block = await L2Block.random(blockNum, size, undefined, undefined, undefined, undefined, maxEffects);
8
- const l1ToL2Messages = Array(NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP).fill(0).map(Fr.random);
9
- {
10
- const insertData = async (treeId, data, subTreeHeight, fork)=>{
11
- for (const dataBatch of data){
12
- await fork.batchInsert(treeId, dataBatch, subTreeHeight);
13
- }
14
- };
15
- const publicDataInsert = insertData(MerkleTreeId.PUBLIC_DATA_TREE, l2Block.body.txEffects.map((txEffect)=>txEffect.publicDataWrites.map((write)=>write.toBuffer())), 0, fork);
16
- const nullifierInsert = insertData(MerkleTreeId.NULLIFIER_TREE, l2Block.body.txEffects.map((txEffect)=>padArrayEnd(txEffect.nullifiers, Fr.ZERO, MAX_NULLIFIERS_PER_TX).map((nullifier)=>nullifier.toBuffer())), NULLIFIER_SUBTREE_HEIGHT, fork);
17
- const noteHashesPadded = l2Block.body.txEffects.flatMap((txEffect)=>padArrayEnd(txEffect.noteHashes, Fr.ZERO, MAX_NOTE_HASHES_PER_TX));
18
- const l1ToL2MessagesPadded = padArrayEnd(l1ToL2Messages, Fr.ZERO, NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP);
19
- const noteHashInsert = fork.appendLeaves(MerkleTreeId.NOTE_HASH_TREE, noteHashesPadded);
20
- const messageInsert = fork.appendLeaves(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, l1ToL2MessagesPadded);
21
- await Promise.all([
22
- publicDataInsert,
23
- nullifierInsert,
24
- noteHashInsert,
25
- messageInsert
26
- ]);
27
- }
9
+ import { BlockHeader } from '@aztec/stdlib/tx';
10
+ export async function updateBlockState(block, l1ToL2Messages, fork) {
11
+ const insertData = async (treeId, data, subTreeHeight, fork)=>{
12
+ for (const dataBatch of data){
13
+ await fork.batchInsert(treeId, dataBatch, subTreeHeight);
14
+ }
15
+ };
16
+ const publicDataInsert = insertData(MerkleTreeId.PUBLIC_DATA_TREE, block.body.txEffects.map((txEffect)=>txEffect.publicDataWrites.map((write)=>write.toBuffer())), 0, fork);
17
+ const nullifierInsert = insertData(MerkleTreeId.NULLIFIER_TREE, block.body.txEffects.map((txEffect)=>padArrayEnd(txEffect.nullifiers, Fr.ZERO, MAX_NULLIFIERS_PER_TX).map((nullifier)=>nullifier.toBuffer())), NULLIFIER_SUBTREE_HEIGHT, fork);
18
+ const noteHashesPadded = block.body.txEffects.flatMap((txEffect)=>padArrayEnd(txEffect.noteHashes, Fr.ZERO, MAX_NOTE_HASHES_PER_TX));
19
+ const l1ToL2MessagesPadded = block.indexWithinCheckpoint === 0 ? padArrayEnd(l1ToL2Messages, Fr.ZERO, NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP) : l1ToL2Messages;
20
+ const noteHashInsert = fork.appendLeaves(MerkleTreeId.NOTE_HASH_TREE, noteHashesPadded);
21
+ const messageInsert = fork.appendLeaves(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, l1ToL2MessagesPadded);
22
+ await Promise.all([
23
+ publicDataInsert,
24
+ nullifierInsert,
25
+ noteHashInsert,
26
+ messageInsert
27
+ ]);
28
28
  const state = await fork.getStateReference();
29
- l2Block.header.state = state;
30
- await fork.updateArchive(l2Block.getBlockHeader());
29
+ block.header = BlockHeader.from({
30
+ ...block.header,
31
+ state
32
+ });
33
+ await fork.updateArchive(block.header);
31
34
  const archiveState = await fork.getTreeInfo(MerkleTreeId.ARCHIVE);
32
- l2Block.archive = new AppendOnlyTreeSnapshot(Fr.fromBuffer(archiveState.root), Number(archiveState.size));
35
+ block.archive = new AppendOnlyTreeSnapshot(Fr.fromBuffer(archiveState.root), Number(archiveState.size));
36
+ }
37
+ export async function mockBlock(blockNum, size, fork, maxEffects = 1000, numL1ToL2Messages = NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP, isFirstBlockInCheckpoint = true) {
38
+ const block = await L2Block.random(blockNum, {
39
+ indexWithinCheckpoint: isFirstBlockInCheckpoint ? IndexWithinCheckpoint(0) : IndexWithinCheckpoint(1),
40
+ txsPerBlock: size,
41
+ txOptions: {
42
+ maxEffects
43
+ }
44
+ });
45
+ const l1ToL2Messages = mockL1ToL2Messages(numL1ToL2Messages);
46
+ await updateBlockState(block, l1ToL2Messages, fork);
33
47
  return {
34
- block: l2Block,
48
+ block,
35
49
  messages: l1ToL2Messages
36
50
  };
37
51
  }
@@ -39,38 +53,18 @@ export async function mockEmptyBlock(blockNum, fork) {
39
53
  const l2Block = L2Block.empty();
40
54
  const l1ToL2Messages = Array(16).fill(0).map(Fr.zero);
41
55
  l2Block.header.globalVariables.blockNumber = blockNum;
42
- // Sync the append only trees
43
- {
44
- const noteHashesPadded = l2Block.body.txEffects.flatMap((txEffect)=>padArrayEnd(txEffect.noteHashes, Fr.ZERO, MAX_NOTE_HASHES_PER_TX));
45
- await fork.appendLeaves(MerkleTreeId.NOTE_HASH_TREE, noteHashesPadded);
46
- const l1ToL2MessagesPadded = padArrayEnd(l1ToL2Messages, Fr.ZERO, NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP);
47
- await fork.appendLeaves(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, l1ToL2MessagesPadded);
48
- }
49
- // Sync the indexed trees
50
- {
51
- // We insert the public data tree leaves with one batch per tx to avoid updating the same key twice
52
- for (const txEffect of l2Block.body.txEffects){
53
- await fork.batchInsert(MerkleTreeId.PUBLIC_DATA_TREE, txEffect.publicDataWrites.map((write)=>write.toBuffer()), 0);
54
- const nullifiersPadded = padArrayEnd(txEffect.nullifiers, Fr.ZERO, MAX_NULLIFIERS_PER_TX);
55
- await fork.batchInsert(MerkleTreeId.NULLIFIER_TREE, nullifiersPadded.map((nullifier)=>nullifier.toBuffer()), NULLIFIER_SUBTREE_HEIGHT);
56
- }
57
- }
58
- const state = await fork.getStateReference();
59
- l2Block.header.state = state;
60
- await fork.updateArchive(l2Block.getBlockHeader());
61
- const archiveState = await fork.getTreeInfo(MerkleTreeId.ARCHIVE);
62
- l2Block.archive = new AppendOnlyTreeSnapshot(Fr.fromBuffer(archiveState.root), Number(archiveState.size));
56
+ await updateBlockState(l2Block, l1ToL2Messages, fork);
63
57
  return {
64
58
  block: l2Block,
65
59
  messages: l1ToL2Messages
66
60
  };
67
61
  }
68
62
  export async function mockBlocks(from, count, numTxs, worldState) {
69
- const tempFork = await worldState.fork(from - 1);
63
+ const tempFork = await worldState.fork(BlockNumber(from - 1));
70
64
  const blocks = [];
71
65
  const messagesArray = [];
72
66
  for(let blockNumber = from; blockNumber < from + count; blockNumber++){
73
- const { block, messages } = await mockBlock(blockNumber, numTxs, tempFork);
67
+ const { block, messages } = await mockBlock(BlockNumber(blockNumber), numTxs, tempFork);
74
68
  blocks.push(block);
75
69
  messagesArray.push(messages);
76
70
  }
@@ -80,6 +74,16 @@ export async function mockBlocks(from, count, numTxs, worldState) {
80
74
  messages: messagesArray
81
75
  };
82
76
  }
77
+ export async function mockCheckpoint(checkpointNumber, fork, options = {}) {
78
+ const { checkpoint, messages } = await mockCheckpointAndMessages(checkpointNumber, options);
79
+ await asyncMap(checkpoint.blocks, async (block, i)=>{
80
+ await updateBlockState(block, i === 0 ? messages : [], fork);
81
+ });
82
+ return {
83
+ checkpoint,
84
+ messages
85
+ };
86
+ }
83
87
  export async function assertSameState(forkA, forkB) {
84
88
  const nativeStateRef = await forkA.getStateReference();
85
89
  const nativeArchive = await forkA.getTreeInfo(MerkleTreeId.ARCHIVE);
package/dest/testing.d.ts CHANGED
@@ -1,10 +1,11 @@
1
- import { Fr } from '@aztec/foundation/fields';
1
+ import { Fr } from '@aztec/foundation/curves/bn254';
2
2
  import type { AztecAddress } from '@aztec/stdlib/aztec-address';
3
3
  import { PublicDataTreeLeaf } from '@aztec/stdlib/trees';
4
+ import type { GenesisData } from '@aztec/stdlib/world-state';
4
5
  export declare const defaultInitialAccountFeeJuice: Fr;
5
- export declare function getGenesisValues(initialAccounts: AztecAddress[], initialAccountFeeJuice?: Fr, genesisPublicData?: PublicDataTreeLeaf[]): Promise<{
6
+ export declare function getGenesisValues(initialAccounts: AztecAddress[], initialAccountFeeJuice?: Fr, genesisPublicData?: PublicDataTreeLeaf[], genesisTimestamp?: bigint): Promise<{
6
7
  genesisArchiveRoot: Fr;
7
- prefilledPublicData: PublicDataTreeLeaf[];
8
+ genesis: GenesisData;
8
9
  fundingNeeded: bigint;
9
10
  }>;
10
- //# sourceMappingURL=data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MvQixzQkFBc0IsS0FBZ0MsRUFDdEQsaUJBQWlCLEdBQUUsa0JBQWtCLEVBQU8sRUFDNUMsZ0JBQWdCLEdBQUUsTUFBVzs7OztHQXNCOUIifQ==
@@ -1 +1 @@
1
- {"version":3,"file":"testing.d.ts","sourceRoot":"","sources":["../src/testing.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,EAAE,EAAE,MAAM,0BAA0B,CAAC;AAE9C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAChE,OAAO,EAAgB,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAyBvE,eAAO,MAAM,6BAA6B,IAAqB,CAAC;AAEhE,wBAAsB,gBAAgB,CACpC,eAAe,EAAE,YAAY,EAAE,EAC/B,sBAAsB,KAAgC,EACtD,iBAAiB,GAAE,kBAAkB,EAAO;;;;GAqB7C"}
1
+ {"version":3,"file":"testing.d.ts","sourceRoot":"","sources":["../src/testing.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,EAAE,EAAE,MAAM,gCAAgC,CAAC;AAEpD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAChE,OAAO,EAAgB,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AACvE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AAqB7D,eAAO,MAAM,6BAA6B,IAAqB,CAAC;AAEhE,wBAAsB,gBAAgB,CACpC,eAAe,EAAE,YAAY,EAAE,EAC/B,sBAAsB,KAAgC,EACtD,iBAAiB,GAAE,kBAAkB,EAAO,EAC5C,gBAAgB,GAAE,MAAW;;;;GAsB9B"}
package/dest/testing.js CHANGED
@@ -1,16 +1,16 @@
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 { MerkleTreeId, PublicDataTreeLeaf } from '@aztec/stdlib/trees';
5
5
  import { NativeWorldStateService } from './native/index.js';
6
- async function generateGenesisValues(prefilledPublicData) {
7
- if (!prefilledPublicData.length) {
6
+ async function generateGenesisValues(genesis) {
7
+ if (!genesis.prefilledPublicData.length && genesis.genesisTimestamp === 0n) {
8
8
  return {
9
9
  genesisArchiveRoot: new Fr(GENESIS_ARCHIVE_ROOT)
10
10
  };
11
11
  }
12
12
  // Create a temporary world state to compute the genesis values.
13
- const ws = await NativeWorldStateService.tmp(undefined /* rollupAddress */ , true, prefilledPublicData);
13
+ const ws = await NativeWorldStateService.tmp(undefined /* rollupAddress */ , true, genesis);
14
14
  const genesisArchiveRoot = new Fr((await ws.getCommitted().getTreeInfo(MerkleTreeId.ARCHIVE)).root);
15
15
  await ws.close();
16
16
  return {
@@ -18,16 +18,20 @@ async function generateGenesisValues(prefilledPublicData) {
18
18
  };
19
19
  }
20
20
  export const defaultInitialAccountFeeJuice = new Fr(10n ** 22n);
21
- export async function getGenesisValues(initialAccounts, initialAccountFeeJuice = defaultInitialAccountFeeJuice, genesisPublicData = []) {
21
+ export async function getGenesisValues(initialAccounts, initialAccountFeeJuice = defaultInitialAccountFeeJuice, genesisPublicData = [], genesisTimestamp = 0n) {
22
22
  // Top up the accounts with fee juice.
23
23
  let prefilledPublicData = await Promise.all(initialAccounts.map(async (address)=>new PublicDataTreeLeaf(await computeFeePayerBalanceLeafSlot(address), initialAccountFeeJuice)));
24
24
  // Add user-defined public data
25
25
  prefilledPublicData = prefilledPublicData.concat(genesisPublicData);
26
26
  prefilledPublicData.sort((a, b)=>b.slot.lt(a.slot) ? 1 : -1);
27
- const { genesisArchiveRoot } = await generateGenesisValues(prefilledPublicData);
27
+ const genesis = {
28
+ prefilledPublicData,
29
+ genesisTimestamp
30
+ };
31
+ const { genesisArchiveRoot } = await generateGenesisValues(genesis);
28
32
  return {
29
33
  genesisArchiveRoot,
30
- prefilledPublicData,
34
+ genesis,
31
35
  fundingNeeded: BigInt(initialAccounts.length) * initialAccountFeeJuice.toBigInt()
32
36
  };
33
37
  }
@@ -1,8 +1,7 @@
1
- import type { Fr } from '@aztec/foundation/fields';
2
- import type { IndexedTreeSnapshot, TreeSnapshot } from '@aztec/merkle-tree';
3
- import type { L2Block, L2BlockNew } from '@aztec/stdlib/block';
4
- import type { ForkMerkleTreeOperations, MerkleTreeReadOperations } from '@aztec/stdlib/interfaces/server';
5
- import type { MerkleTreeId } from '@aztec/stdlib/trees';
1
+ import type { BlockNumber } from '@aztec/foundation/branded-types';
2
+ import type { Fr } from '@aztec/foundation/curves/bn254';
3
+ import type { L2Block } from '@aztec/stdlib/block';
4
+ import type { ForkMerkleTreeOperations, MerkleTreeReadOperations, ReadonlyWorldStateAccess } from '@aztec/stdlib/interfaces/server';
6
5
  import type { WorldStateStatusFull, WorldStateStatusSummary } from '../native/message.js';
7
6
  /**
8
7
  *
@@ -21,22 +20,13 @@ import type { WorldStateStatusFull, WorldStateStatusSummary } from '../native/me
21
20
  */
22
21
  export declare const INITIAL_NULLIFIER_TREE_SIZE: number;
23
22
  export declare const INITIAL_PUBLIC_DATA_TREE_SIZE: number;
24
- export type TreeSnapshots = {
25
- [MerkleTreeId.NULLIFIER_TREE]: IndexedTreeSnapshot;
26
- [MerkleTreeId.NOTE_HASH_TREE]: TreeSnapshot<Fr>;
27
- [MerkleTreeId.PUBLIC_DATA_TREE]: IndexedTreeSnapshot;
28
- [MerkleTreeId.L1_TO_L2_MESSAGE_TREE]: TreeSnapshot<Fr>;
29
- [MerkleTreeId.ARCHIVE]: TreeSnapshot<Fr>;
30
- };
31
- export interface MerkleTreeAdminDatabase extends ForkMerkleTreeOperations {
23
+ export interface MerkleTreeAdminDatabase extends ForkMerkleTreeOperations, ReadonlyWorldStateAccess {
32
24
  /**
33
25
  * Handles a single L2 block (i.e. Inserts the new note hashes into the merkle tree).
34
26
  * @param block - The L2 block to handle.
35
27
  * @param l1ToL2Messages - The L1 to L2 messages for the block.
36
- * @param isFirstBlock - Whether the block is the first block in a checkpoint. Temporary hack to only insert l1 to l2
37
- * messages for the first block in a checkpoint. TODO(#17027) Remove this.
38
28
  */
39
- handleL2BlockAndMessages(block: L2Block | L2BlockNew, l1ToL2Messages: Fr[], isFirstBlock?: boolean): Promise<WorldStateStatusFull>;
29
+ handleL2BlockAndMessages(block: L2Block, l1ToL2Messages: Fr[]): Promise<WorldStateStatusFull>;
40
30
  /**
41
31
  * Gets a handle that allows reading the latest committed state
42
32
  */
@@ -46,19 +36,19 @@ export interface MerkleTreeAdminDatabase extends ForkMerkleTreeOperations {
46
36
  * @param toBlockNumber The block number of the new oldest historical block
47
37
  * @returns The new WorldStateStatus
48
38
  */
49
- removeHistoricalBlocks(toBlockNumber: bigint): Promise<WorldStateStatusFull>;
39
+ removeHistoricalBlocks(toBlockNumber: BlockNumber): Promise<WorldStateStatusFull>;
50
40
  /**
51
41
  * Removes all pending blocks down to but not including the given block number
52
42
  * @param toBlockNumber The block number of the new tip of the pending chain,
53
43
  * @returns The new WorldStateStatus
54
44
  */
55
- unwindBlocks(toBlockNumber: bigint): Promise<WorldStateStatusFull>;
45
+ unwindBlocks(toBlockNumber: BlockNumber): Promise<WorldStateStatusFull>;
56
46
  /**
57
47
  * Advances the finalized block number to be the number provided
58
48
  * @param toBlockNumber The block number that is now the tip of the finalized chain
59
49
  * @returns The new WorldStateStatus
60
50
  */
61
- setFinalized(toBlockNumber: bigint): Promise<WorldStateStatusSummary>;
51
+ setFinalized(toBlockNumber: BlockNumber): Promise<WorldStateStatusSummary>;
62
52
  /**
63
53
  * Gets the current status summary of the database.
64
54
  * @returns The current WorldStateStatus.
@@ -69,4 +59,4 @@ export interface MerkleTreeAdminDatabase extends ForkMerkleTreeOperations {
69
59
  /** Deletes the db. */
70
60
  clear(): Promise<void>;
71
61
  }
72
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibWVya2xlX3RyZWVfZGIuZC50cyIsInNvdXJjZ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,EAAE,oBAAoB,EAAE,uBAAuB,EAAE,MAAM,sBAAsB,CAAC;AAE1F;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,2BAA2B,QAA4B,CAAC;AAErE,eAAO,MAAM,6BAA6B,QAAmD,CAAC;AAE9F,MAAM,WAAW,uBAAwB,SAAQ,wBAAwB,EAAE,wBAAwB;IACjG;;;;OAIG;IACH,wBAAwB,CAAC,KAAK,EAAE,OAAO,EAAE,cAAc,EAAE,EAAE,EAAE,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAC;IAE9F;;OAEG;IACH,YAAY,IAAI,wBAAwB,CAAC;IAEzC;;;;OAIG;IACH,sBAAsB,CAAC,aAAa,EAAE,WAAW,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAC;IAElF;;;;OAIG;IACH,YAAY,CAAC,aAAa,EAAE,WAAW,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAC;IAExE;;;;OAIG;IACH,YAAY,CAAC,aAAa,EAAE,WAAW,GAAG,OAAO,CAAC,uBAAuB,CAAC,CAAC;IAE3E;;;OAGG;IACH,gBAAgB,IAAI,OAAO,CAAC,uBAAuB,CAAC,CAAC;IAErD,yBAAyB;IACzB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAEvB,sBAAsB;IACtB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACxB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aztec/world-state",
3
- "version": "0.0.1-commit.9b94fc1",
3
+ "version": "0.0.1-commit.9badcec54",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": "./dest/index.js",
@@ -18,8 +18,8 @@
18
18
  "tsconfig": "./tsconfig.json"
19
19
  },
20
20
  "scripts": {
21
- "build": "yarn clean && tsgo -b",
22
- "build:dev": "tsgo -b --watch",
21
+ "build": "yarn clean && ../scripts/tsc.sh",
22
+ "build:dev": "../scripts/tsc.sh --watch",
23
23
  "clean": "rm -rf ./dest .tsbuildinfo",
24
24
  "test": "NODE_NO_WARNINGS=1 node --experimental-vm-modules ../node_modules/.bin/jest --passWithNoTests --maxWorkers=${JEST_MAX_WORKERS:-8}"
25
25
  },
@@ -64,23 +64,22 @@
64
64
  ]
65
65
  },
66
66
  "dependencies": {
67
- "@aztec/constants": "0.0.1-commit.9b94fc1",
68
- "@aztec/foundation": "0.0.1-commit.9b94fc1",
69
- "@aztec/kv-store": "0.0.1-commit.9b94fc1",
70
- "@aztec/merkle-tree": "0.0.1-commit.9b94fc1",
71
- "@aztec/native": "0.0.1-commit.9b94fc1",
72
- "@aztec/protocol-contracts": "0.0.1-commit.9b94fc1",
73
- "@aztec/stdlib": "0.0.1-commit.9b94fc1",
74
- "@aztec/telemetry-client": "0.0.1-commit.9b94fc1",
67
+ "@aztec/constants": "0.0.1-commit.9badcec54",
68
+ "@aztec/foundation": "0.0.1-commit.9badcec54",
69
+ "@aztec/kv-store": "0.0.1-commit.9badcec54",
70
+ "@aztec/native": "0.0.1-commit.9badcec54",
71
+ "@aztec/protocol-contracts": "0.0.1-commit.9badcec54",
72
+ "@aztec/stdlib": "0.0.1-commit.9badcec54",
73
+ "@aztec/telemetry-client": "0.0.1-commit.9badcec54",
75
74
  "tslib": "^2.4.0",
76
75
  "zod": "^3.23.8"
77
76
  },
78
77
  "devDependencies": {
79
- "@aztec/archiver": "0.0.1-commit.9b94fc1",
78
+ "@aztec/archiver": "0.0.1-commit.9badcec54",
80
79
  "@jest/globals": "^30.0.0",
81
80
  "@types/jest": "^30.0.0",
82
81
  "@types/node": "^22.15.17",
83
- "@typescript/native-preview": "7.0.0-dev.20251126.1",
82
+ "@typescript/native-preview": "7.0.0-dev.20260113.1",
84
83
  "jest": "^30.0.0",
85
84
  "jest-mock-extended": "^4.0.0",
86
85
  "ts-node": "^10.9.1",
@@ -7,7 +7,7 @@ import {
7
7
  Metrics,
8
8
  type TelemetryClient,
9
9
  type UpDownCounter,
10
- ValueType,
10
+ createUpDownCounterWithDefault,
11
11
  } from '@aztec/telemetry-client';
12
12
 
13
13
  import {
@@ -46,55 +46,31 @@ export class WorldStateInstrumentation {
46
46
  private log: Logger = createLogger('world-state:instrumentation'),
47
47
  ) {
48
48
  const meter = telemetry.getMeter('World State');
49
- this.dbMapSize = meter.createGauge(Metrics.WORLD_STATE_DB_MAP_SIZE, {
50
- description: `The current configured map size for each merkle tree`,
51
- valueType: ValueType.INT,
52
- });
49
+ this.dbMapSize = meter.createGauge(Metrics.WORLD_STATE_DB_MAP_SIZE);
53
50
 
54
- this.dbPhysicalSize = meter.createGauge(Metrics.WORLD_STATE_DB_PHYSICAL_SIZE, {
55
- description: `The current physical disk space used for each database`,
56
- valueType: ValueType.INT,
57
- });
51
+ this.dbPhysicalSize = meter.createGauge(Metrics.WORLD_STATE_DB_PHYSICAL_SIZE);
58
52
 
59
- this.treeSize = meter.createGauge(Metrics.WORLD_STATE_TREE_SIZE, {
60
- description: `The current number of leaves in each merkle tree`,
61
- valueType: ValueType.INT,
62
- });
53
+ this.treeSize = meter.createGauge(Metrics.WORLD_STATE_TREE_SIZE);
63
54
 
64
- this.unfinalizedHeight = meter.createGauge(Metrics.WORLD_STATE_UNFINALIZED_HEIGHT, {
65
- description: `The unfinalized block height of each merkle tree`,
66
- valueType: ValueType.INT,
67
- });
55
+ this.unfinalizedHeight = meter.createGauge(Metrics.WORLD_STATE_UNFINALIZED_HEIGHT);
68
56
 
69
- this.finalizedHeight = meter.createGauge(Metrics.WORLD_STATE_FINALIZED_HEIGHT, {
70
- description: `The finalized block height of each merkle tree`,
71
- valueType: ValueType.INT,
72
- });
57
+ this.finalizedHeight = meter.createGauge(Metrics.WORLD_STATE_FINALIZED_HEIGHT);
73
58
 
74
- this.oldestBlock = meter.createGauge(Metrics.WORLD_STATE_OLDEST_BLOCK, {
75
- description: `The oldest historical block of each merkle tree`,
76
- valueType: ValueType.INT,
77
- });
59
+ this.oldestBlock = meter.createGauge(Metrics.WORLD_STATE_OLDEST_BLOCK);
78
60
 
79
- this.dbUsedSize = meter.createGauge(Metrics.WORLD_STATE_DB_USED_SIZE, {
80
- description: `The current used database size for each db of each merkle tree`,
81
- valueType: ValueType.INT,
82
- });
61
+ this.dbUsedSize = meter.createGauge(Metrics.WORLD_STATE_DB_USED_SIZE);
83
62
 
84
- this.dbNumItems = meter.createGauge(Metrics.WORLD_STATE_DB_NUM_ITEMS, {
85
- description: `The current number of items in each database of each merkle tree`,
86
- valueType: ValueType.INT,
87
- });
63
+ this.dbNumItems = meter.createGauge(Metrics.WORLD_STATE_DB_NUM_ITEMS);
88
64
 
89
- this.requestHistogram = meter.createHistogram(Metrics.WORLD_STATE_REQUEST_TIME, {
90
- description: 'The round trip time of world state requests',
91
- unit: 'us',
92
- valueType: ValueType.INT,
93
- });
65
+ this.requestHistogram = meter.createHistogram(Metrics.WORLD_STATE_REQUEST_TIME);
94
66
 
95
- this.criticalErrors = meter.createUpDownCounter(Metrics.WORLD_STATE_CRITICAL_ERROR_COUNT, {
96
- description: 'The number of critical errors in the world state',
97
- valueType: ValueType.INT,
67
+ this.criticalErrors = createUpDownCounterWithDefault(meter, Metrics.WORLD_STATE_CRITICAL_ERROR_COUNT, {
68
+ [Attributes.ERROR_TYPE]: [
69
+ 'synch_pending_block',
70
+ 'finalize_block',
71
+ 'prune_pending_block',
72
+ 'prune_historical_block',
73
+ ],
98
74
  });
99
75
  }
100
76
 
@@ -3,11 +3,14 @@ import type { MerkleTreeCheckpointOperations } from '@aztec/stdlib/interfaces/se
3
3
  export class ForkCheckpoint {
4
4
  private completed = false;
5
5
 
6
- private constructor(private readonly fork: MerkleTreeCheckpointOperations) {}
6
+ private constructor(
7
+ private readonly fork: MerkleTreeCheckpointOperations,
8
+ public readonly depth: number,
9
+ ) {}
7
10
 
8
11
  static async new(fork: MerkleTreeCheckpointOperations): Promise<ForkCheckpoint> {
9
- await fork.createCheckpoint();
10
- return new ForkCheckpoint(fork);
12
+ const depth = await fork.createCheckpoint();
13
+ return new ForkCheckpoint(fork, depth);
11
14
  }
12
15
 
13
16
  async commit(): Promise<void> {
@@ -27,4 +30,17 @@ export class ForkCheckpoint {
27
30
  await this.fork.revertCheckpoint();
28
31
  this.completed = true;
29
32
  }
33
+
34
+ /**
35
+ * Reverts this checkpoint and any nested checkpoints created on top of it,
36
+ * leaving the checkpoint depth at the level it was before this checkpoint was created.
37
+ */
38
+ async revertToCheckpoint(): Promise<void> {
39
+ if (this.completed) {
40
+ return;
41
+ }
42
+
43
+ await this.fork.revertAllCheckpointsTo(this.depth - 1);
44
+ this.completed = true;
45
+ }
30
46
  }
@@ -1,6 +1,10 @@
1
- import { Fr } from '@aztec/foundation/fields';
1
+ import { BlockNumber } from '@aztec/foundation/branded-types';
2
+ import { Fr } from '@aztec/foundation/curves/bn254';
3
+ import { createLogger } from '@aztec/foundation/log';
2
4
  import { serializeToBuffer } from '@aztec/foundation/serialize';
5
+ import { sleep } from '@aztec/foundation/sleep';
3
6
  import { type IndexedTreeLeafPreimage, SiblingPath } from '@aztec/foundation/trees';
7
+ import { BlockHash } from '@aztec/stdlib/block';
4
8
  import type {
5
9
  BatchInsertionResult,
6
10
  IndexedTreeId,
@@ -115,7 +119,7 @@ export class MerkleTreesFacade implements MerkleTreeReadOperations {
115
119
 
116
120
  const leaf = deserializeLeafValue(resp);
117
121
  if (leaf instanceof Fr) {
118
- return leaf as any;
122
+ return treeId === MerkleTreeId.ARCHIVE ? (new BlockHash(leaf) as any) : (leaf as any);
119
123
  } else {
120
124
  return leaf.toBuffer() as any;
121
125
  }
@@ -191,19 +195,26 @@ export class MerkleTreesFacade implements MerkleTreeReadOperations {
191
195
  async getBlockNumbersForLeafIndices<ID extends MerkleTreeId>(
192
196
  treeId: ID,
193
197
  leafIndices: bigint[],
194
- ): Promise<(bigint | undefined)[]> {
198
+ ): Promise<(BlockNumber | undefined)[]> {
195
199
  const response = await this.instance.call(WorldStateMessageType.GET_BLOCK_NUMBERS_FOR_LEAF_INDICES, {
196
200
  treeId,
197
201
  revision: this.revision,
198
202
  leafIndices,
199
203
  });
200
204
 
201
- return response.blockNumbers.map(x => (x === undefined || x === null ? undefined : BigInt(x)));
205
+ return response.blockNumbers.map(x => (x === undefined || x === null ? undefined : BlockNumber(Number(x))));
202
206
  }
203
207
  }
204
208
 
205
209
  export class MerkleTreesForkFacade extends MerkleTreesFacade implements MerkleTreeWriteOperations {
206
- constructor(instance: NativeWorldStateInstance, initialHeader: BlockHeader, revision: WorldStateRevision) {
210
+ private log = createLogger('world-state:merkle-trees-fork-facade');
211
+
212
+ constructor(
213
+ instance: NativeWorldStateInstance,
214
+ initialHeader: BlockHeader,
215
+ revision: WorldStateRevision,
216
+ private opts: { closeDelayMs?: number },
217
+ ) {
207
218
  assert.notEqual(revision.forkId, 0, 'Fork ID must be set');
208
219
  assert.equal(revision.includeUncommitted, true, 'Fork must include uncommitted data');
209
220
  super(instance, initialHeader, revision);
@@ -218,7 +229,7 @@ export class MerkleTreesForkFacade extends MerkleTreesFacade implements MerkleTr
218
229
 
219
230
  async appendLeaves<ID extends MerkleTreeId>(treeId: ID, leaves: MerkleTreeLeafType<ID>[]): Promise<void> {
220
231
  await this.instance.call(WorldStateMessageType.APPEND_LEAVES, {
221
- leaves: leaves.map(leaf => leaf as any),
232
+ leaves: leaves.map(leaf => serializeLeaf(hydrateLeaf(treeId, leaf as any))),
222
233
  forkId: this.revision.forkId,
223
234
  treeId,
224
235
  });
@@ -282,12 +293,37 @@ export class MerkleTreesForkFacade extends MerkleTreesFacade implements MerkleTr
282
293
 
283
294
  public async close(): Promise<void> {
284
295
  assert.notEqual(this.revision.forkId, 0, 'Fork ID must be set');
285
- await this.instance.call(WorldStateMessageType.DELETE_FORK, { forkId: this.revision.forkId });
296
+ try {
297
+ await this.instance.call(WorldStateMessageType.DELETE_FORK, { forkId: this.revision.forkId });
298
+ } catch (err: any) {
299
+ // Ignore errors due to native instance being closed during shutdown.
300
+ // This can happen when validators are still processing block proposals while the node is stopping.
301
+ if (err?.message === 'Native instance is closed') {
302
+ return;
303
+ }
304
+ throw err;
305
+ }
286
306
  }
287
307
 
288
- public async createCheckpoint(): Promise<void> {
308
+ async [Symbol.asyncDispose](): Promise<void> {
309
+ if (this.opts.closeDelayMs) {
310
+ void sleep(this.opts.closeDelayMs)
311
+ .then(() => this.close())
312
+ .catch(err => {
313
+ if (err && 'message' in err && err.message === 'Native instance is closed') {
314
+ return; // Ignore errors due to native instance being closed
315
+ }
316
+ this.log.warn('Error closing MerkleTreesForkFacade after delay', { err });
317
+ });
318
+ } else {
319
+ await this.close();
320
+ }
321
+ }
322
+
323
+ public async createCheckpoint(): Promise<number> {
289
324
  assert.notEqual(this.revision.forkId, 0, 'Fork ID must be set');
290
- await this.instance.call(WorldStateMessageType.CREATE_CHECKPOINT, { forkId: this.revision.forkId });
325
+ const resp = await this.instance.call(WorldStateMessageType.CREATE_CHECKPOINT, { forkId: this.revision.forkId });
326
+ return resp.depth;
291
327
  }
292
328
 
293
329
  public async commitCheckpoint(): Promise<void> {
@@ -300,20 +336,28 @@ export class MerkleTreesForkFacade extends MerkleTreesFacade implements MerkleTr
300
336
  await this.instance.call(WorldStateMessageType.REVERT_CHECKPOINT, { forkId: this.revision.forkId });
301
337
  }
302
338
 
303
- public async commitAllCheckpoints(): Promise<void> {
339
+ public async commitAllCheckpointsTo(depth: number): Promise<void> {
304
340
  assert.notEqual(this.revision.forkId, 0, 'Fork ID must be set');
305
- await this.instance.call(WorldStateMessageType.COMMIT_ALL_CHECKPOINTS, { forkId: this.revision.forkId });
341
+ await this.instance.call(WorldStateMessageType.COMMIT_ALL_CHECKPOINTS, {
342
+ forkId: this.revision.forkId,
343
+ depth,
344
+ });
306
345
  }
307
346
 
308
- public async revertAllCheckpoints(): Promise<void> {
347
+ public async revertAllCheckpointsTo(depth: number): Promise<void> {
309
348
  assert.notEqual(this.revision.forkId, 0, 'Fork ID must be set');
310
- await this.instance.call(WorldStateMessageType.REVERT_ALL_CHECKPOINTS, { forkId: this.revision.forkId });
349
+ await this.instance.call(WorldStateMessageType.REVERT_ALL_CHECKPOINTS, {
350
+ forkId: this.revision.forkId,
351
+ depth,
352
+ });
311
353
  }
312
354
  }
313
355
 
314
- function hydrateLeaf<ID extends MerkleTreeId>(treeId: ID, leaf: Fr | Buffer) {
356
+ function hydrateLeaf(treeId: MerkleTreeId, leaf: Fr | BlockHash | Buffer) {
315
357
  if (leaf instanceof Fr) {
316
358
  return leaf;
359
+ } else if (leaf instanceof BlockHash) {
360
+ return leaf.toFr();
317
361
  } else if (treeId === MerkleTreeId.NULLIFIER_TREE) {
318
362
  return NullifierLeaf.fromBuffer(leaf);
319
363
  } else if (treeId === MerkleTreeId.PUBLIC_DATA_TREE) {
@@ -323,8 +367,10 @@ function hydrateLeaf<ID extends MerkleTreeId>(treeId: ID, leaf: Fr | Buffer) {
323
367
  }
324
368
  }
325
369
 
326
- export function serializeLeaf(leaf: Fr | NullifierLeaf | PublicDataTreeLeaf): SerializedLeafValue {
327
- if (leaf instanceof Fr) {
370
+ export function serializeLeaf(leaf: Fr | BlockHash | NullifierLeaf | PublicDataTreeLeaf): SerializedLeafValue {
371
+ if (leaf instanceof BlockHash) {
372
+ return leaf.toBuffer();
373
+ } else if (leaf instanceof Fr) {
328
374
  return leaf.toBuffer();
329
375
  } else if (leaf instanceof NullifierLeaf) {
330
376
  return { nullifier: leaf.nullifier.toBuffer() };