@aztec/kv-store 0.0.1-commit.b655e406 → 0.0.1-commit.c0b82b2

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 (128) hide show
  1. package/dest/config.d.ts +1 -1
  2. package/dest/indexeddb/array.d.ts +1 -1
  3. package/dest/indexeddb/array.d.ts.map +1 -1
  4. package/dest/indexeddb/array.js +21 -7
  5. package/dest/indexeddb/index.d.ts +2 -2
  6. package/dest/indexeddb/index.d.ts.map +1 -1
  7. package/dest/indexeddb/index.js +3 -6
  8. package/dest/indexeddb/map.d.ts +8 -2
  9. package/dest/indexeddb/map.d.ts.map +1 -1
  10. package/dest/indexeddb/map.js +23 -13
  11. package/dest/indexeddb/multi_map.d.ts +3 -1
  12. package/dest/indexeddb/multi_map.d.ts.map +1 -1
  13. package/dest/indexeddb/multi_map.js +30 -1
  14. package/dest/indexeddb/set.d.ts +1 -1
  15. package/dest/indexeddb/set.d.ts.map +1 -1
  16. package/dest/indexeddb/singleton.d.ts +1 -1
  17. package/dest/indexeddb/singleton.d.ts.map +1 -1
  18. package/dest/indexeddb/singleton.js +3 -1
  19. package/dest/indexeddb/store.d.ts +3 -3
  20. package/dest/indexeddb/store.d.ts.map +1 -1
  21. package/dest/indexeddb/store.js +6 -4
  22. package/dest/interfaces/array.d.ts +1 -1
  23. package/dest/interfaces/array_test_suite.d.ts +1 -1
  24. package/dest/interfaces/common.d.ts +1 -1
  25. package/dest/interfaces/counter.d.ts +1 -1
  26. package/dest/interfaces/index.d.ts +1 -1
  27. package/dest/interfaces/map.d.ts +1 -1
  28. package/dest/interfaces/map_test_suite.d.ts +1 -1
  29. package/dest/interfaces/map_test_suite.d.ts.map +1 -1
  30. package/dest/interfaces/map_test_suite.js +48 -2
  31. package/dest/interfaces/multi_map.d.ts +7 -1
  32. package/dest/interfaces/multi_map.d.ts.map +1 -1
  33. package/dest/interfaces/multi_map_test_suite.d.ts +1 -1
  34. package/dest/interfaces/multi_map_test_suite.d.ts.map +1 -1
  35. package/dest/interfaces/multi_map_test_suite.js +119 -0
  36. package/dest/interfaces/set.d.ts +1 -1
  37. package/dest/interfaces/set_test_suite.d.ts +1 -1
  38. package/dest/interfaces/singleton.d.ts +1 -1
  39. package/dest/interfaces/singleton_test_suite.d.ts +1 -1
  40. package/dest/interfaces/store.d.ts +1 -1
  41. package/dest/interfaces/utils.d.ts +2 -1
  42. package/dest/interfaces/utils.d.ts.map +1 -1
  43. package/dest/interfaces/utils.js +2 -1
  44. package/dest/lmdb/array.d.ts +1 -1
  45. package/dest/lmdb/array.d.ts.map +1 -1
  46. package/dest/lmdb/array.js +4 -2
  47. package/dest/lmdb/counter.d.ts +1 -1
  48. package/dest/lmdb/counter.d.ts.map +1 -1
  49. package/dest/lmdb/index.d.ts +2 -2
  50. package/dest/lmdb/index.d.ts.map +1 -1
  51. package/dest/lmdb/index.js +3 -3
  52. package/dest/lmdb/map.d.ts +1 -1
  53. package/dest/lmdb/map.d.ts.map +1 -1
  54. package/dest/lmdb/multi_map.d.ts +2 -1
  55. package/dest/lmdb/multi_map.d.ts.map +1 -1
  56. package/dest/lmdb/multi_map.js +15 -0
  57. package/dest/lmdb/set.d.ts +1 -1
  58. package/dest/lmdb/set.d.ts.map +1 -1
  59. package/dest/lmdb/singleton.d.ts +1 -1
  60. package/dest/lmdb/singleton.d.ts.map +1 -1
  61. package/dest/lmdb/store.d.ts +2 -3
  62. package/dest/lmdb/store.d.ts.map +1 -1
  63. package/dest/lmdb/store.js +1 -1
  64. package/dest/lmdb-v2/array.d.ts +2 -2
  65. package/dest/lmdb-v2/array.d.ts.map +1 -1
  66. package/dest/lmdb-v2/array.js +4 -3
  67. package/dest/lmdb-v2/factory.d.ts +6 -9
  68. package/dest/lmdb-v2/factory.d.ts.map +1 -1
  69. package/dest/lmdb-v2/factory.js +14 -10
  70. package/dest/lmdb-v2/index.d.ts +1 -1
  71. package/dest/lmdb-v2/map.d.ts +2 -2
  72. package/dest/lmdb-v2/map.d.ts.map +1 -1
  73. package/dest/lmdb-v2/map.js +1 -2
  74. package/dest/lmdb-v2/message.d.ts +1 -1
  75. package/dest/lmdb-v2/multi_map.d.ts +3 -2
  76. package/dest/lmdb-v2/multi_map.d.ts.map +1 -1
  77. package/dest/lmdb-v2/multi_map.js +11 -1
  78. package/dest/lmdb-v2/read_transaction.d.ts +1 -1
  79. package/dest/lmdb-v2/read_transaction.d.ts.map +1 -1
  80. package/dest/lmdb-v2/set.d.ts +1 -1
  81. package/dest/lmdb-v2/set.d.ts.map +1 -1
  82. package/dest/lmdb-v2/singleton.d.ts +2 -2
  83. package/dest/lmdb-v2/singleton.d.ts.map +1 -1
  84. package/dest/lmdb-v2/singleton.js +1 -2
  85. package/dest/lmdb-v2/store.d.ts +4 -5
  86. package/dest/lmdb-v2/store.d.ts.map +1 -1
  87. package/dest/lmdb-v2/store.js +3 -25
  88. package/dest/lmdb-v2/tx-helpers.d.ts +6 -0
  89. package/dest/lmdb-v2/tx-helpers.d.ts.map +1 -0
  90. package/dest/lmdb-v2/tx-helpers.js +21 -0
  91. package/dest/lmdb-v2/utils.d.ts +1 -10
  92. package/dest/lmdb-v2/utils.d.ts.map +1 -1
  93. package/dest/lmdb-v2/utils.js +0 -94
  94. package/dest/lmdb-v2/write_transaction.d.ts +1 -1
  95. package/dest/lmdb-v2/write_transaction.d.ts.map +1 -1
  96. package/dest/lmdb-v2/write_transaction.js +9 -5
  97. package/dest/stores/index.d.ts +1 -1
  98. package/dest/stores/l2_tips_store.d.ts +24 -9
  99. package/dest/stores/l2_tips_store.d.ts.map +1 -1
  100. package/dest/stores/l2_tips_store.js +61 -52
  101. package/dest/utils.d.ts +9 -6
  102. package/dest/utils.d.ts.map +1 -1
  103. package/dest/utils.js +51 -16
  104. package/package.json +18 -13
  105. package/src/indexeddb/array.ts +4 -4
  106. package/src/indexeddb/index.ts +8 -6
  107. package/src/indexeddb/map.ts +24 -11
  108. package/src/indexeddb/multi_map.ts +27 -1
  109. package/src/indexeddb/singleton.ts +1 -1
  110. package/src/indexeddb/store.ts +13 -6
  111. package/src/interfaces/map_test_suite.ts +30 -2
  112. package/src/interfaces/multi_map.ts +7 -0
  113. package/src/interfaces/multi_map_test_suite.ts +132 -0
  114. package/src/interfaces/utils.ts +1 -0
  115. package/src/lmdb/index.ts +8 -3
  116. package/src/lmdb/multi_map.ts +16 -0
  117. package/src/lmdb/store.ts +1 -1
  118. package/src/lmdb-v2/array.ts +2 -2
  119. package/src/lmdb-v2/factory.ts +15 -11
  120. package/src/lmdb-v2/map.ts +2 -2
  121. package/src/lmdb-v2/multi_map.ts +10 -1
  122. package/src/lmdb-v2/singleton.ts +2 -2
  123. package/src/lmdb-v2/store.ts +5 -31
  124. package/src/lmdb-v2/tx-helpers.ts +29 -0
  125. package/src/lmdb-v2/utils.ts +0 -118
  126. package/src/lmdb-v2/write_transaction.ts +9 -8
  127. package/src/stores/l2_tips_store.ts +65 -56
  128. package/src/utils.ts +79 -21
@@ -1,16 +1,16 @@
1
- import { type Batch, Database, LMDBMessageType } from './message.js';
2
- import { ReadTransaction } from './read_transaction.js';
3
1
  import {
4
2
  dedupeSortedArray,
5
3
  findInSortedArray,
6
4
  findIndexInSortedArray,
7
5
  insertIntoSortedArray,
8
- keyCmp,
9
6
  merge,
10
7
  removeAnyOf,
11
8
  removeFromSortedArray,
12
- singleKeyCmp,
13
- } from './utils.js';
9
+ } from '@aztec/foundation/array';
10
+
11
+ import { type Batch, Database, LMDBMessageType } from './message.js';
12
+ import { ReadTransaction } from './read_transaction.js';
13
+ import { keyCmp, singleKeyCmp } from './utils.js';
14
14
 
15
15
  export class WriteTransaction extends ReadTransaction {
16
16
  // exposed for tests
@@ -44,7 +44,7 @@ export class WriteTransaction extends ReadTransaction {
44
44
  remove(key: Uint8Array): Promise<void> {
45
45
  const removeEntryIndex = findIndexInSortedArray(this.dataBatch.removeEntries, key, singleKeyCmp);
46
46
  if (removeEntryIndex === -1) {
47
- this.dataBatch.removeEntries.push([key, null]);
47
+ insertIntoSortedArray(this.dataBatch.removeEntries, [key, null], keyCmp);
48
48
  }
49
49
 
50
50
  const addEntryIndex = findIndexInSortedArray(this.dataBatch.addEntries, key, singleKeyCmp);
@@ -218,8 +218,9 @@ export class WriteTransaction extends ReadTransaction {
218
218
  ): AsyncIterable<[Uint8Array, T]> {
219
219
  this.assertIsOpen();
220
220
 
221
- // make a copy of this in case we're running in reverse
221
+ // Snapshot both add and remove entries at the start of iteration to ensure consistency
222
222
  const uncommittedEntries = [...batch.addEntries];
223
+ const removeEntries = [...batch.removeEntries];
223
224
  // used to check we're in the right order when comparing between a key and uncommittedEntries
224
225
  let cmpDirection = -1;
225
226
  if (reverse) {
@@ -262,7 +263,7 @@ export class WriteTransaction extends ReadTransaction {
262
263
  break;
263
264
  }
264
265
 
265
- const toRemove = findInSortedArray(batch.removeEntries, key, singleKeyCmp);
266
+ const toRemove = findInSortedArray(removeEntries, key, singleKeyCmp);
266
267
 
267
268
  // at this point we've either exhausted all uncommitted entries,
268
269
  // we reached a key strictly greater/smaller than `key`
@@ -1,79 +1,88 @@
1
- import type {
2
- L2BlockId,
3
- L2BlockStreamEvent,
4
- L2BlockStreamEventHandler,
5
- L2BlockStreamLocalDataProvider,
6
- L2BlockTag,
7
- L2Tips,
8
- } from '@aztec/stdlib/block';
1
+ import { BlockNumber, CheckpointNumber } from '@aztec/foundation/branded-types';
2
+ import { type L2BlockTag, L2TipsStoreBase } from '@aztec/stdlib/block';
3
+ import { PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
9
4
 
10
5
  import type { AztecAsyncMap } from '../interfaces/map.js';
11
6
  import type { AztecAsyncKVStore } from '../interfaces/store.js';
12
7
 
13
- /** Stores currently synced L2 tips and unfinalized block hashes. */
14
- export class L2TipsKVStore implements L2BlockStreamEventHandler, L2BlockStreamLocalDataProvider {
15
- private readonly l2TipsStore: AztecAsyncMap<L2BlockTag, number>;
16
- private readonly l2BlockHashesStore: AztecAsyncMap<number, string>;
8
+ /**
9
+ * Persistent implementation of L2 tips store backed by a KV store.
10
+ * Used by nodes that need to persist chain state across restarts.
11
+ */
12
+ export class L2TipsKVStore extends L2TipsStoreBase {
13
+ private readonly l2TipsStore: AztecAsyncMap<L2BlockTag, BlockNumber>;
14
+ private readonly l2BlockHashesStore: AztecAsyncMap<BlockNumber, string>;
15
+ private readonly l2BlockNumberToCheckpointNumberStore: AztecAsyncMap<BlockNumber, CheckpointNumber>;
16
+ private readonly l2CheckpointStore: AztecAsyncMap<CheckpointNumber, Buffer>;
17
17
 
18
- constructor(store: AztecAsyncKVStore, namespace: string) {
18
+ constructor(
19
+ private store: AztecAsyncKVStore,
20
+ namespace: string,
21
+ ) {
22
+ super();
19
23
  this.l2TipsStore = store.openMap([namespace, 'l2_tips'].join('_'));
20
24
  this.l2BlockHashesStore = store.openMap([namespace, 'l2_block_hashes'].join('_'));
25
+ this.l2BlockNumberToCheckpointNumberStore = store.openMap(
26
+ [namespace, 'l2_block_number_to_checkpoint_number'].join('_'),
27
+ );
28
+ this.l2CheckpointStore = store.openMap([namespace, 'l2_checkpoint_store'].join('_'));
21
29
  }
22
30
 
23
- public getL2BlockHash(number: number): Promise<string | undefined> {
24
- return this.l2BlockHashesStore.getAsync(number);
31
+ protected getTip(tag: L2BlockTag): Promise<BlockNumber | undefined> {
32
+ return this.l2TipsStore.getAsync(tag);
25
33
  }
26
34
 
27
- public async getL2Tips(): Promise<L2Tips> {
28
- return {
29
- latest: await this.getL2Tip('latest'),
30
- finalized: await this.getL2Tip('finalized'),
31
- proven: await this.getL2Tip('proven'),
32
- };
35
+ protected setTip(tag: L2BlockTag, blockNumber: BlockNumber): Promise<void> {
36
+ return this.l2TipsStore.set(tag, blockNumber);
33
37
  }
34
38
 
35
- private async getL2Tip(tag: L2BlockTag): Promise<L2BlockId> {
36
- const blockNumber = await this.l2TipsStore.getAsync(tag);
37
- if (blockNumber === undefined || blockNumber === 0) {
38
- return { number: 0, hash: undefined };
39
- }
40
- const blockHash = await this.l2BlockHashesStore.getAsync(blockNumber);
41
- if (!blockHash) {
42
- throw new Error(`Block hash not found for block number ${blockNumber}`);
39
+ protected getStoredBlockHash(blockNumber: BlockNumber): Promise<string | undefined> {
40
+ return this.l2BlockHashesStore.getAsync(blockNumber);
41
+ }
42
+
43
+ protected setBlockHash(blockNumber: BlockNumber, hash: string): Promise<void> {
44
+ return this.l2BlockHashesStore.set(blockNumber, hash);
45
+ }
46
+
47
+ protected async deleteBlockHashesBefore(blockNumber: BlockNumber): Promise<void> {
48
+ for await (const key of this.l2BlockHashesStore.keysAsync({ end: blockNumber })) {
49
+ await this.l2BlockHashesStore.delete(key);
43
50
  }
51
+ }
52
+
53
+ protected getCheckpointNumberForBlock(blockNumber: BlockNumber): Promise<CheckpointNumber | undefined> {
54
+ return this.l2BlockNumberToCheckpointNumberStore.getAsync(blockNumber);
55
+ }
44
56
 
45
- return { number: blockNumber, hash: blockHash };
57
+ protected setCheckpointNumberForBlock(blockNumber: BlockNumber, checkpointNumber: CheckpointNumber): Promise<void> {
58
+ return this.l2BlockNumberToCheckpointNumberStore.set(blockNumber, checkpointNumber);
46
59
  }
47
60
 
48
- public async handleBlockStreamEvent(event: L2BlockStreamEvent): Promise<void> {
49
- switch (event.type) {
50
- case 'blocks-added': {
51
- const blocks = event.blocks.map(b => b.block);
52
- for (const block of blocks) {
53
- await this.l2BlockHashesStore.set(block.number, (await block.hash()).toString());
54
- }
55
- await this.l2TipsStore.set('latest', blocks.at(-1)!.number);
56
- break;
57
- }
58
- case 'chain-pruned':
59
- await this.saveTag('latest', event.block);
60
- break;
61
- case 'chain-proven':
62
- await this.saveTag('proven', event.block);
63
- break;
64
- case 'chain-finalized':
65
- await this.saveTag('finalized', event.block);
66
- for await (const key of this.l2BlockHashesStore.keysAsync({ end: event.block.number })) {
67
- await this.l2BlockHashesStore.delete(key);
68
- }
69
- break;
61
+ protected async deleteBlockToCheckpointBefore(blockNumber: BlockNumber): Promise<void> {
62
+ for await (const key of this.l2BlockNumberToCheckpointNumberStore.keysAsync({ end: blockNumber })) {
63
+ await this.l2BlockNumberToCheckpointNumberStore.delete(key);
70
64
  }
71
65
  }
72
66
 
73
- private async saveTag(name: L2BlockTag, block: L2BlockId) {
74
- await this.l2TipsStore.set(name, block.number);
75
- if (block.hash) {
76
- await this.l2BlockHashesStore.set(block.number, block.hash);
67
+ protected async getCheckpoint(checkpointNumber: CheckpointNumber): Promise<PublishedCheckpoint | undefined> {
68
+ const buffer = await this.l2CheckpointStore.getAsync(checkpointNumber);
69
+ if (!buffer) {
70
+ return undefined;
77
71
  }
72
+ return PublishedCheckpoint.fromBuffer(buffer);
73
+ }
74
+
75
+ protected saveCheckpointData(checkpoint: PublishedCheckpoint): Promise<void> {
76
+ return this.l2CheckpointStore.set(checkpoint.checkpoint.number, checkpoint.toBuffer());
77
+ }
78
+
79
+ protected async deleteCheckpointsBefore(checkpointNumber: CheckpointNumber): Promise<void> {
80
+ for await (const key of this.l2CheckpointStore.keysAsync({ end: checkpointNumber })) {
81
+ await this.l2CheckpointStore.delete(key);
82
+ }
83
+ }
84
+
85
+ protected runInTransaction<T>(fn: () => Promise<T>): Promise<T> {
86
+ return this.store.transactionAsync(fn);
78
87
  }
79
88
  }
package/src/utils.ts CHANGED
@@ -1,40 +1,98 @@
1
- import type { EthAddress } from '@aztec/foundation/eth-address';
1
+ import { EthAddress } from '@aztec/foundation/eth-address';
2
2
  import type { Logger } from '@aztec/foundation/log';
3
+ import { DatabaseVersion } from '@aztec/stdlib/database-version/version';
3
4
 
4
5
  import type { AztecAsyncSingleton, AztecSingleton } from './interfaces/singleton.js';
5
6
  import type { AztecAsyncKVStore, AztecKVStore } from './interfaces/store.js';
6
7
  import { isSyncStore } from './interfaces/utils.js';
7
8
 
8
9
  /**
9
- * Clears the store if the rollup address does not match the one stored in the database.
10
- * This is to prevent data from being accidentally shared between different rollup instances.
10
+ * Clears the store if the schema version or rollup address does not match the one stored in the database.
11
+ * Also clears if migrating from an older store format that didn't track schema version.
12
+ * This is to prevent data from being accidentally mixed up between different rollup instances or schema versions.
11
13
  * @param store - The store to check
14
+ * @param targetSchemaVersion - The current schema version
12
15
  * @param rollupAddress - The ETH address of the rollup contract
13
- * @returns A promise that resolves when the store is cleared, or rejects if the rollup address does not match
16
+ * @param log - Optional logger
17
+ * @returns The store (cleared if necessary)
14
18
  */
15
- export async function initStoreForRollup<T extends AztecKVStore | AztecAsyncKVStore>(
19
+ export async function initStoreForRollupAndSchemaVersion<T extends AztecKVStore | AztecAsyncKVStore>(
16
20
  store: T,
17
- rollupAddress: EthAddress,
21
+ schemaVersion: number | undefined,
22
+ rollupAddress: EthAddress | undefined,
18
23
  log?: Logger,
19
24
  ): Promise<T> {
20
- if (!rollupAddress) {
21
- throw new Error('Rollup address is required');
22
- }
23
- const rollupAddressValue = store.openSingleton<ReturnType<EthAddress['toString']>>('rollupAddress');
24
- const rollupAddressString = rollupAddress.toString();
25
- const storedRollupAddressString = isSyncStore(store)
26
- ? (rollupAddressValue as AztecSingleton<ReturnType<EthAddress['toString']>>).get()
27
- : await (rollupAddressValue as AztecAsyncSingleton<ReturnType<EthAddress['toString']>>).getAsync();
28
-
29
- if (typeof storedRollupAddressString !== 'undefined' && storedRollupAddressString !== rollupAddressString) {
30
- log?.warn(`Rollup address mismatch. Clearing entire database...`, {
31
- expected: rollupAddressString,
32
- found: storedRollupAddressString,
33
- });
25
+ const targetSchemaVersion = schemaVersion ?? 0;
26
+ const targetRollupAddress = rollupAddress ?? EthAddress.ZERO;
27
+ const targetDatabaseVersion = new DatabaseVersion(targetSchemaVersion, targetRollupAddress);
28
+
29
+ // DB version: database schema version + rollup address combined)
30
+ const dbVersion = store.openSingleton<string>('dbVersion');
31
+
32
+ const storedDatabaseVersion = isSyncStore(store)
33
+ ? (dbVersion as AztecSingleton<string>).get()
34
+ : await (dbVersion as AztecAsyncSingleton<string>).getAsync();
35
+
36
+ // Check if this is an old format store (has rollupAddress singleton but no dbVersion)
37
+ const oldRollupSingleton = store.openSingleton<string>('rollupAddress');
38
+ const hasOldFormat = isSyncStore(store)
39
+ ? !storedDatabaseVersion && !!(oldRollupSingleton as AztecSingleton<string>).get()
40
+ : !storedDatabaseVersion && !!(await (oldRollupSingleton as AztecAsyncSingleton<string>).getAsync());
34
41
 
42
+ if (
43
+ hasOldFormat ||
44
+ doesStoreNeedToBeCleared(
45
+ targetDatabaseVersion,
46
+ storedDatabaseVersion,
47
+ targetSchemaVersion,
48
+ targetRollupAddress,
49
+ log,
50
+ )
51
+ ) {
52
+ if (hasOldFormat) {
53
+ log?.warn('Detected old store format without dbVersion, clearing database');
54
+ }
35
55
  await store.clear();
36
56
  }
37
57
 
38
- await rollupAddressValue.set(rollupAddressString);
58
+ await dbVersion.set(targetDatabaseVersion.toBuffer().toString('utf-8'));
59
+
39
60
  return store;
40
61
  }
62
+
63
+ function doesStoreNeedToBeCleared(
64
+ targetDatabaseVersion: DatabaseVersion,
65
+ storedDatabaseVersion: string | undefined,
66
+ targetSchemaVersion: number,
67
+ targetRollupAddress: EthAddress,
68
+ log?: Logger,
69
+ ) {
70
+ if (storedDatabaseVersion) {
71
+ try {
72
+ const storedVersion = DatabaseVersion.fromBuffer(Buffer.from(storedDatabaseVersion, 'utf-8'));
73
+ const cmp = storedVersion.cmp(targetDatabaseVersion);
74
+
75
+ if (cmp === undefined) {
76
+ log?.warn('Rollup address changed, clearing database', {
77
+ stored: storedVersion.rollupAddress.toString(),
78
+ current: targetRollupAddress.toString(),
79
+ });
80
+ return true;
81
+ }
82
+
83
+ if (cmp !== 0) {
84
+ log?.warn('Schema version changed, clearing database', {
85
+ stored: storedVersion.schemaVersion,
86
+ current: targetSchemaVersion,
87
+ });
88
+
89
+ return true;
90
+ }
91
+ } catch (err) {
92
+ log?.warn('Failed to parse stored version, clearing database', { err });
93
+ return true;
94
+ }
95
+ }
96
+
97
+ return false;
98
+ }