@aztec/kv-store 0.0.0-test.0 → 0.0.1-commit.0208eb9

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 (163) hide show
  1. package/dest/config.d.ts +2 -2
  2. package/dest/config.d.ts.map +1 -1
  3. package/dest/config.js +5 -3
  4. package/dest/indexeddb/array.d.ts +3 -2
  5. package/dest/indexeddb/array.d.ts.map +1 -1
  6. package/dest/indexeddb/array.js +24 -7
  7. package/dest/indexeddb/index.d.ts +2 -2
  8. package/dest/indexeddb/index.d.ts.map +1 -1
  9. package/dest/indexeddb/index.js +4 -7
  10. package/dest/indexeddb/map.d.ts +12 -6
  11. package/dest/indexeddb/map.d.ts.map +1 -1
  12. package/dest/indexeddb/map.js +39 -61
  13. package/dest/indexeddb/multi_map.d.ts +14 -0
  14. package/dest/indexeddb/multi_map.d.ts.map +1 -0
  15. package/dest/indexeddb/multi_map.js +107 -0
  16. package/dest/indexeddb/set.d.ts +1 -1
  17. package/dest/indexeddb/set.d.ts.map +1 -1
  18. package/dest/indexeddb/singleton.d.ts +3 -2
  19. package/dest/indexeddb/singleton.d.ts.map +1 -1
  20. package/dest/indexeddb/singleton.js +6 -2
  21. package/dest/indexeddb/store.d.ts +15 -16
  22. package/dest/indexeddb/store.d.ts.map +1 -1
  23. package/dest/indexeddb/store.js +45 -42
  24. package/dest/interfaces/array.d.ts +5 -4
  25. package/dest/interfaces/array.d.ts.map +1 -1
  26. package/dest/interfaces/array.js +1 -3
  27. package/dest/interfaces/array_test_suite.d.ts +1 -1
  28. package/dest/interfaces/common.d.ts +11 -9
  29. package/dest/interfaces/common.d.ts.map +1 -1
  30. package/dest/interfaces/common.js +8 -3
  31. package/dest/interfaces/counter.d.ts +1 -1
  32. package/dest/interfaces/index.d.ts +4 -2
  33. package/dest/interfaces/index.d.ts.map +1 -1
  34. package/dest/interfaces/index.js +2 -0
  35. package/dest/interfaces/map.d.ts +21 -49
  36. package/dest/interfaces/map.d.ts.map +1 -1
  37. package/dest/interfaces/map.js +1 -1
  38. package/dest/interfaces/map_test_suite.d.ts +1 -1
  39. package/dest/interfaces/map_test_suite.d.ts.map +1 -1
  40. package/dest/interfaces/map_test_suite.js +181 -70
  41. package/dest/interfaces/multi_map.d.ts +41 -0
  42. package/dest/interfaces/multi_map.d.ts.map +1 -0
  43. package/dest/interfaces/multi_map.js +3 -0
  44. package/dest/interfaces/multi_map_test_suite.d.ts +3 -0
  45. package/dest/interfaces/multi_map_test_suite.d.ts.map +1 -0
  46. package/dest/interfaces/multi_map_test_suite.js +364 -0
  47. package/dest/interfaces/set.d.ts +1 -1
  48. package/dest/interfaces/set_test_suite.d.ts +1 -1
  49. package/dest/interfaces/singleton.d.ts +1 -1
  50. package/dest/interfaces/singleton_test_suite.d.ts +1 -1
  51. package/dest/interfaces/store.d.ts +18 -43
  52. package/dest/interfaces/store.d.ts.map +1 -1
  53. package/dest/interfaces/utils.d.ts +3 -1
  54. package/dest/interfaces/utils.d.ts.map +1 -1
  55. package/dest/interfaces/utils.js +3 -1
  56. package/dest/lmdb/array.d.ts +3 -2
  57. package/dest/lmdb/array.d.ts.map +1 -1
  58. package/dest/lmdb/array.js +4 -2
  59. package/dest/lmdb/counter.d.ts +1 -1
  60. package/dest/lmdb/counter.d.ts.map +1 -1
  61. package/dest/lmdb/index.d.ts +2 -2
  62. package/dest/lmdb/index.d.ts.map +1 -1
  63. package/dest/lmdb/index.js +5 -5
  64. package/dest/lmdb/map.d.ts +11 -23
  65. package/dest/lmdb/map.d.ts.map +1 -1
  66. package/dest/lmdb/map.js +15 -81
  67. package/dest/lmdb/multi_map.d.ts +13 -0
  68. package/dest/lmdb/multi_map.d.ts.map +1 -0
  69. package/dest/lmdb/multi_map.js +44 -0
  70. package/dest/lmdb/set.d.ts +1 -1
  71. package/dest/lmdb/set.d.ts.map +1 -1
  72. package/dest/lmdb/singleton.d.ts +1 -1
  73. package/dest/lmdb/singleton.d.ts.map +1 -1
  74. package/dest/lmdb/store.d.ts +9 -25
  75. package/dest/lmdb/store.d.ts.map +1 -1
  76. package/dest/lmdb/store.js +12 -32
  77. package/dest/lmdb-v2/array.d.ts +4 -3
  78. package/dest/lmdb-v2/array.d.ts.map +1 -1
  79. package/dest/lmdb-v2/array.js +4 -2
  80. package/dest/lmdb-v2/factory.d.ts +6 -9
  81. package/dest/lmdb-v2/factory.d.ts.map +1 -1
  82. package/dest/lmdb-v2/factory.js +26 -12
  83. package/dest/lmdb-v2/index.d.ts +1 -1
  84. package/dest/lmdb-v2/map.d.ts +12 -45
  85. package/dest/lmdb-v2/map.d.ts.map +1 -1
  86. package/dest/lmdb-v2/map.js +17 -104
  87. package/dest/lmdb-v2/message.d.ts +24 -5
  88. package/dest/lmdb-v2/message.d.ts.map +1 -1
  89. package/dest/lmdb-v2/message.js +6 -4
  90. package/dest/lmdb-v2/multi_map.d.ts +52 -0
  91. package/dest/lmdb-v2/multi_map.d.ts.map +1 -0
  92. package/dest/lmdb-v2/multi_map.js +123 -0
  93. package/dest/lmdb-v2/read_transaction.d.ts +3 -1
  94. package/dest/lmdb-v2/read_transaction.d.ts.map +1 -1
  95. package/dest/lmdb-v2/read_transaction.js +34 -0
  96. package/dest/lmdb-v2/set.d.ts +15 -0
  97. package/dest/lmdb-v2/set.d.ts.map +1 -0
  98. package/dest/lmdb-v2/set.js +23 -0
  99. package/dest/lmdb-v2/singleton.d.ts +2 -2
  100. package/dest/lmdb-v2/singleton.d.ts.map +1 -1
  101. package/dest/lmdb-v2/singleton.js +1 -1
  102. package/dest/lmdb-v2/store.d.ts +13 -13
  103. package/dest/lmdb-v2/store.d.ts.map +1 -1
  104. package/dest/lmdb-v2/store.js +19 -29
  105. package/dest/lmdb-v2/tx-helpers.d.ts +6 -0
  106. package/dest/lmdb-v2/tx-helpers.d.ts.map +1 -0
  107. package/dest/lmdb-v2/tx-helpers.js +21 -0
  108. package/dest/lmdb-v2/utils.d.ts +3 -14
  109. package/dest/lmdb-v2/utils.d.ts.map +1 -1
  110. package/dest/lmdb-v2/utils.js +0 -94
  111. package/dest/lmdb-v2/write_transaction.d.ts +3 -5
  112. package/dest/lmdb-v2/write_transaction.d.ts.map +1 -1
  113. package/dest/lmdb-v2/write_transaction.js +9 -5
  114. package/dest/stores/index.d.ts +2 -1
  115. package/dest/stores/index.d.ts.map +1 -1
  116. package/dest/stores/index.js +1 -0
  117. package/dest/stores/l2_tips_store.d.ts +24 -8
  118. package/dest/stores/l2_tips_store.d.ts.map +1 -1
  119. package/dest/stores/l2_tips_store.js +63 -45
  120. package/dest/utils.d.ts +9 -6
  121. package/dest/utils.d.ts.map +1 -1
  122. package/dest/utils.js +51 -16
  123. package/package.json +25 -16
  124. package/src/config.ts +6 -4
  125. package/src/indexeddb/array.ts +9 -5
  126. package/src/indexeddb/index.ts +10 -8
  127. package/src/indexeddb/map.ts +38 -55
  128. package/src/indexeddb/multi_map.ts +105 -0
  129. package/src/indexeddb/singleton.ts +5 -2
  130. package/src/indexeddb/store.ts +71 -56
  131. package/src/interfaces/array.ts +5 -3
  132. package/src/interfaces/common.ts +20 -9
  133. package/src/interfaces/index.ts +3 -1
  134. package/src/interfaces/map.ts +19 -53
  135. package/src/interfaces/map_test_suite.ts +101 -44
  136. package/src/interfaces/multi_map.ts +45 -0
  137. package/src/interfaces/multi_map_test_suite.ts +374 -0
  138. package/src/interfaces/store.ts +18 -53
  139. package/src/interfaces/utils.ts +2 -0
  140. package/src/lmdb/array.ts +2 -1
  141. package/src/lmdb/index.ts +11 -6
  142. package/src/lmdb/map.ts +23 -94
  143. package/src/lmdb/multi_map.ts +51 -0
  144. package/src/lmdb/store.ts +24 -48
  145. package/src/lmdb-v2/array.ts +8 -3
  146. package/src/lmdb-v2/factory.ts +29 -18
  147. package/src/lmdb-v2/map.ts +30 -127
  148. package/src/lmdb-v2/message.ts +23 -0
  149. package/src/lmdb-v2/multi_map.ts +150 -0
  150. package/src/lmdb-v2/read_transaction.ts +40 -0
  151. package/src/lmdb-v2/set.ts +33 -0
  152. package/src/lmdb-v2/singleton.ts +6 -2
  153. package/src/lmdb-v2/store.ts +24 -42
  154. package/src/lmdb-v2/tx-helpers.ts +29 -0
  155. package/src/lmdb-v2/utils.ts +0 -118
  156. package/src/lmdb-v2/write_transaction.ts +11 -10
  157. package/src/stores/index.ts +2 -0
  158. package/src/stores/l2_tips_store.ts +67 -49
  159. package/src/utils.ts +79 -21
  160. package/dest/interfaces/store_test_suite.d.ts +0 -3
  161. package/dest/interfaces/store_test_suite.d.ts.map +0 -1
  162. package/dest/interfaces/store_test_suite.js +0 -37
  163. package/src/interfaces/store_test_suite.ts +0 -56
@@ -1,19 +1,20 @@
1
- import { type Logger, createLogger } from '@aztec/foundation/log';
1
+ import { type Logger, type LoggerBindings, createLogger } from '@aztec/foundation/log';
2
2
  import { Semaphore, SerialQueue } from '@aztec/foundation/queue';
3
3
  import { MsgpackChannel, NativeLMDBStore } from '@aztec/native';
4
4
 
5
5
  import { AsyncLocalStorage } from 'async_hooks';
6
- import { rm } from 'fs/promises';
6
+ import { mkdir, rm } from 'fs/promises';
7
7
 
8
8
  import type { AztecAsyncArray } from '../interfaces/array.js';
9
- import type { Key, StoreSize } from '../interfaces/common.js';
9
+ import type { Key, StoreSize, Value } from '../interfaces/common.js';
10
10
  import type { AztecAsyncCounter } from '../interfaces/counter.js';
11
- import type { AztecAsyncMap, AztecAsyncMultiMap } from '../interfaces/map.js';
11
+ import type { AztecAsyncMap } from '../interfaces/map.js';
12
+ import type { AztecAsyncMultiMap } from '../interfaces/multi_map.js';
12
13
  import type { AztecAsyncSet } from '../interfaces/set.js';
13
14
  import type { AztecAsyncSingleton } from '../interfaces/singleton.js';
14
15
  import type { AztecAsyncKVStore } from '../interfaces/store.js';
15
16
  import { LMDBArray } from './array.js';
16
- import { LMDBMap, LMDBMultiMap } from './map.js';
17
+ import { LMDBMap } from './map.js';
17
18
  import {
18
19
  Database,
19
20
  type LMDBMessageChannel,
@@ -21,10 +22,14 @@ import {
21
22
  type LMDBRequestBody,
22
23
  type LMDBResponseBody,
23
24
  } from './message.js';
25
+ import { LMDBMultiMap } from './multi_map.js';
24
26
  import { ReadTransaction } from './read_transaction.js';
27
+ import { LMDBSet } from './set.js';
25
28
  import { LMDBSingleValue } from './singleton.js';
26
29
  import { WriteTransaction } from './write_transaction.js';
27
30
 
31
+ export { execInReadTx, execInWriteTx } from './tx-helpers.js';
32
+
28
33
  export class AztecLMDBStoreV2 implements AztecAsyncKVStore, LMDBMessageChannel {
29
34
  private open = false;
30
35
  private channel: MsgpackChannel<LMDBMessageType, LMDBRequestBody, LMDBResponseBody>;
@@ -70,13 +75,19 @@ export class AztecLMDBStoreV2 implements AztecAsyncKVStore, LMDBMessageChannel {
70
75
  dbMapSizeKb: number = 10 * 1024 * 1024,
71
76
  maxReaders: number = 16,
72
77
  cleanup?: () => Promise<void>,
73
- log = createLogger('kv-store:lmdb-v2'),
78
+ bindings?: LoggerBindings,
74
79
  ) {
80
+ const log = createLogger('kv-store:lmdb-v2', bindings);
75
81
  const db = new AztecLMDBStoreV2(dataDir, dbMapSizeKb, maxReaders, log, cleanup);
76
82
  await db.start();
77
83
  return db;
78
84
  }
79
85
 
86
+ public async backupTo(dstPath: string, compact = true) {
87
+ await mkdir(dstPath, { recursive: true });
88
+ await this.channel.sendMessage(LMDBMessageType.COPY_STORE, { dstPath, compact });
89
+ }
90
+
80
91
  public getReadTx(): ReadTransaction {
81
92
  if (!this.open) {
82
93
  throw new Error('Store is closed');
@@ -92,24 +103,24 @@ export class AztecLMDBStoreV2 implements AztecAsyncKVStore, LMDBMessageChannel {
92
103
  return currentWrite;
93
104
  }
94
105
 
95
- openMap<K extends Key, V>(name: string): AztecAsyncMap<K, V> {
106
+ openMap<K extends Key, V extends Value>(name: string): AztecAsyncMap<K, V> {
96
107
  return new LMDBMap(this, name);
97
108
  }
98
109
 
99
- openMultiMap<K extends Key, V>(name: string): AztecAsyncMultiMap<K, V> {
110
+ openMultiMap<K extends Key, V extends Value>(name: string): AztecAsyncMultiMap<K, V> {
100
111
  return new LMDBMultiMap(this, name);
101
112
  }
102
113
 
103
- openSingleton<T>(name: string): AztecAsyncSingleton<T> {
114
+ openSingleton<T extends Value>(name: string): AztecAsyncSingleton<T> {
104
115
  return new LMDBSingleValue(this, name);
105
116
  }
106
117
 
107
- openArray<T>(name: string): AztecAsyncArray<T> {
118
+ openArray<T extends Value>(name: string): AztecAsyncArray<T> {
108
119
  return new LMDBArray(this, name);
109
120
  }
110
121
 
111
- openSet<K extends Key>(_name: string): AztecAsyncSet<K> {
112
- throw new Error('Not implemented');
122
+ openSet<K extends Key>(name: string): AztecAsyncSet<K> {
123
+ return new LMDBSet(this, name);
113
124
  }
114
125
 
115
126
  openCounter<K extends Key>(_name: string): AztecAsyncCounter<K> {
@@ -150,10 +161,6 @@ export class AztecLMDBStoreV2 implements AztecAsyncKVStore, LMDBMessageChannel {
150
161
  return Promise.resolve();
151
162
  }
152
163
 
153
- fork(): Promise<AztecAsyncKVStore> {
154
- throw new Error('Not implemented');
155
- }
156
-
157
164
  async delete(): Promise<void> {
158
165
  await this.close();
159
166
  await rm(this.dataDir, { recursive: true, force: true, maxRetries: 3 });
@@ -204,34 +211,9 @@ export class AztecLMDBStoreV2 implements AztecAsyncKVStore, LMDBMessageChannel {
204
211
  const resp = await this.sendMessage(LMDBMessageType.STATS, undefined);
205
212
  return {
206
213
  mappingSize: Number(resp.dbMapSizeBytes),
214
+ physicalFileSize: Number(resp.dbPhysicalFileSizeBytes),
207
215
  actualSize: resp.stats.reduce((s, db) => Number(db.totalUsedSize) + s, 0),
208
216
  numItems: resp.stats.reduce((s, db) => Number(db.numDataItems) + s, 0),
209
217
  };
210
218
  }
211
219
  }
212
-
213
- export function execInWriteTx<T>(store: AztecLMDBStoreV2, fn: (tx: WriteTransaction) => Promise<T>): Promise<T> {
214
- const currentWrite = store.getCurrentWriteTx();
215
- if (currentWrite) {
216
- return fn(currentWrite);
217
- } else {
218
- return store.transactionAsync(fn);
219
- }
220
- }
221
-
222
- export async function execInReadTx<T>(
223
- store: AztecLMDBStoreV2,
224
- fn: (tx: ReadTransaction) => T | Promise<T>,
225
- ): Promise<T> {
226
- const currentWrite = store.getCurrentWriteTx();
227
- if (currentWrite) {
228
- return await fn(currentWrite);
229
- } else {
230
- const tx = store.getReadTx();
231
- try {
232
- return await fn(tx);
233
- } finally {
234
- tx.close();
235
- }
236
- }
237
- }
@@ -0,0 +1,29 @@
1
+ import type { ReadTransaction } from './read_transaction.js';
2
+ import type { AztecLMDBStoreV2 } from './store.js';
3
+ import type { WriteTransaction } from './write_transaction.js';
4
+
5
+ export function execInWriteTx<T>(store: AztecLMDBStoreV2, fn: (tx: WriteTransaction) => Promise<T>): Promise<T> {
6
+ const currentWrite = store.getCurrentWriteTx();
7
+ if (currentWrite) {
8
+ return fn(currentWrite);
9
+ } else {
10
+ return store.transactionAsync(fn);
11
+ }
12
+ }
13
+
14
+ export async function execInReadTx<T>(
15
+ store: AztecLMDBStoreV2,
16
+ fn: (tx: ReadTransaction) => T | Promise<T>,
17
+ ): Promise<T> {
18
+ const currentWrite = store.getCurrentWriteTx();
19
+ if (currentWrite) {
20
+ return await fn(currentWrite);
21
+ } else {
22
+ const tx = store.getReadTx();
23
+ try {
24
+ return await fn(tx);
25
+ } finally {
26
+ tx.close();
27
+ }
28
+ }
29
+ }
@@ -2,124 +2,6 @@ import { MAXIMUM_KEY, fromBufferKey, toBufferKey } from 'ordered-binary';
2
2
 
3
3
  import type { Key } from '../interfaces/common.js';
4
4
 
5
- type Cmp<T> = (a: T, b: T) => -1 | 0 | 1;
6
-
7
- export function dedupeSortedArray<T>(arr: T[], cmp: Cmp<T>): void {
8
- for (let i = 0; i < arr.length; i++) {
9
- let j = i + 1;
10
- for (; j < arr.length; j++) {
11
- const res = cmp(arr[i], arr[j]);
12
- if (res === 0) {
13
- continue;
14
- } else if (res < 0) {
15
- break;
16
- } else {
17
- throw new Error('Array not sorted');
18
- }
19
- }
20
-
21
- if (j - i > 1) {
22
- arr.splice(i + 1, j - i - 1);
23
- }
24
- }
25
- }
26
-
27
- export function insertIntoSortedArray<T>(arr: T[], item: T, cmp: (a: T, b: T) => number): void {
28
- let left = 0;
29
- let right = arr.length;
30
-
31
- while (left < right) {
32
- const mid = (left + right) >> 1;
33
- const comparison = cmp(arr[mid], item);
34
-
35
- if (comparison < 0) {
36
- left = mid + 1;
37
- } else {
38
- right = mid;
39
- }
40
- }
41
-
42
- arr.splice(left, 0, item);
43
- }
44
-
45
- export function findIndexInSortedArray<T, N>(values: T[], needle: N, cmp: (a: T, b: N) => number): number {
46
- let start = 0;
47
- let end = values.length - 1;
48
-
49
- while (start <= end) {
50
- const mid = start + (((end - start) / 2) | 0);
51
- const res = cmp(values[mid], needle);
52
- if (res === 0) {
53
- return mid;
54
- } else if (res > 0) {
55
- end = mid - 1;
56
- } else {
57
- start = mid + 1;
58
- }
59
- }
60
-
61
- return -1;
62
- }
63
-
64
- export function findInSortedArray<T, N>(values: T[], needle: N, cmp: (a: T, b: N) => number): T | undefined {
65
- const idx = findIndexInSortedArray(values, needle, cmp);
66
- return idx > -1 ? values[idx] : undefined;
67
- }
68
-
69
- export function removeAnyOf<T, N>(arr: T[], vals: N[], cmp: (a: T, b: N) => -1 | 0 | 1): void {
70
- let writeIdx = 0;
71
- let readIdx = 0;
72
- let valIdx = 0;
73
-
74
- while (readIdx < arr.length && valIdx < vals.length) {
75
- const comparison = cmp(arr[readIdx], vals[valIdx]);
76
-
77
- if (comparison < 0) {
78
- arr[writeIdx++] = arr[readIdx++];
79
- } else if (comparison > 0) {
80
- valIdx++;
81
- } else {
82
- readIdx++;
83
- }
84
- }
85
-
86
- while (readIdx < arr.length) {
87
- arr[writeIdx++] = arr[readIdx++];
88
- }
89
-
90
- arr.length = writeIdx;
91
- }
92
-
93
- export function removeFromSortedArray<T, N>(arr: T[], val: N, cmp: (a: T, b: N) => -1 | 0 | 1) {
94
- const idx = findIndexInSortedArray(arr, val, cmp);
95
- if (idx > -1) {
96
- arr.splice(idx, 1);
97
- }
98
- }
99
-
100
- export function merge<T>(arr: T[], toInsert: T[], cmp: (a: T, b: T) => -1 | 0 | 1): void {
101
- const result = new Array<T>(arr.length + toInsert.length);
102
- let i = 0,
103
- j = 0,
104
- k = 0;
105
-
106
- while (i < arr.length && j < toInsert.length) {
107
- result[k++] = cmp(arr[i], toInsert[j]) <= 0 ? arr[i++] : toInsert[j++];
108
- }
109
-
110
- while (i < arr.length) {
111
- result[k++] = arr[i++];
112
- }
113
- while (j < toInsert.length) {
114
- result[k++] = toInsert[j++];
115
- }
116
-
117
- for (i = 0; i < result.length; i++) {
118
- arr[i] = result[i];
119
- }
120
- arr.length = result.length;
121
- }
122
-
123
5
  export function keyCmp(a: [Uint8Array, Uint8Array[] | null], b: [Uint8Array, Uint8Array[] | null]): -1 | 0 | 1 {
124
6
  return Buffer.compare(a[0], b[0]);
125
7
  }
@@ -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);
@@ -163,7 +163,7 @@ export class WriteTransaction extends ReadTransaction {
163
163
 
164
164
  public override async *iterate(
165
165
  startKey: Uint8Array,
166
- endKey?: Uint8Array | undefined,
166
+ endKey?: Uint8Array,
167
167
  reverse?: boolean,
168
168
  limit?: number,
169
169
  ): AsyncIterable<[Uint8Array, Uint8Array]> {
@@ -181,7 +181,7 @@ export class WriteTransaction extends ReadTransaction {
181
181
 
182
182
  public override async *iterateIndex(
183
183
  startKey: Uint8Array,
184
- endKey?: Uint8Array | undefined,
184
+ endKey?: Uint8Array,
185
185
  reverse?: boolean,
186
186
  limit?: number,
187
187
  ): AsyncIterable<[Uint8Array, Uint8Array[]]> {
@@ -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 +1,3 @@
1
1
  export * from './l2_tips_store.js';
2
+
3
+ export { L2TipsMemoryStore, type L2TipsStore } from '@aztec/stdlib/block';
@@ -1,70 +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 L2TipsStore 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
+ 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);
50
+ }
51
+ }
52
+
53
+ protected getCheckpointNumberForBlock(blockNumber: BlockNumber): Promise<CheckpointNumber | undefined> {
54
+ return this.l2BlockNumberToCheckpointNumberStore.getAsync(blockNumber);
55
+ }
56
+
57
+ protected setCheckpointNumberForBlock(blockNumber: BlockNumber, checkpointNumber: CheckpointNumber): Promise<void> {
58
+ return this.l2BlockNumberToCheckpointNumberStore.set(blockNumber, checkpointNumber);
59
+ }
60
+
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);
39
64
  }
40
- const blockHash = await this.l2BlockHashesStore.getAsync(blockNumber);
41
- if (!blockHash) {
42
- throw new Error(`Block hash not found for block number ${blockNumber}`);
65
+ }
66
+
67
+ protected async getCheckpoint(checkpointNumber: CheckpointNumber): Promise<PublishedCheckpoint | undefined> {
68
+ const buffer = await this.l2CheckpointStore.getAsync(checkpointNumber);
69
+ if (!buffer) {
70
+ return undefined;
43
71
  }
72
+ return PublishedCheckpoint.fromBuffer(buffer);
73
+ }
44
74
 
45
- return { number: blockNumber, hash: blockHash };
75
+ protected saveCheckpointData(checkpoint: PublishedCheckpoint): Promise<void> {
76
+ return this.l2CheckpointStore.set(checkpoint.checkpoint.number, checkpoint.toBuffer());
46
77
  }
47
78
 
48
- public async handleBlockStreamEvent(event: L2BlockStreamEvent): Promise<void> {
49
- switch (event.type) {
50
- case 'blocks-added':
51
- for (const block of event.blocks) {
52
- await this.l2BlockHashesStore.set(block.number, (await block.header.hash()).toString());
53
- }
54
- await this.l2TipsStore.set('latest', event.blocks.at(-1)!.number);
55
- break;
56
- case 'chain-pruned':
57
- await this.l2TipsStore.set('latest', event.blockNumber);
58
- break;
59
- case 'chain-proven':
60
- await this.l2TipsStore.set('proven', event.blockNumber);
61
- break;
62
- case 'chain-finalized':
63
- await this.l2TipsStore.set('finalized', event.blockNumber);
64
- for await (const key of this.l2BlockHashesStore.keysAsync({ end: event.blockNumber })) {
65
- await this.l2BlockHashesStore.delete(key);
66
- }
67
- break;
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);
68
82
  }
69
83
  }
84
+
85
+ protected runInTransaction<T>(fn: () => Promise<T>): Promise<T> {
86
+ return this.store.transactionAsync(fn);
87
+ }
70
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
+ }
@@ -1,3 +0,0 @@
1
- import type { AztecAsyncKVStore, AztecKVStore } from './store.js';
2
- export declare function describeAztecStore(testName: string, getPersistentStore: () => Promise<AztecKVStore | AztecAsyncKVStore>, getPersistentNoPathStore: () => Promise<AztecKVStore | AztecAsyncKVStore>, getEphemeralStore: () => Promise<AztecKVStore | AztecAsyncKVStore>): void;
3
- //# sourceMappingURL=store_test_suite.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"store_test_suite.d.ts","sourceRoot":"","sources":["../../src/interfaces/store_test_suite.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAGlE,wBAAgB,kBAAkB,CAChC,QAAQ,EAAE,MAAM,EAChB,kBAAkB,EAAE,MAAM,OAAO,CAAC,YAAY,GAAG,iBAAiB,CAAC,EACnE,wBAAwB,EAAE,MAAM,OAAO,CAAC,YAAY,GAAG,iBAAiB,CAAC,EACzE,iBAAiB,EAAE,MAAM,OAAO,CAAC,YAAY,GAAG,iBAAiB,CAAC,QA6CnE"}
@@ -1,37 +0,0 @@
1
- import { expect } from 'chai';
2
- import { isSyncStore } from './utils.js';
3
- export function describeAztecStore(testName, getPersistentStore, getPersistentNoPathStore, getEphemeralStore) {
4
- describe(testName, ()=>{
5
- async function get(store, singleton) {
6
- return isSyncStore(store) ? singleton.get() : await singleton.getAsync();
7
- }
8
- const itForks = async (store)=>{
9
- const singleton = store.openSingleton('singleton');
10
- await singleton.set('foo');
11
- const forkedStore = await store.fork();
12
- const forkedSingleton = forkedStore.openSingleton('singleton');
13
- expect(await get(store, singleton)).to.equal('foo');
14
- await forkedSingleton.set('bar');
15
- expect(await get(store, singleton)).to.equal('foo');
16
- expect(await get(forkedStore, forkedSingleton)).to.equal('bar');
17
- await forkedSingleton.delete();
18
- expect(await get(store, singleton)).to.equal('foo');
19
- await forkedStore.delete();
20
- };
21
- it('forks a persistent store', async ()=>{
22
- const store = await getPersistentStore();
23
- await itForks(store);
24
- await store.delete();
25
- });
26
- it('forks a persistent store with no path', async ()=>{
27
- const store = await getPersistentNoPathStore();
28
- await itForks(store);
29
- await store.delete();
30
- });
31
- it('forks an ephemeral store', async ()=>{
32
- const store = await getEphemeralStore();
33
- await itForks(store);
34
- await store.delete();
35
- });
36
- });
37
- }