@openzeppelin/compact-deployer 0.2.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 (103) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +304 -0
  3. package/dist/config/compact-config.d.ts +31 -0
  4. package/dist/config/compact-config.js +123 -0
  5. package/dist/config/compact-config.js.map +1 -0
  6. package/dist/config/schema.d.ts +688 -0
  7. package/dist/config/schema.js +90 -0
  8. package/dist/config/schema.js.map +1 -0
  9. package/dist/deployer.d.ts +154 -0
  10. package/dist/deployer.js +916 -0
  11. package/dist/deployer.js.map +1 -0
  12. package/dist/deployments.d.ts +119 -0
  13. package/dist/deployments.js +144 -0
  14. package/dist/deployments.js.map +1 -0
  15. package/dist/errors.d.ts +94 -0
  16. package/dist/errors.js +124 -0
  17. package/dist/errors.js.map +1 -0
  18. package/dist/loaders/args.d.ts +22 -0
  19. package/dist/loaders/args.js +72 -0
  20. package/dist/loaders/args.js.map +1 -0
  21. package/dist/loaders/argv.d.ts +36 -0
  22. package/dist/loaders/argv.js +101 -0
  23. package/dist/loaders/argv.js.map +1 -0
  24. package/dist/loaders/artifact-path.d.ts +16 -0
  25. package/dist/loaders/artifact-path.js +35 -0
  26. package/dist/loaders/artifact-path.js.map +1 -0
  27. package/dist/loaders/artifact.d.ts +43 -0
  28. package/dist/loaders/artifact.js +115 -0
  29. package/dist/loaders/artifact.js.map +1 -0
  30. package/dist/loaders/constructor-meta.d.ts +17 -0
  31. package/dist/loaders/constructor-meta.js +99 -0
  32. package/dist/loaders/constructor-meta.js.map +1 -0
  33. package/dist/loaders/context.d.ts +14 -0
  34. package/dist/loaders/context.js +43 -0
  35. package/dist/loaders/context.js.map +1 -0
  36. package/dist/loaders/contract-resolve.d.ts +15 -0
  37. package/dist/loaders/contract-resolve.js +53 -0
  38. package/dist/loaders/contract-resolve.js.map +1 -0
  39. package/dist/loaders/init-state.d.ts +8 -0
  40. package/dist/loaders/init-state.js +37 -0
  41. package/dist/loaders/init-state.js.map +1 -0
  42. package/dist/loaders/ref-resolver.d.ts +8 -0
  43. package/dist/loaders/ref-resolver.js +27 -0
  44. package/dist/loaders/ref-resolver.js.map +1 -0
  45. package/dist/loaders/signing-key.d.ts +10 -0
  46. package/dist/loaders/signing-key.js +23 -0
  47. package/dist/loaders/signing-key.js.map +1 -0
  48. package/dist/providers/build.d.ts +20 -0
  49. package/dist/providers/build.js +41 -0
  50. package/dist/providers/build.js.map +1 -0
  51. package/dist/providers/network.d.ts +6 -0
  52. package/dist/providers/network.js +36 -0
  53. package/dist/providers/network.js.map +1 -0
  54. package/dist/providers/private-state-password.d.ts +12 -0
  55. package/dist/providers/private-state-password.js +27 -0
  56. package/dist/providers/private-state-password.js.map +1 -0
  57. package/dist/providers/proof-server.d.ts +29 -0
  58. package/dist/providers/proof-server.js +97 -0
  59. package/dist/providers/proof-server.js.map +1 -0
  60. package/dist/runDeploy.d.ts +167 -0
  61. package/dist/runDeploy.js +228 -0
  62. package/dist/runDeploy.js.map +1 -0
  63. package/dist/services/atomic-json.d.ts +7 -0
  64. package/dist/services/atomic-json.js +34 -0
  65. package/dist/services/atomic-json.js.map +1 -0
  66. package/dist/services/chain-state.d.ts +75 -0
  67. package/dist/services/chain-state.js +151 -0
  68. package/dist/services/chain-state.js.map +1 -0
  69. package/dist/services/contract-state.d.ts +29 -0
  70. package/dist/services/contract-state.js +54 -0
  71. package/dist/services/contract-state.js.map +1 -0
  72. package/dist/services/deploy-plan.d.ts +36 -0
  73. package/dist/services/deploy-plan.js +45 -0
  74. package/dist/services/deploy-plan.js.map +1 -0
  75. package/dist/services/deploy-tx.d.ts +189 -0
  76. package/dist/services/deploy-tx.js +297 -0
  77. package/dist/services/deploy-tx.js.map +1 -0
  78. package/dist/services/error-format.d.ts +10 -0
  79. package/dist/services/error-format.js +91 -0
  80. package/dist/services/error-format.js.map +1 -0
  81. package/dist/services/file-lock.d.ts +23 -0
  82. package/dist/services/file-lock.js +90 -0
  83. package/dist/services/file-lock.js.map +1 -0
  84. package/dist/services/maintenance-tx.d.ts +49 -0
  85. package/dist/services/maintenance-tx.js +43 -0
  86. package/dist/services/maintenance-tx.js.map +1 -0
  87. package/dist/services/wallet-cache.d.ts +99 -0
  88. package/dist/services/wallet-cache.js +239 -0
  89. package/dist/services/wallet-cache.js.map +1 -0
  90. package/dist/services/wallet-sync.d.ts +89 -0
  91. package/dist/services/wallet-sync.js +249 -0
  92. package/dist/services/wallet-sync.js.map +1 -0
  93. package/dist/wallet/handler.d.ts +64 -0
  94. package/dist/wallet/handler.js +151 -0
  95. package/dist/wallet/handler.js.map +1 -0
  96. package/dist/wallet/keystore.d.ts +55 -0
  97. package/dist/wallet/keystore.js +213 -0
  98. package/dist/wallet/keystore.js.map +1 -0
  99. package/dist/wallet/seeds.d.ts +41 -0
  100. package/dist/wallet/seeds.js +84 -0
  101. package/dist/wallet/seeds.js.map +1 -0
  102. package/package.json +133 -0
  103. package/proof-server.yml +16 -0
@@ -0,0 +1,23 @@
1
+ /** A lock older than this is treated as abandoned by a crashed process. */
2
+ export declare const LOCK_STALE_MS = 30000;
3
+ export declare const LOCK_RETRY_MS = 25;
4
+ export declare const LOCK_MAX_WAIT_MS = 10000;
5
+ /** Timing overrides. Production callers take the defaults; tests shrink them. */
6
+ export interface LockOptions {
7
+ staleMs?: number;
8
+ retryMs?: number;
9
+ maxWaitMs?: number;
10
+ }
11
+ /**
12
+ * Take `lockPath` exclusively via `open(O_CREAT|O_EXCL)`. Retries on EEXIST;
13
+ * removes the lock and retries once the holder's mtime passes
14
+ * {@link LOCK_STALE_MS} so a killed deploy can't wedge the ledger
15
+ * permanently. Throws {@link DeployError} past `maxWaitMs`.
16
+ */
17
+ export declare function acquireLock(lockPath: string, opts?: LockOptions): Promise<void>;
18
+ /**
19
+ * Release `lockPath`. Never throws: it runs in the caller's `finally`, where
20
+ * throwing would mask a failing deploy's real error and turn a successful one
21
+ * into a false failure.
22
+ */
23
+ export declare function releaseLock(lockPath: string): Promise<void>;
@@ -0,0 +1,90 @@
1
+ import { rename, stat, unlink, writeFile } from 'node:fs/promises';
2
+ import { DeployError } from "../errors.js";
3
+ /** A lock older than this is treated as abandoned by a crashed process. */
4
+ export const LOCK_STALE_MS = 30_000;
5
+ export const LOCK_RETRY_MS = 25;
6
+ export const LOCK_MAX_WAIT_MS = 10_000;
7
+ /**
8
+ * Take `lockPath` exclusively via `open(O_CREAT|O_EXCL)`. Retries on EEXIST;
9
+ * removes the lock and retries once the holder's mtime passes
10
+ * {@link LOCK_STALE_MS} so a killed deploy can't wedge the ledger
11
+ * permanently. Throws {@link DeployError} past `maxWaitMs`.
12
+ */
13
+ export async function acquireLock(lockPath, opts = {}) {
14
+ const staleMs = opts.staleMs ?? LOCK_STALE_MS;
15
+ const retryMs = opts.retryMs ?? LOCK_RETRY_MS;
16
+ const maxWaitMs = opts.maxWaitMs ?? LOCK_MAX_WAIT_MS;
17
+ const deadline = Date.now() + maxWaitMs;
18
+ for (;;) {
19
+ try {
20
+ await writeFile(lockPath, `${process.pid}\n`, { flag: 'wx' });
21
+ return;
22
+ }
23
+ catch (e) {
24
+ if (e.code !== 'EEXIST')
25
+ throw e;
26
+ if (await breakIfStale(lockPath, staleMs))
27
+ continue;
28
+ if (Date.now() > deadline) {
29
+ throw new DeployError(`Timed out waiting for the deployments lock at ${lockPath}. Remove it if no deploy is running.`);
30
+ }
31
+ await delay(retryMs);
32
+ }
33
+ }
34
+ }
35
+ /**
36
+ * Remove `lockPath` if its mtime is older than `staleMs`. Reports whether it
37
+ * did. The removal renames the lock aside before unlinking it: `rename` is
38
+ * atomic, so of several waiters that all saw the same stale lock exactly one
39
+ * takes it away and the losers go back to waiting.
40
+ */
41
+ async function breakIfStale(lockPath, staleMs) {
42
+ const staleBefore = Date.now() - staleMs;
43
+ const parked = `${lockPath}.stale-${process.pid}-${Date.now()}`;
44
+ try {
45
+ if ((await stat(lockPath)).mtimeMs > staleBefore)
46
+ return false;
47
+ await rename(lockPath, parked);
48
+ // The stat above and this rename are not one instant: a waiter that won
49
+ // the break may already have taken the lock, in which case the file just
50
+ // parked is that waiter's fresh one. Put it back rather than acquire
51
+ // alongside the holder.
52
+ if ((await stat(parked)).mtimeMs > staleBefore) {
53
+ await rename(parked, lockPath);
54
+ return false;
55
+ }
56
+ await unlink(parked);
57
+ return true;
58
+ }
59
+ catch (e) {
60
+ // ENOENT: the holder released, or another waiter broke the lock first,
61
+ // between our EEXIST and this call. Either way the next acquire wins the
62
+ // race. Any other fault is not contention, and retrying it would surface
63
+ // as a misleading lock timeout.
64
+ if (e.code !== 'ENOENT')
65
+ throw e;
66
+ return false;
67
+ }
68
+ }
69
+ /**
70
+ * Release `lockPath`. Never throws: it runs in the caller's `finally`, where
71
+ * throwing would mask a failing deploy's real error and turn a successful one
72
+ * into a false failure.
73
+ */
74
+ export async function releaseLock(lockPath) {
75
+ try {
76
+ await unlink(lockPath);
77
+ }
78
+ catch (e) {
79
+ // Already gone (stale-broken by another waiter). Nothing to release.
80
+ if (e.code === 'ENOENT')
81
+ return;
82
+ // Anything else leaves the lock on disk, blocking other deploys until it
83
+ // ages past `staleMs`. Warn on stderr to keep `--json` stdout parseable.
84
+ process.emitWarning(`Could not release the deployments lock at ${lockPath}: ${e.message}`);
85
+ }
86
+ }
87
+ function delay(ms) {
88
+ return new Promise((r) => setTimeout(r, ms));
89
+ }
90
+ //# sourceMappingURL=file-lock.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"file-lock.js","sourceRoot":"","sources":["../../src/services/file-lock.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AACnE,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAE3C,2EAA2E;AAC3E,MAAM,CAAC,MAAM,aAAa,GAAG,MAAM,CAAC;AACpC,MAAM,CAAC,MAAM,aAAa,GAAG,EAAE,CAAC;AAChC,MAAM,CAA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midnight-js's `submitInsertVerifierKeyTx` does one key per tx and re-reads
5
+ * chain state for each, which costs a tx per circuit. This module assembles
6
+ * many `VerifierKeyInsert`s into a single signed `MaintenanceUpdate`.
7
+ */
8
+ import { MaintenanceUpdate, Transaction } from '@midnight-ntwrk/ledger-v8';
9
+ /**
10
+ * One circuit's key. The absence of any other update shape is what
11
+ * makes removal, replacement, and authority rotation unconstructible here.
12
+ */
13
+ export interface KeyInsert {
14
+ readonly circuitId: string;
15
+ readonly verifierKey: Uint8Array;
16
+ }
17
+ export interface BuildInsertUpdateArgs {
18
+ /** Taken from the fragment-0 result or the record, never recomputed. */
19
+ address: string;
20
+ inserts: readonly KeyInsert[];
21
+ /** Read from chain immediately before this call; never tracked locally. */
22
+ counter: bigint;
23
+ /** Hex signing key. Reaches `signData` and nothing else. */
24
+ signingKey: string;
25
+ /**
26
+ * This key's slot in the on-chain committee, from the same chain read
27
+ * as `counter`. The ledger checks the signature against that slot, so a
28
+ * hardcoded 0 would fail on any contract whose committee is ordered
29
+ * differently.
30
+ */
31
+ signerIndex: number;
32
+ }
33
+ /** Verifying key for a hex signing key. The public half is the only part that may be logged. */
34
+ export declare function verifyingKeyOf(signingKey: string): string;
35
+ /**
36
+ * Signed insert-only maintenance update for `address` at `counter`.
37
+ *
38
+ * The signature covers the address, the whole insert list, and the counter, so
39
+ * a tampered or replayed update fails the ledger's check rather than ours.
40
+ */
41
+ export declare function buildInsertUpdate({ address, inserts, counter, signingKey, signerIndex, }: BuildInsertUpdateArgs): MaintenanceUpdate;
42
+ export interface BuildInsertTxArgs {
43
+ update: MaintenanceUpdate;
44
+ }
45
+ /**
46
+ * Wrap a signed update in an unproven tx. No Zswap offer: a maintenance update
47
+ * creates no coins, and the wallet adds the dust fee spend when it balances.
48
+ */
49
+ export declare function buildInsertTx({ update, }: BuildInsertTxArgs): ReturnType<typeof Transaction.fromParts>;
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Builds the batched verifier-key insert that carries one fragment.
3
+ *
4
+ * midnight-js's `submitInsertVerifierKeyTx` does one key per tx and re-reads
5
+ * chain state for each, which costs a tx per circuit. This module assembles
6
+ * many `VerifierKeyInsert`s into a single signed `MaintenanceUpdate`.
7
+ */
8
+ import { ContractOperationVersionedVerifierKey, Intent, MaintenanceUpdate, signatureVerifyingKey, signData, Transaction, VerifierKeyInsert, } from '@midnight-ntwrk/ledger-v8';
9
+ import { getNetworkId } from '@midnight-ntwrk/midnight-js-network-id';
10
+ import { ttlOneHour } from '@midnight-ntwrk/midnight-js-utils';
11
+ import { DeployError } from "../errors.js";
12
+ /** Only ledger operation version the compiler emits keys for. */
13
+ const VK_VERSION = 'v3';
14
+ /** Verifying key for a hex signing key. The public half is the only part that may be logged. */
15
+ export function verifyingKeyOf(signingKey) {
16
+ return signatureVerifyingKey(signingKey);
17
+ }
18
+ /**
19
+ * Signed insert-only maintenance update for `address` at `counter`.
20
+ *
21
+ * The signature covers the address, the whole insert list, and the counter, so
22
+ * a tampered or replayed update fails the ledger's check rather than ours.
23
+ */
24
+ export function buildInsertUpdate({ address, inserts, counter, signingKey, signerIndex, }) {
25
+ if (inserts.length === 0) {
26
+ // An empty update would spend dust and change nothing.
27
+ throw new DeployError('Refusing to build an empty maintenance update.');
28
+ }
29
+ const updates = inserts.map(({ circuitId, verifierKey }) => new VerifierKeyInsert(circuitId, new ContractOperationVersionedVerifierKey(VK_VERSION, verifierKey)));
30
+ // Sign the built update, then attach; `addSignature` returns the
31
+ // signed value rather than mutating in place.
32
+ const update = new MaintenanceUpdate(address, updates, counter);
33
+ return update.addSignature(BigInt(signerIndex), signData(signingKey, update.dataToSign));
34
+ }
35
+ /**
36
+ * Wrap a signed update in an unproven tx. No Zswap offer: a maintenance update
37
+ * creates no coins, and the wallet adds the dust fee spend when it balances.
38
+ */
39
+ export function buildInsertTx({ update, }) {
40
+ const intent = Intent.new(ttlOneHour()).addMaintenanceUpdate(update);
41
+ return Transaction.fromParts(getNetworkId(), undefined, undefined, intent);
42
+ }
43
+ //# sourceMappingURL=maintenance-tx.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"maintenance-tx.js","sourceRoot":"","sources":["../../src/services/maintenance-tx.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EACL,qCAAqC,EACrC,MAAM,EACN,iBAAiB,EACjB,qBAAqB,EACrB,QAAQ,EACR,WAAW,EACX,iBAAiB,GAClB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,YAAY,EAAE,MAAM,wCAAwC,CAAC;AACtE,OAAO,EAAE,UAAU,EAAE,MAAM,mCAAmC,CAAC;AAC/D,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAE3C,iEAAiE;AACjE,MAAM,UAAU,GAAG,IAAa,CAAC;AA4BjC,gGAAgG;AAChG,MAAM,UAAU,cAAc,CAAC,UAAkB;IAC/C,OAAO,qBAAqB,CAAC,UAAU,CAAC,CAAC;AAC3C,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,iBAAiB,CAAC,EAChC,OAAO,EACP,OAAO,EACP,OAAO,EACP,UAAU,EACV,WAAW,GACW;IACtB,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACzB,uDAAuD;QACvD,MAAM,IAAI,WAAW,CAAC,gDAAgD,CAAC,CAAC;IAC1E,CAAC;IACD,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CACzB,CAAC,EAAE,SAAS,EAAE,WAAW,EAAE,EAAE,EAAE,CAC7B,IAAI,iBAAiB,CACnB,SAAS,EACT,IAAI,qCAAqC,CAAC,UAAU,EAAE,WAAW,CAAC,CACnE,CACJ,CAAC;IACF,iEAAiE;IACjE,8CAA8C;IAC9C,MAAM,MAAM,GAAG,IAAI,iBAAiB,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IAChE,OAAO,MAAM,CAAC,YAAY,CACxB,MAAM,CAAC,WAAW,CAAC,EACnB,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC,UAAU,CAAC,CACxC,CAAC;AACJ,CAAC;AAMD;;;GAGG;AACH,MAAM,UAAU,aAAa,CAAC,EAC5B,MAAM,GACY;IAClB,MAAM,MAAM,GAAG,MAAM,CAAC,GAAG,CAAC,UAAU,EAAE,CAAC,CAAC,oBAAoB,CAAC,MAAM,CAAC,CAAC;IACrE,OAAO,WAAW,CAAC,SAAS,CAAC,YAAY,EAAE,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,CAAC,CAAC;AAC7E,CAAC"}
@@ -0,0 +1,99 @@
1
+ import { type DustWalletOptions, type EnvironmentConfiguration } from '@midnight-ntwrk/testkit-js';
2
+ import { type DustWalletAPI } from '@midnight-ntwrk/wallet-sdk-dust-wallet';
3
+ import type { ShieldedWalletAPI } from '@midnight-ntwrk/wallet-sdk-shielded';
4
+ import { type UnshieldedKeystore, type UnshieldedWalletAPI } from '@midnight-ntwrk/wallet-sdk-unshielded-wallet';
5
+ import type { Logger } from 'pino';
6
+ /** Opaque testkit-js `FluentWalletBuilder.config` (not exported by testkit). */
7
+ export type ConfigShape = unknown;
8
+ /** Sub-wallet a snapshot belongs to. Snapshots are not interchangeable across kinds. */
9
+ export type SubWalletKind = 'shielded' | 'dust' | 'unshielded';
10
+ export interface WalletCacheOptions {
11
+ logger: Logger;
12
+ env: EnvironmentConfiguration;
13
+ /** Directory `compact.toml` was loaded from; see `CompactConfig.rootDir`. */
14
+ rootDir: string;
15
+ shieldedSeed: Uint8Array;
16
+ dustSeed: Uint8Array;
17
+ unshieldedSeed: Uint8Array;
18
+ }
19
+ /**
20
+ * On-disk persistence for the three sub-wallets: seed-derived `.states/`
21
+ * paths, pre-warmed cache import, restore-or-build, and post-sync
22
+ * snapshots.
23
+ *
24
+ * Shielded and dust are cached because they are slow to sync on real
25
+ * networks (shielded trial-decrypts every note; dust streams the global
26
+ * unfiltered ledger event log). Unshielded is cheap to scan but the sync
27
+ * gate waits on its progress too, so an uncached unshielded sub-wallet
28
+ * re-syncs from genesis and becomes the long pole on every cached boot.
29
+ */
30
+ export declare class WalletCache {
31
+ #private;
32
+ /** Seed-derived `.states/` path for the shielded snapshot. */
33
+ readonly shieldedCacheFilePath: string;
34
+ /** Seed-derived `.states/` path for the dust snapshot. */
35
+ readonly dustCacheFilePath: string;
36
+ /** Seed-derived `.states/` path for the unshielded snapshot. */
37
+ readonly unshieldedCacheFilePath: string;
38
+ constructor(opts: WalletCacheOptions);
39
+ /**
40
+ * Drop a user-supplied wallet-state file into `.states/` under the
41
+ * seed-derived filename so the existing restore path picks it up.
42
+ * Detects gzip via magic bytes (`0x1f 0x8b`); raw JSON is gzipped on
43
+ * the way in. Throws {@link WalletError} on read failure so a bad path
44
+ * fails fast instead of silently doing a cold sync from genesis.
45
+ *
46
+ * Safety guarantees:
47
+ * 1. **Source is read-only.** Only `readFileSync` touches `srcPath`.
48
+ * 2. **Backup is preserved forever.** If the target `.gz` already
49
+ * exists, it is `copyFileSync`'d to `<target>.bak` *before* any
50
+ * write — never deleted, never overwritten by this helper. A user
51
+ * who hits a bad-format import can roll back with
52
+ * `mv <target>.bak <target>` and re-run.
53
+ * 3. **Write is atomic.** New bytes land in `<target>.tmp` first,
54
+ * then `rename(2)` over the final path. POSIX rename is atomic
55
+ * within the same filesystem, so a mid-write crash can never leave
56
+ * the existing cache half-overwritten. A stale `.tmp` left by a
57
+ * failed rename is harmless (cache load only scans `.gz`) and gets
58
+ * overwritten by the next import attempt.
59
+ */
60
+ importSeedCache(srcPath: string, kind: SubWalletKind): void;
61
+ loadOrCreateShieldedWallet(args: {
62
+ config: ConfigShape;
63
+ seed: Uint8Array;
64
+ skipCache: boolean;
65
+ }): Promise<ShieldedWalletAPI>;
66
+ /**
67
+ * Restore dust wallet from cache, else build fresh. Routes through
68
+ * `DustWallet(config).restore(...)` because testkit doesn't expose a
69
+ * `WalletFactory.restoreDustWallet`. Caching turns preprod's 1 h+
70
+ * first-run dust sync into seconds on subsequent boots.
71
+ */
72
+ loadOrCreateDustWallet(args: {
73
+ config: ConfigShape;
74
+ seed: Uint8Array;
75
+ dustOptions: DustWalletOptions;
76
+ skipCache: boolean;
77
+ }): Promise<DustWalletAPI>;
78
+ /**
79
+ * Restore the unshielded wallet from cache, else build fresh. Routes
80
+ * through `UnshieldedWallet(config).restore(...)` because testkit
81
+ * doesn't expose a `WalletFactory.restoreUnshieldedWallet`. The
82
+ * snapshot carries the public key, so no keystore is needed to
83
+ * rehydrate; the keystore is only used on the fresh path.
84
+ */
85
+ loadOrCreateUnshieldedWallet(args: {
86
+ config: ConfigShape;
87
+ keystore: UnshieldedKeystore;
88
+ skipCache: boolean;
89
+ }): Promise<UnshieldedWalletAPI>;
90
+ /**
91
+ * Snapshot every sub-wallet to disk. Best-effort and independent per
92
+ * sub-wallet: one failure never blocks the others.
93
+ */
94
+ save(wallet: {
95
+ shielded: unknown;
96
+ dust: unknown;
97
+ unshielded: unknown;
98
+ }): Promise<void>;
99
+ }
@@ -0,0 +1,239 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync, } from 'node:fs';
3
+ import { basename, dirname, resolve } from 'node:path';
4
+ import { gzipSync } from 'node:zlib';
5
+ import { DEFAULT_WALLET_STATE_DIRECTORY, WalletFactory, WalletSaveStateProvider, } from '@midnight-ntwrk/testkit-js';
6
+ import { DustWallet, } from '@midnight-ntwrk/wallet-sdk-dust-wallet';
7
+ import { UnshieldedWallet, } from '@midnight-ntwrk/wallet-sdk-unshielded-wallet';
8
+ import { WalletError } from "../errors.js";
9
+ import { formatError } from "./error-format.js";
10
+ /**
11
+ * On-disk persistence for the three sub-wallets: seed-derived `.states/`
12
+ * paths, pre-warmed cache import, restore-or-build, and post-sync
13
+ * snapshots.
14
+ *
15
+ * Shielded and dust are cached because they are slow to sync on real
16
+ * networks (shielded trial-decrypts every note; dust streams the global
17
+ * unfiltered ledger event log). Unshielded is cheap to scan but the sync
18
+ * gate waits on its progress too, so an uncached unshielded sub-wallet
19
+ * re-syncs from genesis and becomes the long pole on every cached boot.
20
+ */
21
+ export class WalletCache {
22
+ /** Seed-derived `.states/` path for the shielded snapshot. */
23
+ shieldedCacheFilePath;
24
+ /** Seed-derived `.states/` path for the dust snapshot. */
25
+ dustCacheFilePath;
26
+ /** Seed-derived `.states/` path for the unshielded snapshot. */
27
+ unshieldedCacheFilePath;
28
+ #logger;
29
+ constructor(opts) {
30
+ this.#logger = opts.logger;
31
+ this.shieldedCacheFilePath = computeCacheFilePath(opts.rootDir, opts.env, opts.shieldedSeed, 'shielded');
32
+ this.dustCacheFilePath = computeCacheFilePath(opts.rootDir, opts.env, opts.dustSeed, 'dust');
33
+ this.unshieldedCacheFilePath = computeCacheFilePath(opts.rootDir, opts.env, opts.unshieldedSeed, 'unshielded');
34
+ }
35
+ /**
36
+ * Drop a user-supplied wallet-state file into `.states/` under the
37
+ * seed-derived filename so the existing restore path picks it up.
38
+ * Detects gzip via magic bytes (`0x1f 0x8b`); raw JSON is gzipped on
39
+ * the way in. Throws {@link WalletError} on read failure so a bad path
40
+ * fails fast instead of silently doing a cold sync from genesis.
41
+ *
42
+ * Safety guarantees:
43
+ * 1. **Source is read-only.** Only `readFileSync` touches `srcPath`.
44
+ * 2. **Backup is preserved forever.** If the target `.gz` already
45
+ * exists, it is `copyFileSync`'d to `<target>.bak` *before* any
46
+ * write — never deleted, never overwritten by this helper. A user
47
+ * who hits a bad-format import can roll back with
48
+ * `mv <target>.bak <target>` and re-run.
49
+ * 3. **Write is atomic.** New bytes land in `<target>.tmp` first,
50
+ * then `rename(2)` over the final path. POSIX rename is atomic
51
+ * within the same filesystem, so a mid-write crash can never leave
52
+ * the existing cache half-overwritten. A stale `.tmp` left by a
53
+ * failed rename is harmless (cache load only scans `.gz`) and gets
54
+ * overwritten by the next import attempt.
55
+ */
56
+ importSeedCache(srcPath, kind) {
57
+ const targetPath = {
58
+ shielded: this.shieldedCacheFilePath,
59
+ dust: this.dustCacheFilePath,
60
+ unshielded: this.unshieldedCacheFilePath,
61
+ }[kind];
62
+ // CWD-relative on purpose: `srcPath` is what the user typed after
63
+ // `--seed-cache-from-*`, usually shell-completed against the
64
+ // directory they are standing in. `rootDir` governs where the
65
+ // deployer *puts* its own files, not how it reads the user's.
66
+ const absoluteSrc = resolve(process.cwd(), srcPath);
67
+ let bytes;
68
+ try {
69
+ bytes = readFileSync(absoluteSrc);
70
+ }
71
+ catch (e) {
72
+ throw new WalletError(`--seed-cache-from-${kind}: cannot read ${absoluteSrc}: ${e.message}`);
73
+ }
74
+ const isGzipped = bytes.length >= 2 && bytes[0] === 0x1f && bytes[1] === 0x8b;
75
+ const payload = isGzipped ? bytes : gzipSync(bytes);
76
+ const backupPath = `${targetPath}.bak`;
77
+ const tempPath = `${targetPath}.tmp`;
78
+ mkdirSync(pathDir(targetPath), { recursive: true });
79
+ // Preserve the previous cache forever as `<target>.bak` so a
80
+ // bad-format import is always recoverable by hand. We use copy (not
81
+ // rename) so the live `<target>` keeps its bytes throughout the
82
+ // window before the atomic rename below.
83
+ const backedUp = existsSync(targetPath);
84
+ if (backedUp) {
85
+ copyFileSync(targetPath, backupPath);
86
+ }
87
+ // 0o600: a wallet state snapshot exposes the full UTXO set and every
88
+ // derived address. Set at create time so the bytes are never group- or
89
+ // world-readable, not even between write and rename.
90
+ writeFileSync(tempPath, payload, { mode: 0o600 });
91
+ renameSync(tempPath, targetPath);
92
+ this.#logger.info(`Imported ${kind} cache: ${absoluteSrc} → ${targetPath}${backedUp ? ` (previous cache backed up to ${backupPath})` : ''}`);
93
+ }
94
+ async loadOrCreateShieldedWallet(args) {
95
+ const { config, seed, skipCache } = args;
96
+ const logger = this.#logger;
97
+ const cacheFilePath = this.shieldedCacheFilePath;
98
+ if (!skipCache && existsSync(cacheFilePath)) {
99
+ try {
100
+ const dir = pathDir(cacheFilePath);
101
+ const filename = pathBase(cacheFilePath);
102
+ const loader = new WalletSaveStateProvider(logger, '', dir, filename);
103
+ const serializedState = await loader.load();
104
+ const restored = await WalletFactory.restoreShieldedWallet(config, serializedState);
105
+ logger.info(`Restored wallet state from ${cacheFilePath}`);
106
+ return restored;
107
+ }
108
+ catch (e) {
109
+ logger.warn({ err: formatError(e), cacheFilePath }, 'Wallet cache restore failed; falling back to fresh sync');
110
+ }
111
+ }
112
+ else if (skipCache) {
113
+ logger.info('Wallet cache disabled (--no-cache); doing fresh sync');
114
+ }
115
+ return WalletFactory.createShieldedWallet(config, seed);
116
+ }
117
+ /**
118
+ * Restore dust wallet from cache, else build fresh. Routes through
119
+ * `DustWallet(config).restore(...)` because testkit doesn't expose a
120
+ * `WalletFactory.restoreDustWallet`. Caching turns preprod's 1 h+
121
+ * first-run dust sync into seconds on subsequent boots.
122
+ */
123
+ async loadOrCreateDustWallet(args) {
124
+ const { config, seed, dustOptions, skipCache } = args;
125
+ const logger = this.#logger;
126
+ const cacheFilePath = this.dustCacheFilePath;
127
+ if (!skipCache && existsSync(cacheFilePath)) {
128
+ try {
129
+ const dir = pathDir(cacheFilePath);
130
+ const filename = pathBase(cacheFilePath);
131
+ const loader = new WalletSaveStateProvider(logger, '', dir, filename);
132
+ const serializedState = await loader.load();
133
+ // `costParameters` is runtime state on the builder, not baked
134
+ // into the snapshot. Re-apply `dustOptions` so the restored
135
+ // wallet honours our `additionalFeeOverhead` override.
136
+ const dustConfig = buildDustConfig(config, dustOptions);
137
+ const dustClass = DustWallet(dustConfig);
138
+ const restored = dustClass.restore(serializedState);
139
+ logger.info(`Restored dust wallet state from ${cacheFilePath}`);
140
+ return restored;
141
+ }
142
+ catch (e) {
143
+ logger.warn({ err: formatError(e), cacheFilePath }, 'Dust wallet cache restore failed; falling back to fresh sync');
144
+ }
145
+ }
146
+ else if (skipCache) {
147
+ logger.info('Dust wallet cache disabled (--no-cache); doing fresh sync');
148
+ }
149
+ return WalletFactory.createDustWallet(config, seed, dustOptions);
150
+ }
151
+ /**
152
+ * Restore the unshielded wallet from cache, else build fresh. Routes
153
+ * through `UnshieldedWallet(config).restore(...)` because testkit
154
+ * doesn't expose a `WalletFactory.restoreUnshieldedWallet`. The
155
+ * snapshot carries the public key, so no keystore is needed to
156
+ * rehydrate; the keystore is only used on the fresh path.
157
+ */
158
+ async loadOrCreateUnshieldedWallet(args) {
159
+ const { config, keystore, skipCache } = args;
160
+ const logger = this.#logger;
161
+ const cacheFilePath = this.unshieldedCacheFilePath;
162
+ if (!skipCache && existsSync(cacheFilePath)) {
163
+ try {
164
+ const dir = pathDir(cacheFilePath);
165
+ const filename = pathBase(cacheFilePath);
166
+ const loader = new WalletSaveStateProvider(logger, '', dir, filename);
167
+ const serializedState = await loader.load();
168
+ const unshieldedClass = UnshieldedWallet(config);
169
+ const restored = unshieldedClass.restore(serializedState);
170
+ logger.info(`Restored unshielded wallet state from ${cacheFilePath}`);
171
+ return restored;
172
+ }
173
+ catch (e) {
174
+ logger.warn({ err: formatError(e), cacheFilePath }, 'Unshielded wallet cache restore failed; falling back to fresh sync');
175
+ }
176
+ }
177
+ else if (skipCache) {
178
+ logger.info('Unshielded wallet cache disabled (--no-cache); doing fresh sync');
179
+ }
180
+ return WalletFactory.createUnshieldedWallet(config, keystore);
181
+ }
182
+ /**
183
+ * Snapshot every sub-wallet to disk. Best-effort and independent per
184
+ * sub-wallet: one failure never blocks the others.
185
+ */
186
+ async save(wallet) {
187
+ await Promise.allSettled([
188
+ this.#saveSubWalletCache(this.shieldedCacheFilePath, wallet.shielded, 'shielded'),
189
+ this.#saveSubWalletCache(this.dustCacheFilePath, wallet.dust, 'dust'),
190
+ this.#saveSubWalletCache(this.unshieldedCacheFilePath, wallet.unshielded, 'unshielded'),
191
+ ]);
192
+ }
193
+ async #saveSubWalletCache(filePath, subWallet, label) {
194
+ try {
195
+ const dir = pathDir(filePath);
196
+ const filename = pathBase(filePath);
197
+ // `seed` param only feeds the default filename; we pass an
198
+ // explicit one, so the empty string is fine.
199
+ const saver = new WalletSaveStateProvider(this.#logger, '', dir, filename);
200
+ await saver.save(subWallet);
201
+ // WalletSaveStateProvider writes at the process umask and offers no
202
+ // mode control, so tighten the snapshot after the fact.
203
+ chmodSync(filePath, 0o600);
204
+ }
205
+ catch (e) {
206
+ this.#logger.warn({ err: formatError(e), label, filePath }, 'Wallet sub-wallet cache save failed; continuing');
207
+ }
208
+ }
209
+ }
210
+ /**
211
+ * `<rootDir>/.states/<network>-<sha256(seed)[:16]>-<kind>.gz`. Per-kind
212
+ * suffix prevents cross-loading one sub-wallet's snapshot into another
213
+ * (different state schemas). Don't reuse testkit's helper: it embeds the
214
+ * seed verbatim, resolves against the CWD, and gates the network on env
215
+ * vars instead of runtime ID.
216
+ */
217
+ function computeCacheFilePath(rootDir, env, seed, kind) {
218
+ const seedHash = createHash('sha256').update(seed).digest('hex').slice(0, 16);
219
+ const filename = `${env.walletNetworkId}-${seedHash}-${kind}.gz`;
220
+ return resolve(rootDir, DEFAULT_WALLET_STATE_DIRECTORY, filename);
221
+ }
222
+ /** Layer `dustOptions` onto the base config so cache-restored wallets honour `additionalFeeOverhead`. */
223
+ function buildDustConfig(config, dustOptions) {
224
+ return {
225
+ ...config,
226
+ costParameters: {
227
+ ledgerParams: dustOptions.ledgerParams,
228
+ additionalFeeOverhead: dustOptions.additionalFeeOverhead,
229
+ feeBlocksMargin: dustOptions.feeBlocksMargin,
230
+ },
231
+ };
232
+ }
233
+ function pathDir(p) {
234
+ return dirname(p);
235
+ }
236
+ function pathBase(p) {
237
+ return basename(p);
238
+ }
239
+ //# sourceMappingURL=wallet-cache.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wallet-cache.js","sourceRoot":"","sources":["../../src/services/wallet-cache.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EACL,SAAS,EACT,YAAY,EACZ,UAAU,EACV,SAAS,EACT,YAAY,EACZ,UAAU,EACV,aAAa,GACd,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,C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,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;IAC9E,MAAM,QAAQ,GAAG,GAAG,GAAG,CAAC,eAAe,IAAI,QAAQ,IAAI,IAAI,KAAK,CAAC;IACjE,OAAO,OAAO,CAAC,OAAO,EAAE,8BAA8B,EAAE,QAAQ,CAAC,CAAC;AACpE,CAAC;AAED,yGAAyG;AACzG,SAAS,eAAe,CACtB,MAAmB,EACnB,WAA8B;IAE9B,OAAO;QACL,GAAI,MAAkC;QACtC,cAAc,EAAE;YACd,YAAY,EAAE,WAAW,CAAC,YAAY;YACtC,qBAAqB,EAAE,WAAW,CAAC,qBAAqB;YACxD,eAAe,EAAE,WAAW,CAAC,eAAe;SAC7C;KACa,CAAC;AACnB,CAAC;AAED,SAAS,OAAO,CAAC,CAAS;IACxB,OAAO,OAAO,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC;AAED,SAAS,QAAQ,CAAC,CAAS;IACzB,OAAO,QAAQ,CAAC,CAAC,CAAC,CAAC;AACrB,CAAC"}
@@ -0,0 +1,89 @@
1
+ import type { MidnightWalletProvider } from '@midnight-ntwrk/testkit-js';
2
+ import type { Logger } from 'pino';
3
+ /**
4
+ * Default sync ceiling (10 min). Overrides testkit-js's hardcoded 90 s
5
+ * `waitForFunds` timeout, which is too short for real networks.
6
+ */
7
+ export declare const DEFAULT_SYNC_TIMEOUT_MS: number;
8
+ /**
9
+ * Tolerated sync gap, in events, for the chain-tip gate.
10
+ * `FacadeState.isSynced` requires every sub-wallet to be *strictly*
11
+ * complete (gap 0). On a live network the global dust stream advances
12
+ * continuously, so the dust wallet sits a few events behind the tip
13
+ * indefinitely and strict `isSynced` never flips. The gate would then time
14
+ * out on a wallet that is in fact fully usable. `isCompleteWithin(50)` is the
15
+ * SDK default (and what the unshielded wallet uses internally): it treats
16
+ * "within 50 events of tip" as synced, which a live wallet reaches and
17
+ * holds. See OpenZeppelin/compact-tools#115.
18
+ */
19
+ export declare const SYNC_MAX_GAP = 50n;
20
+ /**
21
+ * Print the wallet's three bech32m addresses so the user can verify
22
+ * the seed before a long sync. Best-effort: warn-and-continue on
23
+ * failure.
24
+ */
25
+ export declare function logWalletAddresses(wallet: MidnightWalletProvider, logger: Logger): Promise<void>;
26
+ /**
27
+ * The two sub-wallet progress shapes, mirrored structurally: neither
28
+ * `SyncProgress` (`wallet-sdk-abstractions`, used by shielded and dust)
29
+ * nor its unshielded twin (`wallet-sdk-unshielded-wallet/v1/SyncProgress`)
30
+ * is re-exported from a package root we depend on. Only the fields this
31
+ * module reads are declared, so both SDK types stay assignable.
32
+ */
33
+ export type SubWalletSyncProgress = {
34
+ isStrictlyComplete: () => boolean;
35
+ readonly appliedIndex: bigint;
36
+ readonly highestIndex: bigint;
37
+ readonly isConnected: boolean;
38
+ } | {
39
+ isStrictlyComplete: () => boolean;
40
+ readonly appliedId: bigint;
41
+ readonly highestTransactionId: bigint;
42
+ readonly isConnected: boolean;
43
+ };
44
+ /**
45
+ * One-liner progress string for "Still syncing". Accepts both progress
46
+ * shapes (shielded/dust use `appliedIndex`/`highestIndex`; unshielded
47
+ * uses `appliedId`/`highestTransactionId`).
48
+ */
49
+ export declare function describeProgress(p: SubWalletSyncProgress): string;
50
+ /**
51
+ * The dust index the wallet must pass before its view can include a spend
52
+ * submitted now. Read immediately before submitting.
53
+ */
54
+ export declare function readDustTip(wallet: MidnightWalletProvider): Promise<bigint>;
55
+ export interface AwaitDustSettledArgs {
56
+ wallet: MidnightWalletProvider;
57
+ /** From {@link readDustTip}, taken before the transaction was submitted. */
58
+ appliedBeyond: bigint;
59
+ timeoutMs: number;
60
+ }
61
+ /**
62
+ * Wait for the wallet to have applied dust events past `appliedBeyond` and to
63
+ * hold no transaction of its own still pending.
64
+ *
65
+ * Two fragments balanced against the same dust UTXO make the second a
66
+ * double-spend. `isCompleteWithin` is not enough: it passes a wallet sitting a
67
+ * few events behind the tip, which is exactly the window where the spend is
68
+ * still unseen.
69
+ */
70
+ export declare function awaitDustSettled({ wallet, appliedBeyond, timeoutMs, }: AwaitDustSettledArgs): Promise<void>;
71
+ export interface SyncAndVerifyFundsArgs {
72
+ wallet: MidnightWalletProvider;
73
+ timeoutMs: number;
74
+ logger: Logger;
75
+ /** Periodic checkpoint so a Ctrl+C mid-sync survives. Owned-wallet branch only. */
76
+ onCheckpoint?: () => Promise<void>;
77
+ }
78
+ /**
79
+ * Drive the wallet to chain tip and assert spendable funds. Gates on each
80
+ * sub-wallet being within {@link SYNC_MAX_GAP} events of the tip rather
81
+ * than strictly complete: on a live network the global dust stream never
82
+ * settles to gap 0, so strict `FacadeState.isSynced` never fires and the
83
+ * gate times out on a perfectly usable wallet (#115). The gate still waits
84
+ * on all three sub-wallets; dropping the dust/shielded wait entirely
85
+ * regressed on local with `Invalid Transaction (custom error 170)`.
86
+ * Throttles progress logs to once per 30 s. Throws {@link WalletError} on
87
+ * timeout and {@link UnfundedWalletError} on an empty wallet.
88
+ */
89
+ export declare function syncAndVerifyFunds(args: SyncAndVerifyFundsArgs): Promise<void>;