@aztec/kv-store 0.0.1-commit.b6e433891 → 0.0.1-commit.b9865e97

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 (91) hide show
  1. package/README.md +8 -1
  2. package/dest/bench/shared_map_bench.d.ts +19 -0
  3. package/dest/bench/shared_map_bench.d.ts.map +1 -0
  4. package/dest/bench/shared_map_bench.js +91 -0
  5. package/dest/indexeddb/index.js +1 -1
  6. package/dest/interfaces/array_test_suite.d.ts +1 -1
  7. package/dest/interfaces/array_test_suite.d.ts.map +1 -1
  8. package/dest/interfaces/array_test_suite.js +33 -34
  9. package/dest/interfaces/index.d.ts +2 -2
  10. package/dest/interfaces/index.d.ts.map +1 -1
  11. package/dest/interfaces/map_test_suite.d.ts +1 -1
  12. package/dest/interfaces/map_test_suite.d.ts.map +1 -1
  13. package/dest/interfaces/map_test_suite.js +32 -33
  14. package/dest/interfaces/multi_map_test_suite.d.ts +1 -1
  15. package/dest/interfaces/multi_map_test_suite.d.ts.map +1 -1
  16. package/dest/interfaces/multi_map_test_suite.js +68 -69
  17. package/dest/interfaces/set_test_suite.d.ts +1 -1
  18. package/dest/interfaces/set_test_suite.d.ts.map +1 -1
  19. package/dest/interfaces/set_test_suite.js +13 -14
  20. package/dest/interfaces/singleton_test_suite.d.ts +1 -1
  21. package/dest/interfaces/singleton_test_suite.d.ts.map +1 -1
  22. package/dest/interfaces/singleton_test_suite.js +6 -7
  23. package/dest/lmdb/index.js +2 -2
  24. package/dest/lmdb-v2/factory.d.ts +28 -3
  25. package/dest/lmdb-v2/factory.d.ts.map +1 -1
  26. package/dest/lmdb-v2/factory.js +61 -10
  27. package/dest/lmdb-v2/read_transaction.js +21 -19
  28. package/dest/lmdb-v2/store.d.ts +2 -2
  29. package/dest/lmdb-v2/store.d.ts.map +1 -1
  30. package/dest/lmdb-v2/store.js +4 -4
  31. package/dest/sqlite-opfs/array.d.ts +21 -0
  32. package/dest/sqlite-opfs/array.d.ts.map +1 -0
  33. package/dest/sqlite-opfs/array.js +128 -0
  34. package/dest/sqlite-opfs/errors.d.ts +27 -0
  35. package/dest/sqlite-opfs/errors.d.ts.map +1 -0
  36. package/dest/sqlite-opfs/errors.js +34 -0
  37. package/dest/sqlite-opfs/index.d.ts +16 -0
  38. package/dest/sqlite-opfs/index.d.ts.map +1 -0
  39. package/dest/sqlite-opfs/index.js +22 -0
  40. package/dest/sqlite-opfs/internal/ordered-binary-browser.d.ts +32 -0
  41. package/dest/sqlite-opfs/internal/ordered-binary-browser.d.ts.map +1 -0
  42. package/dest/sqlite-opfs/internal/ordered-binary-browser.js +448 -0
  43. package/dest/sqlite-opfs/map.d.ts +35 -0
  44. package/dest/sqlite-opfs/map.d.ts.map +1 -0
  45. package/dest/sqlite-opfs/map.js +163 -0
  46. package/dest/sqlite-opfs/messages.d.ts +66 -0
  47. package/dest/sqlite-opfs/messages.d.ts.map +1 -0
  48. package/dest/sqlite-opfs/messages.js +5 -0
  49. package/dest/sqlite-opfs/multi_map.d.ts +16 -0
  50. package/dest/sqlite-opfs/multi_map.d.ts.map +1 -0
  51. package/dest/sqlite-opfs/multi_map.js +67 -0
  52. package/dest/sqlite-opfs/set.d.ts +13 -0
  53. package/dest/sqlite-opfs/set.d.ts.map +1 -0
  54. package/dest/sqlite-opfs/set.js +19 -0
  55. package/dest/sqlite-opfs/singleton.d.ts +13 -0
  56. package/dest/sqlite-opfs/singleton.d.ts.map +1 -0
  57. package/dest/sqlite-opfs/singleton.js +48 -0
  58. package/dest/sqlite-opfs/store.d.ts +79 -0
  59. package/dest/sqlite-opfs/store.d.ts.map +1 -0
  60. package/dest/sqlite-opfs/store.js +281 -0
  61. package/dest/sqlite-opfs/worker.d.ts +2 -0
  62. package/dest/sqlite-opfs/worker.d.ts.map +1 -0
  63. package/dest/sqlite-opfs/worker.js +249 -0
  64. package/dest/stores/l2_tips_store.d.ts +3 -3
  65. package/dest/stores/l2_tips_store.d.ts.map +1 -1
  66. package/dest/stores/l2_tips_store.js +2 -2
  67. package/package.json +22 -19
  68. package/src/bench/shared_map_bench.ts +111 -0
  69. package/src/indexeddb/index.ts +1 -1
  70. package/src/interfaces/array_test_suite.ts +33 -35
  71. package/src/interfaces/index.ts +1 -1
  72. package/src/interfaces/map_test_suite.ts +32 -34
  73. package/src/interfaces/multi_map_test_suite.ts +65 -67
  74. package/src/interfaces/set_test_suite.ts +13 -15
  75. package/src/interfaces/singleton_test_suite.ts +6 -8
  76. package/src/lmdb/index.ts +2 -2
  77. package/src/lmdb-v2/factory.ts +79 -9
  78. package/src/lmdb-v2/read_transaction.ts +23 -23
  79. package/src/lmdb-v2/store.ts +4 -2
  80. package/src/sqlite-opfs/array.ts +124 -0
  81. package/src/sqlite-opfs/errors.ts +44 -0
  82. package/src/sqlite-opfs/index.ts +39 -0
  83. package/src/sqlite-opfs/internal/ordered-binary-browser.js +465 -0
  84. package/src/sqlite-opfs/map.ts +163 -0
  85. package/src/sqlite-opfs/messages.ts +39 -0
  86. package/src/sqlite-opfs/multi_map.ts +74 -0
  87. package/src/sqlite-opfs/set.ts +29 -0
  88. package/src/sqlite-opfs/singleton.ts +48 -0
  89. package/src/sqlite-opfs/store.ts +296 -0
  90. package/src/sqlite-opfs/worker.ts +231 -0
  91. package/src/stores/l2_tips_store.ts +3 -2
@@ -1,9 +1,9 @@
1
1
  import { EthAddress } from '@aztec/foundation/eth-address';
2
2
  import { type LoggerBindings, createLogger } from '@aztec/foundation/log';
3
- import { DatabaseVersionManager } from '@aztec/stdlib/database-version/manager';
3
+ import { DatabaseVersionManager, type SchemaVersionMismatchPolicy } from '@aztec/stdlib/database-version/manager';
4
4
  import type { DataStoreConfig } from '@aztec/stdlib/kv-store';
5
5
 
6
- import { mkdir, mkdtemp, rm } from 'fs/promises';
6
+ import { copyFile, mkdir, mkdtemp, rm } from 'fs/promises';
7
7
  import { tmpdir } from 'os';
8
8
  import { join } from 'path';
9
9
 
@@ -11,14 +11,21 @@ import { AztecLMDBStoreV2 } from './store.js';
11
11
 
12
12
  const MAX_READERS = 16;
13
13
 
14
+ /** Optional versioning hooks for persistent LMDB stores. */
15
+ export type CreateStoreOptions = {
16
+ onUpgrade?: (dataDir: string, currentVersion: number, latestVersion: number) => Promise<void>;
17
+ schemaVersionMismatchPolicy?: SchemaVersionMismatchPolicy;
18
+ };
19
+
14
20
  export async function createStore(
15
21
  name: string,
16
22
  schemaVersion: number,
17
23
  config: DataStoreConfig,
18
24
  bindings?: LoggerBindings,
25
+ options: CreateStoreOptions = {},
19
26
  ): Promise<AztecLMDBStoreV2> {
20
27
  const log = createLogger('kv-store:lmdb-v2:' + name, bindings);
21
- const { dataDirectory, l1Contracts } = config;
28
+ const { dataDirectory, rollupAddress: rollupFromConfig } = config;
22
29
 
23
30
  let store: AztecLMDBStoreV2;
24
31
  if (typeof dataDirectory !== 'undefined') {
@@ -26,7 +33,7 @@ export async function createStore(
26
33
  const subDir = join(dataDirectory, name);
27
34
  await mkdir(subDir, { recursive: true });
28
35
 
29
- const rollupAddress = l1Contracts ? l1Contracts.rollupAddress : EthAddress.ZERO;
36
+ const rollupAddress = rollupFromConfig ?? EthAddress.ZERO;
30
37
 
31
38
  // Create a version manager
32
39
  const versionManager = new DatabaseVersionManager({
@@ -35,6 +42,8 @@ export async function createStore(
35
42
  dataDirectory: subDir,
36
43
  onOpen: dbDirectory =>
37
44
  AztecLMDBStoreV2.new(dbDirectory, config.dataStoreMapSizeKb, MAX_READERS, () => Promise.resolve(), bindings),
45
+ onUpgrade: options.onUpgrade,
46
+ schemaVersionMismatchPolicy: options.schemaVersionMismatchPolicy,
38
47
  });
39
48
 
40
49
  log.info(
@@ -48,9 +57,14 @@ export async function createStore(
48
57
  return store;
49
58
  }
50
59
 
60
+ /**
61
+ * Open a persistent on-disk store rooted in OS tmpdir. Caller chooses whether to
62
+ * auto-remove the directory on close. Uses standard durable LMDB flags (fsync on
63
+ * every commit) — for full in-memory / NOSYNC semantics use `openEphemeralStore`.
64
+ */
51
65
  export async function openTmpStore(
52
66
  name: string,
53
- ephemeral: boolean = true,
67
+ cleanupTmpDir: boolean = true,
54
68
  dbMapSizeKb = 10 * 1_024 * 1_024, // 10GB
55
69
  maxReaders = MAX_READERS,
56
70
  bindings?: LoggerBindings,
@@ -61,7 +75,7 @@ export async function openTmpStore(
61
75
 
62
76
  // pass a cleanup callback because process.on('beforeExit', cleanup) does not work under Jest
63
77
  const cleanup = async () => {
64
- if (ephemeral) {
78
+ if (cleanupTmpDir) {
65
79
  try {
66
80
  await rm(dataDir, { recursive: true, force: true, maxRetries: 3 });
67
81
  log.debug(`Deleted temporary data store: ${dataDir}`);
@@ -73,9 +87,35 @@ export async function openTmpStore(
73
87
  }
74
88
  };
75
89
 
76
- // For temporary stores, we don't need to worry about versioning
77
- // as they are ephemeral and get cleaned up after use
78
- return AztecLMDBStoreV2.new(dataDir, dbMapSizeKb, maxReaders, cleanup, bindings);
90
+ return AztecLMDBStoreV2.new(dataDir, dbMapSizeKb, maxReaders, cleanup, bindings, false);
91
+ }
92
+
93
+ /**
94
+ * Open a fully-ephemeral store: a fresh tmpdir backing file, LMDB opened with
95
+ * MDB_NOSYNC | MDB_NOMETASYNC (no fsync, kernel-only writeback), and the directory
96
+ * unconditionally removed on close. Intended for tests and worker-local scratch
97
+ * stores where durability is explicitly not desired.
98
+ */
99
+ export async function openEphemeralStore(
100
+ name: string,
101
+ dbMapSizeKb = 10 * 1_024 * 1_024, // 10GB
102
+ maxReaders = MAX_READERS,
103
+ bindings?: LoggerBindings,
104
+ ): Promise<AztecLMDBStoreV2> {
105
+ const log = createLogger('kv-store:lmdb-v2:' + name, bindings);
106
+ const dataDir = await mkdtemp(join(tmpdir(), name + '-'));
107
+ log.debug(`Created ephemeral data store at: ${dataDir} with size: ${dbMapSizeKb} KB (LMDB v2)`);
108
+
109
+ const cleanup = async () => {
110
+ try {
111
+ await rm(dataDir, { recursive: true, force: true, maxRetries: 3 });
112
+ log.debug(`Deleted ephemeral data store: ${dataDir}`);
113
+ } catch (err) {
114
+ log.warn(`Failed to delete ephemeral data directory (LMDB v2) ${dataDir}: ${err}`);
115
+ }
116
+ };
117
+
118
+ return AztecLMDBStoreV2.new(dataDir, dbMapSizeKb, maxReaders, cleanup, bindings, true);
79
119
  }
80
120
 
81
121
  export async function openStoreAt(
@@ -89,6 +129,36 @@ export async function openStoreAt(
89
129
  return await AztecLMDBStoreV2.new(dataDir, dbMapSizeKb, maxReaders, undefined, bindings);
90
130
  }
91
131
 
132
+ /**
133
+ * Open a fully-ephemeral store seeded from an existing `data.mdb` file. Creates a fresh tmpdir,
134
+ * copies `srcDataMdbPath` into it as `data.mdb`, opens with MDB_NOSYNC | MDB_NOMETASYNC, and
135
+ * removes the tmpdir on close. Intended for worker clones of a main-thread-built store — the
136
+ * source file is never written to.
137
+ */
138
+ export async function cloneEphemeralStoreFrom(
139
+ srcDataMdbPath: string,
140
+ name: string,
141
+ dbMapSizeKb = 10 * 1_024 * 1_024, // 10GB
142
+ maxReaders = MAX_READERS,
143
+ bindings?: LoggerBindings,
144
+ ): Promise<AztecLMDBStoreV2> {
145
+ const log = createLogger('kv-store:lmdb-v2:' + name, bindings);
146
+ const dataDir = await mkdtemp(join(tmpdir(), name + '-'));
147
+ await copyFile(srcDataMdbPath, join(dataDir, 'data.mdb'));
148
+ log.debug(`Cloned ephemeral data store at: ${dataDir} from ${srcDataMdbPath} (LMDB v2)`);
149
+
150
+ const cleanup = async () => {
151
+ try {
152
+ await rm(dataDir, { recursive: true, force: true, maxRetries: 3 });
153
+ log.debug(`Deleted ephemeral data store: ${dataDir}`);
154
+ } catch (err) {
155
+ log.warn(`Failed to delete ephemeral data directory (LMDB v2) ${dataDir}: ${err}`);
156
+ }
157
+ };
158
+
159
+ return AztecLMDBStoreV2.new(dataDir, dbMapSizeKb, maxReaders, cleanup, bindings, true);
160
+ }
161
+
92
162
  export async function openVersionedStoreAt(
93
163
  dataDirectory: string,
94
164
  schemaVersion: number,
@@ -66,20 +66,20 @@ export class ReadTransaction {
66
66
  ): AsyncIterable<[Uint8Array, T]> {
67
67
  this.assertIsOpen();
68
68
 
69
- const response = await this.channel.sendMessage(LMDBMessageType.START_CURSOR, {
70
- key: startKey,
71
- reverse,
72
- count: typeof limit === 'number' ? Math.min(limit, CURSOR_PAGE_SIZE) : CURSOR_PAGE_SIZE,
73
- onePage: typeof limit === 'number' && limit < CURSOR_PAGE_SIZE,
74
- db,
75
- });
76
-
77
- const cursor = response.cursor;
78
- let entries = response.entries;
79
- let done = typeof cursor !== 'number';
80
- let count = 0;
81
-
69
+ let cursor: number | undefined;
82
70
  try {
71
+ const response = await this.channel.sendMessage(LMDBMessageType.START_CURSOR, {
72
+ key: startKey,
73
+ reverse,
74
+ count: typeof limit === 'number' ? Math.min(limit, CURSOR_PAGE_SIZE) : CURSOR_PAGE_SIZE,
75
+ onePage: typeof limit === 'number' && limit < CURSOR_PAGE_SIZE,
76
+ db,
77
+ });
78
+
79
+ cursor = response.cursor ?? undefined;
80
+ let entries = response.entries;
81
+ let done = typeof cursor !== 'number';
82
+ let count = 0;
83
83
  // emit the first page and any subsequent pages in a while loop
84
84
  // NB: end contition is in the middle of the while loop
85
85
  while (entries.length > 0) {
@@ -125,17 +125,17 @@ export class ReadTransaction {
125
125
  async #countEntries(db: string, startKey: Uint8Array, endKey: Uint8Array, reverse: boolean): Promise<number> {
126
126
  this.assertIsOpen();
127
127
 
128
- const response = await this.channel.sendMessage(LMDBMessageType.START_CURSOR, {
129
- key: startKey,
130
- reverse,
131
- count: 0,
132
- onePage: false,
133
- db,
134
- });
135
-
136
- const cursor = response.cursor;
137
-
128
+ let cursor: number | undefined;
138
129
  try {
130
+ const response = await this.channel.sendMessage(LMDBMessageType.START_CURSOR, {
131
+ key: startKey,
132
+ reverse,
133
+ count: 0,
134
+ onePage: false,
135
+ db,
136
+ });
137
+
138
+ cursor = response.cursor ?? undefined;
139
139
  if (!cursor) {
140
140
  return 0;
141
141
  }
@@ -43,9 +43,10 @@ export class AztecLMDBStoreV2 implements AztecAsyncKVStore, LMDBMessageChannel {
43
43
  maxReaders: number,
44
44
  private log: Logger,
45
45
  private cleanup?: () => Promise<void>,
46
+ ephemeral: boolean = false,
46
47
  ) {
47
48
  this.log.info(`Starting data store with maxReaders ${maxReaders}`);
48
- this.channel = new MsgpackChannel(new NativeLMDBStore(dataDir, mapSize, maxReaders));
49
+ this.channel = new MsgpackChannel(new NativeLMDBStore(dataDir, mapSize, maxReaders, ephemeral));
49
50
  // leave one reader to always be available for regular, atomic, reads
50
51
  this.availableCursors = new Semaphore(maxReaders - 1);
51
52
  }
@@ -76,9 +77,10 @@ export class AztecLMDBStoreV2 implements AztecAsyncKVStore, LMDBMessageChannel {
76
77
  maxReaders: number = 16,
77
78
  cleanup?: () => Promise<void>,
78
79
  bindings?: LoggerBindings,
80
+ ephemeral: boolean = false,
79
81
  ) {
80
82
  const log = createLogger('kv-store:lmdb-v2', bindings);
81
- const db = new AztecLMDBStoreV2(dataDir, dbMapSizeKb, maxReaders, log, cleanup);
83
+ const db = new AztecLMDBStoreV2(dataDir, dbMapSizeKb, maxReaders, log, cleanup, ephemeral);
82
84
  await db.start();
83
85
  return db;
84
86
  }
@@ -0,0 +1,124 @@
1
+ import { Encoder } from '#msgpackr';
2
+ import { toBufferKey } from '#ordered-binary';
3
+ import { hash } from 'ohash';
4
+
5
+ import type { AztecAsyncArray } from '../interfaces/array.js';
6
+ import type { Value } from '../interfaces/common.js';
7
+ import type { AztecSQLiteOPFSStore } from './store.js';
8
+
9
+ /**
10
+ * Persistent array backed by SQLite. Entries share a common `key` (the array name)
11
+ * and are ordered by `key_count`, which doubles as the 1-indexed slot number.
12
+ */
13
+ export class SQLiteOPFSAztecArray<T extends Value> implements AztecAsyncArray<T> {
14
+ readonly #name: string;
15
+ readonly #container: string;
16
+ readonly #encoder = new Encoder();
17
+
18
+ constructor(
19
+ private readonly store: AztecSQLiteOPFSStore,
20
+ name: string,
21
+ ) {
22
+ this.#name = name;
23
+ this.#container = `array:${name}`;
24
+ }
25
+
26
+ async lengthAsync(): Promise<number> {
27
+ const rows = await this.store.allAsync('SELECT COUNT(*) FROM data WHERE container = ? AND key = ?', [
28
+ this.#container,
29
+ this.#encodedKey(),
30
+ ]);
31
+ return Number(rows[0]?.[0] ?? 0);
32
+ }
33
+
34
+ async push(...vals: T[]): Promise<number> {
35
+ if (vals.length === 0) {
36
+ return this.lengthAsync();
37
+ }
38
+ return await this.store.transactionAsync(async () => {
39
+ let length = await this.lengthAsync();
40
+ for (const val of vals) {
41
+ await this.store.runAsync(
42
+ `INSERT INTO data (slot, container, key, key_count, hash, value)
43
+ VALUES (?, ?, ?, ?, ?, ?)`,
44
+ [this.#slot(length), this.#container, this.#encodedKey(), length + 1, hash(val), this.#encoder.pack(val)],
45
+ );
46
+ length += 1;
47
+ }
48
+ return length;
49
+ });
50
+ }
51
+
52
+ async pop(): Promise<T | undefined> {
53
+ return await this.store.transactionAsync(async () => {
54
+ const length = await this.lengthAsync();
55
+ if (length === 0) {
56
+ return undefined;
57
+ }
58
+ const slot = this.#slot(length - 1);
59
+ const rows = await this.store.allAsync('SELECT value FROM data WHERE slot = ? LIMIT 1', [slot]);
60
+ await this.store.runAsync('DELETE FROM data WHERE slot = ?', [slot]);
61
+ const raw = rows[0]?.[0];
62
+ return raw instanceof Uint8Array ? (this.#encoder.unpack(raw) as T) : undefined;
63
+ });
64
+ }
65
+
66
+ async atAsync(index: number): Promise<T | undefined> {
67
+ const length = await this.lengthAsync();
68
+ const resolved = index < 0 ? length + index : index;
69
+ if (resolved < 0 || resolved >= length) {
70
+ return undefined;
71
+ }
72
+ const rows = await this.store.allAsync('SELECT value FROM data WHERE slot = ? LIMIT 1', [this.#slot(resolved)]);
73
+ const raw = rows[0]?.[0];
74
+ return raw instanceof Uint8Array ? (this.#encoder.unpack(raw) as T) : undefined;
75
+ }
76
+
77
+ async setAt(index: number, val: T): Promise<boolean> {
78
+ return await this.store.transactionAsync(async () => {
79
+ const length = await this.lengthAsync();
80
+ const resolved = index < 0 ? length + index : index;
81
+ if (resolved < 0 || resolved >= length) {
82
+ return false;
83
+ }
84
+ await this.store.runAsync(
85
+ `INSERT OR REPLACE INTO data (slot, container, key, key_count, hash, value)
86
+ VALUES (?, ?, ?, ?, ?, ?)`,
87
+ [this.#slot(resolved), this.#container, this.#encodedKey(), resolved + 1, hash(val), this.#encoder.pack(val)],
88
+ );
89
+ return true;
90
+ });
91
+ }
92
+
93
+ async *entriesAsync(): AsyncIterableIterator<[number, T]> {
94
+ const rows = await this.store.allAsync(
95
+ 'SELECT key_count, value FROM data WHERE container = ? AND key = ? ORDER BY key_count ASC',
96
+ [this.#container, this.#encodedKey()],
97
+ );
98
+ for (const row of rows) {
99
+ const keyCount = Number(row[0]);
100
+ const raw = row[1];
101
+ if (raw instanceof Uint8Array) {
102
+ yield [keyCount - 1, this.#encoder.unpack(raw) as T];
103
+ }
104
+ }
105
+ }
106
+
107
+ async *valuesAsync(): AsyncIterableIterator<T> {
108
+ for await (const [, val] of this.entriesAsync()) {
109
+ yield val;
110
+ }
111
+ }
112
+
113
+ [Symbol.asyncIterator](): AsyncIterableIterator<T> {
114
+ return this.valuesAsync();
115
+ }
116
+
117
+ #encodedKey(): Buffer {
118
+ return toBufferKey([this.#name]);
119
+ }
120
+
121
+ #slot(index: number): string {
122
+ return `array:${this.#name}:slot:${index}`;
123
+ }
124
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Typed error surface for sqlite3mc-backed page-level encryption failures.
3
+ *
4
+ * Three concrete failure modes are surfaced:
5
+ *
6
+ * - `invalid_key_length`: caller-side pre-flight (key not 32 bytes).
7
+ * - `encryption_not_supported_for_ephemeral`: caller-side pre-flight (encryption was requested on an ephemeral
8
+ * `:memory:` store, which sqlite3mc does not support).
9
+ * - `decrypt_failed`: runtime failure raised when sqlite3mc cannot decode page 1 of an existing database. Covers
10
+ * both "wrong key supplied" and "no key supplied to an encrypted DB".
11
+ */
12
+ export type SqliteEncryptionErrorCode =
13
+ | 'invalid_key_length'
14
+ | 'encryption_not_supported_for_ephemeral'
15
+ | 'decrypt_failed';
16
+
17
+ /**
18
+ * Error thrown by sqlite-opfs when an encryption operation fails.
19
+ **/
20
+ export class SqliteEncryptionError extends Error {
21
+ readonly code: SqliteEncryptionErrorCode;
22
+
23
+ constructor(code: SqliteEncryptionErrorCode, message: string, opts?: { cause?: unknown }) {
24
+ super(message, opts?.cause !== undefined ? { cause: opts.cause } : undefined);
25
+ this.name = 'SqliteEncryptionError';
26
+ this.code = code;
27
+ }
28
+ }
29
+
30
+ /**
31
+ * Strings raised by sqlite3mc when page 1 cannot be decoded.
32
+ **/
33
+ const SQLITE3MC_DECRYPT_ERROR_PATTERNS: readonly RegExp[] = [
34
+ /file is not a database/i,
35
+ /file is encrypted or is not a database/i,
36
+ ];
37
+
38
+ /**
39
+ * Returns `true` if `message` matches one of the known sqlite3mc decrypt-failure
40
+ * strings.
41
+ **/
42
+ export function isDecryptFailureMessage(message: string): boolean {
43
+ return SQLITE3MC_DECRYPT_ERROR_PATTERNS.some(p => p.test(message));
44
+ }
@@ -0,0 +1,39 @@
1
+ import { type Logger, createLogger } from '@aztec/foundation/log';
2
+ import type { DataStoreConfig } from '@aztec/stdlib/kv-store';
3
+
4
+ import { initStoreForRollupAndSchemaVersion } from '../utils.js';
5
+ import { AztecSQLiteOPFSStore } from './store.js';
6
+
7
+ export { AztecSQLiteOPFSStore } from './store.js';
8
+ export { SqliteEncryptionError } from './errors.js';
9
+ export type { SqliteEncryptionErrorCode } from './errors.js';
10
+
11
+ export async function createStore(
12
+ name: string,
13
+ config: DataStoreConfig,
14
+ schemaVersion: number | undefined = undefined,
15
+ log: Logger = createLogger('kv-store'),
16
+ ) {
17
+ const { dataDirectory } = config;
18
+ log.info(
19
+ dataDirectory
20
+ ? `Creating ${name} SQLite-OPFS data store with map size ${config.dataStoreMapSizeKb} KB`
21
+ : `Creating ${name} ephemeral SQLite-OPFS data store with map size ${config.dataStoreMapSizeKb} KB`,
22
+ );
23
+ const store = await AztecSQLiteOPFSStore.open(createLogger('kv-store:sqlite-opfs'), name, false);
24
+ return initStoreForRollupAndSchemaVersion(store, schemaVersion, config.rollupAddress, log);
25
+ }
26
+
27
+ export function openTmpStore(ephemeral: boolean = false): Promise<AztecSQLiteOPFSStore> {
28
+ return AztecSQLiteOPFSStore.open(createLogger('kv-store:sqlite-opfs'), undefined, ephemeral);
29
+ }
30
+
31
+ /**
32
+ * Convenience helper for tests and consumers that want an encrypted sqlite-opfs
33
+ * store without dealing with the full `open()` parameter order. Key must be 32
34
+ * bytes. Creates a fresh persistent store (sqlite3mc does not support encryption
35
+ * on ephemeral `:memory:` databases) in an auto-generated OPFS directory.
36
+ */
37
+ export function openEncryptedStore(encryptionKey: Uint8Array, name?: string, poolDirectory?: string) {
38
+ return AztecSQLiteOPFSStore.open(createLogger('kv-store:sqlite-opfs'), name, false, poolDirectory, encryptionKey);
39
+ }