@aztec/wallets 0.0.1-commit.a89ec08 → 0.0.1-commit.aa0c64f

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 (36) hide show
  1. package/dest/embedded/account-contract-providers/bundle.d.ts +3 -6
  2. package/dest/embedded/account-contract-providers/bundle.d.ts.map +1 -1
  3. package/dest/embedded/account-contract-providers/bundle.js +10 -9
  4. package/dest/embedded/account-contract-providers/lazy.d.ts +3 -6
  5. package/dest/embedded/account-contract-providers/lazy.d.ts.map +1 -1
  6. package/dest/embedded/account-contract-providers/lazy.js +10 -10
  7. package/dest/embedded/account-contract-providers/types.d.ts +3 -6
  8. package/dest/embedded/account-contract-providers/types.d.ts.map +1 -1
  9. package/dest/embedded/embedded_wallet.d.ts +29 -4
  10. package/dest/embedded/embedded_wallet.d.ts.map +1 -1
  11. package/dest/embedded/embedded_wallet.js +136 -45
  12. package/dest/embedded/entrypoints/browser.d.ts +1 -1
  13. package/dest/embedded/entrypoints/browser.d.ts.map +1 -1
  14. package/dest/embedded/entrypoints/browser.js +33 -13
  15. package/dest/embedded/entrypoints/node.d.ts +1 -1
  16. package/dest/embedded/entrypoints/node.d.ts.map +1 -1
  17. package/dest/embedded/entrypoints/node.js +36 -13
  18. package/dest/embedded/store_encryption.d.ts +74 -0
  19. package/dest/embedded/store_encryption.d.ts.map +1 -0
  20. package/dest/embedded/store_encryption.js +93 -0
  21. package/dest/embedded/wallet_db.d.ts +9 -6
  22. package/dest/embedded/wallet_db.d.ts.map +1 -1
  23. package/dest/embedded/wallet_db.js +13 -11
  24. package/dest/testing.d.ts +8 -4
  25. package/dest/testing.d.ts.map +1 -1
  26. package/dest/testing.js +8 -14
  27. package/package.json +17 -15
  28. package/src/embedded/account-contract-providers/bundle.ts +12 -11
  29. package/src/embedded/account-contract-providers/lazy.ts +12 -12
  30. package/src/embedded/account-contract-providers/types.ts +2 -2
  31. package/src/embedded/embedded_wallet.ts +163 -40
  32. package/src/embedded/entrypoints/browser.ts +32 -17
  33. package/src/embedded/entrypoints/node.ts +37 -21
  34. package/src/embedded/store_encryption.ts +146 -0
  35. package/src/embedded/wallet_db.ts +18 -12
  36. package/src/testing.ts +11 -17
@@ -0,0 +1,146 @@
1
+ /**
2
+ * Wallet-layer helpers for opening the embedded wallet's two encrypted stores (PXE + walletDB) as a cohesive unit.
3
+ *
4
+ * Sits on top of `@aztec/kv-store/sqlite-opfs`'s typed `SqliteEncryptionError` and adds:
5
+ *
6
+ * - `storeName: 'pxe' | 'wallet'`, telling callers WHICH store failed.
7
+ * - Cleanup: when the wallet store fails to open, ensures the already-opened PXE store is closed before the error
8
+ * surfaces, so callers don't leak the SAH Pool's OPFS lock.
9
+ */
10
+ import type { Logger } from '@aztec/foundation/log';
11
+ import {
12
+ AztecSQLiteOPFSStore,
13
+ SqliteCorruptionError,
14
+ SqliteEncryptionError,
15
+ deletePoolDirectory,
16
+ } from '@aztec/kv-store/sqlite-opfs';
17
+
18
+ /** Which of the embedded wallet's two stores failed to open. */
19
+ export type EmbeddedStoreName = 'pxe' | 'wallet';
20
+
21
+ /**
22
+ * Thrown by {@link openEncryptedEmbeddedStores} when one of the two stores cannot be decrypted with the supplied
23
+ * key. The original {@link SqliteEncryptionError} is preserved as `cause`.
24
+ */
25
+ export class EmbeddedWalletEncryptionError extends Error {
26
+ readonly storeName: EmbeddedStoreName;
27
+
28
+ constructor(storeName: EmbeddedStoreName, opts: { cause: SqliteEncryptionError }) {
29
+ super(`Embedded wallet '${storeName}' store could not be decrypted with the provided key`, { cause: opts.cause });
30
+ this.name = 'EmbeddedWalletEncryptionError';
31
+ this.storeName = storeName;
32
+ }
33
+ }
34
+
35
+ /** Configuration for {@link openEncryptedEmbeddedStores}. */
36
+ export interface OpenEncryptedEmbeddedStoresOptions {
37
+ pxe: { name: string; poolDirectory?: string };
38
+ wallet: { name: string; poolDirectory?: string };
39
+ }
40
+
41
+ /**
42
+ * Internal seam for tests to inject a fake store opener. Defaults to `AztecSQLiteOPFSStore.open`. Not part of the
43
+ * public API.
44
+ *
45
+ * @internal
46
+ */
47
+ export type OpenSqliteEncryptedStoreFn = (
48
+ log: Logger,
49
+ name: string,
50
+ poolDirectory: string | undefined,
51
+ encryptionKey: Uint8Array,
52
+ ) => Promise<AztecSQLiteOPFSStore>;
53
+
54
+ const defaultOpenStore: OpenSqliteEncryptedStoreFn = (log, name, poolDirectory, encryptionKey) =>
55
+ AztecSQLiteOPFSStore.open(log, name, false, poolDirectory, encryptionKey);
56
+
57
+ /**
58
+ * Internal seam for tests to inject a fake store wiper. Defaults to removing the store's OPFS pool directory
59
+ * outright. Not part of the public API.
60
+ *
61
+ * @internal
62
+ */
63
+ export type WipeSqliteStoreFn = (poolDirectory: string | undefined) => Promise<void>;
64
+
65
+ /**
66
+ * Deletes a store's OPFS pool directory. Safe to call only after a *failed* open() — a live store's SAH pool holds
67
+ * a lock on the directory and the removal would reject. A store with no `poolDirectory` lives in the shared default
68
+ * pool, which we won't blow away (it would take unrelated stores with it), so wiping is a no-op there.
69
+ */
70
+ const defaultWipeStore: WipeSqliteStoreFn = async poolDirectory => {
71
+ if (!poolDirectory) {
72
+ return;
73
+ }
74
+ await deletePoolDirectory(poolDirectory).catch(() => {
75
+ // Already gone / never created — nothing to wipe.
76
+ });
77
+ };
78
+
79
+ /**
80
+ * Opens the PXE and wallet stores in sequence, both encrypted with keys obtained from `getEncryptionKey`.
81
+ *
82
+ * The callback is invoked once per store (twice total per call) because `AztecSQLiteOPFSStore.open` *transfers*
83
+ * the key buffer to its worker. A single buffer would detach between the two opens.
84
+ *
85
+ * Failure modes:
86
+ *
87
+ * - PXE store fails to decrypt → throws `EmbeddedWalletEncryptionError({ storeName: 'pxe', cause })`. No cleanup
88
+ * needed (nothing was opened).
89
+ * - Wallet store fails to decrypt → closes the already-opened PXE store then throws
90
+ * `EmbeddedWalletEncryptionError({ storeName: 'wallet', cause })`.
91
+ * - Any non-decrypt error during the wallet open → still closes PXE, then re-throws the original error unwrapped
92
+ * (preserves callers' existing untyped error handling for non-encryption faults).
93
+ *
94
+ * @param config - Per-store name/poolDirectory.
95
+ * @param getEncryptionKey - Returns a fresh 32-byte key per call (the buffer
96
+ * detaches on transfer, so each call must allocate).
97
+ * @param log - Logger for both stores.
98
+ * @param openStore - Internal test seam. Do not pass in production code.
99
+ */
100
+ export async function openEncryptedEmbeddedStores(
101
+ config: OpenEncryptedEmbeddedStoresOptions,
102
+ getEncryptionKey: () => Promise<Uint8Array>,
103
+ log: Logger,
104
+ openStore: OpenSqliteEncryptedStoreFn = defaultOpenStore,
105
+ wipeStore: WipeSqliteStoreFn = defaultWipeStore,
106
+ ): Promise<{ pxeStore: AztecSQLiteOPFSStore; walletStore: AztecSQLiteOPFSStore }> {
107
+ const pxeStore = await openOneStore('pxe', config.pxe, getEncryptionKey, log, openStore, wipeStore);
108
+ try {
109
+ const walletStore = await openOneStore('wallet', config.wallet, getEncryptionKey, log, openStore, wipeStore);
110
+ return { pxeStore, walletStore };
111
+ } catch (err) {
112
+ // Cleanup is best-effort — if close() itself throws (e.g. worker already dead), swallow it so the original error
113
+ // surfaces unobstructed.
114
+ await pxeStore.close().catch(() => {});
115
+ throw err;
116
+ }
117
+ }
118
+
119
+ async function openOneStore(
120
+ storeName: EmbeddedStoreName,
121
+ { name, poolDirectory }: { name: string; poolDirectory?: string },
122
+ getEncryptionKey: () => Promise<Uint8Array>,
123
+ log: Logger,
124
+ openStore: OpenSqliteEncryptedStoreFn,
125
+ wipeStore: WipeSqliteStoreFn,
126
+ ): Promise<AztecSQLiteOPFSStore> {
127
+ const key = await getEncryptionKey();
128
+ try {
129
+ return await openStore(log, name, poolDirectory, key);
130
+ } catch (err) {
131
+ if (err instanceof SqliteEncryptionError && err.code === 'decrypt_failed') {
132
+ throw new EmbeddedWalletEncryptionError(storeName, { cause: err });
133
+ }
134
+ if (err instanceof SqliteCorruptionError) {
135
+ // A corrupt image is unrecoverable — no key or retry against the same bytes brings it back. Self-heal
136
+ // instead of dead-ending forever: wipe the store's OPFS directory (safe — the failed open left no SAH-pool
137
+ // lock behind) and reopen a fresh, empty one, so callers see a normal first-run rather than a permanent
138
+ // "database disk image is malformed" on every open.
139
+ log.warn(`Embedded wallet '${storeName}' store is corrupt (${err.message}); wiping and reopening fresh`);
140
+ await wipeStore(poolDirectory);
141
+ // open() transferred (detached) the previous key buffer, so fetch a fresh one for the reopen.
142
+ return await openStore(log, name, poolDirectory, await getEncryptionKey());
143
+ }
144
+ throw err;
145
+ }
146
+ }
@@ -4,24 +4,26 @@ import type { LogFn } from '@aztec/foundation/log';
4
4
  import type { AztecAsyncKVStore, AztecAsyncMap } from '@aztec/kv-store';
5
5
  import { AztecAddress } from '@aztec/stdlib/aztec-address';
6
6
 
7
- export const AccountTypes = ['schnorr', 'ecdsasecp256r1', 'ecdsasecp256k1'] as const;
7
+ export const AccountTypes = ['schnorr', 'schnorr_initializerless', 'ecdsasecp256r1', 'ecdsasecp256k1'] as const;
8
8
  export type AccountType = (typeof AccountTypes)[number];
9
9
 
10
10
  function accountKey(field: string, address: AztecAddress | string): string {
11
11
  return `${field}:${address.toString()}`;
12
12
  }
13
13
 
14
+ /** Bump when the WalletDB layout changes; a new version selects a fresh store, leaving the old one intact. */
15
+ export const WALLET_DATA_SCHEMA_VERSION = 1;
16
+
14
17
  export class WalletDB {
15
- private constructor(
16
- private accounts: AztecAsyncMap<string, Buffer>,
17
- private aliases: AztecAsyncMap<string, Buffer>,
18
- private userLog: LogFn,
19
- ) {}
18
+ private accounts: AztecAsyncMap<string, Buffer>;
19
+ private aliases: AztecAsyncMap<string, Buffer>;
20
20
 
21
- static init(store: AztecAsyncKVStore, userLog: LogFn) {
22
- const accounts = store.openMap<string, Buffer>('accounts');
23
- const aliases = store.openMap<string, Buffer>('aliases');
24
- return new WalletDB(accounts, aliases, userLog);
21
+ constructor(
22
+ private store: AztecAsyncKVStore,
23
+ private userLog: LogFn,
24
+ ) {
25
+ this.accounts = store.openMap<string, Buffer>('accounts');
26
+ this.aliases = store.openMap<string, Buffer>('aliases');
25
27
  }
26
28
 
27
29
  async storeAccount(
@@ -84,7 +86,7 @@ export class WalletDB {
84
86
 
85
87
  return accountAddresses.map(addressStr => ({
86
88
  alias: aliasesByAddress.get(addressStr) ?? '',
87
- item: AztecAddress.fromString(addressStr),
89
+ item: AztecAddress.fromStringUnsafe(addressStr),
88
90
  }));
89
91
  }
90
92
 
@@ -93,7 +95,7 @@ export class WalletDB {
93
95
  for await (const [alias, item] of this.aliases.entriesAsync({ start: 'senders:', end: 'senders:\uffff' })) {
94
96
  result.push({
95
97
  alias: alias.slice('senders:'.length),
96
- item: AztecAddress.fromString(item.toString()),
98
+ item: AztecAddress.fromStringUnsafe(item.toString()),
97
99
  });
98
100
  }
99
101
  return result;
@@ -131,4 +133,8 @@ export class WalletDB {
131
133
  await this.aliases.delete(`accounts:${alias}`);
132
134
  }
133
135
  }
136
+
137
+ async close() {
138
+ await this.store.close();
139
+ }
134
140
  }
package/src/testing.ts CHANGED
@@ -1,32 +1,25 @@
1
1
  import type { InitialAccountData } from '@aztec/accounts/testing';
2
2
  import { getInitialTestAccountsData } from '@aztec/accounts/testing/lazy';
3
- import { NO_FROM } from '@aztec/aztec.js/account';
4
- import type { WaitOpts } from '@aztec/aztec.js/contracts';
5
3
  import type { AccountManager } from '@aztec/aztec.js/wallet';
6
4
  import type { Fq, Fr } from '@aztec/foundation/curves/bn254';
7
5
  import { AztecAddress } from '@aztec/stdlib/aztec-address';
8
6
 
9
7
  interface WalletWithSchnorrAccounts {
10
- createSchnorrAccount(secret: Fr, salt: Fr, signingKey?: Fq, alias?: string): Promise<AccountManager>;
8
+ createSchnorrInitializerlessAccount(secret: Fr, salt: Fr, signingKey: Fq, alias?: string): Promise<AccountManager>;
11
9
  }
12
10
 
13
- export async function deployFundedSchnorrAccounts(
11
+ /**
12
+ * Creates the given (genesis-funded) test accounts as initializerless schnorr accounts. Initializerless
13
+ * accounts need no deployment tx — creating one registers the instance and materializes its immutable keys
14
+ * locally — so the accounts are usable as soon as they are created, funded via genesis at their addresses.
15
+ */
16
+ export async function createFundedInitializerlessAccounts(
14
17
  wallet: WalletWithSchnorrAccounts,
15
18
  accountsData: InitialAccountData[],
16
- waitOptions?: WaitOpts,
17
19
  ) {
18
20
  const accountManagers = [];
19
- // Serial due to https://github.com/AztecProtocol/aztec-packages/issues/12045
20
- for (let i = 0; i < accountsData.length; i++) {
21
- const { secret, salt, signingKey } = accountsData[i];
22
- const accountManager = await wallet.createSchnorrAccount(secret, salt, signingKey);
23
- const deployMethod = await accountManager.getDeployMethod();
24
- await deployMethod.send({
25
- from: NO_FROM,
26
- skipClassPublication: i !== 0,
27
- wait: waitOptions,
28
- });
29
- accountManagers.push(accountManager);
21
+ for (const { secret, salt, signingKey } of accountsData) {
22
+ accountManagers.push(await wallet.createSchnorrInitializerlessAccount(secret, salt, signingKey));
30
23
  }
31
24
  return accountManagers;
32
25
  }
@@ -37,7 +30,8 @@ export async function registerInitialLocalNetworkAccountsInWallet(
37
30
  const testAccounts = await getInitialTestAccountsData();
38
31
  return Promise.all(
39
32
  testAccounts.map(async account => {
40
- return (await wallet.createSchnorrAccount(account.secret, account.salt, account.signingKey)).address;
33
+ return (await wallet.createSchnorrInitializerlessAccount(account.secret, account.salt, account.signingKey))
34
+ .address;
41
35
  }),
42
36
  );
43
37
  }