@bsv/expo-wallet-toolbox 0.9.0 → 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.
@@ -5,7 +5,6 @@
5
5
  * stands; the reference is retried on the next wallet build.
6
6
  */
7
7
  import { ADMIN_ORIGINATOR, LEGACY_ADMIN_ORIGINATOR } from '../config'
8
- import { VAULT_ABORT_REPLAY_MARKER } from '../services/vault/guard'
9
8
  import {
10
9
  computePendingAbortAuthorityTag,
11
10
  verifyPendingAbortAuthorityTag,
@@ -150,10 +149,7 @@ export interface ReplayPendingAbortsResult {
150
149
 
151
150
  export async function replayPendingAborts(args: {
152
151
  wallet: {
153
- abortAction: (
154
- args: { reference: string; [VAULT_ABORT_REPLAY_MARKER]?: true },
155
- originator?: string
156
- ) => Promise<{ aborted?: boolean } | void>
152
+ abortAction: (args: { reference: string }, originator?: string) => Promise<{ aborted?: boolean } | void>
157
153
  } & PendingAbortVerifyWallet
158
154
  storage: StorageLike
159
155
  }): Promise<ReplayPendingAbortsResult> {
@@ -163,12 +159,9 @@ export async function replayPendingAborts(args: {
163
159
  const kept: PendingAbort[] = []
164
160
  let droppedUntrusted = 0
165
161
  for (const item of pending) {
166
- // XR-102 (non-Vault residual): the vault-inventory replay marker below
167
- // only protects a Vault reference — an ordinary localpay/PeerPay
168
- // reference has no settlement row and no vault-inventory entry, so
169
- // nothing else stops a forged `pending_aborts` entry naming one from
170
- // being replayed. Authenticate first: an entry this wallet did not
171
- // itself tag at queue time (queuePendingAbort) is dropped, never
162
+ // XR-102: a forged `pending_aborts` entry would otherwise be replayed
163
+ // with the admin originator. Authenticate first: an entry this wallet
164
+ // did not itself tag at queue time (queuePendingAbort) is dropped, never
172
165
  // replayed — fail closed, since the only thing a replay ever does is
173
166
  // free a reservation, and a dropped reference stays recoverable through
174
167
  // WalletHomeScreen's manual per-row abort.
@@ -179,25 +172,13 @@ export async function replayPendingAborts(args: {
179
172
  }
180
173
  try {
181
174
  // XR-102: the persisted `originator` is never trusted here — this is a
182
- // raw KV record, writable by anything with local storage access, and a
183
- // forged admin-originator string used to replay straight past
184
- // guardVaultAccess's inventory check. The ONLY originator ever used to
185
- // replay is the real, imported constant every legitimate queued abort
186
- // was already created under (see queuePendingAbort's call sites — all
187
- // pass `adminOriginator`), never the field read back off disk.
188
- //
189
- // That alone is not enough: `assertPendingActionOriginator` requires
190
- // this exact originator for a legitimate replay to succeed at all, and
191
- // guardVaultAccess treats every admin-originator call as trusted. The
192
- // marker opts this specific call OUT of that trust and into the same
193
- // vault-inventory reference check a non-admin caller gets — so a
194
- // reference an attacker injected that happens to name a Vault action is
195
- // refused, while an ordinary (and authentically-tagged) localpay/
196
- // PeerPay reference still replays.
197
- const result = await args.wallet.abortAction(
198
- { reference: item.reference, [VAULT_ABORT_REPLAY_MARKER]: true },
199
- ADMIN_ORIGINATOR
200
- )
175
+ // raw KV record, writable by anything with local storage access. The
176
+ // ONLY originator ever used to replay is the real, imported constant
177
+ // every legitimate queued abort was already created under (see
178
+ // queuePendingAbort's call sites — all pass `adminOriginator`), never
179
+ // the field read back off disk; the authority tag above is what makes
180
+ // replaying under it safe.
181
+ const result = await args.wallet.abortAction({ reference: item.reference }, ADMIN_ORIGINATOR)
201
182
  if (result && typeof result === 'object' && result.aborted === false) {
202
183
  kept.push(item)
203
184
  }
@@ -40,13 +40,21 @@ export type DeclineReason =
40
40
  * their own chain admitted before this payment can be accepted by anyone.
41
41
  */
42
42
  | 'not_covered'
43
+ /**
44
+ * The transaction's ancestry ends at a block whose merkle root this device
45
+ * could not confirm — usually an offline payee whose header window does not
46
+ * reach that block yet. Retryable once the PAYEE has been online long enough
47
+ * to sync headers. A payer on an older build shows this code verbatim.
48
+ */
49
+ | 'root_unverified'
43
50
 
44
51
  const DECLINE_REASONS: readonly string[] = [
45
52
  'session_mismatch',
46
53
  'already_paid',
47
54
  'save_failed',
48
55
  'decode_failed',
49
- 'not_covered'
56
+ 'not_covered',
57
+ 'root_unverified'
50
58
  ]
51
59
 
52
60
  export function isDeclineReason(value: string): value is DeclineReason {
@@ -29,14 +29,17 @@ export type VerifiedPayment =
29
29
  /**
30
30
  * Why a frame could not be shown to pay this device.
31
31
  *
32
- * Three kinds, because the payee's decline reason differs: bytes that are not a
32
+ * Four kinds, because the payee's decline reason differs: bytes that are not a
33
33
  * transaction are a decode problem the payer can retry from; a transaction that
34
- * pays someone else is a frame that was never for us; and a token frame whose
34
+ * pays someone else is a frame that was never for us; a token frame whose
35
35
  * evidence does not COVER its own ancestry is a frame that pays us with a coin
36
- * the issuer's overlay has never vouched for — retrying it will not help, and
37
- * the payer needs to hear which of the three it was.
36
+ * the issuer's overlay has never vouched for — retrying it will not help; and
37
+ * a transaction whose ancestry ends at a block root this device could not
38
+ * confirm, which is what an offline payee with no header for that block sees.
39
+ * That last one is fixed by the PAYEE getting online briefly, so the payer
40
+ * needs to hear which of the four it was.
38
41
  */
39
- export type FrameVerifyKind = 'unparseable' | 'not_mine' | 'not_covered'
42
+ export type FrameVerifyKind = 'unparseable' | 'not_mine' | 'not_covered' | 'root_unverified'
40
43
 
41
44
  /**
42
45
  * The decline code the payer is told, for each way verification can fail.
@@ -50,6 +53,7 @@ export type FrameVerifyKind = 'unparseable' | 'not_mine' | 'not_covered'
50
53
  export function declineReasonFor(kind: FrameVerifyKind): DeclineReason {
51
54
  if (kind === 'not_mine') return 'session_mismatch'
52
55
  if (kind === 'not_covered') return 'not_covered'
56
+ if (kind === 'root_unverified') return 'root_unverified'
53
57
  return 'decode_failed'
54
58
  }
55
59
 
@@ -62,17 +66,29 @@ export class FrameVerifyError extends Error {
62
66
  }
63
67
  }
64
68
 
65
- /** The wallet capabilities this module needs: BRC-42 derivation, plus (for the
66
- * BSV branch) the same chain tracker `internalizeAction` itself consults.
67
- *
68
- * `getServices` mirrors the toolbox's own `Wallet`/`WalletStorageManager`
69
- * shape exactly (`wallet.getServices().getChainTracker()`, not a promise of
70
- * an object) — the real object NearbyFlow passes in already implements this,
71
- * so widening the interface needs no new wiring.
72
- */
69
+ /** The one wallet capability this module needs: BRC-42 derivation. The
70
+ * permissions manager satisfies it as is. */
73
71
  export interface DerivingWallet {
74
72
  getPublicKey(args: unknown, originator?: string): Promise<{ publicKey: string }>
75
- getServices(): { getChainTracker(): Promise<ChainTracker> | ChainTracker }
73
+ }
74
+
75
+ /**
76
+ * What `verifyFramePayment` needs from this device, as two separate
77
+ * dependencies rather than one object that must happen to provide both: the
78
+ * permissions manager derives keys but holds no chain services, and a single
79
+ * "wallet" parameter asking for both is how a missing `getServices()` once
80
+ * reached production as a TypeError on every Nearby BSV payment.
81
+ */
82
+ export interface FrameVerifyDeps {
83
+ wallet: DerivingWallet
84
+ /**
85
+ * The chain tracker the BSV branch's SPV check walks merkle paths against —
86
+ * the same one `internalizeAction` consults, i.e.
87
+ * `storage.getServices().getChainTracker()`. In the app that is the
88
+ * offline-first tracker over the local header window, so an offline payee
89
+ * can still verify. Not read for a token frame.
90
+ */
91
+ chainTracker: ChainTracker
76
92
  }
77
93
 
78
94
  /**
@@ -91,7 +107,7 @@ export interface DerivingWallet {
91
107
  * this module enforces on itself — a "queued nothing" decline, by construction.
92
108
  */
93
109
  export async function verifyFramePayment(
94
- wallet: DerivingWallet,
110
+ { wallet, chainTracker }: FrameVerifyDeps,
95
111
  frame: PaymentFrame,
96
112
  originator: string,
97
113
  /**
@@ -187,14 +203,35 @@ export async function verifyFramePayment(
187
203
  // input, which is the desired refusal for an ancestor this device cannot
188
204
  // actually verify. No feeModel is passed, so a legitimate low-fee frame
189
205
  // is never refused on fee grounds — only on SPV/script/value grounds.
190
- const chainTracker = await wallet.getServices().getChainTracker()
206
+ //
207
+ // The tracker is wrapped only to notice a refused merkle root, so that
208
+ // refusal can be told apart from a bad script or value: `tx.verify`
209
+ // returns false for both. A refused root is what an offline payee sees
210
+ // for a block its header window does not reach yet (and what anyone sees
211
+ // for a forged proof), and the remedy — the payee going online — is
212
+ // different from a malformed transaction's.
213
+ let rootRefused = false
214
+ const observed: ChainTracker = {
215
+ isValidRootForHeight: async (root, height) => {
216
+ const ok = await chainTracker.isValidRootForHeight(root, height)
217
+ if (!ok) rootRefused = true
218
+ return ok
219
+ },
220
+ currentHeight: async () => await chainTracker.currentHeight()
221
+ }
222
+ // A refused root surfaces as a throw ("Invalid merkle path"), so both exits
223
+ // check the flag.
224
+ const rootUnverified = () =>
225
+ new FrameVerifyError('root_unverified', 'a merkle root in the frame could not be confirmed on this device')
191
226
  let verified: boolean
192
227
  try {
193
- verified = await tx.verify(chainTracker)
228
+ verified = await tx.verify(observed)
194
229
  } catch (e) {
230
+ if (rootRefused) throw rootUnverified()
195
231
  throw new FrameVerifyError('unparseable', `transaction failed SPV/script verification: ${messageOf(e)}`)
196
232
  }
197
233
  if (!verified) {
234
+ if (rootRefused) throw rootUnverified()
198
235
  throw new FrameVerifyError('unparseable', 'transaction failed SPV/script verification')
199
236
  }
200
237
 
@@ -754,14 +754,16 @@ export class MandalaTokenModule implements PermissionsModule {
754
754
  * (`GUARD_TARGETS`/`GUARDED_PROXIES` in `services/vault/guard.ts`), which
755
755
  * several screens rely on (`guardVaultAccess(managers.permissionsManager,
756
756
  * ADMIN_ORIGINATOR)` again in e.g. `PairScreen.tsx`/`ConnectionsScreen.tsx`)
757
- * to avoid creating a second, unsynchronized guard runtime around the same
758
- * wallet. That dedup only recognizes an object IT previously wrapped —
759
- * putting this wrapper's Proxy on the OUTSIDE (wrapping an already-guarded
760
- * manager) would make every such re-application invisible to the dedup and
761
- * silently double-guard the wallet, splitting its single-flight queue in
762
- * two. Wrapping the raw manager first, then guarding the result, keeps the
763
- * publicly published value exactly what `guardVaultAccess` itself produced
764
- * and expects to see again — in this app that is `WalletContext.tsx`'s
757
+ * to avoid creating a second guard runtime around the same wallet. That
758
+ * dedup only recognizes an object IT previously wrapped — putting this
759
+ * wrapper's Proxy on the OUTSIDE (wrapping an already-guarded manager) would
760
+ * make every such re-application invisible to the dedup and silently
761
+ * double-guard the wallet with a second runtime that has no storage lookup
762
+ * (so it refuses every external call naming an outpoint) and its own
763
+ * listActions queue. Wrapping the raw manager first, then guarding the
764
+ * result, keeps the publicly published value exactly what `guardVaultAccess`
765
+ * itself produced and expects to see again — in this app that is
766
+ * `WalletContext.tsx`'s
765
767
  * `newManagers.permissionsManager = guardVaultAccess(
766
768
  * wrapCreateActionForTokenInputs(permissionsManager, listMandalaTokenOutpoints,
767
769
  * adminOriginator), adminOriginator)`. A manager constructed anywhere else
@@ -79,6 +79,7 @@ export {
79
79
  declineReasonFor,
80
80
  verifyFramePayment,
81
81
  type DerivingWallet,
82
+ type FrameVerifyDeps,
82
83
  type FrameVerifyKind,
83
84
  type VerifiedPayment
84
85
  } from '../../localpay/verify'
@@ -30,7 +30,7 @@ import {
30
30
  verifyVaultMetaAuthorityTag,
31
31
  type HmacCapableWallet
32
32
  } from './metaAuthority'
33
- import { compressPubkey, type VaultInstructions } from './r1comb'
33
+ import { compressPubkey, type VaultInstructionKey, type VaultInstructions } from './r1comb'
34
34
  import { randomBytes } from './random'
35
35
  import { withKeySession, VaultSessionGuard } from './session'
36
36
  import { VaultError } from './types'
@@ -919,6 +919,63 @@ export async function adoptVaultKey(args: {
919
919
  return { ...args.record }
920
920
  }
921
921
 
922
+ /**
923
+ * Find which of `records`' keys the tapped YubiKey actually holds, proving it
924
+ * in the same step: the card signs a fresh random challenge (PIN + touch) and
925
+ * the signature is checked against every key the records list for the
926
+ * card's serial. A reset writes a new key to the same serial, so the serial
927
+ * alone cannot tell setups apart; the signature can.
928
+ *
929
+ * Throws 'key-opens-nothing' when no record names this serial, or none of
930
+ * its keys verifies (the card's key was replaced after those deposits).
931
+ * PIN checks match adoptVaultKey.
932
+ */
933
+ export async function proveHeldVaultKey(args: {
934
+ records: readonly Pick<VaultInstructions, 'keys'>[]
935
+ onPhase: (p: AdoptPhase) => void
936
+ getPin: () => Promise<string>
937
+ nfcMessage?: string
938
+ }): Promise<VaultInstructionKey> {
939
+ const driver = getVaultDriver()
940
+ if (!driver) throw new VaultError('driver-unavailable')
941
+
942
+ args.onPhase('pin-check')
943
+ const pin = await args.getPin()
944
+ requirePivCode(pin, 'PIN')
945
+ const challenge = randomBytes(32)
946
+ const digest = Utils.toHex(challenge)
947
+
948
+ const held = await withKeySession(
949
+ driver,
950
+ async () => {
951
+ const info = await driver.getKeyInfo()
952
+ const named = new Map<string, VaultInstructionKey>()
953
+ for (const record of args.records) {
954
+ for (const key of record.keys) {
955
+ if (key.serial === info.serial && !named.has(key.pubkey)) named.set(key.pubkey, { ...key })
956
+ }
957
+ }
958
+ if (named.size === 0) {
959
+ throw new VaultError('key-opens-nothing', 'No vault deposit on the blockchain names this YubiKey')
960
+ }
961
+ if (info.pinRetries === 0) throw new VaultError('pin-locked', 'PIN is blocked')
962
+ const verified = await driver.verifyPin(info.serial, pin)
963
+ requireVerifiedPin(verified)
964
+
965
+ args.onPhase('challenging')
966
+ const { signature } = await driver.signEcdsa(info.serial, pin, digest)
967
+ for (const key of named.values()) {
968
+ if (signatureProvesKey(key.pubkey, Uint8Array.from(challenge), signature)) return key
969
+ }
970
+ throw new VaultError('key-opens-nothing', 'This YubiKey holds none of the keys its deposits are locked to')
971
+ },
972
+ () => args.onPhase('connecting'),
973
+ { nfcMessage: args.nfcMessage }
974
+ )
975
+ args.onPhase('done')
976
+ return held
977
+ }
978
+
922
979
  export interface VerifiedVaultRecoveryOutput {
923
980
  /** Decoded only after baked-salt and exact-lock verification by transfers.
924
981
  * v6 or v7 — this function only reads fields common to both shapes
@@ -25,6 +25,15 @@
25
25
  * whose transaction the injected lookup reports as not-yet-confirmed is
26
26
  * reported back as `pendingConfirmation`, never thrown and never silently
27
27
  * dropped, and does not consume a gap-scan slot.
28
+ *
29
+ * KEY FILTER: every setup of the same YubiKeys writes fresh PIV keys (and a
30
+ * new vaultId), yet its deposits still authenticate here — the marker and
31
+ * descriptor derive from the wallet root, not the keys. So a scan also finds
32
+ * deposits from earlier setups that nothing the owner still holds can open.
33
+ * Only candidates sharing a key with the live set are internalized: this
34
+ * device's authenticated key list when it has one, otherwise every key of the
35
+ * newest setup the scan found (latest createdAt). The rest are counted as
36
+ * `unreachable`, never inserted.
28
37
  */
29
38
  import { Transaction, Utils } from '@bsv/sdk'
30
39
  import {
@@ -32,12 +41,17 @@ import {
32
41
  commitment,
33
42
  decodeVaultInstructionsV7,
34
43
  encodeVaultInstructionsV7,
44
+ type VaultInstructionKey,
35
45
  type VaultInstructionsV7,
36
46
  type VaultSaltChain
37
47
  } from './r1comb'
38
48
  import { VaultError } from './types'
49
+ import { vaultStore } from './vaultStore'
50
+ import { verifyVaultMetaAuthorityTag, type HmacCapableWallet } from './metaAuthority'
39
51
  import {
40
52
  VAULT_BASKET,
53
+ liveVaultPubkeys,
54
+ opensWithAny,
41
55
  deriveVaultMarkerScript,
42
56
  deriveVaultSalt,
43
57
  decryptVaultDescriptorPlaintext,
@@ -117,6 +131,9 @@ export interface VaultChainRecoveryProblem {
117
131
  export interface VaultChainRecoveryResult {
118
132
  /** Indices newly inserted into 'admin vault' by this run. */
119
133
  found: number
134
+ /** Authenticated, unspent deposits no live key can open (an earlier setup's)
135
+ * — skipped rather than inserted. See this file's KEY FILTER note. */
136
+ unreachable: number
120
137
  /** Marker history existed and decrypted to a valid, unspent v7 record, but
121
138
  * the lookup could not yet show it as confirmed — the honest zero-conf
122
139
  * scope cut (this file's docstring). Not a miss: does not consume a
@@ -135,17 +152,25 @@ export interface VaultChainRecoveryResult {
135
152
  scanned: number
136
153
  }
137
154
 
155
+ /** An authenticated, unspent candidate, held until the scan ends so the key
156
+ * filter can see every setup before anything is inserted. */
157
+ export interface RecoverableCandidate {
158
+ index: number
159
+ ci: VaultInstructionsV7
160
+ beef: number[]
161
+ vaultOutputIndex: number
162
+ }
163
+
138
164
  type CandidateOutcome =
139
- | { kind: 'found' }
140
- | { kind: 'pending' }
165
+ | ({ kind: 'ready' } & RecoverableCandidate)
166
+ | { kind: 'pending'; ci: VaultInstructionsV7 }
141
167
  | { kind: 'spent' }
142
168
  | { kind: 'problem'; reason: string }
143
169
 
144
170
  /**
145
- * Locate, authenticate and (if usable) internalize ONE candidate marker
146
- * transaction for scan index `k`. Never throws — every failure mode is a
147
- * distinct, reported outcome, per this module's "found-but-unusable is not
148
- * a miss" contract.
171
+ * Locate and authenticate ONE candidate marker transaction for scan index
172
+ * `k`. Never throws — every failure mode is a distinct, reported outcome, per
173
+ * this module's "found-but-unusable is not a miss" contract.
149
174
  */
150
175
  async function recoverOneCandidate(
151
176
  w: VaultWallet,
@@ -228,17 +253,24 @@ async function recoverOneCandidate(
228
253
  if (status === 'spent') return { kind: 'spent' }
229
254
  if (status === 'unknown') return { kind: 'problem', reason: 'could not confirm the vault output is unspent' }
230
255
 
231
- if (!entry.confirmed) return { kind: 'pending' }
256
+ if (!entry.confirmed) return { kind: 'pending', ci }
257
+ return { kind: 'ready', index: k, ci, beef: entry.beef, vaultOutputIndex }
258
+ }
232
259
 
260
+ async function internalizeCandidate(
261
+ w: VaultWallet,
262
+ adminOriginator: string,
263
+ candidate: RecoverableCandidate
264
+ ): Promise<string | undefined> {
233
265
  try {
234
266
  await w.internalizeAction({
235
- tx: entry.beef,
267
+ tx: candidate.beef,
236
268
  outputs: [{
237
- outputIndex: vaultOutputIndex,
269
+ outputIndex: candidate.vaultOutputIndex,
238
270
  protocol: 'basket insertion',
239
271
  insertionRemittance: {
240
272
  basket: VAULT_BASKET,
241
- customInstructions: encodeVaultInstructionsV7(ci),
273
+ customInstructions: encodeVaultInstructionsV7(candidate.ci),
242
274
  tags: ['vault']
243
275
  }
244
276
  }],
@@ -246,9 +278,38 @@ async function recoverOneCandidate(
246
278
  seekPermission: false
247
279
  }, adminOriginator)
248
280
  } catch (e) {
249
- return { kind: 'problem', reason: `could not internalize the recovered output: ${(e as Error)?.message ?? 'unknown error'}` }
281
+ return `could not internalize the recovered output: ${(e as Error)?.message ?? 'unknown error'}`
282
+ }
283
+ return undefined
284
+ }
285
+
286
+ /**
287
+ * The keys a recovered deposit must share one of (KEY FILTER). A local key
288
+ * list counts only when its authority tag verifies: a forged list would
289
+ * otherwise hide every real deposit. Without one, the newest setup found
290
+ * wins — an older setup's PIV keys were replaced by the reset that made it.
291
+ */
292
+ async function recoveryLiveKeys(
293
+ w: VaultWallet,
294
+ adminOriginator: string,
295
+ records: readonly VaultInstructionsV7[]
296
+ ): Promise<ReadonlySet<string>> {
297
+ const scopeToken = vaultStore.captureScopeToken()
298
+ const scope = vaultStore.getScope()
299
+ const meta = await vaultStore.getMeta(scopeToken)
300
+ if (meta && scope) {
301
+ const tag = await vaultStore.getMetaTag(scopeToken)
302
+ if (await verifyVaultMetaAuthorityTag(w as unknown as HmacCapableWallet, adminOriginator, meta, scope, tag)) {
303
+ return liveVaultPubkeys(meta)
304
+ }
250
305
  }
251
- return { kind: 'found' }
306
+ if (records.length === 0) return new Set()
307
+ const newest = records.reduce((a, b) => (b.createdAt > a.createdAt ? b : a))
308
+ return new Set(
309
+ records
310
+ .filter(r => r.vaultId === newest.vaultId && r.createdAt === newest.createdAt)
311
+ .flatMap(r => r.keys.map(key => key.pubkey))
312
+ )
252
313
  }
253
314
 
254
315
  /**
@@ -271,11 +332,60 @@ export async function recoverVaultFromChain(
271
332
  chain: VaultSaltChain,
272
333
  gap: number = VAULT_RECOVERY_GAP_DEFAULT
273
334
  ): Promise<VaultChainRecoveryResult> {
335
+ const scan = await scanVaultChain(w, adminOriginator, lookup, chain, gap)
336
+ const live = await recoveryLiveKeys(w, adminOriginator, [...scan.ready.map(c => c.ci), ...scan.pending])
337
+ return await restoreScannedDeposits(w, adminOriginator, scan, live)
338
+ }
339
+
340
+ /**
341
+ * Restore with one tapped YubiKey (no local key list needed, and no guessing
342
+ * between setups): scan the chain, let `prove` pick and prove the key the
343
+ * card holds (proveHeldVaultKey), then restore every deposit of the setups
344
+ * that key belongs to. The proven key is marked adopted, so it can withdraw
345
+ * without a second challenge.
346
+ */
347
+ export async function recoverVaultWithKey(
348
+ w: VaultWallet,
349
+ adminOriginator: string,
350
+ lookup: VaultChainLookup,
351
+ chain: VaultSaltChain,
352
+ prove: (records: readonly VaultInstructionsV7[]) => Promise<VaultInstructionKey>,
353
+ gap: number = VAULT_RECOVERY_GAP_DEFAULT
354
+ ): Promise<VaultChainRecoveryResult & { key: VaultInstructionKey }> {
355
+ const scan = await scanVaultChain(w, adminOriginator, lookup, chain, gap)
356
+ const records = [...scan.ready.map(c => c.ci), ...scan.pending]
357
+ const key = await prove(records)
358
+ // Every key of a setup the proven key is part of, so that setup's deposits
359
+ // come back whole and rebuild one consistent key list.
360
+ const live = new Set(
361
+ records.filter(r => r.keys.some(k => k.pubkey === key.pubkey)).flatMap(r => r.keys.map(k => k.pubkey))
362
+ )
363
+ const result = await restoreScannedDeposits(w, adminOriginator, scan, live)
364
+ if (result.found > 0) await vaultStore.markKeyAdopted(key)
365
+ return { ...result, key }
366
+ }
367
+
368
+ interface VaultChainScan {
369
+ ready: RecoverableCandidate[]
370
+ pending: VaultInstructionsV7[]
371
+ problems: VaultChainRecoveryProblem[]
372
+ scanned: number
373
+ }
374
+
375
+ /** The scan half of recovery: find and authenticate every candidate without
376
+ * inserting any. */
377
+ async function scanVaultChain(
378
+ w: VaultWallet,
379
+ adminOriginator: string,
380
+ lookup: VaultChainLookup,
381
+ chain: VaultSaltChain,
382
+ gap: number
383
+ ): Promise<VaultChainScan> {
274
384
  if (!Number.isSafeInteger(gap) || gap < 1) {
275
385
  throw new VaultError('template-invalid', 'Vault recovery gap must be a positive integer')
276
386
  }
277
- let found = 0
278
- let pendingConfirmation = 0
387
+ const ready: RecoverableCandidate[] = []
388
+ const pending: VaultInstructionsV7[] = []
279
389
  const problems: VaultChainRecoveryProblem[] = []
280
390
  let consecutiveMisses = 0
281
391
  // Bounds the loop independently of consecutiveMisses — see
@@ -344,8 +454,8 @@ export async function recoverVaultFromChain(
344
454
  }
345
455
  inspected++
346
456
  const outcome = await recoverOneCandidate(w, adminOriginator, lookup, chain, k, markerScriptHex, txid)
347
- if (outcome.kind === 'found') { found++; break }
348
- else if (outcome.kind === 'pending') { pendingConfirmation++; break }
457
+ if (outcome.kind === 'ready') { ready.push(outcome); break }
458
+ else if (outcome.kind === 'pending') { pending.push(outcome.ci); break }
349
459
  else if (outcome.kind === 'problem') problems.push({ index: k, reason: outcome.reason })
350
460
  // 'spent': a superseded output (already withdrawn or re-locked) —
351
461
  // entirely normal, silently skipped; keep inspecting other candidates
@@ -353,8 +463,34 @@ export async function recoverVaultFromChain(
353
463
  }
354
464
  k++
355
465
  }
466
+ return { ready, pending, problems, scanned }
467
+ }
468
+
469
+ /** The insert half: internalize the scanned deposits `live` can open, count
470
+ * the rest as unreachable, then rebuild local vault metadata. */
471
+ async function restoreScannedDeposits(
472
+ w: VaultWallet,
473
+ adminOriginator: string,
474
+ scan: VaultChainScan,
475
+ live: ReadonlySet<string>
476
+ ): Promise<VaultChainRecoveryResult> {
477
+ const { ready, pending, scanned } = scan
478
+ const problems = [...scan.problems]
479
+ let found = 0
480
+ let pendingConfirmation = 0
481
+ let unreachable = 0
482
+ for (const candidate of ready) {
483
+ if (!opensWithAny(candidate.ci, live)) { unreachable++; continue }
484
+ const failure = await internalizeCandidate(w, adminOriginator, candidate)
485
+ if (failure) problems.push({ index: candidate.index, reason: failure })
486
+ else found++
487
+ }
488
+ for (const ci of pending) {
489
+ if (opensWithAny(ci, live)) pendingConfirmation++
490
+ else unreachable++
491
+ }
356
492
  await recoverVaultMetaFromOutputs(w, adminOriginator)
357
- return { found, pendingConfirmation, problems, scanned }
493
+ return { found, pendingConfirmation, unreachable, problems, scanned }
358
494
  }
359
495
 
360
496
  // ───────────────────────── default WhatsOnChain implementation ─────────────
@@ -364,16 +500,11 @@ export async function recoverVaultFromChain(
364
500
  * patterns already used by core/pay/rails/address.ts (getUtxosForAddress,
365
501
  * the `/tx/{txid}/beef` fetch, parseWocBeefBody's response-shape checks).
366
502
  *
367
- * NEEDS-NETWORK / UNPROVEN (see the security-review residuals this module
368
- * closes): the exact WhatsOnChain response shapes assumed here —
369
- * `/address/{address}/history` returning `[{tx_hash, ...}]`, and
370
- * `/tx/{hash}/out/{index}` carrying a `spentTxId`/`spent` field for the
371
- * unspent-vs-spent check — were not exercised against the live API as part
372
- * of this change (no network access in this environment). This must be
373
- * smoke-tested against real WhatsOnChain responses (mainnet and testnet)
374
- * before being relied on in production; recoverVaultFromChain's own logic
375
- * is unit-tested against an in-memory VaultChainLookup fake and does not
376
- * depend on these HTTP details being exactly right.
503
+ * Response shapes checked against live mainnet WhatsOnChain on 2026-09-27:
504
+ * `/address/{address}/history` answers `[{tx_hash, height}]`, or 404 "Not
505
+ * Found" for an address with no history; `/tx/{txid}/out/{index}` answers
506
+ * 502 for every output, so spent status comes from `POST /utxos/spent`,
507
+ * which returns one row per outpoint (see outputStatus).
377
508
  */
378
509
  export function wocChainLookup(chain: AppChain): VaultChainLookup {
379
510
  const woc: WocConfig = wocConfigFor(chain)
@@ -398,6 +529,9 @@ export function wocChainLookup(chain: AppChain): VaultChainLookup {
398
529
  throw new Error('wocChainLookup: marker script is not a recognizable P2PKH script')
399
530
  }
400
531
  const response = await fetch(`${base}/address/${address}/history`)
532
+ // WhatsOnChain's answer for an address that has never been used: a
533
+ // genuine miss, not a failure.
534
+ if (response.status === 404) return []
401
535
  if (!response.ok) {
402
536
  throw new Error(`wocChainLookup: address history request failed (HTTP ${response.status})`)
403
537
  }
@@ -428,18 +562,35 @@ export function wocChainLookup(chain: AppChain): VaultChainLookup {
428
562
 
429
563
  async outputStatus(outpoint: { txid: string; vout: number }): Promise<'unspent' | 'spent' | 'unknown'> {
430
564
  // Fail-safe default is 'unknown' (never trusted as unspent — see this
431
- // file's VaultChainLookup interface doc). ONLY a well-formed response
432
- // that explicitly carries `spentTxId: null` counts as confirmed
433
- // unspent; any other shape — including the field simply being ABSENT,
434
- // which `=== undefined` would previously conflate with an explicit
435
- // null — falls through to 'unknown' rather than failing open.
565
+ // file's VaultChainLookup interface doc). The row must be about this
566
+ // exact outpoint. Unspent is a clean row with no `spentIn`; spent is a
567
+ // `spentIn` naming another transaction; an unknown output comes back as
568
+ // `spentIn.status: "Unknown UTXO"` echoing its own txid, which is
569
+ // neither.
436
570
  try {
437
- const response = await fetch(`${base}/tx/${outpoint.txid}/out/${outpoint.vout}`)
571
+ const response = await fetch(`${base}/utxos/spent`, {
572
+ method: 'POST',
573
+ headers: { 'Content-Type': 'application/json' },
574
+ body: JSON.stringify({ utxos: [{ txid: outpoint.txid, vout: outpoint.vout }] })
575
+ })
438
576
  if (!response.ok) return 'unknown'
439
- const info = await response.json()
440
- if (info === null || typeof info !== 'object' || !('spentTxId' in info)) return 'unknown'
441
- if (info.spentTxId === null) return 'unspent'
442
- if (typeof info.spentTxId === 'string' && info.spentTxId.length > 0) return 'spent'
577
+ const body = await response.json()
578
+ const row = Array.isArray(body) && body.length === 1 ? body[0] : undefined
579
+ if (row === null || typeof row !== 'object') return 'unknown'
580
+ if (row.utxo?.txid !== outpoint.txid || row.utxo?.vout !== outpoint.vout) return 'unknown'
581
+ if (row.error !== '') return 'unknown'
582
+ const spentIn = row.spentIn
583
+ if (spentIn === undefined) return 'unspent'
584
+ if (
585
+ spentIn !== null &&
586
+ typeof spentIn === 'object' &&
587
+ typeof spentIn.txid === 'string' &&
588
+ /^[0-9a-fA-F]{64}$/.test(spentIn.txid) &&
589
+ spentIn.txid.toLowerCase() !== outpoint.txid.toLowerCase() &&
590
+ spentIn.status !== 'Unknown UTXO'
591
+ ) {
592
+ return 'spent'
593
+ }
443
594
  return 'unknown'
444
595
  } catch {
445
596
  return 'unknown'