@aztec-labs/wallets 6.0.0-nightly.20260829

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 (41) hide show
  1. package/dest/embedded/account-contract-providers/bundle.d.ts +19 -0
  2. package/dest/embedded/account-contract-providers/bundle.d.ts.map +1 -0
  3. package/dest/embedded/account-contract-providers/bundle.js +29 -0
  4. package/dest/embedded/account-contract-providers/lazy.d.ts +19 -0
  5. package/dest/embedded/account-contract-providers/lazy.d.ts.map +1 -0
  6. package/dest/embedded/account-contract-providers/lazy.js +39 -0
  7. package/dest/embedded/account-contract-providers/types.d.ts +20 -0
  8. package/dest/embedded/account-contract-providers/types.d.ts.map +1 -0
  9. package/dest/embedded/account-contract-providers/types.js +6 -0
  10. package/dest/embedded/embedded_wallet.d.ts +103 -0
  11. package/dest/embedded/embedded_wallet.d.ts.map +1 -0
  12. package/dest/embedded/embedded_wallet.js +359 -0
  13. package/dest/embedded/entrypoints/browser.d.ts +14 -0
  14. package/dest/embedded/entrypoints/browser.d.ts.map +1 -0
  15. package/dest/embedded/entrypoints/browser.js +72 -0
  16. package/dest/embedded/entrypoints/node.d.ts +14 -0
  17. package/dest/embedded/entrypoints/node.d.ts.map +1 -0
  18. package/dest/embedded/entrypoints/node.js +75 -0
  19. package/dest/embedded/entrypoints/resolve_aztec_node.d.ts +4 -0
  20. package/dest/embedded/entrypoints/resolve_aztec_node.d.ts.map +1 -0
  21. package/dest/embedded/entrypoints/resolve_aztec_node.js +4 -0
  22. package/dest/embedded/store_encryption.d.ts +74 -0
  23. package/dest/embedded/store_encryption.d.ts.map +1 -0
  24. package/dest/embedded/store_encryption.js +93 -0
  25. package/dest/embedded/wallet_db.d.ts +41 -0
  26. package/dest/embedded/wallet_db.d.ts.map +1 -0
  27. package/dest/embedded/wallet_db.js +133 -0
  28. package/dest/testing.d.ts +16 -0
  29. package/dest/testing.d.ts.map +1 -0
  30. package/dest/testing.js +18 -0
  31. package/package.json +102 -0
  32. package/src/embedded/account-contract-providers/bundle.ts +43 -0
  33. package/src/embedded/account-contract-providers/lazy.ts +53 -0
  34. package/src/embedded/account-contract-providers/types.ts +21 -0
  35. package/src/embedded/embedded_wallet.ts +481 -0
  36. package/src/embedded/entrypoints/browser.ts +93 -0
  37. package/src/embedded/entrypoints/node.ts +100 -0
  38. package/src/embedded/entrypoints/resolve_aztec_node.ts +10 -0
  39. package/src/embedded/store_encryption.ts +146 -0
  40. package/src/embedded/wallet_db.ts +150 -0
  41. package/src/testing.ts +37 -0
@@ -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-labs/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-labs/foundation/log';
11
+ import {
12
+ AztecSQLiteOPFSStore,
13
+ SqliteCorruptionError,
14
+ SqliteEncryptionError,
15
+ deletePoolDirectory,
16
+ } from '@aztec-labs/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
+ }
@@ -0,0 +1,150 @@
1
+ import type { Aliased } from '@aztec-labs/aztec.js/wallet';
2
+ import { Fq, Fr } from '@aztec-labs/foundation/curves/bn254';
3
+ import type { LogFn } from '@aztec-labs/foundation/log';
4
+ import type { AztecAsyncKVStore, AztecAsyncMap } from '@aztec-labs/kv-store';
5
+ import { AztecAddress } from '@aztec-labs/stdlib/aztec-address';
6
+
7
+ export const AccountTypes = ['schnorr', 'schnorr_initializerless', 'ecdsasecp256r1', 'ecdsasecp256k1'] as const;
8
+ export type AccountType = (typeof AccountTypes)[number];
9
+
10
+ function accountKey(field: string, address: AztecAddress | string): string {
11
+ return `${field}:${address.toString()}`;
12
+ }
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
+
17
+ export class WalletDB {
18
+ private accounts: AztecAsyncMap<string, Buffer>;
19
+ private aliases: AztecAsyncMap<string, Buffer>;
20
+
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');
27
+ }
28
+
29
+ async storeAccount(
30
+ address: AztecAddress,
31
+ {
32
+ type,
33
+ secretKey,
34
+ salt,
35
+ alias,
36
+ signingKey,
37
+ }: {
38
+ type: AccountType;
39
+ secretKey: Fr;
40
+ salt: Fr;
41
+ signingKey: Fq | Buffer;
42
+ alias: string | undefined;
43
+ },
44
+ log: LogFn = this.userLog,
45
+ ) {
46
+ await this.store.transactionAsync(async () => {
47
+ if (alias) {
48
+ await this.aliases.set(`accounts:${alias}`, Buffer.from(address.toString()));
49
+ }
50
+ await this.accounts.set(accountKey('type', address), Buffer.from(type));
51
+ await this.accounts.set(accountKey('sk', address), secretKey.toBuffer());
52
+ await this.accounts.set(accountKey('salt', address), salt.toBuffer());
53
+ await this.accounts.set(
54
+ accountKey('signingKey', address),
55
+ 'toBuffer' in signingKey ? signingKey.toBuffer() : signingKey,
56
+ );
57
+ });
58
+ log(`Account stored in database${alias ? ` with alias ${alias}` : ''}`);
59
+ }
60
+
61
+ async storeSender(address: AztecAddress, alias: string, log: LogFn = this.userLog) {
62
+ await this.aliases.set(`senders:${alias}`, Buffer.from(address.toString()));
63
+ log(`Sender stored in database with alias ${alias}`);
64
+ }
65
+
66
+ async retrieveAccount(address: AztecAddress | string) {
67
+ const secretKeyBuffer = await this.accounts.getAsync(accountKey('sk', address));
68
+ if (!secretKeyBuffer) {
69
+ throw new Error(`Account "${address.toString()}" does not exist on this wallet.`);
70
+ }
71
+ const [saltBuffer, typeBuffer, signingKey] = await Promise.all([
72
+ this.accounts.getAsync(accountKey('salt', address)),
73
+ this.accounts.getAsync(accountKey('type', address)),
74
+ this.accounts.getAsync(accountKey('signingKey', address)),
75
+ ]);
76
+ const secretKey = Fr.fromBuffer(secretKeyBuffer);
77
+ const salt = Fr.fromBuffer(saltBuffer!);
78
+ const type = typeBuffer!.toString('utf8') as AccountType;
79
+ return { address, secretKey, salt, type, signingKey: signingKey! };
80
+ }
81
+
82
+ async listAccounts(): Promise<Aliased<AztecAddress>[]> {
83
+ // Read aliases and account addresses in parallel using range queries
84
+ const [aliasesByAddress, accountAddresses] = await Promise.all([
85
+ this.#readAccountAliases(),
86
+ this.#readAccountAddresses(),
87
+ ]);
88
+
89
+ return accountAddresses.map(addressStr => ({
90
+ alias: aliasesByAddress.get(addressStr) ?? '',
91
+ item: AztecAddress.fromStringUnsafe(addressStr),
92
+ }));
93
+ }
94
+
95
+ async listSenders(): Promise<Aliased<AztecAddress>[]> {
96
+ const result: Aliased<AztecAddress>[] = [];
97
+ for await (const [alias, item] of this.aliases.entriesAsync({ start: 'senders:', end: 'senders:\uffff' })) {
98
+ result.push({
99
+ alias: alias.slice('senders:'.length),
100
+ item: AztecAddress.fromStringUnsafe(item.toString()),
101
+ });
102
+ }
103
+ return result;
104
+ }
105
+
106
+ async #readAccountAliases(): Promise<Map<string, string>> {
107
+ const aliasesByAddress = new Map<string, string>();
108
+ for await (const [alias, item] of this.aliases.entriesAsync({ start: 'accounts:', end: 'accounts:\uffff' })) {
109
+ const address = item.toString();
110
+ aliasesByAddress.set(address, alias.slice('accounts:'.length));
111
+ }
112
+ return aliasesByAddress;
113
+ }
114
+
115
+ async #readAccountAddresses(): Promise<string[]> {
116
+ const addresses: string[] = [];
117
+ // Range query on 'type:' prefix — one entry per account, avoids scanning sk/salt/signingKey entries
118
+ for await (const [key] of this.accounts.entriesAsync({ start: 'type:', end: 'type:\uffff' })) {
119
+ addresses.push(key.slice('type:'.length));
120
+ }
121
+ return addresses;
122
+ }
123
+
124
+ /**
125
+ * Deletes an account's stored data and every alias pointing at it atomically. Deletion is local to this store;
126
+ * any state the PXE holds for the account is unaffected.
127
+ */
128
+ async deleteAccount(address: AztecAddress) {
129
+ await this.store.transactionAsync(async () => {
130
+ await Promise.all([
131
+ this.accounts.delete(accountKey('sk', address)),
132
+ this.accounts.delete(accountKey('salt', address)),
133
+ this.accounts.delete(accountKey('type', address)),
134
+ this.accounts.delete(accountKey('signingKey', address)),
135
+ ]);
136
+
137
+ const aliasKeys: string[] = [];
138
+ for await (const [key, item] of this.aliases.entriesAsync({ start: 'accounts:', end: 'accounts:\uffff' })) {
139
+ if (item.toString() === address.toString()) {
140
+ aliasKeys.push(key);
141
+ }
142
+ }
143
+ await Promise.all(aliasKeys.map(key => this.aliases.delete(key)));
144
+ });
145
+ }
146
+
147
+ async close() {
148
+ await this.store.close();
149
+ }
150
+ }
package/src/testing.ts ADDED
@@ -0,0 +1,37 @@
1
+ import type { InitialAccountData } from '@aztec-labs/accounts/testing';
2
+ import { getInitialTestAccountsData } from '@aztec-labs/accounts/testing/lazy';
3
+ import type { AccountManager } from '@aztec-labs/aztec.js/wallet';
4
+ import type { Fq, Fr } from '@aztec-labs/foundation/curves/bn254';
5
+ import { AztecAddress } from '@aztec-labs/stdlib/aztec-address';
6
+
7
+ interface WalletWithSchnorrAccounts {
8
+ createSchnorrInitializerlessAccount(secret: Fr, salt: Fr, signingKey: Fq, alias?: string): Promise<AccountManager>;
9
+ }
10
+
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(
17
+ wallet: WalletWithSchnorrAccounts,
18
+ accountsData: InitialAccountData[],
19
+ ) {
20
+ const accountManagers = [];
21
+ for (const { secret, salt, signingKey } of accountsData) {
22
+ accountManagers.push(await wallet.createSchnorrInitializerlessAccount(secret, salt, signingKey));
23
+ }
24
+ return accountManagers;
25
+ }
26
+
27
+ export async function registerInitialLocalNetworkAccountsInWallet(
28
+ wallet: WalletWithSchnorrAccounts,
29
+ ): Promise<AztecAddress[]> {
30
+ const testAccounts = await getInitialTestAccountsData();
31
+ return Promise.all(
32
+ testAccounts.map(async account => {
33
+ return (await wallet.createSchnorrInitializerlessAccount(account.secret, account.salt, account.signingKey))
34
+ .address;
35
+ }),
36
+ );
37
+ }