@bsv/expo-wallet-toolbox 0.24.3 → 0.25.1

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.
@@ -11,8 +11,12 @@
11
11
  * database, SecureStore, nor any backup service is needed to find or
12
12
  * authenticate a v7 output — only the wallet root (the mnemonic), a chain
13
13
  * lookup, and — to actually SPEND it — one physically-present enrolled
14
- * YubiKey, through the unchanged withdraw path. The YubiKey is NOT needed to
15
- * restore.
14
+ * YubiKey, through the unchanged withdraw path. A restore needs one
15
+ * physically-present enrolled YubiKey: a scan alone only REPORTS what the
16
+ * chain holds (`needsKey`), and a tap (`recoverVaultWithKey`,
17
+ * `recoverVaultFromTxidsWithKey`) restores it. The one exception is a phone
18
+ * that already holds a vault with a checked key: there a scan merges new
19
+ * outputs by outpoint.
16
20
  *
17
21
  * SCOPE (deliberate, disclosed — design v7 §1.3 "rejected: rebuilding
18
22
  * zero-conf ancestor BEEF assembly"): recovery claims CONFIRMED deposits.
@@ -26,16 +30,19 @@
26
30
  * reported back as `pendingConfirmation`, never thrown and never silently
27
31
  * dropped, and does not consume a gap-scan slot.
28
32
  *
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.
33
+ * ADMISSION (a scan only adds outputs): the marker and descriptor derive from
34
+ * the wallet root, so anyone holding the mnemonic can plant a record, and
35
+ * earlier setups' deposits authenticate too. Candidates are grouped into
36
+ * lineages (`vaultId:createdAt`) and, at a lineage's highest revision, into one
37
+ * variant per distinct key list. With a local, authenticated meta only
38
+ * candidates of that lineage that add no unknown key are internalized (the rest
39
+ * are set apart). With a tapped key and no local meta one group is
40
+ * internalized; more than one is a conflict: nothing is internalized and the
41
+ * groups are reported. A tapped restore keeps only outputs whose OWN key list
42
+ * holds the tapped key. With no tapped key and no checked local vault nothing
43
+ * is internalized.
37
44
  */
38
- import { Transaction, Utils } from '@bsv/sdk'
45
+ import { Hash, Transaction, Utils } from '@bsv/sdk'
39
46
  import {
40
47
  buildLock,
41
48
  commitment,
@@ -46,22 +53,30 @@ import {
46
53
  type VaultSaltChain
47
54
  } from './r1comb'
48
55
  import { VaultError } from './types'
49
- import { vaultStore } from './vaultStore'
50
- import { verifyVaultMetaAuthorityTag, type HmacCapableWallet } from './metaAuthority'
56
+ import { vaultStore, type VaultMeta } from './vaultStore'
57
+ import { computeVaultMetaAuthorityTag, verifyVaultMetaAuthorityTag, type HmacCapableWallet } from './metaAuthority'
51
58
  import {
52
59
  VAULT_BASKET,
60
+ introducesUnknownKey,
53
61
  liveVaultPubkeys,
54
62
  opensWithAny,
55
63
  deriveVaultMarkerScript,
56
64
  deriveVaultSalt,
57
65
  decryptVaultDescriptorPlaintext,
58
66
  parseVaultDescriptorScript,
67
+ listVaultBasketOutpoints,
59
68
  recoverVaultMetaFromOutputs,
60
69
  vaultChainKeyId,
61
70
  type VaultWallet
62
71
  } from './transfers'
63
- import { wocConfigFor, type WocConfig } from '../../pay/rails/address'
64
- import type { AppChain } from '../../config'
72
+ import {
73
+ VAULT_SCAN_MIN_SATS,
74
+ lookupMarker,
75
+ noteSaltFloor,
76
+ type MarkerHistory,
77
+ type VaultChainLookup
78
+ } from './markerLookup'
79
+ import { p2pkhAddressFromScript } from './wocLookup'
65
80
 
66
81
  /** Default, caller-raisable gap: consecutive indices with NO marker history
67
82
  * (a found-but-unusable record does not count — see below) before the scan
@@ -85,88 +100,119 @@ export const VAULT_RECOVERY_GAP_DEFAULT = 20
85
100
  * recovery parameter. */
86
101
  export const VAULT_RECOVERY_MAX_CONSECUTIVE_PROBLEMS = 20
87
102
 
88
- /** Defensive cap on how many candidate transactions a single scan index will
89
- * inspect. A v7 marker is an ordinary P2PKH address that becomes publicly
90
- * visible the moment its real deposit confirms; nothing stops a stranger
91
- * from paying arbitrary dust to it afterward. A legitimate index has exactly
92
- * one real deposit history, so recovery never needs more than a handful of
93
- * candidates to find it — this only bounds how much free decrypt-and-discard
94
- * work a targeted victim's recovery can be forced to do. */
95
- const VAULT_RECOVERY_MAX_CANDIDATES_PER_INDEX = 50
96
-
97
- /**
98
- * Injected chain lookup — the only network/indexer dependency this module
99
- * has. Unit-tested against an in-memory fake; core/services/vault/wocChainLookup.ts
100
- * (see below) is the production WhatsOnChain implementation.
101
- */
102
- export interface VaultChainLookup {
103
- /** Every txid whose output list includes an output with exactly this
104
- * locking script — from address history and/or the current unspent set.
105
- * An empty result is a genuine "no marker at this index" miss. */
106
- transactionsForLockingScript(lockingScriptHex: string): Promise<string[]>
107
- /** AtomicBEEF-decodable bytes for `txid` (a plain raw-tx-only BEEF is
108
- * fine — recoverOneCandidate only reads `tx.outputs` from it locally; the
109
- * bytes handed to `wallet.internalizeAction` are these same bytes, and
110
- * ITS OWN chain-tracker validation is the actual SPV gate), plus whether
111
- * this lookup can currently show the transaction as confirmed. `null`
112
- * means the lookup could not produce usable bytes at all (reported as a
113
- * problem, not a miss — see recoverOneCandidate). `confirmed: false` is
114
- * the explicit, disclosed zero-conf boundary (see this file's docstring):
115
- * recoverOneCandidate reports it as `pendingConfirmation` rather than
116
- * attempting `internalizeAction`, which the toolbox's own SPV gate would
117
- * otherwise throw on.
118
- */
119
- transactionForTxid(txid: string): Promise<{ beef: number[]; confirmed: boolean } | null>
120
- /** Spent/unspent/unknown for one outpoint. 'unknown' is never trusted as
121
- * unspent — see recoverOneCandidate. */
122
- outputStatus(outpoint: { txid: string; vout: number }): Promise<'unspent' | 'spent' | 'unknown'>
123
- }
124
-
125
103
  export interface VaultChainRecoveryProblem {
126
104
  /** The scan index (saltKeyId) this problem was found at. */
127
105
  index: number
128
106
  reason: string
107
+ /** Base58 marker address of the index, set when known, so a person can look
108
+ * it up in a block explorer. */
109
+ markerAddress?: string
110
+ }
111
+
112
+ /** One lineage (`vaultId:createdAt`), or one variant of it, found by a scan. */
113
+ export interface VaultRecoveryGroup {
114
+ /** '<vaultId>:<createdAt>', or for a variant '<vaultId>:<createdAt>:<16 hex>'. */
115
+ id: string
116
+ vaultId: string
117
+ createdAt: number
118
+ /** Highest revision in the group. */
119
+ revision: number
120
+ /** Key list at that revision. */
121
+ keys: VaultInstructionKey[]
122
+ /** Internalizable outputs (at or above the floor, unspent, confirmed). */
123
+ outputs: number
124
+ satoshis: number
129
125
  }
130
126
 
131
- export interface VaultChainRecoveryResult {
132
- /** Indices newly inserted into 'admin vault' by this run. */
127
+ /** What one scan run found. `found`, `unreachable`, `pendingConfirmation`,
128
+ * `problems` and `scanned` keep the meaning they always had. */
129
+ export interface VaultScanResult {
130
+ /** Outputs newly internalized by this run. */
133
131
  found: number
134
- /** Authenticated, unspent deposits no live key can open (an earlier setup's)
132
+ /** Authenticated, unspent, and no live key opens them (an earlier setup's)
135
133
  * — skipped rather than inserted. See this file's KEY FILTER note. */
136
134
  unreachable: number
137
- /** Marker history existed and decrypted to a valid, unspent v7 record, but
138
- * the lookup could not yet show it as confirmed — the honest zero-conf
139
- * scope cut (this file's docstring). Not a miss: does not consume a
140
- * gap-scan slot, and is not a "problem" (nothing is wrong; it just isn't
141
- * recoverable yet). */
135
+ /** A valid, unspent v7 record the lookup could not yet show as confirmed —
136
+ * the honest zero-conf scope cut (this file's docstring). Not a miss and not
137
+ * a problem. */
142
138
  pendingConfirmation: number
143
- /** A found-but-unusable record (bad decrypt, wrong version, index/chain
144
- * mismatch, lock-rebuild mismatch, unreadable transaction bytes) — reported
145
- * distinctly and does NOT count as a "no marker" miss, so a version
146
- * mismatch or transient lookup hiccup at one index can never silently
147
- * truncate the scan. */
139
+ /** Valid candidates under VAULT_SCAN_MIN_SATS: counted, never internalized,
140
+ * not pending and not a problem. */
141
+ ignoredBelowMinimum: number
142
+ /** Rows at a marker address that are structurally not a Vault record of
143
+ * ours: no marker between a vault output and a descriptor, the adjacent
144
+ * output is not a v7 descriptor, or the descriptor does not decrypt under
145
+ * this index. Anyone can pay a public marker address, so these are counted
146
+ * as noise: never a problem, and never a reason for status 'incomplete'. */
147
+ ignoredNonVault: number
148
+ /** A found-but-unusable record, an index whose lookup was incomplete, or a
149
+ * failed internalize. Reported distinctly; none of them counts as a "no
150
+ * marker" miss, so one bad index can never silently truncate the scan. */
148
151
  problems: VaultChainRecoveryProblem[]
152
+ /** = problems.length */
153
+ problemCount: number
154
+ /** Indexes whose lookup was unknown (window full, request failed, rate
155
+ * limited). Their rows, if any were read, were still examined. */
156
+ unknownIndexes: number[]
157
+ /** Highest index with any marker history or any recovered record; 0 if none. */
158
+ maxUsedIndex: number
149
159
  /** Highest index actually scanned this run — surfaced so a UI can offer
150
- * "scan further" when the gap default (or a caller-raised one) turns out
151
- * to be too small for a heavily re-tried enrollment. */
160
+ * "scan further" when the gap default turns out to be too small. */
152
161
  scanned: number
162
+ /** 'incomplete' when problemCount > 0 or unknownIndexes is not empty. */
163
+ status: 'complete' | 'incomplete'
164
+ /** Every group found (after the tapped-key filter, when there is one),
165
+ * including set-apart ones. */
166
+ groups?: VaultRecoveryGroup[]
167
+ /** True when more than one group is a candidate and nothing was internalized. */
168
+ conflict?: boolean
169
+ /** Groups that were not internalized. */
170
+ setApart?: VaultRecoveryGroup[]
171
+ /** True when this scan saw at least one Vault record of this wallet and restored none of it, because no key
172
+ * was tapped and this phone holds no vault with a checked key. Nothing was internalized and no meta was
173
+ * written. Not an error, not 'incomplete', not "none". The next step is a tap (recoverVaultWithKey or
174
+ * recoverVaultFromTxidsWithKey). */
175
+ needsKey?: boolean
153
176
  }
154
177
 
178
+ /** Options that pick one group when a scan finds several. */
179
+ export interface VaultRestoreOptions {
180
+ /** A `VaultRecoveryGroup.id`. */
181
+ groupId?: string
182
+ /** Alias for `groupId`; matches a lineage with exactly one group. */
183
+ vaultId?: string
184
+ }
185
+
186
+ /** Alias kept for existing callers. */
187
+ export type VaultChainRecoveryResult = VaultScanResult
188
+
155
189
  /** An authenticated, unspent candidate, held until the scan ends so the key
156
190
  * filter can see every setup before anything is inserted. */
157
191
  export interface RecoverableCandidate {
158
192
  index: number
193
+ txid: string
159
194
  ci: VaultInstructionsV7
160
195
  beef: number[]
161
196
  vaultOutputIndex: number
197
+ satoshis: number
162
198
  }
163
199
 
164
200
  type CandidateOutcome =
165
201
  | ({ kind: 'ready' } & RecoverableCandidate)
166
202
  | { kind: 'pending'; ci: VaultInstructionsV7 }
167
203
  | { kind: 'spent' }
204
+ | { kind: 'below-minimum' }
205
+ | { kind: 'non-vault' }
168
206
  | { kind: 'problem'; reason: string }
169
207
 
208
+ /** True only for the two ways a stranger-planted ciphertext fails to open
209
+ * under SymmetricKey.decrypt: AES-GCM authentication failure and a ciphertext
210
+ * too short for IV + tag. Everything else is a wallet-level failure. */
211
+ function isForeignCiphertextError(error: unknown): boolean {
212
+ const message = error instanceof Error ? error.message : String(error)
213
+ return /decryption failed|ciphertext too short/i.test(message)
214
+ }
215
+
170
216
  /**
171
217
  * Locate and authenticate ONE candidate marker transaction for scan index
172
218
  * `k`. Never throws — every failure mode is a distinct, reported outcome, per
@@ -205,17 +251,24 @@ async function recoverOneCandidate(
205
251
  const vaultOutput = markerIndex >= 1 ? tx.outputs[markerIndex - 1] : undefined
206
252
  const descriptorOutput = markerIndex >= 0 ? tx.outputs[markerIndex + 1] : undefined
207
253
  if (!vaultOutput || !descriptorOutput) {
208
- return { kind: 'problem', reason: 'marker is not immediately between a vault output and a descriptor' }
254
+ // Structural noise: a stranger can pay a public marker address.
255
+ return { kind: 'non-vault' }
209
256
  }
210
257
 
211
258
  const parsedDescriptor = parseVaultDescriptorScript(descriptorOutput.lockingScript)
212
- if (!parsedDescriptor) return { kind: 'problem', reason: 'adjacent output is not a v7 descriptor' }
259
+ if (!parsedDescriptor) return { kind: 'non-vault' }
213
260
 
214
261
  let plaintext: string
215
262
  try {
216
263
  plaintext = await decryptVaultDescriptorPlaintext(w, adminOriginator, chain, saltKeyId, parsedDescriptor.ciphertext)
217
- } catch {
218
- return { kind: 'problem', reason: 'descriptor did not decrypt under this index' }
264
+ } catch (error) {
265
+ // Only an AES-GCM authentication failure (or a ciphertext too short to
266
+ // hold an IV and tag) proves the descriptor is not encrypted to this
267
+ // wallet's key for this index: a stranger can plant either. Any other
268
+ // throw (wallet locked, storage error, transient failure) says nothing
269
+ // about the record, so a real deposit must not be dropped as noise.
270
+ if (isForeignCiphertextError(error)) return { kind: 'non-vault' }
271
+ return { kind: 'problem', reason: 'could not decrypt the descriptor (wallet error)' }
219
272
  }
220
273
 
221
274
  const ci: VaultInstructionsV7 | null = decodeVaultInstructionsV7(plaintext)
@@ -249,6 +302,12 @@ async function recoverOneCandidate(
249
302
  }
250
303
 
251
304
  const vaultOutputIndex = markerIndex - 1
305
+ // A real Vault output is never under the frozen scan floor (every deposit,
306
+ // remainder and re-lock is at least VAULT_DEPOSIT_MIN). Anything smaller is
307
+ // a copy or dust: counted, never internalized, never pending.
308
+ if (vaultOutput.satoshis === undefined || vaultOutput.satoshis < VAULT_SCAN_MIN_SATS) {
309
+ return { kind: 'below-minimum' }
310
+ }
252
311
  let status: 'unspent' | 'spent' | 'unknown'
253
312
  try {
254
313
  status = await lookup.outputStatus({ txid, vout: vaultOutputIndex })
@@ -259,7 +318,7 @@ async function recoverOneCandidate(
259
318
  if (status === 'unknown') return { kind: 'problem', reason: 'could not confirm the vault output is unspent' }
260
319
 
261
320
  if (!entry.confirmed) return { kind: 'pending', ci }
262
- return { kind: 'ready', index: k, ci, beef: entry.beef, vaultOutputIndex }
321
+ return { kind: 'ready', index: k, txid, ci, beef: entry.beef, vaultOutputIndex, satoshis: vaultOutput.satoshis }
263
322
  }
264
323
 
265
324
  async function internalizeCandidate(
@@ -293,40 +352,95 @@ async function internalizeCandidate(
293
352
  return undefined
294
353
  }
295
354
 
296
- /**
297
- * The keys a recovered deposit must share one of (KEY FILTER). A local key
298
- * list counts only when its authority tag verifies: a forged list would
299
- * otherwise hide every real deposit. Without one, the newest setup found
300
- * wins — an older setup's PIV keys were replaced by the reset that made it.
301
- */
302
- async function recoveryLiveKeys(
303
- w: VaultWallet,
304
- adminOriginator: string,
305
- records: readonly VaultInstructionsV7[]
306
- ): Promise<ReadonlySet<string>> {
355
+ /** This device's local meta, only when its authority tag verifies: a forged
356
+ * record must never decide what is admitted. */
357
+ async function authenticatedLocalMeta(w: VaultWallet, adminOriginator: string): Promise<VaultMeta | null> {
307
358
  const scopeToken = vaultStore.captureScopeToken()
308
359
  const scope = vaultStore.getScope()
309
360
  const meta = await vaultStore.getMeta(scopeToken)
310
- if (meta && scope) {
311
- const tag = await vaultStore.getMetaTag(scopeToken)
312
- if (await verifyVaultMetaAuthorityTag(w as unknown as HmacCapableWallet, adminOriginator, meta, scope, tag)) {
313
- return liveVaultPubkeys(meta)
361
+ if (!meta || !scope) return null
362
+ const tag = await vaultStore.getMetaTag(scopeToken)
363
+ if (await verifyVaultMetaAuthorityTag(w as unknown as HmacCapableWallet, adminOriginator, meta, scope, tag)) {
364
+ return meta
365
+ }
366
+ return null
367
+ }
368
+
369
+ const lineageId = (ci: Pick<VaultInstructionsV7, 'vaultId' | 'createdAt'>): string => `${ci.vaultId}:${ci.createdAt}`
370
+
371
+ const sameKeyList = (a: readonly VaultInstructionKey[], b: readonly VaultInstructionKey[]): boolean =>
372
+ a.length === b.length && a.every((key, i) => key.serial === b[i].serial && key.pubkey === b[i].pubkey)
373
+
374
+ function keyListDigest(keys: readonly VaultInstructionKey[]): string {
375
+ const json = JSON.stringify(keys.map(key => ({ serial: key.serial, pubkey: key.pubkey })))
376
+ return Utils.toHex(Hash.sha256(Utils.toArray(json, 'utf8'))).slice(0, 16)
377
+ }
378
+
379
+ /** A group with the candidates it would internalize. */
380
+ interface InternalGroup {
381
+ group: VaultRecoveryGroup
382
+ ready: RecoverableCandidate[]
383
+ pending: VaultInstructionsV7[]
384
+ }
385
+
386
+ /**
387
+ * Form the groups of a set of records: one per lineage, split at the lineage's
388
+ * highest revision into one per distinct key list (a variant). Outputs of a
389
+ * lower revision belong to every variant of their lineage.
390
+ */
391
+ function formGroups(ready: readonly RecoverableCandidate[], pending: readonly VaultInstructionsV7[]): InternalGroup[] {
392
+ const lineages = new Map<string, { ready: RecoverableCandidate[]; pending: VaultInstructionsV7[] }>()
393
+ const entry = (id: string) => {
394
+ let e = lineages.get(id)
395
+ if (!e) lineages.set(id, (e = { ready: [], pending: [] }))
396
+ return e
397
+ }
398
+ for (const c of ready) entry(lineageId(c.ci)).ready.push(c)
399
+ for (const ci of pending) entry(lineageId(ci)).pending.push(ci)
400
+
401
+ const groups: InternalGroup[] = []
402
+ for (const [id, members] of lineages) {
403
+ const records = [...members.ready.map(c => c.ci), ...members.pending]
404
+ const revision = Math.max(...records.map(ci => ci.revision))
405
+ const variants: VaultInstructionKey[][] = []
406
+ for (const ci of records) {
407
+ if (ci.revision === revision && !variants.some(v => sameKeyList(v, ci.keys))) variants.push(ci.keys)
408
+ }
409
+ for (const keys of variants) {
410
+ const belongs = (ci: VaultInstructionsV7): boolean => ci.revision < revision || sameKeyList(keys, ci.keys)
411
+ const groupReady = members.ready.filter(c => belongs(c.ci))
412
+ const first = records[0]
413
+ groups.push({
414
+ group: {
415
+ id: variants.length > 1 ? `${id}:${keyListDigest(keys)}` : id,
416
+ vaultId: first.vaultId,
417
+ createdAt: first.createdAt,
418
+ revision,
419
+ keys: keys.map(key => ({ ...key })),
420
+ outputs: groupReady.length,
421
+ satoshis: groupReady.reduce((sum, c) => sum + c.satoshis, 0)
422
+ },
423
+ ready: groupReady,
424
+ pending: members.pending.filter(belongs)
425
+ })
314
426
  }
315
427
  }
316
- if (records.length === 0) return new Set()
317
- const newest = records.reduce((a, b) => (b.createdAt > a.createdAt ? b : a))
318
- return new Set(
319
- records
320
- .filter(r => r.vaultId === newest.vaultId && r.createdAt === newest.createdAt)
321
- .flatMap(r => r.keys.map(key => key.pubkey))
322
- )
428
+ return groups
323
429
  }
324
430
 
325
431
  /**
326
- * Scan k = 1.. for chain-published v7 Vault outputs and internalize every
327
- * confirmed, unspent, authenticated one into 'admin vault'. Then rebuilds
328
- * local vault metadata from the now-listed outputs via the unchanged
329
- * recoverVaultMetaFromOutputs (which itself re-authenticates everything).
432
+ * "Scan the blockchain for deposits": scan k = 1.. for chain-published v7
433
+ * Vault outputs. On a phone that holds a vault with a checked key it
434
+ * internalizes every confirmed, unspent, authenticated one that is not already
435
+ * in 'admin vault' (merge by outpoint, so a second run is a no-op for known
436
+ * outputs) and rebuilds local vault metadata from the now-listed outputs via
437
+ * the unchanged recoverVaultMetaFromOutputs (which itself re-authenticates
438
+ * everything). On any other phone it only REPORTS (`needsKey`): a restore needs
439
+ * a tap (recoverVaultWithKey).
440
+ *
441
+ * It works with or without local metadata, and the result says what was found
442
+ * and what went wrong: `status` is 'incomplete' when any index had a problem
443
+ * or an unknown lookup, so a caller never shows a partial scan as complete.
330
444
  *
331
445
  * `wallet` need only satisfy VaultWallet (already used throughout
332
446
  * transfers.ts) — getPublicKey/encrypt/decrypt/createHmac/internalizeAction
@@ -335,6 +449,21 @@ async function recoveryLiveKeys(
335
449
  * marker, decrypt the descriptor, or derive the salt — see INT-10's fail-closed
336
450
  * claim in restoreSalt.test.ts).
337
451
  */
452
+ export async function scanVaultDeposits(
453
+ w: VaultWallet,
454
+ adminOriginator: string,
455
+ lookup: VaultChainLookup,
456
+ chain: VaultSaltChain,
457
+ gap: number = VAULT_RECOVERY_GAP_DEFAULT
458
+ ): Promise<VaultScanResult> {
459
+ const scan = await scanVaultChain(w, adminOriginator, lookup, chain, gap)
460
+ return await restoreScannedDeposits(w, adminOriginator, scan, {})
461
+ }
462
+
463
+ /** Kept for existing callers: the same scan. It has no tapped key, so on a
464
+ * phone with no checked vault it only reports (`needsKey`) and internalizes
465
+ * nothing; with more than one group it reports `conflict`. Restoring, and
466
+ * picking a group, needs the tap (recoverVaultWithKey). */
338
467
  export async function recoverVaultFromChain(
339
468
  w: VaultWallet,
340
469
  adminOriginator: string,
@@ -342,17 +471,60 @@ export async function recoverVaultFromChain(
342
471
  chain: VaultSaltChain,
343
472
  gap: number = VAULT_RECOVERY_GAP_DEFAULT
344
473
  ): Promise<VaultChainRecoveryResult> {
345
- const scan = await scanVaultChain(w, adminOriginator, lookup, chain, gap)
346
- const live = await recoveryLiveKeys(w, adminOriginator, [...scan.ready.map(c => c.ci), ...scan.pending])
347
- return await restoreScannedDeposits(w, adminOriginator, scan, live)
474
+ return await scanVaultDeposits(w, adminOriginator, lookup, chain, gap)
475
+ }
476
+
477
+ /** The tapped half of every restore: `prove` picks and proves the held key, only outputs whose OWN key list
478
+ * holds it are restored, and the key is marked proven whenever the stored meta holds that exact pair. */
479
+ async function finishTappedRestore(
480
+ w: VaultWallet,
481
+ adminOriginator: string,
482
+ scan: VaultChainScan,
483
+ prove: (records: readonly VaultInstructionsV7[]) => Promise<VaultInstructionKey>,
484
+ options?: VaultRestoreOptions
485
+ ): Promise<VaultScanResult & { key: VaultInstructionKey }> {
486
+ const records = [...scan.ready.map(c => c.ci), ...scan.pending]
487
+ const key = await prove(records)
488
+ const selection: RestoreSelection = {
489
+ pubkey: key.pubkey,
490
+ groupId: options?.groupId,
491
+ vaultId: options?.vaultId,
492
+ requireGroup: true
493
+ }
494
+ const result = await restoreScannedDeposits(w, adminOriginator, scan, selection)
495
+ const scope = vaultStore.getScope()
496
+ const snapshot = scope ? await vaultStore.getMeta() : null
497
+ const holdsKey =
498
+ !!snapshot &&
499
+ [
500
+ ...snapshot.keys,
501
+ ...(snapshot.staged ? [snapshot.staged] : []),
502
+ ...(snapshot.pendingRemoval ? [snapshot.pendingRemoval.key] : [])
503
+ ].some(k => k.serial === key.serial && k.pubkey === key.pubkey)
504
+ if (scope && snapshot && holdsKey) {
505
+ // A durable proof re-tags the whole stored meta, so it is only written over a meta whose own tag verifies.
506
+ // Any other meta gets a session proof (no tagger).
507
+ const hmacWallet = w as unknown as HmacCapableWallet
508
+ const tag = await vaultStore.getMetaTag()
509
+ const authentic = await verifyVaultMetaAuthorityTag(hmacWallet, adminOriginator, snapshot, scope, tag)
510
+ await vaultStore.markKeyAdopted(
511
+ key,
512
+ undefined,
513
+ authentic ? next => computeVaultMetaAuthorityTag(hmacWallet, adminOriginator, next, scope) : undefined,
514
+ authentic ? snapshot : undefined
515
+ )
516
+ }
517
+ return { ...result, key }
348
518
  }
349
519
 
350
520
  /**
351
- * Restore with one tapped YubiKey (no local key list needed, and no guessing
352
- * between setups): scan the chain, let `prove` pick and prove the key the
353
- * card holds (proveHeldVaultKey), then restore every deposit of the setups
354
- * that key belongs to. The proven key is marked adopted, so it can withdraw
355
- * without a second challenge.
521
+ * Restore with one tapped YubiKey (no local key list needed): scan the chain,
522
+ * let `prove` pick and prove the key the card holds (proveHeldVaultKey), then
523
+ * keep only the outputs whose OWN key list holds that key and restore the group
524
+ * they form. More than one group and no `options.groupId`: restore nothing and
525
+ * report `conflict` with the groups. The proven key is marked adopted, so it
526
+ * can withdraw without a second challenge. The key is proven whenever the
527
+ * stored meta holds it, also when nothing new was internalized.
356
528
  */
357
529
  export async function recoverVaultWithKey(
358
530
  w: VaultWallet,
@@ -360,28 +532,247 @@ export async function recoverVaultWithKey(
360
532
  lookup: VaultChainLookup,
361
533
  chain: VaultSaltChain,
362
534
  prove: (records: readonly VaultInstructionsV7[]) => Promise<VaultInstructionKey>,
363
- gap: number = VAULT_RECOVERY_GAP_DEFAULT
535
+ gap: number = VAULT_RECOVERY_GAP_DEFAULT,
536
+ options?: VaultRestoreOptions
364
537
  ): Promise<VaultChainRecoveryResult & { key: VaultInstructionKey }> {
365
538
  const scan = await scanVaultChain(w, adminOriginator, lookup, chain, gap)
366
- const records = [...scan.ready.map(c => c.ci), ...scan.pending]
367
- const key = await prove(records)
368
- // Every key of a setup the proven key is part of, so that setup's deposits
369
- // come back whole and rebuild one consistent key list.
370
- const live = new Set(
371
- records.filter(r => r.keys.some(k => k.pubkey === key.pubkey)).flatMap(r => r.keys.map(k => k.pubkey))
539
+ return await finishTappedRestore(w, adminOriginator, scan, prove, options)
540
+ }
541
+
542
+ /** Most transaction IDs one `recoverVaultFromTxids` call accepts. */
543
+ export const VAULT_TXID_RESTORE_MAX = 50
544
+ /** Highest `maxIndex` recoverVaultFromTxids accepts (one derivation each). */
545
+ export const VAULT_TXID_RESTORE_MAX_INDEX = 1000
546
+
547
+ const TXID_PATTERN = /^[0-9a-f]{64}$/
548
+ const P2PKH_PATTERN = /^76a914[0-9a-f]{40}88ac$/
549
+
550
+ /**
551
+ * Restore deposits from their transaction IDs. This is the exit for a marker
552
+ * address whose history is too large to read (dust can fill any window): no
553
+ * history is used, so nothing can hide the deposit. The txid comes from the
554
+ * marker address a person looks up in a block explorer
555
+ * (`problems[].markerAddress`).
556
+ *
557
+ * Each transaction is fetched, its P2PKH outputs are tested against the
558
+ * marker scripts of indexes 1..maxIndex, and a match goes through the same
559
+ * `recoverOneCandidate` path as the scan (descriptor decrypt, lock rebuild,
560
+ * floor, `outputStatus`). The result feeds `restoreScannedDeposits`, so the
561
+ * same admission rules apply and it never adds keys or revisions to an
562
+ * existing local meta. With no checked local vault it only reports
563
+ * (`needsKey`); use recoverVaultFromTxidsWithKey to restore. `scanned` is
564
+ * `maxIndex`.
565
+ */
566
+ export async function recoverVaultFromTxids(
567
+ w: VaultWallet,
568
+ adminOriginator: string,
569
+ lookup: VaultChainLookup,
570
+ chain: VaultSaltChain,
571
+ txids: readonly string[],
572
+ maxIndex: number = 200
573
+ ): Promise<VaultScanResult> {
574
+ return await restoreScannedDeposits(
575
+ w,
576
+ adminOriginator,
577
+ await collectTxidRecords(w, adminOriginator, lookup, chain, txids, maxIndex),
578
+ {}
372
579
  )
373
- const result = await restoreScannedDeposits(w, adminOriginator, scan, live)
374
- if (result.found > 0) await vaultStore.markKeyAdopted(key)
375
- return { ...result, key }
580
+ }
581
+
582
+ /** The same restore with one tapped key: `prove` picks and proves the key the card holds. When the given
583
+ * transactions hold no usable record, `prove` is not called (a typo in a txid must not cost a tap), `key` is
584
+ * absent and `problems` says why. */
585
+ export async function recoverVaultFromTxidsWithKey(
586
+ w: VaultWallet,
587
+ adminOriginator: string,
588
+ lookup: VaultChainLookup,
589
+ chain: VaultSaltChain,
590
+ txids: readonly string[],
591
+ prove: (records: readonly VaultInstructionsV7[]) => Promise<VaultInstructionKey>,
592
+ maxIndex: number = 200,
593
+ options?: VaultRestoreOptions
594
+ ): Promise<VaultScanResult & { key?: VaultInstructionKey }> {
595
+ const scan = await collectTxidRecords(w, adminOriginator, lookup, chain, txids, maxIndex)
596
+ if (scan.ready.length + scan.pending.length === 0) {
597
+ // Nothing a key could open: do not present the card. Report what was seen (restoreScannedDeposits with no
598
+ // tap and no meta change is report-only, and with nothing found it admits nothing).
599
+ return await restoreScannedDeposits(w, adminOriginator, scan, {})
600
+ }
601
+ return await finishTappedRestore(w, adminOriginator, scan, prove, options)
602
+ }
603
+
604
+ async function collectTxidRecords(
605
+ w: VaultWallet,
606
+ adminOriginator: string,
607
+ lookup: VaultChainLookup,
608
+ chain: VaultSaltChain,
609
+ txids: readonly string[],
610
+ maxIndex: number
611
+ ): Promise<VaultChainScan> {
612
+ if (!Number.isSafeInteger(maxIndex) || maxIndex < 1) {
613
+ throw new VaultError('template-invalid', 'Vault restore index limit must be a positive integer')
614
+ }
615
+ if (maxIndex > VAULT_TXID_RESTORE_MAX_INDEX) {
616
+ throw new VaultError(
617
+ 'template-invalid',
618
+ `Vault restore index limit is at most ${VAULT_TXID_RESTORE_MAX_INDEX}, got ${maxIndex}`
619
+ )
620
+ }
621
+ const distinct: string[] = []
622
+ for (const raw of txids) {
623
+ const txid = typeof raw === 'string' ? raw.toLowerCase() : ''
624
+ if (!TXID_PATTERN.test(txid)) {
625
+ throw new VaultError('template-invalid', 'A transaction ID must be 64 hexadecimal characters')
626
+ }
627
+ if (!distinct.includes(txid)) distinct.push(txid)
628
+ }
629
+ if (distinct.length > VAULT_TXID_RESTORE_MAX) {
630
+ throw new VaultError('template-invalid', `At most ${VAULT_TXID_RESTORE_MAX} transaction IDs per restore`)
631
+ }
632
+
633
+ // Derive every marker script once: script hex -> index.
634
+ const markerIndexByScript = new Map<string, number>()
635
+ for (let k = 1; k <= maxIndex; k++) {
636
+ markerIndexByScript.set((await deriveVaultMarkerScript(w, adminOriginator, chain, String(k))).toHex(), k)
637
+ }
638
+
639
+ // recoverOneCandidate fetches the bytes again; answer it from this cache.
640
+ const fetched = new Map<string, { beef: number[]; confirmed: boolean } | null>()
641
+ const cachedLookup: VaultChainLookup = {
642
+ ...lookup,
643
+ transactionForTxid: async txid => {
644
+ if (!fetched.has(txid)) fetched.set(txid, await lookup.transactionForTxid(txid))
645
+ return fetched.get(txid) ?? null
646
+ }
647
+ }
648
+
649
+ const ready: RecoverableCandidate[] = []
650
+ const pending: VaultInstructionsV7[] = []
651
+ const problems: VaultChainRecoveryProblem[] = []
652
+ let ignoredBelowMinimum = 0
653
+ let ignoredNonVault = 0
654
+ let maxUsedIndex = 0
655
+ const seenOutpoints = new Set<string>()
656
+
657
+ for (const txid of distinct) {
658
+ let entry: { beef: number[]; confirmed: boolean } | null
659
+ try {
660
+ entry = await cachedLookup.transactionForTxid(txid)
661
+ } catch {
662
+ problems.push({ index: 0, reason: 'chain lookup failed to fetch transaction bytes' })
663
+ continue
664
+ }
665
+ if (!entry) {
666
+ problems.push({ index: 0, reason: 'no transaction bytes available for this transaction' })
667
+ continue
668
+ }
669
+ let tx: Transaction
670
+ try {
671
+ try {
672
+ tx = Transaction.fromAtomicBEEF(entry.beef)
673
+ } catch {
674
+ tx = Transaction.fromBEEF(entry.beef)
675
+ }
676
+ } catch {
677
+ problems.push({ index: 0, reason: 'malformed transaction bytes' })
678
+ continue
679
+ }
680
+ const matches = new Map<number, string>()
681
+ for (const output of tx.outputs) {
682
+ const hex = output.lockingScript.toHex()
683
+ if (!P2PKH_PATTERN.test(hex)) continue
684
+ const k = markerIndexByScript.get(hex)
685
+ if (k !== undefined) matches.set(k, hex)
686
+ }
687
+ if (matches.size === 0) {
688
+ problems.push({ index: 0, reason: 'no vault marker found in this transaction' })
689
+ continue
690
+ }
691
+ for (const [k, hex] of [...matches].sort((a, b) => a[0] - b[0])) {
692
+ const outcome = await recoverOneCandidate(w, adminOriginator, cachedLookup, chain, k, hex, txid)
693
+ if (outcome.kind === 'ready') {
694
+ maxUsedIndex = Math.max(maxUsedIndex, k)
695
+ const outpoint = `${txid}.${outcome.vaultOutputIndex}`
696
+ if (seenOutpoints.has(outpoint)) continue
697
+ seenOutpoints.add(outpoint)
698
+ ready.push(outcome)
699
+ } else if (outcome.kind === 'pending') {
700
+ maxUsedIndex = Math.max(maxUsedIndex, k)
701
+ pending.push(outcome.ci)
702
+ } else if (outcome.kind === 'below-minimum') ignoredBelowMinimum++
703
+ else if (outcome.kind === 'non-vault') {
704
+ // The person named this transaction, so unlike a scan row it is reported.
705
+ ignoredNonVault++
706
+ problems.push({
707
+ index: k,
708
+ reason: 'this transaction pays a vault marker address but holds no vault record for this wallet'
709
+ })
710
+ } else if (outcome.kind === 'problem') problems.push({ index: k, reason: outcome.reason })
711
+ // 'spent': already withdrawn or re-locked, normal.
712
+ }
713
+ }
714
+
715
+ return {
716
+ ready,
717
+ pending,
718
+ problems,
719
+ unknownIndexes: [],
720
+ ignoredBelowMinimum,
721
+ ignoredNonVault,
722
+ maxUsedIndex,
723
+ scanned: maxIndex
724
+ }
376
725
  }
377
726
 
378
727
  interface VaultChainScan {
379
728
  ready: RecoverableCandidate[]
380
729
  pending: VaultInstructionsV7[]
381
730
  problems: VaultChainRecoveryProblem[]
731
+ unknownIndexes: number[]
732
+ ignoredBelowMinimum: number
733
+ ignoredNonVault: number
734
+ maxUsedIndex: number
382
735
  scanned: number
383
736
  }
384
737
 
738
+ /**
739
+ * A read-only scan. It never internalizes and never writes local metadata: it
740
+ * only reports what the chain holds for this wallet. The reset gate
741
+ * (setupGate.ts) uses it. `ready` is authenticated, unspent, confirmed and at
742
+ * or above VAULT_SCAN_MIN_SATS; `pending` is valid but not yet confirmed.
743
+ * Throws `chain-scan-failed` when the lookup fails persistently.
744
+ */
745
+ export async function scanVaultRecords(
746
+ w: VaultWallet,
747
+ adminOriginator: string,
748
+ lookup: VaultChainLookup,
749
+ chain: VaultSaltChain,
750
+ gap: number = VAULT_RECOVERY_GAP_DEFAULT
751
+ ): Promise<{
752
+ ready: RecoverableCandidate[]
753
+ pending: VaultInstructionsV7[]
754
+ problems: VaultChainRecoveryProblem[]
755
+ unknownIndexes: number[]
756
+ scanned: number
757
+ }> {
758
+ const { ready, pending, problems, unknownIndexes, scanned } = await scanVaultChain(
759
+ w,
760
+ adminOriginator,
761
+ lookup,
762
+ chain,
763
+ gap
764
+ )
765
+ return { ready, pending, problems, unknownIndexes, scanned }
766
+ }
767
+
768
+ /** The lineage groups of some scanned records (read-only, for display). */
769
+ export function vaultGroupsOf(
770
+ ready: readonly RecoverableCandidate[],
771
+ pending: readonly VaultInstructionsV7[]
772
+ ): VaultRecoveryGroup[] {
773
+ return formGroups(ready, pending).map(g => g.group)
774
+ }
775
+
385
776
  /** The scan half of recovery: find and authenticate every candidate without
386
777
  * inserting any. */
387
778
  async function scanVaultChain(
@@ -397,6 +788,10 @@ async function scanVaultChain(
397
788
  const ready: RecoverableCandidate[] = []
398
789
  const pending: VaultInstructionsV7[] = []
399
790
  const problems: VaultChainRecoveryProblem[] = []
791
+ const unknownIndexes: number[] = []
792
+ let ignoredBelowMinimum = 0
793
+ let ignoredNonVault = 0
794
+ let maxUsedIndex = 0
400
795
  let consecutiveMisses = 0
401
796
  // Bounds the loop independently of consecutiveMisses — see
402
797
  // VAULT_RECOVERY_MAX_CONSECUTIVE_PROBLEMS's doc comment. Reset on any
@@ -405,6 +800,14 @@ async function scanVaultChain(
405
800
  let consecutiveProblems = 0
406
801
  let scanned = 0
407
802
  let k = 1
803
+ const tooManyProblems = (): VaultError =>
804
+ // A plain Error here left VaultScreen (vaultErrorCopy(undefined)) showing
805
+ // its generic fallback copy instead of a message actually describing what
806
+ // happened — 'chain-scan-failed' is a code the UI already translates.
807
+ new VaultError(
808
+ 'chain-scan-failed',
809
+ `Vault recovery scan could not complete: ${consecutiveProblems} consecutive derivation/lookup failures, most recently at index ${k}`
810
+ )
408
811
  while (consecutiveMisses < gap) {
409
812
  scanned = k
410
813
  const saltKeyId = String(k)
@@ -417,245 +820,293 @@ async function scanVaultChain(
417
820
  // — but still bounded, so a persistent failure fails loudly instead of
418
821
  // looping forever (INT-01/INT-06/XQ-012 availability review).
419
822
  problems.push({ index: k, reason: 'could not derive the marker key for this index' })
420
- if (++consecutiveProblems >= VAULT_RECOVERY_MAX_CONSECUTIVE_PROBLEMS) {
421
- // A plain Error here left VaultScreen (vaultErrorCopy(undefined))
422
- // showing its generic fallback copy instead of a message actually
423
- // describing what happened — 'chain-scan-failed' is a code the UI
424
- // already translates.
425
- throw new VaultError(
426
- 'chain-scan-failed',
427
- `Vault recovery scan could not complete: ${consecutiveProblems} consecutive derivation/lookup failures, most recently at index ${k}`
428
- )
429
- }
823
+ if (++consecutiveProblems >= VAULT_RECOVERY_MAX_CONSECUTIVE_PROBLEMS) throw tooManyProblems()
430
824
  k++
431
825
  continue
432
826
  }
433
- let txids: string[]
827
+ const markerAddress = markerAddressFor(lookup, markerScriptHex, chain)
828
+ let history: MarkerHistory
434
829
  try {
435
- txids = await lookup.transactionsForLockingScript(markerScriptHex)
830
+ history = await lookupMarker(lookup, markerScriptHex)
436
831
  } catch {
437
- problems.push({ index: k, reason: 'chain lookup failed for this marker' })
438
- if (++consecutiveProblems >= VAULT_RECOVERY_MAX_CONSECUTIVE_PROBLEMS) {
439
- throw new VaultError(
440
- 'chain-scan-failed',
441
- `Vault recovery scan could not complete: ${consecutiveProblems} consecutive derivation/lookup failures, most recently at index ${k}`
442
- )
443
- }
444
- k++
445
- continue
832
+ history = { status: 'unknown', reason: 'request-failed', txids: [] }
446
833
  }
447
- consecutiveProblems = 0
448
- if (txids.length === 0) {
834
+ if (history.status === 'none') {
835
+ consecutiveProblems = 0
449
836
  consecutiveMisses++
450
837
  k++
451
838
  continue
452
839
  }
840
+ const rows = [...new Set(history.txids.map(txid => txid.toLowerCase()))]
841
+ if (history.status === 'unknown') {
842
+ // Never a "no funds" answer: reported, kept out of the miss count, and
843
+ // the rows that were read are still examined below.
844
+ unknownIndexes.push(k)
845
+ problems.push({ index: k, reason: `lookup incomplete: ${history.reason}`, markerAddress })
846
+ if (rows.length === 0) {
847
+ if (++consecutiveProblems >= VAULT_RECOVERY_MAX_CONSECUTIVE_PROBLEMS) throw tooManyProblems()
848
+ k++
849
+ continue
850
+ }
851
+ }
852
+ consecutiveProblems = 0
453
853
  // Marker history exists at this index — never a "no marker" miss from
454
854
  // here on, no matter how every candidate below turns out.
455
855
  consecutiveMisses = 0
456
- let inspected = 0
457
- for (const txid of txids) {
458
- if (inspected >= VAULT_RECOVERY_MAX_CANDIDATES_PER_INDEX) {
459
- problems.push({
460
- index: k,
461
- reason: `stopped after ${VAULT_RECOVERY_MAX_CANDIDATES_PER_INDEX} candidates at this index`
462
- })
463
- break
464
- }
465
- inspected++
856
+ maxUsedIndex = Math.max(maxUsedIndex, k)
857
+ // Every row is examined. The window is already bounded by the lookup (at
858
+ // most a few thousand rows), and a valid row never hides another.
859
+ const seenOutpoints = new Set<string>()
860
+ for (const txid of rows) {
466
861
  const outcome = await recoverOneCandidate(w, adminOriginator, lookup, chain, k, markerScriptHex, txid)
467
862
  if (outcome.kind === 'ready') {
863
+ const outpoint = `${txid}.${outcome.vaultOutputIndex}`
864
+ if (seenOutpoints.has(outpoint)) continue
865
+ seenOutpoints.add(outpoint)
468
866
  ready.push(outcome)
469
- break
470
- } else if (outcome.kind === 'pending') {
471
- pending.push(outcome.ci)
472
- break
473
- } else if (outcome.kind === 'problem') problems.push({ index: k, reason: outcome.reason })
867
+ } else if (outcome.kind === 'pending') pending.push(outcome.ci)
868
+ else if (outcome.kind === 'below-minimum') ignoredBelowMinimum++
869
+ else if (outcome.kind === 'non-vault') ignoredNonVault++
870
+ else if (outcome.kind === 'problem') problems.push({ index: k, reason: outcome.reason, markerAddress })
474
871
  // 'spent': a superseded output (already withdrawn or re-locked) —
475
872
  // entirely normal, silently skipped; keep inspecting other candidates
476
873
  // at this index.
477
874
  }
478
875
  k++
479
876
  }
480
- return { ready, pending, problems, scanned }
877
+ return { ready, pending, problems, unknownIndexes, ignoredBelowMinimum, ignoredNonVault, maxUsedIndex, scanned }
481
878
  }
482
879
 
483
- /** The insert half: internalize the scanned deposits `live` can open, count
484
- * the rest as unreachable, then rebuild local vault metadata. */
880
+ function markerAddressFor(
881
+ lookup: VaultChainLookup,
882
+ markerScriptHex: string,
883
+ chain: VaultSaltChain
884
+ ): string | undefined {
885
+ try {
886
+ return (
887
+ lookup.markerAddress?.(markerScriptHex) ??
888
+ p2pkhAddressFromScript(markerScriptHex, chain === 'main' ? 'mainnet' : 'testnet')
889
+ )
890
+ } catch {
891
+ return undefined
892
+ }
893
+ }
894
+
895
+ interface RestoreSelection {
896
+ /** Tapped key: keep only outputs whose own key list holds it. */
897
+ pubkey?: string
898
+ groupId?: string
899
+ vaultId?: string
900
+ /** A named group must be one of the groups found (tapped restore). */
901
+ requireGroup?: boolean
902
+ /** Output flag: set when an unproven local meta was forgotten and rebuilt
903
+ * from the chosen group, so the caller adopts the tapped key even if every
904
+ * output was already in the basket. */
905
+ metaReplaced?: boolean
906
+ }
907
+
908
+ /**
909
+ * With an authenticated local meta: which candidates a scan may internalize.
910
+ * Same lineage as meta, and either older than meta or adding no unknown key.
911
+ * Two further guards keep the later metaFromVerifiedOutputs from ever seeing a
912
+ * disagreement: at meta's own revision the key list must equal meta's, and above
913
+ * it a revision with more than one key list admits none of them.
914
+ */
915
+ function admitAgainstMeta(meta: VaultMeta, ready: readonly RecoverableCandidate[]): Set<RecoverableCandidate> {
916
+ const admitted = ready.filter(c => {
917
+ const { ci } = c
918
+ if (ci.vaultId !== meta.vaultId || ci.createdAt !== meta.createdAt) return false
919
+ if (ci.revision < meta.revision) return true
920
+ if (introducesUnknownKey(meta, ci.keys)) return false
921
+ if (ci.revision === meta.revision) return sameKeyList(meta.keys, ci.keys)
922
+ return true
923
+ })
924
+ const above = admitted.filter(c => c.ci.revision > meta.revision)
925
+ if (above.length > 0) {
926
+ const top = Math.max(...above.map(c => c.ci.revision))
927
+ const atTop = above.filter(c => c.ci.revision === top)
928
+ if (atTop.some(c => !sameKeyList(atTop[0].ci.keys, c.ci.keys))) {
929
+ return new Set(admitted.filter(c => c.ci.revision !== top))
930
+ }
931
+ }
932
+ return new Set(admitted)
933
+ }
934
+
935
+ /** The insert half: decide which groups are admitted (see this file's
936
+ * ADMISSION note), internalize their candidates that are not yet in the basket,
937
+ * then rebuild local vault metadata. */
485
938
  async function restoreScannedDeposits(
486
939
  w: VaultWallet,
487
940
  adminOriginator: string,
488
941
  scan: VaultChainScan,
489
- live: ReadonlySet<string>
490
- ): Promise<VaultChainRecoveryResult> {
491
- const { ready, pending, scanned } = scan
942
+ selection: RestoreSelection
943
+ ): Promise<VaultScanResult> {
944
+ const { scanned, unknownIndexes, ignoredBelowMinimum, ignoredNonVault } = scan
492
945
  const problems = [...scan.problems]
493
946
  let found = 0
494
947
  let pendingConfirmation = 0
495
948
  let unreachable = 0
496
- for (const candidate of ready) {
497
- if (!opensWithAny(candidate.ci, live)) {
498
- unreachable++
499
- continue
949
+ let maxUsedIndex = scan.maxUsedIndex
950
+ const scopeToken = vaultStore.captureScopeToken()
951
+
952
+ // Tapped key: an output counts only if its OWN key list holds the key.
953
+ const holds = (keys: readonly VaultInstructionKey[]): boolean =>
954
+ !selection.pubkey || keys.some(key => key.pubkey === selection.pubkey)
955
+ const ready = scan.ready.filter(c => holds(c.ci.keys))
956
+ const pending = scan.pending.filter(ci => holds(ci.keys))
957
+ unreachable += scan.ready.length - ready.length + (scan.pending.length - pending.length)
958
+ for (const candidate of scan.ready) maxUsedIndex = Math.max(maxUsedIndex, candidate.index)
959
+
960
+ const groups = formGroups(ready, pending)
961
+ let meta = await authenticatedLocalMeta(w, adminOriginator)
962
+ // Tap-only restore (planted-lockout). Without a tapped key a scan may only report, unless this phone already
963
+ // holds a vault with a CHECKED key (then it merges new outputs by outpoint, as before: outputs only, never
964
+ // keys). A chain record alone never creates or extends trust (R2).
965
+ const mayAdd =
966
+ selection.pubkey !== undefined || (meta !== null && vaultStore.provenKeyRecords(meta, scopeToken).length > 0)
967
+ if (!mayAdd) {
968
+ const seen = groups.map(g => g.group)
969
+ if (maxUsedIndex > 0) noteSaltFloor(scopeToken.storageKey, maxUsedIndex)
970
+ return {
971
+ found: 0,
972
+ pendingConfirmation: pending.length,
973
+ unreachable: 0,
974
+ ignoredBelowMinimum,
975
+ ignoredNonVault,
976
+ problems,
977
+ problemCount: problems.length,
978
+ unknownIndexes,
979
+ maxUsedIndex,
980
+ scanned,
981
+ status: problems.length > 0 || unknownIndexes.length > 0 ? 'incomplete' : 'complete',
982
+ groups: seen,
983
+ conflict: seen.length > 1,
984
+ setApart: seen,
985
+ needsKey: seen.length > 0
500
986
  }
501
- const failure = await internalizeCandidate(w, adminOriginator, candidate)
502
- if (failure) problems.push({ index: candidate.index, reason: failure })
503
- else found++
504
987
  }
505
- for (const ci of pending) {
506
- if (opensWithAny(ci, live)) pendingConfirmation++
507
- else unreachable++
988
+ let replaceMeta = false
989
+ // I-1: a tapped restore over an authentic local meta that carries no proof
990
+ // (recovery.required, nothing adopted) and does not hold the tapped key has
991
+ // no authority: a planted lineage record can have produced it. Forget the
992
+ // meta and its tag (outputs stay) and rebuild from the chosen group. This
993
+ // cannot weaken R2, because a meta with no proof gates nothing. The meta is
994
+ // forgotten only directly before the rebuild from the chosen group (below), so a
995
+ // restore that throws or chooses nothing changes nothing.
996
+ if (meta && selection.pubkey && meta.recovery?.required && (meta.recovery.adopted ?? []).length === 0) {
997
+ const tapped = selection.pubkey
998
+ const holdsTapped =
999
+ meta.keys.some(k => k.pubkey === tapped) ||
1000
+ meta.staged?.pubkey === tapped ||
1001
+ meta.pendingRemoval?.key.pubkey === tapped
1002
+ if (!holdsTapped) {
1003
+ replaceMeta = true
1004
+ meta = null
1005
+ }
508
1006
  }
509
- await recoverVaultMetaFromOutputs(w, adminOriginator)
510
- return { found, pendingConfirmation, unreachable, problems, scanned }
511
- }
512
-
513
- // ───────────────────────── default WhatsOnChain implementation ─────────────
514
-
515
- /**
516
- * Production VaultChainLookup over WhatsOnChain, following the exact request
517
- * patterns already used by core/pay/rails/address.ts (getUtxosForAddress,
518
- * the `/tx/{txid}/beef` fetch, parseWocBeefBody's response-shape checks).
519
- *
520
- * Response shapes checked against live mainnet WhatsOnChain on 2026-09-27:
521
- * `/address/{address}/history` answers `[{tx_hash, height}]`, or 404 "Not
522
- * Found" for an address with no history; `/tx/{txid}/out/{index}` answers
523
- * 502 for every output, so spent status comes from `POST /utxos/spent`,
524
- * which returns one row per outpoint (see outputStatus).
525
- */
526
- export function wocChainLookup(chain: AppChain): VaultChainLookup {
527
- const woc: WocConfig | undefined = wocConfigFor(chain)
528
- // Vault is mainnet-only, so this only fires on a misrouted call. Refuse it
529
- // rather than answer "no marker": an empty answer is a genuine miss here.
530
- if (!woc) throw new Error(`Vault chain recovery needs WhatsOnChain, which ${chain} does not have`)
531
- const base = `${woc.apiBase}/v1/bsv/${woc.segment}`
1007
+ const admittedReady = new Set<RecoverableCandidate>()
1008
+ const admittedPending: VaultInstructionsV7[] = []
1009
+ let conflict = false
1010
+ let chosenGroup: VaultRecoveryGroup | undefined
1011
+ let setApart: VaultRecoveryGroup[]
532
1012
 
533
- return {
534
- async transactionsForLockingScript(lockingScriptHex: string): Promise<string[]> {
535
- // The marker is always a P2PKH output; derive its address from the
536
- // script's hash160 rather than adding a second WoC endpoint shape.
537
- //
538
- // The VaultChainLookup contract (see this file's interface doc) treats
539
- // an EMPTY result as a genuine "no marker at this index" miss — so a
540
- // failure to even ask the question (an unrecognizable script), a
541
- // non-2xx response (rate limiting, a transient 5xx, a maintenance
542
- // window) or a thrown exception (DNS failure, timeout, offline) must
543
- // never collapse into that same empty array: recoverVaultFromChain's
544
- // OWN catch around this call (never a miss, and now bounded — see
545
- // VAULT_RECOVERY_MAX_CONSECUTIVE_PROBLEMS) is what has to handle these,
546
- // not the miss-counting branch.
547
- const address = p2pkhAddressFromScript(lockingScriptHex, woc.network)
548
- if (!address) {
549
- throw new Error('wocChainLookup: marker script is not a recognizable P2PKH script')
1013
+ if (meta) {
1014
+ const admitted = admitAgainstMeta(meta, ready)
1015
+ for (const c of admitted) admittedReady.add(c)
1016
+ for (const ci of pending) {
1017
+ if (ci.vaultId === meta.vaultId && ci.createdAt === meta.createdAt && !introducesUnknownKey(meta, ci.keys)) {
1018
+ admittedPending.push(ci)
550
1019
  }
551
- const response = await fetch(`${base}/address/${address}/history`)
552
- // WhatsOnChain's answer for an address that has never been used: a
553
- // genuine miss, not a failure.
554
- if (response.status === 404) return []
555
- if (!response.ok) {
556
- throw new Error(`wocChainLookup: address history request failed (HTTP ${response.status})`)
557
- }
558
- const body = await response.json()
559
- const rows = Array.isArray(body) ? body : Array.isArray(body?.result) ? body.result : []
560
- const txids = rows.map((r: any) => r?.tx_hash).filter((h: unknown) => typeof h === 'string')
561
- return [...new Set<string>(txids)]
562
- },
563
-
564
- async transactionForTxid(txid: string): Promise<{ beef: number[]; confirmed: boolean } | null> {
565
- try {
566
- const [beefResp, txResp] = await Promise.all([
567
- fetch(`${base}/tx/${txid}/beef`),
568
- fetch(`${base}/tx/hash/${txid}`)
569
- ])
570
- const beef = parseWocBeefBodyText(beefResp.ok, await beefResp.text())
571
- if (!beef) return null
572
- let confirmed = false
573
- if (txResp.ok) {
574
- const info = await txResp.json()
575
- confirmed = Number.isInteger(info?.confirmations) && info.confirmations > 0
576
- }
577
- return { beef, confirmed }
578
- } catch {
579
- return null
1020
+ }
1021
+ // Not admitted and sharing no key with this device's list (an earlier
1022
+ // setup's deposit): counted as unreachable, as well as set apart below.
1023
+ const live = liveVaultPubkeys(meta)
1024
+ unreachable += ready.filter(c => !admitted.has(c) && !opensWithAny(c.ci, live)).length
1025
+ unreachable += pending.filter(ci => !admittedPending.includes(ci) && !opensWithAny(ci, live)).length
1026
+ // A group is set apart when none of its outputs at its own revision were admitted.
1027
+ setApart = groups
1028
+ .filter(g => !g.ready.some(c => admitted.has(c) && c.ci.revision === g.group.revision))
1029
+ .filter(g => !g.pending.some(ci => admittedPending.includes(ci) && ci.revision === g.group.revision))
1030
+ .map(g => {
1031
+ // A lower-revision output shared with an admitted group is not set apart.
1032
+ const apart = g.ready.filter(c => !admitted.has(c))
1033
+ return { ...g.group, outputs: apart.length, satoshis: apart.reduce((sum, c) => sum + c.satoshis, 0) }
1034
+ })
1035
+ } else {
1036
+ const wanted = selection.groupId ?? selection.vaultId
1037
+ let chosen: InternalGroup[]
1038
+ if (wanted) {
1039
+ chosen = groups.filter(g => g.group.id === wanted)
1040
+ if (chosen.length === 0 && selection.vaultId && !selection.groupId) {
1041
+ const byLineage = groups.filter(g => `${g.group.vaultId}` === wanted)
1042
+ if (byLineage.length === 1) chosen = byLineage
580
1043
  }
581
- },
582
-
583
- async outputStatus(outpoint: { txid: string; vout: number }): Promise<'unspent' | 'spent' | 'unknown'> {
584
- // Fail-safe default is 'unknown' (never trusted as unspent — see this
585
- // file's VaultChainLookup interface doc). The row must be about this
586
- // exact outpoint. Unspent is a clean row with no `spentIn`; spent is a
587
- // `spentIn` naming another transaction; an unknown output comes back as
588
- // `spentIn.status: "Unknown UTXO"` echoing its own txid, which is
589
- // neither.
590
- try {
591
- const response = await fetch(`${base}/utxos/spent`, {
592
- method: 'POST',
593
- headers: { 'Content-Type': 'application/json' },
594
- body: JSON.stringify({ utxos: [{ txid: outpoint.txid, vout: outpoint.vout }] })
595
- })
596
- if (!response.ok) return 'unknown'
597
- const body = await response.json()
598
- const row = Array.isArray(body) && body.length === 1 ? body[0] : undefined
599
- if (row === null || typeof row !== 'object') return 'unknown'
600
- if (row.utxo?.txid !== outpoint.txid || row.utxo?.vout !== outpoint.vout) return 'unknown'
601
- if (row.error !== '') return 'unknown'
602
- const spentIn = row.spentIn
603
- if (spentIn === undefined) return 'unspent'
604
- if (
605
- spentIn !== null &&
606
- typeof spentIn === 'object' &&
607
- typeof spentIn.txid === 'string' &&
608
- /^[0-9a-fA-F]{64}$/.test(spentIn.txid) &&
609
- spentIn.txid.toLowerCase() !== outpoint.txid.toLowerCase() &&
610
- spentIn.status !== 'Unknown UTXO'
611
- ) {
612
- return 'spent'
613
- }
614
- return 'unknown'
615
- } catch {
616
- return 'unknown'
1044
+ if (chosen.length === 0 && selection.requireGroup) {
1045
+ throw new VaultError('key-opens-nothing', 'No vault group found for this key matches the requested group')
617
1046
  }
1047
+ } else if (groups.length === 1) {
1048
+ chosen = groups
1049
+ } else {
1050
+ chosen = []
1051
+ conflict = groups.length > 1
1052
+ }
1053
+ if (chosen.length === 1) chosenGroup = chosen[0].group
1054
+ for (const g of chosen) {
1055
+ for (const c of g.ready) admittedReady.add(c)
1056
+ for (const ci of g.pending) admittedPending.push(ci)
618
1057
  }
1058
+ setApart = groups.filter(g => !chosen.includes(g)).map(g => g.group)
619
1059
  }
620
- }
621
1060
 
622
- /** Local copy of address.ts's parseWocBeefBody signature over (ok, text)
623
- * rather than a Response, so this module does not need to import it just to
624
- * reshape the call. */
625
- function parseWocBeefBodyText(ok: boolean, text: string): number[] | undefined {
626
- if (!ok) return undefined
627
- const hex = text.trim()
628
- if (hex.length === 0 || hex.length % 2 !== 0 || !/^[0-9a-fA-F]+$/.test(hex)) return undefined
629
- try {
630
- return Utils.toArray(hex, 'hex') as number[]
631
- } catch {
632
- return undefined
1061
+ // Merge by outpoint: what the basket already holds is neither re-added nor
1062
+ // counted, so a second scan is a no-op for known outputs.
1063
+ const known = await listVaultBasketOutpoints(w, adminOriginator, scopeToken)
1064
+ for (const candidate of ready) {
1065
+ if (!admittedReady.has(candidate)) continue
1066
+ if (known.has(`${candidate.txid.toLowerCase()}.${candidate.vaultOutputIndex}`)) continue
1067
+ known.add(`${candidate.txid.toLowerCase()}.${candidate.vaultOutputIndex}`)
1068
+ const failure = await internalizeCandidate(w, adminOriginator, candidate)
1069
+ if (failure) problems.push({ index: candidate.index, reason: failure })
1070
+ else found++
633
1071
  }
634
- }
635
-
636
- /** hash160 out of a standard P2PKH script, re-encoded as a base58check
637
- * address for the WoC address-history endpoint, via @bsv/sdk's own public
638
- * `Utils.toBase58Check` (already imported for toHex/toArray above) — the
639
- * same primitive `PublicKey.prototype.toAddress()` uses internally elsewhere
640
- * in this codebase (core/pay/rails/address.ts). Returns undefined for
641
- * anything else (defensive — deriveVaultMarkerScript always builds P2PKH). */
642
- function p2pkhAddressFromScript(lockingScriptHex: string, network: 'mainnet' | 'testnet'): string | undefined {
643
- let bytes: number[]
644
- try {
645
- bytes = Utils.toArray(lockingScriptHex, 'hex') as number[]
646
- } catch {
647
- return undefined
1072
+ pendingConfirmation = admittedPending.length
1073
+ // Rebuild meta only from the records of the group just chosen (or, with an
1074
+ // authenticated local meta, from records that agree with it). Nothing chosen
1075
+ // and no local meta: nothing to rebuild from, and no guessing.
1076
+ if (meta) await recoverVaultMetaFromOutputs(w, adminOriginator)
1077
+ else if (chosenGroup) {
1078
+ // The unproven meta is dropped only now, directly before its rebuild from
1079
+ // the chosen group; every step that can throw has already run.
1080
+ if (replaceMeta) {
1081
+ await vaultStore.forgetSetup(scopeToken)
1082
+ selection.metaReplaced = true
1083
+ }
1084
+ await recoverVaultMetaFromOutputs(w, adminOriginator, {
1085
+ vaultId: chosenGroup.vaultId,
1086
+ createdAt: chosenGroup.createdAt,
1087
+ revision: chosenGroup.revision,
1088
+ keys: chosenGroup.keys
1089
+ })
648
1090
  }
649
- if (
650
- bytes.length !== 25 ||
651
- bytes[0] !== 0x76 ||
652
- bytes[1] !== 0xa9 ||
653
- bytes[2] !== 0x14 ||
654
- bytes[23] !== 0x88 ||
655
- bytes[24] !== 0xac
656
- ) {
657
- return undefined
1091
+ // The next salt allocation starts above every index this scan saw in use.
1092
+ if (maxUsedIndex > 0) noteSaltFloor(scopeToken.storageKey, maxUsedIndex)
1093
+ return {
1094
+ found,
1095
+ pendingConfirmation,
1096
+ unreachable,
1097
+ ignoredBelowMinimum,
1098
+ ignoredNonVault,
1099
+ problems,
1100
+ problemCount: problems.length,
1101
+ unknownIndexes,
1102
+ maxUsedIndex,
1103
+ scanned,
1104
+ status: problems.length > 0 || unknownIndexes.length > 0 ? 'incomplete' : 'complete',
1105
+ groups: groups.map(g => g.group),
1106
+ conflict,
1107
+ setApart,
1108
+ needsKey: false
658
1109
  }
659
- const hash160 = bytes.slice(3, 23)
660
- return Utils.toBase58Check(hash160, [network === 'mainnet' ? 0x00 : 0x6f])
661
1110
  }
1111
+
1112
+ export { wocChainLookup } from './wocLookup'