@provablehq/sdk 0.10.5 → 0.11.0

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 (75) hide show
  1. package/dist/mainnet/browser.cjs +1027 -418
  2. package/dist/mainnet/browser.cjs.map +1 -1
  3. package/dist/mainnet/browser.d.cts +6 -4
  4. package/dist/mainnet/browser.d.ts +6 -4
  5. package/dist/mainnet/browser.js +1021 -427
  6. package/dist/mainnet/browser.js.map +1 -1
  7. package/dist/mainnet/keys/keystore/indexeddb.d.cts +60 -0
  8. package/dist/mainnet/keys/keystore/indexeddb.d.ts +60 -0
  9. package/dist/mainnet/keys/provider/memory.d.cts +1 -1
  10. package/dist/mainnet/keys/provider/memory.d.ts +1 -1
  11. package/dist/mainnet/models/record-scanner/error.d.cts +1 -1
  12. package/dist/mainnet/models/record-scanner/error.d.ts +1 -1
  13. package/dist/mainnet/models/record-scanner/registrationResult.d.cts +1 -1
  14. package/dist/mainnet/models/record-scanner/registrationResult.d.ts +1 -1
  15. package/dist/mainnet/network-client.d.cts +22 -2
  16. package/dist/mainnet/network-client.d.ts +22 -2
  17. package/dist/mainnet/node.cjs +15 -0
  18. package/dist/mainnet/node.cjs.map +1 -1
  19. package/dist/mainnet/node.js +2 -2
  20. package/dist/mainnet/program-manager.d.cts +61 -1
  21. package/dist/mainnet/program-manager.d.ts +61 -1
  22. package/dist/mainnet/record-scanner.d.cts +13 -10
  23. package/dist/mainnet/record-scanner.d.ts +13 -10
  24. package/dist/mainnet/utils/index.d.cts +3 -0
  25. package/dist/mainnet/utils/index.d.ts +3 -0
  26. package/dist/mainnet/utils/logger.d.cts +34 -0
  27. package/dist/mainnet/utils/logger.d.ts +34 -0
  28. package/dist/mainnet/wasm-Bnb_v1_O.js +3 -0
  29. package/dist/mainnet/wasm-Bnb_v1_O.js.map +1 -0
  30. package/dist/mainnet/wasm.cjs +251 -0
  31. package/dist/mainnet/wasm.cjs.map +1 -0
  32. package/dist/mainnet/wasm.d.cts +1 -1
  33. package/dist/mainnet/wasm.d.ts +1 -1
  34. package/dist/testnet/browser.cjs +1027 -418
  35. package/dist/testnet/browser.cjs.map +1 -1
  36. package/dist/testnet/browser.d.cts +6 -4
  37. package/dist/testnet/browser.d.ts +6 -4
  38. package/dist/testnet/browser.js +1021 -427
  39. package/dist/testnet/browser.js.map +1 -1
  40. package/dist/testnet/keys/keystore/indexeddb.d.cts +60 -0
  41. package/dist/testnet/keys/keystore/indexeddb.d.ts +60 -0
  42. package/dist/testnet/keys/provider/memory.d.cts +1 -1
  43. package/dist/testnet/keys/provider/memory.d.ts +1 -1
  44. package/dist/testnet/models/record-scanner/error.d.cts +1 -1
  45. package/dist/testnet/models/record-scanner/error.d.ts +1 -1
  46. package/dist/testnet/models/record-scanner/registrationResult.d.cts +1 -1
  47. package/dist/testnet/models/record-scanner/registrationResult.d.ts +1 -1
  48. package/dist/testnet/network-client.d.cts +22 -2
  49. package/dist/testnet/network-client.d.ts +22 -2
  50. package/dist/testnet/node.cjs +15 -0
  51. package/dist/testnet/node.cjs.map +1 -1
  52. package/dist/testnet/node.js +2 -2
  53. package/dist/testnet/program-manager.d.cts +61 -1
  54. package/dist/testnet/program-manager.d.ts +61 -1
  55. package/dist/testnet/record-scanner.d.cts +13 -10
  56. package/dist/testnet/record-scanner.d.ts +13 -10
  57. package/dist/testnet/utils/index.d.cts +3 -0
  58. package/dist/testnet/utils/index.d.ts +3 -0
  59. package/dist/testnet/utils/logger.d.cts +34 -0
  60. package/dist/testnet/utils/logger.d.ts +34 -0
  61. package/dist/testnet/wasm-BCrMb35a.js +3 -0
  62. package/dist/testnet/wasm-BCrMb35a.js.map +1 -0
  63. package/dist/testnet/wasm.cjs +251 -0
  64. package/dist/testnet/wasm.cjs.map +1 -0
  65. package/dist/testnet/wasm.d.cts +1 -1
  66. package/dist/testnet/wasm.d.ts +1 -1
  67. package/package.json +2 -2
  68. package/dist/mainnet/models/record-scanner/registrationRequest.d.cts +0 -13
  69. package/dist/mainnet/models/record-scanner/registrationRequest.d.ts +0 -13
  70. package/dist/testnet/models/record-scanner/registrationRequest.d.cts +0 -13
  71. package/dist/testnet/models/record-scanner/registrationRequest.d.ts +0 -13
  72. /package/dist/mainnet/{utils.d.cts → utils/utils.d.cts} +0 -0
  73. /package/dist/mainnet/{utils.d.ts → utils/utils.d.ts} +0 -0
  74. /package/dist/testnet/{utils.d.cts → utils/utils.d.cts} +0 -0
  75. /package/dist/testnet/{utils.d.ts → utils/utils.d.ts} +0 -0
@@ -0,0 +1,60 @@
1
+ import { FunctionKeyPair } from "../../models/keyPair.js";
2
+ import { KeyFingerprint } from "../verifier/interface.js";
3
+ import { KeyLocator, KeyStore, ProvingKeyLocator, VerifyingKeyLocator } from "./interface.js";
4
+ import { ProvingKey, VerifyingKey } from "../../wasm.js";
5
+ /**
6
+ * Browser-compatible {@link KeyStore} backed by IndexedDB.
7
+ *
8
+ * This is the browser counterpart to {@link LocalFileKeyStore} (which requires Node.js `fs`).
9
+ * It persists proving and verifying keys across page reloads and browser sessions using the
10
+ * IndexedDB API available in all modern browsers and Web Workers.
11
+ *
12
+ * **Environment**: Browser / Web Worker only. Instantiating this class is safe in any
13
+ * environment, but the first IndexedDB operation will reject with a clear error when
14
+ * `globalThis.indexedDB` is not available (e.g., Node.js, SSR contexts). Guard your
15
+ * imports accordingly if you bundle for server-side rendering.
16
+ *
17
+ * **Security**: Keys are stored as plaintext `Uint8Array` in IndexedDB. Any script
18
+ * running on the same origin — including scripts injected via XSS — can read the stored
19
+ * proving and verifying keys. Do **not** use this keystore for data that must remain
20
+ * confidential under an XSS-capable adversary; encrypt sensitive material at the
21
+ * application layer before persisting, or use an in-memory store.
22
+ *
23
+ * @example
24
+ * ```ts
25
+ * import { IndexedDBKeyStore, ProgramManager } from "@provablehq/sdk";
26
+ *
27
+ * const keyStore = new IndexedDBKeyStore();
28
+ * const pm = new ProgramManager();
29
+ * pm.setKeyStore(keyStore);
30
+ * // Keys synthesized during execution are now cached in IndexedDB
31
+ * // and reloaded automatically on subsequent runs.
32
+ * ```
33
+ */
34
+ export declare class IndexedDBKeyStore implements KeyStore {
35
+ private readonly dbName;
36
+ private readonly storeName;
37
+ private readonly keyVerifier;
38
+ private dbPromise;
39
+ /**
40
+ * @param dbName IndexedDB database name. Defaults to `"aleo-keystore"`.
41
+ */
42
+ constructor(dbName?: string);
43
+ /** Opens (or creates) the database, returning a cached promise. */
44
+ private openDB;
45
+ /** Runs a single read-write transaction and returns the request result. */
46
+ private tx;
47
+ private validateComponent;
48
+ private validateNonNegative;
49
+ private serializeLocator;
50
+ private checksumToFingerprint;
51
+ getKeyBytes(locator: KeyLocator): Promise<Uint8Array | null>;
52
+ getProvingKey(locator: ProvingKeyLocator): Promise<ProvingKey | null>;
53
+ getVerifyingKey(locator: VerifyingKeyLocator): Promise<VerifyingKey | null>;
54
+ setKeys(proverLocator: ProvingKeyLocator, verifierLocator: VerifyingKeyLocator, keys: FunctionKeyPair): Promise<void>;
55
+ setKeyBytes(keyBytes: Uint8Array, locator: KeyLocator): Promise<void>;
56
+ getKeyMetadata(locator: KeyLocator): Promise<KeyFingerprint | null>;
57
+ has(locator: KeyLocator): Promise<boolean>;
58
+ delete(locator: KeyLocator): Promise<void>;
59
+ clear(): Promise<void>;
60
+ }
@@ -0,0 +1,60 @@
1
+ import { FunctionKeyPair } from "../../models/keyPair.js";
2
+ import { KeyFingerprint } from "../verifier/interface.js";
3
+ import { KeyLocator, KeyStore, ProvingKeyLocator, VerifyingKeyLocator } from "./interface.js";
4
+ import { ProvingKey, VerifyingKey } from "../../wasm.js";
5
+ /**
6
+ * Browser-compatible {@link KeyStore} backed by IndexedDB.
7
+ *
8
+ * This is the browser counterpart to {@link LocalFileKeyStore} (which requires Node.js `fs`).
9
+ * It persists proving and verifying keys across page reloads and browser sessions using the
10
+ * IndexedDB API available in all modern browsers and Web Workers.
11
+ *
12
+ * **Environment**: Browser / Web Worker only. Instantiating this class is safe in any
13
+ * environment, but the first IndexedDB operation will reject with a clear error when
14
+ * `globalThis.indexedDB` is not available (e.g., Node.js, SSR contexts). Guard your
15
+ * imports accordingly if you bundle for server-side rendering.
16
+ *
17
+ * **Security**: Keys are stored as plaintext `Uint8Array` in IndexedDB. Any script
18
+ * running on the same origin — including scripts injected via XSS — can read the stored
19
+ * proving and verifying keys. Do **not** use this keystore for data that must remain
20
+ * confidential under an XSS-capable adversary; encrypt sensitive material at the
21
+ * application layer before persisting, or use an in-memory store.
22
+ *
23
+ * @example
24
+ * ```ts
25
+ * import { IndexedDBKeyStore, ProgramManager } from "@provablehq/sdk";
26
+ *
27
+ * const keyStore = new IndexedDBKeyStore();
28
+ * const pm = new ProgramManager();
29
+ * pm.setKeyStore(keyStore);
30
+ * // Keys synthesized during execution are now cached in IndexedDB
31
+ * // and reloaded automatically on subsequent runs.
32
+ * ```
33
+ */
34
+ export declare class IndexedDBKeyStore implements KeyStore {
35
+ private readonly dbName;
36
+ private readonly storeName;
37
+ private readonly keyVerifier;
38
+ private dbPromise;
39
+ /**
40
+ * @param dbName IndexedDB database name. Defaults to `"aleo-keystore"`.
41
+ */
42
+ constructor(dbName?: string);
43
+ /** Opens (or creates) the database, returning a cached promise. */
44
+ private openDB;
45
+ /** Runs a single read-write transaction and returns the request result. */
46
+ private tx;
47
+ private validateComponent;
48
+ private validateNonNegative;
49
+ private serializeLocator;
50
+ private checksumToFingerprint;
51
+ getKeyBytes(locator: KeyLocator): Promise<Uint8Array | null>;
52
+ getProvingKey(locator: ProvingKeyLocator): Promise<ProvingKey | null>;
53
+ getVerifyingKey(locator: VerifyingKeyLocator): Promise<VerifyingKey | null>;
54
+ setKeys(proverLocator: ProvingKeyLocator, verifierLocator: VerifyingKeyLocator, keys: FunctionKeyPair): Promise<void>;
55
+ setKeyBytes(keyBytes: Uint8Array, locator: KeyLocator): Promise<void>;
56
+ getKeyMetadata(locator: KeyLocator): Promise<KeyFingerprint | null>;
57
+ has(locator: KeyLocator): Promise<boolean>;
58
+ delete(locator: KeyLocator): Promise<void>;
59
+ clear(): Promise<void>;
60
+ }
@@ -2,7 +2,7 @@ import { Key } from "../../constants.js";
2
2
  import { CachedKeyPair, FunctionKeyPair } from "../../models/keyPair.js";
3
3
  import { FunctionKeyProvider, KeySearchParams } from "./interface.js";
4
4
  import { ProvingKey, VerifyingKey } from "../../wasm.js";
5
- import { TransportFunction } from "../../utils.js";
5
+ import { TransportFunction } from "../../utils/utils.js";
6
6
  import { KeyStore } from "../keystore/interface.js";
7
7
  type AleoKeyProviderInitParams = {
8
8
  proverUri?: string;
@@ -2,7 +2,7 @@ import { Key } from "../../constants.js";
2
2
  import { CachedKeyPair, FunctionKeyPair } from "../../models/keyPair.js";
3
3
  import { FunctionKeyProvider, KeySearchParams } from "./interface.js";
4
4
  import { ProvingKey, VerifyingKey } from "../../wasm.js";
5
- import { TransportFunction } from "../../utils.js";
5
+ import { TransportFunction } from "../../utils/utils.js";
6
6
  import { KeyStore } from "../keystore/interface.js";
7
7
  type AleoKeyProviderInitParams = {
8
8
  proverUri?: string;
@@ -1,6 +1,6 @@
1
1
  import { OwnedFilter } from "./ownedFilter.js";
2
2
  /**
3
- * Error thrown when a record scanner request fails (e.g. /register, /register/encrypted).
3
+ * Error thrown when a record scanner request fails (e.g. /register/encrypted).
4
4
  * Includes HTTP status so callers can handle 422 vs 500 etc.
5
5
  */
6
6
  export declare class RecordScannerRequestError extends Error {
@@ -1,6 +1,6 @@
1
1
  import { OwnedFilter } from "./ownedFilter.js";
2
2
  /**
3
- * Error thrown when a record scanner request fails (e.g. /register, /register/encrypted).
3
+ * Error thrown when a record scanner request fails (e.g. /register/encrypted).
4
4
  * Includes HTTP status so callers can handle 422 vs 500 etc.
5
5
  */
6
6
  export declare class RecordScannerRequestError extends Error {
@@ -5,5 +5,5 @@ export interface RegisterSuccess {
5
5
  ok: true;
6
6
  data: RegistrationResponse;
7
7
  }
8
- /** Result of register() and registerEncrypted(); never throws on HTTP error. */
8
+ /** Result of registerEncrypted(); never throws on HTTP error. */
9
9
  export type RegisterResult = RegisterSuccess | RecordScannerFailure;
@@ -5,5 +5,5 @@ export interface RegisterSuccess {
5
5
  ok: true;
6
6
  data: RegistrationResponse;
7
7
  }
8
- /** Result of register() and registerEncrypted(); never throws on HTTP error. */
8
+ /** Result of registerEncrypted(); never throws on HTTP error. */
9
9
  export type RegisterResult = RegisterSuccess | RecordScannerFailure;
@@ -1,4 +1,4 @@
1
- import { TransportFunction } from "./utils.js";
1
+ import { TransportFunction } from "./utils/utils.js";
2
2
  import { Account } from "./account.js";
3
3
  import { BlockJSON } from "./models/blockJSON.js";
4
4
  import { TransactionJSON } from "./models/transaction/transactionJSON.js";
@@ -41,6 +41,10 @@ interface DelegatedProvingParams {
41
41
  apiKey?: string;
42
42
  consumerId?: string;
43
43
  jwtData?: JWTData;
44
+ /**
45
+ * @deprecated All proving requests are now encrypted. This flag is ignored
46
+ * and will be removed in a future release.
47
+ */
44
48
  dpsPrivacy?: boolean;
45
49
  }
46
50
  /**
@@ -489,6 +493,22 @@ declare class AleoNetworkClient {
489
493
  * assert.equal(programVersion, 1);
490
494
  */
491
495
  getLatestProgramEdition(programId: string): Promise<number>;
496
+ /**
497
+ * Returns the current edition and amendment count for a program.
498
+ *
499
+ * @param {string} programId - The program ID (e.g. "hello_hello.aleo")
500
+ * @returns {{ program_id: string, edition: number, amendment_count: number }}
501
+ *
502
+ * @example
503
+ * const networkClient = new AleoNetworkClient("https://api.provable.com/v2");
504
+ * const info = await networkClient.getProgramAmendmentCount("hello_hello.aleo");
505
+ * console.log(info.edition, info.amendment_count);
506
+ */
507
+ getProgramAmendmentCount(programId: string): Promise<{
508
+ program_id: string;
509
+ edition: number;
510
+ amendment_count: number;
511
+ }>;
492
512
  /**
493
513
  * Returns a program object from a program ID or program source code.
494
514
  *
@@ -809,7 +829,7 @@ declare class AleoNetworkClient {
809
829
  */
810
830
  private refreshJwt;
811
831
  /**
812
- * Parses a /prove or /prove/encrypted response. Returns a result object (never throws for 200/400/500/503).
832
+ * Parses a /prove/authorization or /prove/request response. Returns a result object (never throws for 200/400/500/503).
813
833
  */
814
834
  private handleProvingResponse;
815
835
  /**
@@ -1,4 +1,4 @@
1
- import { TransportFunction } from "./utils.js";
1
+ import { TransportFunction } from "./utils/utils.js";
2
2
  import { Account } from "./account.js";
3
3
  import { BlockJSON } from "./models/blockJSON.js";
4
4
  import { TransactionJSON } from "./models/transaction/transactionJSON.js";
@@ -41,6 +41,10 @@ interface DelegatedProvingParams {
41
41
  apiKey?: string;
42
42
  consumerId?: string;
43
43
  jwtData?: JWTData;
44
+ /**
45
+ * @deprecated All proving requests are now encrypted. This flag is ignored
46
+ * and will be removed in a future release.
47
+ */
44
48
  dpsPrivacy?: boolean;
45
49
  }
46
50
  /**
@@ -489,6 +493,22 @@ declare class AleoNetworkClient {
489
493
  * assert.equal(programVersion, 1);
490
494
  */
491
495
  getLatestProgramEdition(programId: string): Promise<number>;
496
+ /**
497
+ * Returns the current edition and amendment count for a program.
498
+ *
499
+ * @param {string} programId - The program ID (e.g. "hello_hello.aleo")
500
+ * @returns {{ program_id: string, edition: number, amendment_count: number }}
501
+ *
502
+ * @example
503
+ * const networkClient = new AleoNetworkClient("https://api.provable.com/v2");
504
+ * const info = await networkClient.getProgramAmendmentCount("hello_hello.aleo");
505
+ * console.log(info.edition, info.amendment_count);
506
+ */
507
+ getProgramAmendmentCount(programId: string): Promise<{
508
+ program_id: string;
509
+ edition: number;
510
+ amendment_count: number;
511
+ }>;
492
512
  /**
493
513
  * Returns a program object from a program ID or program source code.
494
514
  *
@@ -809,7 +829,7 @@ declare class AleoNetworkClient {
809
829
  */
810
830
  private refreshJwt;
811
831
  /**
812
- * Parses a /prove or /prove/encrypted response. Returns a result object (never throws for 200/400/500/503).
832
+ * Parses a /prove/authorization or /prove/request response. Returns a result object (never throws for 200/400/500/503).
813
833
  */
814
834
  private handleProvingResponse;
815
835
  /**
@@ -409,6 +409,7 @@ exports.BlockHeightSearch = browser.BlockHeightSearch;
409
409
  exports.CREDITS_PROGRAM_KEYS = browser.CREDITS_PROGRAM_KEYS;
410
410
  exports.ChecksumMismatchError = browser.ChecksumMismatchError;
411
411
  exports.DecryptionNotEnabledError = browser.DecryptionNotEnabledError;
412
+ exports.IndexedDBKeyStore = browser.IndexedDBKeyStore;
412
413
  exports.InvalidLocatorError = browser.InvalidLocatorError;
413
414
  exports.KEY_STORE = browser.KEY_STORE;
414
415
  exports.KeyVerificationError = browser.ChecksumMismatchError;
@@ -437,6 +438,7 @@ exports.encryptAuthorization = browser.encryptAuthorization;
437
438
  exports.encryptProvingRequest = browser.encryptProvingRequest;
438
439
  exports.encryptRegistrationRequest = browser.encryptRegistrationRequest;
439
440
  exports.encryptViewKey = browser.encryptViewKey;
441
+ exports.getLogLevel = browser.getLogLevel;
440
442
  exports.initializeWasm = browser.initializeWasm;
441
443
  exports.inputsToFields = browser.inputsToFields;
442
444
  exports.isInputIdStrategy = browser.isInputIdStrategy;
@@ -447,6 +449,7 @@ exports.isViewKeyStrategy = browser.isViewKeyStrategy;
447
449
  exports.logAndThrow = browser.logAndThrow;
448
450
  exports.programChecksum = browser.programChecksum;
449
451
  exports.provingKeyLocator = browser.provingKeyLocator;
452
+ exports.setLogLevel = browser.setLogLevel;
450
453
  exports.sha256Hex = browser.sha256Hex;
451
454
  exports.toAddress = browser.toAddress;
452
455
  exports.toField = browser.toField;
@@ -586,6 +589,10 @@ Object.defineProperty(exports, "Program", {
586
589
  enumerable: true,
587
590
  get: function () { return mainnet_js.Program; }
588
591
  });
592
+ Object.defineProperty(exports, "ProgramImportsBuilder", {
593
+ enumerable: true,
594
+ get: function () { return mainnet_js.ProgramImports; }
595
+ });
589
596
  Object.defineProperty(exports, "ProgramManagerBase", {
590
597
  enumerable: true,
591
598
  get: function () { return mainnet_js.ProgramManager; }
@@ -602,6 +609,10 @@ Object.defineProperty(exports, "ProvingRequest", {
602
609
  enumerable: true,
603
610
  get: function () { return mainnet_js.ProvingRequest; }
604
611
  });
612
+ Object.defineProperty(exports, "QueryOption", {
613
+ enumerable: true,
614
+ get: function () { return mainnet_js.QueryOption; }
615
+ });
605
616
  Object.defineProperty(exports, "RecordCiphertext", {
606
617
  enumerable: true,
607
618
  get: function () { return mainnet_js.RecordCiphertext; }
@@ -666,6 +677,10 @@ Object.defineProperty(exports, "initThreadPool", {
666
677
  enumerable: true,
667
678
  get: function () { return mainnet_js.initThreadPool; }
668
679
  });
680
+ Object.defineProperty(exports, "setWasmLogLevel", {
681
+ enumerable: true,
682
+ get: function () { return mainnet_js.setWasmLogLevel; }
683
+ });
669
684
  Object.defineProperty(exports, "snarkVerify", {
670
685
  enumerable: true,
671
686
  get: function () { return mainnet_js.snarkVerify; }
@@ -1 +1 @@
1
- {"version":3,"file":"node.cjs","sources":["../../src/keys/keystore/file.ts"],"sourcesContent":["import * as fs from \"node:fs/promises\";\nimport * as fsSync from \"node:fs\";\nimport * as path from \"path\";\n\nimport { FunctionKeyPair } from \"../../models/keyPair.js\";\nimport { KeyFingerprint } from \"../verifier/interface.js\";\nimport { InvalidLocatorError } from \"./error.js\";\nimport { KeyLocator, KeyStore, ProvingKeyLocator, VerifyingKeyLocator } from \"./interface.js\";\nimport { MemKeyVerifier } from \"../verifier/memory.js\";\nimport { ProvingKey, VerifyingKey } from \"../../wasm.js\";\n\nexport class LocalFileKeyStore implements KeyStore {\n private directory: string;\n private readonly keyVerifier = new MemKeyVerifier();\n\n /**\n * Creates a new directory at the given path or CURRENTDIR/.aleo if none is provided to store keys.\n * If a custom directory is passed and its last path segment is not \".aleo\", \".aleo\" is appended\n * so keys are stored under that subdirectory (e.g. /home/project → /home/project/.aleo).\n *\n * @param {string} [directory] - Optional custom directory path for key storage. Defaults to \".aleo\" in current working directory.\n * @throws {Error} If directory creation fails.\n */\n constructor(directory?: string) {\n this.directory = directory ?? path.join(process.cwd(), \".aleo\");\n if (directory !== undefined && path.basename(this.directory) !== \".aleo\") {\n this.directory = path.join(this.directory, \".aleo\");\n }\n fsSync.mkdirSync(this.directory, { recursive: true });\n }\n\n /**\n * Validates a single locator component for unsafe filesystem characters.\n *\n * @private\n * @param {string} value - The component value to validate.\n * @param {string} label - Label for error messages (e.g. \"program\", \"functionName\").\n * @throws {InvalidLocatorError} If the value is empty, contains traversal sequences, path separators, or null bytes.\n */\n private validateComponent(value: string, label: string): void {\n if (value === \"\" || value === \".\") {\n throw new InvalidLocatorError(\n `KeyLocator ${label} must not be empty or \".\" (got \"${value}\")`,\n value,\n \"reserved_name\"\n );\n }\n if (value.includes(\"..\")) {\n throw new InvalidLocatorError(\n `KeyLocator ${label} must not contain \"..\" (got \"${value}\")`,\n value,\n \"path_traversal\"\n );\n }\n if (value.includes(\"/\") || value.includes(\"\\\\\") || value.includes(\"\\0\")) {\n throw new InvalidLocatorError(\n `KeyLocator ${label} must not contain path separators or null bytes (got \"${value}\")`,\n value,\n \"path_separator\"\n );\n }\n }\n\n /**\n * Validates that a numeric locator field is not negative.\n *\n * @private\n * @param {number} value - The numeric value to validate.\n * @param {string} label - Label for error messages (e.g. \"edition\", \"amendment\").\n * @throws {InvalidLocatorError} If the value is negative.\n */\n private validateNonNegative(value: number, label: string): void {\n if (!Number.isInteger(value) || value < 0) {\n throw new InvalidLocatorError(\n `KeyLocator ${label} must be a non-negative integer (got ${value})`,\n String(value),\n \"negative_value\"\n );\n }\n }\n\n /**\n * Serializes a {@link KeyLocator} to a filesystem-safe flat string, validating components first.\n *\n * For prover/verifier keys: `{program}.{functionName}.e{edition}.a{amendment}.{network}.{keyType}`\n * For translation keys: `{program}.{functionName}.e{edition}.a{amendment}.{network}.translation.{recordName}.{recordInputPosition}`\n *\n * Note: The optional `checksum` field is excluded — it is used for integrity verification only\n * (via {@link checksumToFingerprint}) and is not part of the key identity.\n *\n * @private\n * @param {KeyLocator} locator - The key locator.\n * @returns {string} A dot-delimited string safe for use as a filename.\n * @throws {InvalidLocatorError} If any component contains unsafe characters.\n */\n private serializeLocator(locator: KeyLocator): string {\n this.validateComponent(locator.program, \"program\");\n this.validateComponent(locator.functionName, \"functionName\");\n this.validateComponent(locator.network, \"network\");\n this.validateNonNegative(locator.edition, \"edition\");\n this.validateNonNegative(locator.amendment, \"amendment\");\n const base = `${locator.program}.${locator.functionName}.e${locator.edition}.a${locator.amendment}.${locator.network}.${locator.keyType}`;\n if (locator.keyType === \"translation\") {\n this.validateComponent(locator.recordName, \"recordName\");\n this.validateNonNegative(locator.recordInputPosition, \"recordInputPosition\");\n return `${base}.${locator.recordName}.${locator.recordInputPosition}`;\n }\n return base;\n }\n\n /**\n * Converts an optional checksum string from a locator into a KeyFingerprint\n * suitable for the key verifier, using the actual key byte length for size.\n *\n * @private\n */\n private checksumToFingerprint(checksum: string | undefined, keyBytes: Uint8Array): KeyFingerprint | undefined {\n if (!checksum) return undefined;\n return { checksum, size: keyBytes.length };\n }\n\n /**\n * Generates the path for a key metadata file based on the locator.\n *\n * @private\n * @param {string} locator - Unique identifier for the key.\n * @returns {string} Full filesystem path to the metadata file.\n */\n private metadataPath(locator: string): string {\n return path.join(this.directory, `${locator}.metadata`);\n }\n\n /**\n * Reads and parses the key fingerprint metadata from storage.\n *\n * @private\n * @param {string} locator - Unique identifier for the key.\n * @returns {Promise<KeyFingerprint | null>} The key fingerprint if found, null if file doesn't exist.\n * @throws {Error} If file read fails for any reason other than not found.\n */\n private async readKeyMetadata(\n locator: string,\n ): Promise<KeyFingerprint | null> {\n try {\n const data = await fs.readFile(this.metadataPath(locator), \"utf-8\");\n return JSON.parse(data) as KeyFingerprint;\n } catch (err: unknown) {\n if (\n err &&\n typeof err === \"object\" &&\n \"code\" in err &&\n err.code === \"ENOENT\"\n )\n return null;\n throw err;\n }\n }\n\n /**\n * Writes key fingerprint metadata to storage.\n *\n * @private\n * @param {string} locator - Unique identifier for the key.\n * @param {KeyFingerprint} metadata - Key fingerprint metadata to store.\n * @returns {Promise<void>}\n * @throws {Error} If directory creation or file write fails.\n */\n private async writeKeyMetadata(\n locator: string,\n metadata: KeyFingerprint,\n ): Promise<void> {\n await fs.mkdir(path.dirname(this.metadataPath(locator)), {\n recursive: true,\n });\n await fs.writeFile(\n this.metadataPath(locator),\n JSON.stringify(metadata, null, 0),\n \"utf-8\",\n );\n }\n\n private async readFileOptional(\n filepath: string,\n ): Promise<Uint8Array | null> {\n try {\n const data = await fs.readFile(filepath);\n return new Uint8Array(data);\n } catch (err: any) {\n if (err.code === \"ENOENT\") return null;\n throw err;\n }\n }\n\n /**\n * Atomically writes data to a file, ensuring the parent directories exist.\n *\n * @private\n * @param {string} filepath - Full path to the file to write\n * @param {Uint8Array} data - Binary data to write to the file\n * @returns {Promise<void>} Resolves when write is complete\n * @throws {Error} If directory creation or file write fails\n */\n private async writeFileAtomic(\n filepath: string,\n data: Uint8Array,\n ): Promise<void> {\n const dir = path.dirname(filepath);\n await fs.mkdir(dir, { recursive: true });\n const tempPath = path.join(\n dir,\n `.${path.basename(filepath)}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`\n );\n await fs.writeFile(tempPath, data);\n try {\n await fs.rename(tempPath, filepath);\n } catch (err: unknown) {\n const code = err && typeof err === \"object\" && \"code\" in err ? (err as NodeJS.ErrnoException).code : undefined;\n // Windows often throws EEXIST when target exists; EPERM/EACCES happen with locks/AV.\n if (code === \"EEXIST\" || code === \"EPERM\" || code === \"EACCES\") {\n await fs.unlink(filepath).catch(() => {});\n try {\n await fs.rename(tempPath, filepath);\n } catch (err2) {\n await fs.unlink(tempPath).catch(() => {});\n throw err2;\n }\n } else {\n await fs.unlink(tempPath).catch(() => {});\n throw err;\n }\n }\n }\n\n /**\n * Recursively removes all files and subdirectories under the given directory, then removes the directory itself.\n * Uses fs.rm with recursive: true and force: true so that symbolic links are removed without following them,\n * avoiding deletion of content outside the keystore.\n *\n * @private\n * @param {string} dir - Directory path to clear\n * @returns {Promise<void>} Resolves when clearing is complete\n * @throws {Error} If directory removal fails for reasons other than non-existence\n */\n private async clearDirectory(dir: string): Promise<void> {\n try {\n await fs.rm(dir, { recursive: true, force: true });\n } catch (err: unknown) {\n const code = err && typeof err === \"object\" && \"code\" in err ? (err as NodeJS.ErrnoException).code : undefined;\n if (code === \"ENOENT\") {\n return;\n }\n throw err;\n }\n }\n\n // -------------------------------------------------------\n // KEYSTORE INTERFACE\n // -------------------------------------------------------\n\n /**\n * Retrieves the key bytes from storage and optionally verifies them.\n *\n * @param {KeyLocator} locator - The key locator with optional checksum for verification.\n * @returns {Promise<Uint8Array | null>} The key bytes if found and verified, null if not found.\n * @throws {KeyVerificationError} If verification fails.\n */\n async getKeyBytes(locator: KeyLocator): Promise<Uint8Array | null> {\n const fileKey = this.serializeLocator(locator);\n\n // Attempt to read key bytes from storage (under this.directory).\n const keyBytes = await this.readFileOptional(path.join(this.directory, fileKey));\n\n // If no key bytes were found, return null.\n if (!keyBytes) return null;\n\n // Use caller-provided checksum or metadata stored on disk for verification.\n const fingerprint =\n this.checksumToFingerprint(locator.checksum, keyBytes) ?? (await this.getKeyMetadata(locator));\n if (fingerprint) {\n await this.keyVerifier.verifyKeyBytes({\n keyBytes,\n locator: fileKey,\n fingerprint,\n });\n }\n\n // Return the verified key bytes.\n return keyBytes;\n }\n\n /**\n * Retrieves and verifies a proving key from storage.\n *\n * @param {ProvingKeyLocator} locator - The proving key locator.\n * @returns {Promise<ProvingKey | null>} The proving key if found and verified, null if not found.\n * @throws {KeyVerificationError} If verification fails.\n * @throws {Error} If key bytes cannot be parsed into a valid ProvingKey.\n */\n async getProvingKey(locator: ProvingKeyLocator): Promise<ProvingKey | null> {\n const proverBytes = await this.getKeyBytes(locator);\n if (!proverBytes) return null;\n return ProvingKey.fromBytes(proverBytes);\n }\n\n /**\n * Retrieves and verifies a verifying key from storage.\n *\n * @param {VerifyingKeyLocator} locator - The verifying key locator.\n * @returns {Promise<VerifyingKey | null>} The verifying key if found and verified, null if not found.\n * @throws {KeyVerificationError} If verification fails.\n * @throws {Error} If key bytes cannot be parsed into a valid VerifyingKey.\n */\n async getVerifyingKey(locator: VerifyingKeyLocator): Promise<VerifyingKey | null> {\n const verifierBytes = await this.getKeyBytes(locator);\n if (!verifierBytes) return null;\n return VerifyingKey.fromBytes(verifierBytes);\n }\n\n /**\n * Stores proving and verifying keys in key storage.\n *\n * @param {ProvingKeyLocator} proverLocator The locator for the proving key.\n * @param {VerifyingKeyLocator} verifierLocator The locator for the verifying key.\n * @param {FunctionKeyPair} keys The proving and verifying keys.\n */\n async setKeys(\n proverLocator: ProvingKeyLocator,\n verifierLocator: VerifyingKeyLocator,\n keys: FunctionKeyPair,\n ): Promise<void> {\n const proverKey = this.serializeLocator(proverLocator);\n const verifierKey = this.serializeLocator(verifierLocator);\n\n // Convert the WASM keys to raw bytes.\n const [provingKey, verifyingKey] = keys;\n const [provingKeyBytes, verifyingKeyBytes] = [\n provingKey.toBytes(),\n verifyingKey.toBytes(),\n ];\n\n // Compute the fingerprints for the proving and verifying keys, verify against expected checksums if provided.\n const [proverFingerPrint, verifierFingerPrint] = await Promise.all([\n this.keyVerifier.computeKeyMetadata({\n keyBytes: provingKeyBytes,\n locator: proverKey,\n fingerprint: this.checksumToFingerprint(proverLocator.checksum, provingKeyBytes),\n }),\n this.keyVerifier.computeKeyMetadata({\n keyBytes: verifyingKeyBytes,\n locator: verifierKey,\n fingerprint: this.checksumToFingerprint(verifierLocator.checksum, verifyingKeyBytes),\n }),\n ]);\n\n // Write the proving and verifying key bytes and their metadata to storage (under this.directory).\n await this.writeFileAtomic(path.join(this.directory, proverKey), provingKeyBytes);\n await this.writeFileAtomic(path.join(this.directory, verifierKey), verifyingKeyBytes);\n await this.writeKeyMetadata(proverKey, proverFingerPrint);\n await this.writeKeyMetadata(verifierKey, verifierFingerPrint);\n }\n\n /**\n * Store a raw key in storage along with its fingerprint metadata for future verification.\n *\n * @param {Uint8Array} keyBytes The raw key bytes.\n * @param {KeyLocator} locator The unique locator for the key.\n * @returns {Promise<void>}\n * @throws {Error} If computing key metadata or writing to storage fails\n */\n async setKeyBytes(keyBytes: Uint8Array, locator: KeyLocator): Promise<void> {\n const fileKey = this.serializeLocator(locator);\n\n // Compute the key metadata including fingerprint\n const computedMetadata = await this.keyVerifier.computeKeyMetadata({\n keyBytes: keyBytes,\n locator: fileKey,\n fingerprint: this.checksumToFingerprint(locator.checksum, keyBytes),\n });\n\n // Write the key bytes and metadata atomically (key file under this.directory).\n await this.writeFileAtomic(path.join(this.directory, fileKey), keyBytes);\n await this.writeKeyMetadata(fileKey, computedMetadata);\n }\n\n /**\n * Returns stored metadata for a key, if any.\n *\n * @param {KeyLocator} locator The unique locator for the key.\n * @returns {Promise<KeyFingerprint | null>} The stored fingerprint metadata, or null if none exists.\n */\n async getKeyMetadata(locator: KeyLocator): Promise<KeyFingerprint | null> {\n const fileKey = this.serializeLocator(locator);\n return this.readKeyMetadata(fileKey);\n }\n\n /**\n * Checks if a key exists for the given locator.\n *\n * @param {KeyLocator} locator - The unique key locator.\n * @returns {Promise<boolean>} True if key exists, false otherwise.\n */\n async has(locator: KeyLocator): Promise<boolean> {\n const fileKey = this.serializeLocator(locator);\n const keyPath = path.join(this.directory, fileKey);\n return await fs\n .access(keyPath)\n .then(() => true)\n .catch(() => false);\n }\n\n /**\n * Deletes a key and its associated metadata from storage. Silently ignores errors if files don't exist.\n *\n * @param {KeyLocator} locator - The unique key locator.\n * @returns {Promise<void>}\n */\n async delete(locator: KeyLocator): Promise<void> {\n const fileKey = this.serializeLocator(locator);\n const p = path.join(this.directory, fileKey);\n const m = this.metadataPath(fileKey);\n\n await fs.unlink(p).catch(() => {});\n await fs.unlink(m).catch(() => {});\n }\n\n /**\n * Clears the key storage directory by recursively removing all files and subdirectories under it, then removes the keystore directory itself.\n *\n * @returns {Promise<void>}\n * @throws {Error} If directory listing fails for reasons other than non-existence.\n */\n async clear(): Promise<void> {\n await this.clearDirectory(this.directory);\n }\n}\n"],"names":["MemKeyVerifier","path","fsSync","InvalidLocatorError","fs","ProvingKey","VerifyingKey"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;MAWa,iBAAiB,CAAA;AAClB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aAAE,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,MAAK,EAAE,CAAC,CAAC;AAClC,QAAA,MAAMA,aAAE,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,MAAK,EAAE,CAAC,CAAC;IACtC;AAEA;;;;;AAKG;AACH,IAAA,MAAM,KAAK,GAAA;QACP,MAAM,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,SAAS,CAAC;IAC7C;AACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"node.cjs","sources":["../../src/keys/keystore/file.ts"],"sourcesContent":["import * as fs from \"node:fs/promises\";\nimport * as fsSync from \"node:fs\";\nimport * as path from \"path\";\n\nimport { FunctionKeyPair } from \"../../models/keyPair.js\";\nimport { KeyFingerprint } from \"../verifier/interface.js\";\nimport { InvalidLocatorError } from \"./error.js\";\nimport { KeyLocator, KeyStore, ProvingKeyLocator, VerifyingKeyLocator } from \"./interface.js\";\nimport { MemKeyVerifier } from \"../verifier/memory.js\";\nimport { ProvingKey, VerifyingKey } from \"../../wasm.js\";\n\nexport class LocalFileKeyStore implements KeyStore {\n private directory: string;\n private readonly keyVerifier = new MemKeyVerifier();\n\n /**\n * Creates a new directory at the given path or CURRENTDIR/.aleo if none is provided to store keys.\n * If a custom directory is passed and its last path segment is not \".aleo\", \".aleo\" is appended\n * so keys are stored under that subdirectory (e.g. /home/project → /home/project/.aleo).\n *\n * @param {string} [directory] - Optional custom directory path for key storage. Defaults to \".aleo\" in current working directory.\n * @throws {Error} If directory creation fails.\n */\n constructor(directory?: string) {\n this.directory = directory ?? path.join(process.cwd(), \".aleo\");\n if (directory !== undefined && path.basename(this.directory) !== \".aleo\") {\n this.directory = path.join(this.directory, \".aleo\");\n }\n fsSync.mkdirSync(this.directory, { recursive: true });\n }\n\n /**\n * Validates a single locator component for unsafe filesystem characters.\n *\n * @private\n * @param {string} value - The component value to validate.\n * @param {string} label - Label for error messages (e.g. \"program\", \"functionName\").\n * @throws {InvalidLocatorError} If the value is empty, contains traversal sequences, path separators, or null bytes.\n */\n private validateComponent(value: string, label: string): void {\n if (value === \"\" || value === \".\") {\n throw new InvalidLocatorError(\n `KeyLocator ${label} must not be empty or \".\" (got \"${value}\")`,\n value,\n \"reserved_name\"\n );\n }\n if (value.includes(\"..\")) {\n throw new InvalidLocatorError(\n `KeyLocator ${label} must not contain \"..\" (got \"${value}\")`,\n value,\n \"path_traversal\"\n );\n }\n if (value.includes(\"/\") || value.includes(\"\\\\\") || value.includes(\"\\0\")) {\n throw new InvalidLocatorError(\n `KeyLocator ${label} must not contain path separators or null bytes (got \"${value}\")`,\n value,\n \"path_separator\"\n );\n }\n }\n\n /**\n * Validates that a numeric locator field is not negative.\n *\n * @private\n * @param {number} value - The numeric value to validate.\n * @param {string} label - Label for error messages (e.g. \"edition\", \"amendment\").\n * @throws {InvalidLocatorError} If the value is negative.\n */\n private validateNonNegative(value: number, label: string): void {\n if (!Number.isInteger(value) || value < 0) {\n throw new InvalidLocatorError(\n `KeyLocator ${label} must be a non-negative integer (got ${value})`,\n String(value),\n \"negative_value\"\n );\n }\n }\n\n /**\n * Serializes a {@link KeyLocator} to a filesystem-safe flat string, validating components first.\n *\n * For prover/verifier keys: `{program}.{functionName}.e{edition}.a{amendment}.{network}.{keyType}`\n * For translation keys: `{program}.{functionName}.e{edition}.a{amendment}.{network}.translation.{recordName}.{recordInputPosition}`\n *\n * Note: The optional `checksum` field is excluded — it is used for integrity verification only\n * (via {@link checksumToFingerprint}) and is not part of the key identity.\n *\n * @private\n * @param {KeyLocator} locator - The key locator.\n * @returns {string} A dot-delimited string safe for use as a filename.\n * @throws {InvalidLocatorError} If any component contains unsafe characters.\n */\n private serializeLocator(locator: KeyLocator): string {\n this.validateComponent(locator.program, \"program\");\n this.validateComponent(locator.functionName, \"functionName\");\n this.validateComponent(locator.network, \"network\");\n this.validateNonNegative(locator.edition, \"edition\");\n this.validateNonNegative(locator.amendment, \"amendment\");\n const base = `${locator.program}.${locator.functionName}.e${locator.edition}.a${locator.amendment}.${locator.network}.${locator.keyType}`;\n if (locator.keyType === \"translation\") {\n this.validateComponent(locator.recordName, \"recordName\");\n this.validateNonNegative(locator.recordInputPosition, \"recordInputPosition\");\n return `${base}.${locator.recordName}.${locator.recordInputPosition}`;\n }\n return base;\n }\n\n /**\n * Converts an optional checksum string from a locator into a KeyFingerprint\n * suitable for the key verifier, using the actual key byte length for size.\n *\n * @private\n */\n private checksumToFingerprint(checksum: string | undefined, keyBytes: Uint8Array): KeyFingerprint | undefined {\n if (!checksum) return undefined;\n return { checksum, size: keyBytes.length };\n }\n\n /**\n * Generates the path for a key metadata file based on the locator.\n *\n * @private\n * @param {string} locator - Unique identifier for the key.\n * @returns {string} Full filesystem path to the metadata file.\n */\n private metadataPath(locator: string): string {\n return path.join(this.directory, `${locator}.metadata`);\n }\n\n /**\n * Reads and parses the key fingerprint metadata from storage.\n *\n * @private\n * @param {string} locator - Unique identifier for the key.\n * @returns {Promise<KeyFingerprint | null>} The key fingerprint if found, null if file doesn't exist.\n * @throws {Error} If file read fails for any reason other than not found.\n */\n private async readKeyMetadata(\n locator: string,\n ): Promise<KeyFingerprint | null> {\n try {\n const data = await fs.readFile(this.metadataPath(locator), \"utf-8\");\n return JSON.parse(data) as KeyFingerprint;\n } catch (err: unknown) {\n if (\n err &&\n typeof err === \"object\" &&\n \"code\" in err &&\n err.code === \"ENOENT\"\n )\n return null;\n throw err;\n }\n }\n\n /**\n * Writes key fingerprint metadata to storage.\n *\n * @private\n * @param {string} locator - Unique identifier for the key.\n * @param {KeyFingerprint} metadata - Key fingerprint metadata to store.\n * @returns {Promise<void>}\n * @throws {Error} If directory creation or file write fails.\n */\n private async writeKeyMetadata(\n locator: string,\n metadata: KeyFingerprint,\n ): Promise<void> {\n await fs.mkdir(path.dirname(this.metadataPath(locator)), {\n recursive: true,\n });\n await fs.writeFile(\n this.metadataPath(locator),\n JSON.stringify(metadata, null, 0),\n \"utf-8\",\n );\n }\n\n private async readFileOptional(\n filepath: string,\n ): Promise<Uint8Array | null> {\n try {\n const data = await fs.readFile(filepath);\n return new Uint8Array(data);\n } catch (err: any) {\n if (err.code === \"ENOENT\") return null;\n throw err;\n }\n }\n\n /**\n * Atomically writes data to a file, ensuring the parent directories exist.\n *\n * @private\n * @param {string} filepath - Full path to the file to write\n * @param {Uint8Array} data - Binary data to write to the file\n * @returns {Promise<void>} Resolves when write is complete\n * @throws {Error} If directory creation or file write fails\n */\n private async writeFileAtomic(\n filepath: string,\n data: Uint8Array,\n ): Promise<void> {\n const dir = path.dirname(filepath);\n await fs.mkdir(dir, { recursive: true });\n const tempPath = path.join(\n dir,\n `.${path.basename(filepath)}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`\n );\n await fs.writeFile(tempPath, data);\n try {\n await fs.rename(tempPath, filepath);\n } catch (err: unknown) {\n const code = err && typeof err === \"object\" && \"code\" in err ? (err as NodeJS.ErrnoException).code : undefined;\n // Windows often throws EEXIST when target exists; EPERM/EACCES happen with locks/AV.\n if (code === \"EEXIST\" || code === \"EPERM\" || code === \"EACCES\") {\n await fs.unlink(filepath).catch(() => {});\n try {\n await fs.rename(tempPath, filepath);\n } catch (err2) {\n await fs.unlink(tempPath).catch(() => {});\n throw err2;\n }\n } else {\n await fs.unlink(tempPath).catch(() => {});\n throw err;\n }\n }\n }\n\n /**\n * Recursively removes all files and subdirectories under the given directory, then removes the directory itself.\n * Uses fs.rm with recursive: true and force: true so that symbolic links are removed without following them,\n * avoiding deletion of content outside the keystore.\n *\n * @private\n * @param {string} dir - Directory path to clear\n * @returns {Promise<void>} Resolves when clearing is complete\n * @throws {Error} If directory removal fails for reasons other than non-existence\n */\n private async clearDirectory(dir: string): Promise<void> {\n try {\n await fs.rm(dir, { recursive: true, force: true });\n } catch (err: unknown) {\n const code = err && typeof err === \"object\" && \"code\" in err ? (err as NodeJS.ErrnoException).code : undefined;\n if (code === \"ENOENT\") {\n return;\n }\n throw err;\n }\n }\n\n // -------------------------------------------------------\n // KEYSTORE INTERFACE\n // -------------------------------------------------------\n\n /**\n * Retrieves the key bytes from storage and optionally verifies them.\n *\n * @param {KeyLocator} locator - The key locator with optional checksum for verification.\n * @returns {Promise<Uint8Array | null>} The key bytes if found and verified, null if not found.\n * @throws {KeyVerificationError} If verification fails.\n */\n async getKeyBytes(locator: KeyLocator): Promise<Uint8Array | null> {\n const fileKey = this.serializeLocator(locator);\n\n // Attempt to read key bytes from storage (under this.directory).\n const keyBytes = await this.readFileOptional(path.join(this.directory, fileKey));\n\n // If no key bytes were found, return null.\n if (!keyBytes) return null;\n\n // Use caller-provided checksum or metadata stored on disk for verification.\n const fingerprint =\n this.checksumToFingerprint(locator.checksum, keyBytes) ?? (await this.getKeyMetadata(locator));\n if (fingerprint) {\n await this.keyVerifier.verifyKeyBytes({\n keyBytes,\n locator: fileKey,\n fingerprint,\n });\n }\n\n // Return the verified key bytes.\n return keyBytes;\n }\n\n /**\n * Retrieves and verifies a proving key from storage.\n *\n * @param {ProvingKeyLocator} locator - The proving key locator.\n * @returns {Promise<ProvingKey | null>} The proving key if found and verified, null if not found.\n * @throws {KeyVerificationError} If verification fails.\n * @throws {Error} If key bytes cannot be parsed into a valid ProvingKey.\n */\n async getProvingKey(locator: ProvingKeyLocator): Promise<ProvingKey | null> {\n const proverBytes = await this.getKeyBytes(locator);\n if (!proverBytes) return null;\n return ProvingKey.fromBytes(proverBytes);\n }\n\n /**\n * Retrieves and verifies a verifying key from storage.\n *\n * @param {VerifyingKeyLocator} locator - The verifying key locator.\n * @returns {Promise<VerifyingKey | null>} The verifying key if found and verified, null if not found.\n * @throws {KeyVerificationError} If verification fails.\n * @throws {Error} If key bytes cannot be parsed into a valid VerifyingKey.\n */\n async getVerifyingKey(locator: VerifyingKeyLocator): Promise<VerifyingKey | null> {\n const verifierBytes = await this.getKeyBytes(locator);\n if (!verifierBytes) return null;\n return VerifyingKey.fromBytes(verifierBytes);\n }\n\n /**\n * Stores proving and verifying keys in key storage.\n *\n * @param {ProvingKeyLocator} proverLocator The locator for the proving key.\n * @param {VerifyingKeyLocator} verifierLocator The locator for the verifying key.\n * @param {FunctionKeyPair} keys The proving and verifying keys.\n */\n async setKeys(\n proverLocator: ProvingKeyLocator,\n verifierLocator: VerifyingKeyLocator,\n keys: FunctionKeyPair,\n ): Promise<void> {\n const proverKey = this.serializeLocator(proverLocator);\n const verifierKey = this.serializeLocator(verifierLocator);\n\n // Convert the WASM keys to raw bytes.\n const [provingKey, verifyingKey] = keys;\n const [provingKeyBytes, verifyingKeyBytes] = [\n provingKey.toBytes(),\n verifyingKey.toBytes(),\n ];\n\n // Compute the fingerprints for the proving and verifying keys, verify against expected checksums if provided.\n const [proverFingerPrint, verifierFingerPrint] = await Promise.all([\n this.keyVerifier.computeKeyMetadata({\n keyBytes: provingKeyBytes,\n locator: proverKey,\n fingerprint: this.checksumToFingerprint(proverLocator.checksum, provingKeyBytes),\n }),\n this.keyVerifier.computeKeyMetadata({\n keyBytes: verifyingKeyBytes,\n locator: verifierKey,\n fingerprint: this.checksumToFingerprint(verifierLocator.checksum, verifyingKeyBytes),\n }),\n ]);\n\n // Write the proving and verifying key bytes and their metadata to storage (under this.directory).\n await this.writeFileAtomic(path.join(this.directory, proverKey), provingKeyBytes);\n await this.writeFileAtomic(path.join(this.directory, verifierKey), verifyingKeyBytes);\n await this.writeKeyMetadata(proverKey, proverFingerPrint);\n await this.writeKeyMetadata(verifierKey, verifierFingerPrint);\n }\n\n /**\n * Store a raw key in storage along with its fingerprint metadata for future verification.\n *\n * @param {Uint8Array} keyBytes The raw key bytes.\n * @param {KeyLocator} locator The unique locator for the key.\n * @returns {Promise<void>}\n * @throws {Error} If computing key metadata or writing to storage fails\n */\n async setKeyBytes(keyBytes: Uint8Array, locator: KeyLocator): Promise<void> {\n const fileKey = this.serializeLocator(locator);\n\n // Compute the key metadata including fingerprint\n const computedMetadata = await this.keyVerifier.computeKeyMetadata({\n keyBytes: keyBytes,\n locator: fileKey,\n fingerprint: this.checksumToFingerprint(locator.checksum, keyBytes),\n });\n\n // Write the key bytes and metadata atomically (key file under this.directory).\n await this.writeFileAtomic(path.join(this.directory, fileKey), keyBytes);\n await this.writeKeyMetadata(fileKey, computedMetadata);\n }\n\n /**\n * Returns stored metadata for a key, if any.\n *\n * @param {KeyLocator} locator The unique locator for the key.\n * @returns {Promise<KeyFingerprint | null>} The stored fingerprint metadata, or null if none exists.\n */\n async getKeyMetadata(locator: KeyLocator): Promise<KeyFingerprint | null> {\n const fileKey = this.serializeLocator(locator);\n return this.readKeyMetadata(fileKey);\n }\n\n /**\n * Checks if a key exists for the given locator.\n *\n * @param {KeyLocator} locator - The unique key locator.\n * @returns {Promise<boolean>} True if key exists, false otherwise.\n */\n async has(locator: KeyLocator): Promise<boolean> {\n const fileKey = this.serializeLocator(locator);\n const keyPath = path.join(this.directory, fileKey);\n return await fs\n .access(keyPath)\n .then(() => true)\n .catch(() => false);\n }\n\n /**\n * Deletes a key and its associated metadata from storage. Silently ignores errors if files don't exist.\n *\n * @param {KeyLocator} locator - The unique key locator.\n * @returns {Promise<void>}\n */\n async delete(locator: KeyLocator): Promise<void> {\n const fileKey = this.serializeLocator(locator);\n const p = path.join(this.directory, fileKey);\n const m = this.metadataPath(fileKey);\n\n await fs.unlink(p).catch(() => {});\n await fs.unlink(m).catch(() => {});\n }\n\n /**\n * Clears the key storage directory by recursively removing all files and subdirectories under it, then removes the keystore directory itself.\n *\n * @returns {Promise<void>}\n * @throws {Error} If directory listing fails for reasons other than non-existence.\n */\n async clear(): Promise<void> {\n await this.clearDirectory(this.directory);\n }\n}\n"],"names":["MemKeyVerifier","path","fsSync","InvalidLocatorError","fs","ProvingKey","VerifyingKey"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;MAWa,iBAAiB,CAAA;AAClB,IAAA,SAAS;AACA,IAAA,WAAW,GAAG,IAAIA,sBAAc,EAAE;AAEnD;;;;;;;AAOG;AACH,IAAA,WAAA,CAAY,SAAkB,EAAA;AAC1B,QAAA,IAAI,CAAC,SAAS,GAAG,SAAS,IAAIC,eAAI,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,OAAO,CAAC;AAC/D,QAAA,IAAI,SAAS,KAAK,SAAS,IAAIA,eAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,OAAO,EAAE;AACtE,YAAA,IAAI,CAAC,SAAS,GAAGA,eAAI,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,OAAO,CAAC;QACvD;AACA,QAAAC,cAAM,CAAC,SAAS,CAAC,IAAI,CAAC,SAAS,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC;IACzD;AAEA;;;;;;;AAOG;IACK,iBAAiB,CAAC,KAAa,EAAE,KAAa,EAAA;QAClD,IAAI,KAAK,KAAK,EAAE,IAAI,KAAK,KAAK,GAAG,EAAE;AAC/B,YAAA,MAAM,IAAIC,2BAAmB,CACzB,CAAA,WAAA,EAAc,KAAK,CAAA,gCAAA,EAAmC,KAAK,CAAA,EAAA,CAAI,EAC/D,KAAK,EACL,eAAe,CAClB;QACL;AACA,QAAA,IAAI,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE;AACtB,YAAA,MAAM,IAAIA,2BAAmB,CACzB,CAAA,WAAA,EAAc,KAAK,CAAA,6BAAA,EAAgC,KAAK,CAAA,EAAA,CAAI,EAC5D,KAAK,EACL,gBAAgB,CACnB;Q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G,IAAI,CAAC,gBAAgB,CAAC,OAAO,CAAC;AAC9C,QAAA,MAAM,CAAC,GAAGH,eAAI,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,OAAO,CAAC;QAC5C,MAAM,CAAC,GAAG,IAAI,CAAC,YAAY,CAAC,OAAO,CAAC;AAEpC,QAAA,MAAMG,aAAE,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,MAAK,EAAE,CAAC,CAAC;AAClC,QAAA,MAAMA,aAAE,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,MAAK,EAAE,CAAC,CAAC;IACtC;AAEA;;;;;AAKG;AACH,IAAA,MAAM,KAAK,GAAA;QACP,MAAM,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,SAAS,CAAC;IAC7C;AACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
@@ -3,9 +3,9 @@ import * as fs from 'node:fs/promises';
3
3
  import * as $fs from 'node:fs';
4
4
  import * as path from 'path';
5
5
  import { MemKeyVerifier, InvalidLocatorError } from './browser.js';
6
- export { Account, AleoKeyProvider, AleoKeyProviderParams, AleoNetworkClient, BlockHeightSearch, CREDITS_PROGRAM_KEYS, ChecksumMismatchError, DecryptionNotEnabledError, KEY_STORE, ChecksumMismatchError as KeyVerificationError, NetworkRecordProvider, OfflineKeyProvider, OfflineSearchParams, PRIVATE_TO_PUBLIC_TRANSFER, PRIVATE_TRANSFER, PRIVATE_TRANSFER_TYPES, PUBLIC_TO_PRIVATE_TRANSFER, PUBLIC_TRANSFER, PUBLIC_TRANSFER_AS_SIGNER, ProgramManager, RECORD_DOMAIN, RecordNotFoundError, RecordScanner, RecordScannerRequestError, SealanceMerkleTree, UUIDError, VALID_TRANSFER_TYPES, ViewKeyNotStoredError, buildExecutionRequestFromExternallySignedData, computeExternalSigningInputs, encryptAuthorization, encryptProvingRequest, encryptRegistrationRequest, encryptViewKey, initializeWasm, inputsToFields, isInputIdStrategy, isProveApiErrorBody, isProvingResponse, isRecordViewKeyStrategy, isViewKeyStrategy, logAndThrow, programChecksum, provingKeyLocator, sha256Hex, toAddress, toField, toGroup, toSignature, toViewKey, translationKeyLocator, verifyBatchProof, verifyProof, verifyingKeyLocator, zeroizeBytes } from './browser.js';
6
+ export { Account, AleoKeyProvider, AleoKeyProviderParams, AleoNetworkClient, BlockHeightSearch, CREDITS_PROGRAM_KEYS, ChecksumMismatchError, DecryptionNotEnabledError, IndexedDBKeyStore, KEY_STORE, ChecksumMismatchError as KeyVerificationError, NetworkRecordProvider, OfflineKeyProvider, OfflineSearchParams, PRIVATE_TO_PUBLIC_TRANSFER, PRIVATE_TRANSFER, PRIVATE_TRANSFER_TYPES, PUBLIC_TO_PRIVATE_TRANSFER, PUBLIC_TRANSFER, PUBLIC_TRANSFER_AS_SIGNER, ProgramManager, RECORD_DOMAIN, RecordNotFoundError, RecordScanner, RecordScannerRequestError, SealanceMerkleTree, UUIDError, VALID_TRANSFER_TYPES, ViewKeyNotStoredError, buildExecutionRequestFromExternallySignedData, computeExternalSigningInputs, encryptAuthorization, encryptProvingRequest, encryptRegistrationRequest, encryptViewKey, getLogLevel, initializeWasm, inputsToFields, isInputIdStrategy, isProveApiErrorBody, isProvingResponse, isRecordViewKeyStrategy, isViewKeyStrategy, logAndThrow, programChecksum, provingKeyLocator, setLogLevel, sha256Hex, toAddress, toField, toGroup, toSignature, toViewKey, translationKeyLocator, verifyBatchProof, verifyProof, verifyingKeyLocator, zeroizeBytes } from './browser.js';
7
7
  import { ProvingKey, VerifyingKey } from '@provablehq/wasm/mainnet.js';
8
- export { Address, Authorization, BHP1024, BHP256, BHP512, BHP768, Boolean, Ciphertext, ComputeKey, DynamicRecord, EncryptionToolkit, ExecutionRequest, ExecutionResponse, Field, Execution as FunctionExecution, GraphKey, Group, I128, I16, I32, I64, I8, OfflineQuery, Pedersen128, Pedersen64, Plaintext, Poseidon2, Poseidon4, Poseidon8, PrivateKey, PrivateKeyCiphertext, Program, ProgramManager as ProgramManagerBase, Proof, ProvingKey, ProvingRequest, RecordCiphertext, RecordPlaintext, Scalar, Signature, Transaction, Transition, U128, U16, U32, U64, U8, Value, VerifyingKey, ViewKey, getOrInitConsensusVersionTestHeights, initThreadPool, snarkVerify, snarkVerifyBatch, stringToField, verifyFunctionExecution } from '@provablehq/wasm/mainnet.js';
8
+ export { Address, Authorization, BHP1024, BHP256, BHP512, BHP768, Boolean, Ciphertext, ComputeKey, DynamicRecord, EncryptionToolkit, ExecutionRequest, ExecutionResponse, Field, Execution as FunctionExecution, GraphKey, Group, I128, I16, I32, I64, I8, OfflineQuery, Pedersen128, Pedersen64, Plaintext, Poseidon2, Poseidon4, Poseidon8, PrivateKey, PrivateKeyCiphertext, Program, ProgramImports as ProgramImportsBuilder, ProgramManager as ProgramManagerBase, Proof, ProvingKey, ProvingRequest, QueryOption, RecordCiphertext, RecordPlaintext, Scalar, Signature, Transaction, Transition, U128, U16, U32, U64, U8, Value, VerifyingKey, ViewKey, getOrInitConsensusVersionTestHeights, initThreadPool, setWasmLogLevel, snarkVerify, snarkVerifyBatch, stringToField, verifyFunctionExecution } from '@provablehq/wasm/mainnet.js';
9
9
  import 'core-js/proposals/json-parse-with-source.js';
10
10
  import 'node:crypto';
11
11
  import 'mime/lite';
@@ -4,6 +4,7 @@ import { ImportedPrograms, ImportedVerifyingKeys } from "./models/imports.js";
4
4
  import { RecordProvider } from "./record-provider.js";
5
5
  import { RecordSearchParams } from "./models/record-provider/recordSearchParams.js";
6
6
  import { FunctionKeyProvider, KeySearchParams } from "./keys/provider/interface.js";
7
+ import { KeyStore } from "./keys/keystore/interface.js";
7
8
  import { FunctionKeyPair } from "./models/keyPair.js";
8
9
  import { Authorization, ExecutionRequest, ExecutionResponse, OfflineQuery, RecordPlaintext, PrivateKey, Program, ProvingKey, ProvingRequest, VerifyingKey, Transaction } from "./wasm.js";
9
10
  import { ExternalSigningOptions } from "./models/external-signing.js";
@@ -120,6 +121,7 @@ interface ExecuteAuthorizationOptions {
120
121
  offlineQuery?: OfflineQuery;
121
122
  program?: string | Program;
122
123
  imports?: ProgramImports;
124
+ edition?: number;
123
125
  }
124
126
  /**
125
127
  * Represents the options for executing a transaction in the Aleo network.
@@ -213,13 +215,14 @@ declare class ProgramManager {
213
215
  networkClient: AleoNetworkClient;
214
216
  recordProvider: RecordProvider | undefined;
215
217
  inclusionKeysLoaded: boolean;
218
+ private _keyStore;
216
219
  /** Create a new instance of the ProgramManager
217
220
  *
218
221
  * @param { string | undefined } host A host uri running the official Aleo API
219
222
  * @param { FunctionKeyProvider | undefined } keyProvider A key provider that implements {@link FunctionKeyProvider} interface
220
223
  * @param { RecordProvider | undefined } recordProvider A record provider that implements {@link RecordProvider} interface
221
224
  */
222
- constructor(host?: string | undefined, keyProvider?: FunctionKeyProvider | undefined, recordProvider?: RecordProvider | undefined, networkClientOptions?: AleoNetworkClientOptions | undefined);
225
+ constructor(host?: string | undefined, keyProvider?: FunctionKeyProvider | undefined, recordProvider?: RecordProvider | undefined, networkClientOptions?: AleoNetworkClientOptions | undefined, keyStore?: KeyStore | undefined);
223
226
  /**
224
227
  * Pre-load the inclusion prover for offline execution. Required when the
225
228
  * user provides an explicit OfflineQuery (truly offline — can't fetch lazily).
@@ -262,6 +265,63 @@ declare class ProgramManager {
262
265
  * @param {RecordProvider} recordProvider
263
266
  */
264
267
  setRecordProvider(recordProvider: RecordProvider): void;
268
+ /**
269
+ * Set the key store for automatic key caching across executions.
270
+ *
271
+ * @param {KeyStore} keyStore
272
+ */
273
+ setKeyStore(keyStore: KeyStore): void;
274
+ /**
275
+ * Build a ProgramImportsBuilder from a program and its imports.
276
+ * Fetches imports from the network if not provided, resolves transitive
277
+ * dependencies, and optionally pre-loads cached keys from the KeyStore.
278
+ *
279
+ * @param loadKeys When true (default), loads cached proving/verifying keys
280
+ * from the KeyStore into the builder. Set to false for authorization and
281
+ * proving request paths where keys are not synthesized.
282
+ */
283
+ private buildProgramImports;
284
+ /**
285
+ * Extract `import program_name.aleo;` names from program source via regex.
286
+ * Avoids a WASM round-trip compared to Program.fromString + getImports.
287
+ */
288
+ private static getImportNames;
289
+ /**
290
+ * Convert the JS object returned by Program.getCallGraph() into a
291
+ * Map<string, Set<string>> for use in buildProgramImports.
292
+ */
293
+ private static callGraphToMap;
294
+ /**
295
+ * Resolve the active KeyStore, preferring the directly-set _keyStore
296
+ * over the KeyProvider's keyStore().
297
+ */
298
+ private resolveKeyStore;
299
+ /**
300
+ * Resolve the edition and amendment count for a program from the network.
301
+ * Returns `{ edition, amendment }` or falls back to `{ edition: 1, amendment: 0 }`.
302
+ */
303
+ private resolveEditionAndAmendment;
304
+ /**
305
+ * Load cached proving/verifying keys from the KeyStore into a ProgramImportsBuilder.
306
+ * Only loads keys for the specified functions — returns immediately if
307
+ * functionNames is empty or undefined.
308
+ * Resolves edition and amendment from the network for accurate key locator
309
+ * construction when not explicitly provided.
310
+ */
311
+ private loadKeysFromStore;
312
+ /**
313
+ * Persist newly synthesized keys from the returned ProgramImportsBuilder
314
+ * into the KeyStore. Only writes keys that are not already in the store,
315
+ * avoiding unnecessary writes of large proving keys.
316
+ * Fetches each program's current edition and amendment count from the network
317
+ * for accurate key locator construction.
318
+ */
319
+ private persistExtractedKeys;
320
+ /**
321
+ * Resolve top-level function keys, checking the KeyStore first and
322
+ * falling back to the KeyProvider.
323
+ */
324
+ private resolveTopLevelKeys;
265
325
  /**
266
326
  * Set a header in the `AleoNetworkClient`s header map
267
327
  *