@bsv/expo-wallet-toolbox 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/CHANGELOG.md +1745 -0
  2. package/README.md +47 -1
  3. package/core/amountFormatHelpers.ts +20 -2
  4. package/core/backup/RemoteSyncReader.ts +131 -19
  5. package/core/backup/appData.ts +157 -0
  6. package/core/backup/client.ts +15 -1
  7. package/core/backup/codec.ts +147 -9
  8. package/core/backup/constants.ts +30 -1
  9. package/core/backup/cursor.ts +31 -2
  10. package/core/backup/push.ts +70 -4
  11. package/core/backup/restore.ts +104 -16
  12. package/core/backup/restoreOnImport.ts +94 -30
  13. package/core/backup/status.ts +13 -8
  14. package/core/constants.ts +14 -1
  15. package/core/context/ExchangeRateContext.tsx +34 -27
  16. package/core/context/LocalStorageProvider.tsx +43 -40
  17. package/core/context/UserContext.tsx +18 -7
  18. package/core/context/VaultContext.tsx +49 -2
  19. package/core/context/WalletConnectionContext.tsx +203 -11
  20. package/core/context/WalletContext.tsx +631 -162
  21. package/core/headers/OfflineFirstChaintracks.ts +48 -4
  22. package/core/headers/headerStore.ts +26 -4
  23. package/core/headers/syncHeaders.ts +12 -1
  24. package/core/i18n/translations.tsx +953 -25
  25. package/core/identity/handleRegistry/client.ts +31 -2
  26. package/core/identity/handleRegistry/keyPinStore.ts +70 -0
  27. package/core/identity/handleRegistry/resolver.ts +71 -3
  28. package/core/index.ts +33 -3
  29. package/core/localpay/build.ts +225 -24
  30. package/core/localpay/pending.ts +110 -7
  31. package/core/localpay/pendingAbortAuthority.ts +95 -0
  32. package/core/localpay/pendingAborts.ts +264 -28
  33. package/core/localpay/session.ts +42 -17
  34. package/core/localpay/settlementAck.ts +10 -1
  35. package/core/localpay/transport/socket.ts +52 -3
  36. package/core/localpay/verify.ts +100 -10
  37. package/core/mandala/abortGuard.ts +96 -20
  38. package/core/mandala/createRuntime.ts +206 -33
  39. package/core/mandala/drain.ts +89 -11
  40. package/core/mandala/inboxPrehold.ts +186 -0
  41. package/core/mandala/permissionModule.ts +202 -20
  42. package/core/mandala/settlementStore.ts +24 -2
  43. package/core/mandala/types.ts +40 -5
  44. package/core/monitor/TaskBackupPush.ts +14 -0
  45. package/core/monitor/TaskDrainOutbox.ts +14 -0
  46. package/core/monitor/TaskSendOffline.ts +14 -0
  47. package/core/net/publicDestination.ts +91 -0
  48. package/core/net/validateArcUrl.ts +22 -0
  49. package/core/offline/cancelParked.ts +134 -13
  50. package/core/offline/payerHold.ts +100 -24
  51. package/core/offline/plan.ts +36 -7
  52. package/core/pay/beefRepair.ts +6 -2
  53. package/core/pay/damagedInbox.ts +24 -0
  54. package/core/pay/rails/address.ts +107 -12
  55. package/core/pay/rails/handle.ts +117 -22
  56. package/core/pay/rails/index.ts +45 -7
  57. package/core/pay/rails/nativeIntent.ts +61 -0
  58. package/core/pay/receiveHistory.ts +93 -0
  59. package/core/pay/recordProof.ts +19 -1
  60. package/core/pay/refreshProofGuard.ts +42 -1
  61. package/core/pay/watchlist.ts +5 -2
  62. package/core/peerpay/control.ts +17 -18
  63. package/core/peerpay/handleResendRequests.ts +58 -4
  64. package/core/peerpay/outbox.ts +3 -1
  65. package/core/recovery/backupMaterial.ts +61 -0
  66. package/core/recovery/createWallet.ts +95 -0
  67. package/core/recovery/recoverWallet.ts +120 -0
  68. package/core/recovery/restoreWallet.ts +170 -0
  69. package/core/recovery/secret.ts +92 -0
  70. package/core/recovery/shareCollector.ts +71 -0
  71. package/core/recovery/shareParsing.ts +87 -0
  72. package/core/recovery/shares.ts +116 -0
  73. package/core/recovery/useRecoveryDeps.ts +70 -0
  74. package/core/services/arcTokenStorage.ts +52 -0
  75. package/core/services/arcadeBroadcastProvider.ts +232 -48
  76. package/core/services/autoApprovePolicy.ts +105 -0
  77. package/core/services/callbackToken.ts +19 -0
  78. package/core/services/capWalletArgs.ts +14 -2
  79. package/core/services/connectionAuthority.ts +98 -0
  80. package/core/services/exchangeRate.ts +35 -12
  81. package/core/services/externalOrigin.ts +11 -0
  82. package/core/services/secrets/kek.ts +126 -29
  83. package/core/services/secrets/migration.ts +16 -4
  84. package/core/services/secrets/store.ts +42 -14
  85. package/core/services/vault/VaultKeyService.ts +228 -45
  86. package/core/services/vault/chainRecovery.ts +483 -0
  87. package/core/services/vault/driver.ts +9 -1
  88. package/core/services/vault/enrolledSerialRegistry.ts +150 -0
  89. package/core/services/vault/guard.ts +218 -32
  90. package/core/services/vault/hardwareLease.ts +19 -0
  91. package/core/services/vault/metaAuthority.ts +210 -0
  92. package/core/services/vault/pivReset.ts +64 -23
  93. package/core/services/vault/r1comb.ts +139 -3
  94. package/core/services/vault/session.ts +25 -4
  95. package/core/services/vault/transfers.ts +866 -170
  96. package/core/services/vault/types.ts +19 -4
  97. package/core/services/vault/vaultStore.ts +256 -29
  98. package/core/services/walletArgLimits.ts +45 -2
  99. package/core/services/walletConnectionValidation.ts +76 -6
  100. package/core/services/walletServiceConfig.ts +10 -8
  101. package/core/storage/StorageExpoSQLite.ts +47 -13
  102. package/core/storage/methods/findSql.ts +21 -2
  103. package/core/storage/methods/offlineActions.ts +10 -1
  104. package/core/storage/methods/processOfflineActions.ts +116 -23
  105. package/core/storage/schema/createTables.ts +126 -2
  106. package/core/stores/ConnectionStore.ts +34 -0
  107. package/core/toolboxConfig.ts +45 -11
  108. package/core/walletDbRegistry.ts +63 -0
  109. package/core/walletMonitor.ts +17 -1
  110. package/core/walletRepair/releaseStuckReservations.ts +72 -0
  111. package/core/walletRepair/shouldMarkUnspendable.ts +20 -0
  112. package/core/walletRepair/spenderConsumesOutpoint.ts +29 -0
  113. package/package.json +2 -2
  114. package/ui/backupShares.ts +26 -169
  115. package/ui/components/pay/AddressReceive.tsx +13 -6
  116. package/ui/components/pay/AssetPicker.tsx +30 -9
  117. package/ui/components/pay/MessageBoxConfig.tsx +16 -0
  118. package/ui/components/pay/NearbyFlow.tsx +480 -243
  119. package/ui/components/pay/PaymentSuccessOverlay.tsx +39 -4
  120. package/ui/components/pay/UniversalSend.tsx +167 -73
  121. package/ui/components/ui/AlertCard.tsx +38 -5
  122. package/ui/components/ui/PermissionSheet.tsx +197 -66
  123. package/ui/components/vault/EnrollWizard.tsx +61 -13
  124. package/ui/components/vault/vaultErrorCopy.ts +3 -1
  125. package/ui/components/wallet/ActivityRow.tsx +5 -3
  126. package/ui/components/wallet/AmountInput.tsx +8 -2
  127. package/ui/components/wallet/AssetSwitcherDropdown.tsx +22 -2
  128. package/ui/components/wallet/Balance.tsx +42 -23
  129. package/ui/components/wallet/BiometricAdvisoryModal.tsx +16 -3
  130. package/ui/exportTransactions.ts +36 -4
  131. package/ui/hooks/useExportWalletData.ts +25 -2
  132. package/ui/importDatabases.ts +339 -24
  133. package/ui/index.ts +9 -3
  134. package/ui/isImageUrl.ts +6 -0
  135. package/ui/printRecoveryShares.ts +9 -10
  136. package/ui/recoveryPrompts.ts +91 -0
  137. package/ui/resolveIdentity.ts +31 -9
  138. package/ui/screens/ConnectionsScreen.tsx +86 -19
  139. package/ui/screens/IdentifierScreen.tsx +30 -8
  140. package/ui/screens/PairScreen.tsx +74 -2
  141. package/ui/screens/SettingsScreen.tsx +10 -4
  142. package/ui/screens/TrustScreen.tsx +99 -4
  143. package/ui/screens/VaultScreen.tsx +410 -61
  144. package/ui/screens/VaultTransferScreen.tsx +59 -7
  145. package/ui/screens/WalletCheckScreen.tsx +17 -6
  146. package/ui/screens/WalletConfigScreen.tsx +82 -28
  147. package/ui/screens/WalletHomeScreen.tsx +179 -88
  148. package/ui/screens/detailActionKeys.ts +55 -0
  149. package/ui/tokenFormat.ts +44 -4
  150. package/ui/txStatus.ts +5 -0
  151. package/core/storage/LocalStorageAdapter.ts +0 -58
@@ -0,0 +1,483 @@
1
+ /**
2
+ * Chain recovery — clean-device discovery of v7 Vault outputs (spec v7 §1.2
3
+ * item 3; ledger rows INT-01, INT-06, XQ-012, and the backup-independence
4
+ * half of XR-005/INT-02).
5
+ *
6
+ * A v7 vault output publishes its own recoverable index on-chain: a marker
7
+ * (a 1-sat P2PKH output to `wallet.getPublicKey([2,'vault marker'], keyID
8
+ * "${chain}:${k}", counterparty 'self')`, an ordinary indexer can answer)
9
+ * and an encrypted descriptor (a 0-sat `OP_FALSE OP_RETURN 'r1c7' <ciphertext>`
10
+ * output carrying the exact v7 recovery record). Neither the local SQLite
11
+ * database, SecureStore, nor any backup service is needed to find or
12
+ * authenticate a v7 output — only the wallet root (the mnemonic), a chain
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.
16
+ *
17
+ * SCOPE (deliberate, disclosed — design v7 §1.3 "rejected: rebuilding
18
+ * zero-conf ancestor BEEF assembly"): recovery claims CONFIRMED deposits.
19
+ * internalizeAction's own SPV gate (@bsv/sdk Beef.verify with
20
+ * allowTxidOnly=false) requires either a BUMP or a present raw-input chain
21
+ * back to one; teaching this module to assemble an arbitrary-depth
22
+ * unconfirmed ancestor chain from a public indexer is real, open-ended
23
+ * complexity for a narrow confirmation-window edge case that isn't required
24
+ * by I1's core promise (survive phone loss of a SETTLED deposit). A marker
25
+ * whose transaction the injected lookup reports as not-yet-confirmed is
26
+ * reported back as `pendingConfirmation`, never thrown and never silently
27
+ * dropped, and does not consume a gap-scan slot.
28
+ */
29
+ import { Transaction, Utils } from '@bsv/sdk'
30
+ import {
31
+ buildLock,
32
+ commitment,
33
+ decodeVaultInstructionsV7,
34
+ encodeVaultInstructionsV7,
35
+ type VaultInstructionsV7,
36
+ type VaultSaltChain
37
+ } from './r1comb'
38
+ import { VaultError } from './types'
39
+ import {
40
+ VAULT_BASKET,
41
+ deriveVaultMarkerScript,
42
+ deriveVaultSalt,
43
+ decryptVaultDescriptorPlaintext,
44
+ parseVaultDescriptorScript,
45
+ recoverVaultMetaFromOutputs,
46
+ vaultChainKeyId,
47
+ type VaultWallet
48
+ } from './transfers'
49
+ import { wocConfigFor, type WocConfig } from '../../pay/rails/address'
50
+ import type { AppChain } from '../../config'
51
+
52
+ /** Default, caller-raisable gap: consecutive indices with NO marker history
53
+ * (a found-but-unusable record does not count — see below) before the scan
54
+ * stops. */
55
+ export const VAULT_RECOVERY_GAP_DEFAULT = 20
56
+
57
+ /**
58
+ * Hard ceiling on CONSECUTIVE marker-derivation/lookup failures within a
59
+ * single scan — distinct from `consecutiveMisses`, which only ever counts
60
+ * genuine no-history results. A wallet-layer failure (cannot derive our own
61
+ * marker key) or a lookup-layer failure (the injected VaultChainLookup
62
+ * threw) is not evidence of "no marker" — same reasoning as the
63
+ * found-but-unusable contract below — but it also cannot be scanned past
64
+ * indefinitely: without this bound, a lookup that keeps throwing (a
65
+ * persistent outage, or a bug) spins `recoverVaultFromChain`'s `while` loop
66
+ * forever, because neither failure ever touches `consecutiveMisses`. This is
67
+ * a real, empirically-reproduced livelock, not a theoretical one: a tight
68
+ * recursive async loop with no genuine timer/I/O yield drains the microtask
69
+ * queue ahead of any macrotask, which starves even a `setTimeout`-based
70
+ * test/command timeout. Not caller-tunable — this is a safety net, not a
71
+ * recovery parameter. */
72
+ export const VAULT_RECOVERY_MAX_CONSECUTIVE_PROBLEMS = 20
73
+
74
+ /** Defensive cap on how many candidate transactions a single scan index will
75
+ * inspect. A v7 marker is an ordinary P2PKH address that becomes publicly
76
+ * visible the moment its real deposit confirms; nothing stops a stranger
77
+ * from paying arbitrary dust to it afterward. A legitimate index has exactly
78
+ * one real deposit history, so recovery never needs more than a handful of
79
+ * candidates to find it — this only bounds how much free decrypt-and-discard
80
+ * work a targeted victim's recovery can be forced to do. */
81
+ const VAULT_RECOVERY_MAX_CANDIDATES_PER_INDEX = 50
82
+
83
+ /**
84
+ * Injected chain lookup — the only network/indexer dependency this module
85
+ * has. Unit-tested against an in-memory fake; core/services/vault/wocChainLookup.ts
86
+ * (see below) is the production WhatsOnChain implementation.
87
+ */
88
+ export interface VaultChainLookup {
89
+ /** Every txid whose output list includes an output with exactly this
90
+ * locking script — from address history and/or the current unspent set.
91
+ * An empty result is a genuine "no marker at this index" miss. */
92
+ transactionsForLockingScript(lockingScriptHex: string): Promise<string[]>
93
+ /** AtomicBEEF-decodable bytes for `txid` (a plain raw-tx-only BEEF is
94
+ * fine — recoverOneCandidate only reads `tx.outputs` from it locally; the
95
+ * bytes handed to `wallet.internalizeAction` are these same bytes, and
96
+ * ITS OWN chain-tracker validation is the actual SPV gate), plus whether
97
+ * this lookup can currently show the transaction as confirmed. `null`
98
+ * means the lookup could not produce usable bytes at all (reported as a
99
+ * problem, not a miss — see recoverOneCandidate). `confirmed: false` is
100
+ * the explicit, disclosed zero-conf boundary (see this file's docstring):
101
+ * recoverOneCandidate reports it as `pendingConfirmation` rather than
102
+ * attempting `internalizeAction`, which the toolbox's own SPV gate would
103
+ * otherwise throw on.
104
+ */
105
+ transactionForTxid(txid: string): Promise<{ beef: number[]; confirmed: boolean } | null>
106
+ /** Spent/unspent/unknown for one outpoint. 'unknown' is never trusted as
107
+ * unspent — see recoverOneCandidate. */
108
+ outputStatus(outpoint: { txid: string; vout: number }): Promise<'unspent' | 'spent' | 'unknown'>
109
+ }
110
+
111
+ export interface VaultChainRecoveryProblem {
112
+ /** The scan index (saltKeyId) this problem was found at. */
113
+ index: number
114
+ reason: string
115
+ }
116
+
117
+ export interface VaultChainRecoveryResult {
118
+ /** Indices newly inserted into 'admin vault' by this run. */
119
+ found: number
120
+ /** Marker history existed and decrypted to a valid, unspent v7 record, but
121
+ * the lookup could not yet show it as confirmed — the honest zero-conf
122
+ * scope cut (this file's docstring). Not a miss: does not consume a
123
+ * gap-scan slot, and is not a "problem" (nothing is wrong; it just isn't
124
+ * recoverable yet). */
125
+ pendingConfirmation: number
126
+ /** A found-but-unusable record (bad decrypt, wrong version, index/chain
127
+ * mismatch, lock-rebuild mismatch, unreadable transaction bytes) — reported
128
+ * distinctly and does NOT count as a "no marker" miss, so a version
129
+ * mismatch or transient lookup hiccup at one index can never silently
130
+ * truncate the scan. */
131
+ problems: VaultChainRecoveryProblem[]
132
+ /** Highest index actually scanned this run — surfaced so a UI can offer
133
+ * "scan further" when the gap default (or a caller-raised one) turns out
134
+ * to be too small for a heavily re-tried enrollment. */
135
+ scanned: number
136
+ }
137
+
138
+ type CandidateOutcome =
139
+ | { kind: 'found' }
140
+ | { kind: 'pending' }
141
+ | { kind: 'spent' }
142
+ | { kind: 'problem'; reason: string }
143
+
144
+ /**
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.
149
+ */
150
+ async function recoverOneCandidate(
151
+ w: VaultWallet,
152
+ adminOriginator: string,
153
+ lookup: VaultChainLookup,
154
+ chain: VaultSaltChain,
155
+ k: number,
156
+ markerScriptHex: string,
157
+ txid: string
158
+ ): Promise<CandidateOutcome> {
159
+ const saltKeyId = String(k)
160
+ let entry: { beef: number[]; confirmed: boolean } | null
161
+ try {
162
+ entry = await lookup.transactionForTxid(txid)
163
+ } catch {
164
+ return { kind: 'problem', reason: 'chain lookup failed to fetch transaction bytes' }
165
+ }
166
+ if (!entry) return { kind: 'problem', reason: 'no transaction bytes available for this candidate' }
167
+
168
+ let tx: Transaction
169
+ try {
170
+ tx = Transaction.fromAtomicBEEF(entry.beef)
171
+ } catch {
172
+ try {
173
+ tx = Transaction.fromBEEF(entry.beef)
174
+ } catch {
175
+ return { kind: 'problem', reason: 'malformed transaction bytes' }
176
+ }
177
+ }
178
+
179
+ const markerIndex = tx.outputs.findIndex(o => o.lockingScript.toHex() === markerScriptHex)
180
+ const vaultOutput = markerIndex >= 1 ? tx.outputs[markerIndex - 1] : undefined
181
+ const descriptorOutput = markerIndex >= 0 ? tx.outputs[markerIndex + 1] : undefined
182
+ if (!vaultOutput || !descriptorOutput) {
183
+ return { kind: 'problem', reason: 'marker is not immediately between a vault output and a descriptor' }
184
+ }
185
+
186
+ const parsedDescriptor = parseVaultDescriptorScript(descriptorOutput.lockingScript)
187
+ if (!parsedDescriptor) return { kind: 'problem', reason: 'adjacent output is not a v7 descriptor' }
188
+
189
+ let plaintext: string
190
+ try {
191
+ plaintext = await decryptVaultDescriptorPlaintext(w, adminOriginator, chain, saltKeyId, parsedDescriptor.ciphertext)
192
+ } catch {
193
+ return { kind: 'problem', reason: 'descriptor did not decrypt under this index' }
194
+ }
195
+
196
+ const ci: VaultInstructionsV7 | null = decodeVaultInstructionsV7(plaintext)
197
+ if (!ci) return { kind: 'problem', reason: 'descriptor decoded to an invalid or non-v7 record' }
198
+ // Hard-require: closes the "missing piece" the availability review flagged
199
+ // — a descriptor claiming a different index or network must never be
200
+ // accepted at this scan position.
201
+ if (ci.saltKeyId !== saltKeyId || ci.chain !== chain) {
202
+ return { kind: 'problem', reason: 'descriptor index/chain does not match its scan position' }
203
+ }
204
+
205
+ let salt: string
206
+ try {
207
+ salt = await deriveVaultSalt(w, adminOriginator, ci.saltKeyId, ci.keys.map(key => key.serial))
208
+ } catch {
209
+ return { kind: 'problem', reason: 'could not derive the salt for this record' }
210
+ }
211
+ let rebuilt: ReturnType<typeof buildLock>
212
+ try {
213
+ rebuilt = buildLock({ commitments: ci.keys.map(key => commitment(key.pubkey, salt)), saltHex64: salt })
214
+ } catch {
215
+ return { kind: 'problem', reason: 'recovery metadata does not build a valid lock' }
216
+ }
217
+ if (rebuilt.toHex() !== vaultOutput.lockingScript.toHex()) {
218
+ return { kind: 'problem', reason: 'recovery metadata does not rebuild its adjacent lock' }
219
+ }
220
+
221
+ const vaultOutputIndex = markerIndex - 1
222
+ let status: 'unspent' | 'spent' | 'unknown'
223
+ try {
224
+ status = await lookup.outputStatus({ txid, vout: vaultOutputIndex })
225
+ } catch {
226
+ status = 'unknown'
227
+ }
228
+ if (status === 'spent') return { kind: 'spent' }
229
+ if (status === 'unknown') return { kind: 'problem', reason: 'could not confirm the vault output is unspent' }
230
+
231
+ if (!entry.confirmed) return { kind: 'pending' }
232
+
233
+ try {
234
+ await w.internalizeAction({
235
+ tx: entry.beef,
236
+ outputs: [{
237
+ outputIndex: vaultOutputIndex,
238
+ protocol: 'basket insertion',
239
+ insertionRemittance: {
240
+ basket: VAULT_BASKET,
241
+ customInstructions: encodeVaultInstructionsV7(ci),
242
+ tags: ['vault']
243
+ }
244
+ }],
245
+ description: 'Recovered vault deposit',
246
+ seekPermission: false
247
+ }, adminOriginator)
248
+ } catch (e) {
249
+ return { kind: 'problem', reason: `could not internalize the recovered output: ${(e as Error)?.message ?? 'unknown error'}` }
250
+ }
251
+ return { kind: 'found' }
252
+ }
253
+
254
+ /**
255
+ * Scan k = 1.. for chain-published v7 Vault outputs and internalize every
256
+ * confirmed, unspent, authenticated one into 'admin vault'. Then rebuilds
257
+ * local vault metadata from the now-listed outputs via the unchanged
258
+ * recoverVaultMetaFromOutputs (which itself re-authenticates everything).
259
+ *
260
+ * `wallet` need only satisfy VaultWallet (already used throughout
261
+ * transfers.ts) — getPublicKey/encrypt/decrypt/createHmac/internalizeAction
262
+ * must be backed by the wallet's real root key derivation for this to prove
263
+ * anything (a stub wallet with no live mnemonic session cannot reproduce the
264
+ * marker, decrypt the descriptor, or derive the salt — see INT-10's fail-closed
265
+ * claim in restoreSalt.test.ts).
266
+ */
267
+ export async function recoverVaultFromChain(
268
+ w: VaultWallet,
269
+ adminOriginator: string,
270
+ lookup: VaultChainLookup,
271
+ chain: VaultSaltChain,
272
+ gap: number = VAULT_RECOVERY_GAP_DEFAULT
273
+ ): Promise<VaultChainRecoveryResult> {
274
+ if (!Number.isSafeInteger(gap) || gap < 1) {
275
+ throw new VaultError('template-invalid', 'Vault recovery gap must be a positive integer')
276
+ }
277
+ let found = 0
278
+ let pendingConfirmation = 0
279
+ const problems: VaultChainRecoveryProblem[] = []
280
+ let consecutiveMisses = 0
281
+ // Bounds the loop independently of consecutiveMisses — see
282
+ // VAULT_RECOVERY_MAX_CONSECUTIVE_PROBLEMS's doc comment. Reset on any
283
+ // iteration that gets a real answer (a miss or a hit alike), so only a
284
+ // PERSISTENT run of failures aborts the scan, never an occasional hiccup.
285
+ let consecutiveProblems = 0
286
+ let scanned = 0
287
+ let k = 1
288
+ while (consecutiveMisses < gap) {
289
+ scanned = k
290
+ const saltKeyId = String(k)
291
+ let markerScriptHex: string
292
+ try {
293
+ markerScriptHex = (await deriveVaultMarkerScript(w, adminOriginator, chain, saltKeyId)).toHex()
294
+ } catch {
295
+ // Cannot even derive our own marker key — a wallet-layer problem, not
296
+ // evidence this index has no deposit. Reported, not counted as a miss
297
+ // — but still bounded, so a persistent failure fails loudly instead of
298
+ // looping forever (INT-01/INT-06/XQ-012 availability review).
299
+ problems.push({ index: k, reason: 'could not derive the marker key for this index' })
300
+ if (++consecutiveProblems >= VAULT_RECOVERY_MAX_CONSECUTIVE_PROBLEMS) {
301
+ // A plain Error here left VaultScreen (vaultErrorCopy(undefined))
302
+ // showing its generic fallback copy instead of a message actually
303
+ // describing what happened — 'chain-scan-failed' is a code the UI
304
+ // already translates.
305
+ throw new VaultError(
306
+ 'chain-scan-failed',
307
+ `Vault recovery scan could not complete: ${consecutiveProblems} consecutive derivation/lookup failures, most recently at index ${k}`
308
+ )
309
+ }
310
+ k++
311
+ continue
312
+ }
313
+ let txids: string[]
314
+ try {
315
+ txids = await lookup.transactionsForLockingScript(markerScriptHex)
316
+ } catch {
317
+ problems.push({ index: k, reason: 'chain lookup failed for this marker' })
318
+ if (++consecutiveProblems >= VAULT_RECOVERY_MAX_CONSECUTIVE_PROBLEMS) {
319
+ throw new VaultError(
320
+ 'chain-scan-failed',
321
+ `Vault recovery scan could not complete: ${consecutiveProblems} consecutive derivation/lookup failures, most recently at index ${k}`
322
+ )
323
+ }
324
+ k++
325
+ continue
326
+ }
327
+ consecutiveProblems = 0
328
+ if (txids.length === 0) {
329
+ consecutiveMisses++
330
+ k++
331
+ continue
332
+ }
333
+ // Marker history exists at this index — never a "no marker" miss from
334
+ // here on, no matter how every candidate below turns out.
335
+ consecutiveMisses = 0
336
+ let inspected = 0
337
+ for (const txid of txids) {
338
+ if (inspected >= VAULT_RECOVERY_MAX_CANDIDATES_PER_INDEX) {
339
+ problems.push({
340
+ index: k,
341
+ reason: `stopped after ${VAULT_RECOVERY_MAX_CANDIDATES_PER_INDEX} candidates at this index`
342
+ })
343
+ break
344
+ }
345
+ inspected++
346
+ 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 }
349
+ else if (outcome.kind === 'problem') problems.push({ index: k, reason: outcome.reason })
350
+ // 'spent': a superseded output (already withdrawn or re-locked) —
351
+ // entirely normal, silently skipped; keep inspecting other candidates
352
+ // at this index.
353
+ }
354
+ k++
355
+ }
356
+ await recoverVaultMetaFromOutputs(w, adminOriginator)
357
+ return { found, pendingConfirmation, problems, scanned }
358
+ }
359
+
360
+ // ───────────────────────── default WhatsOnChain implementation ─────────────
361
+
362
+ /**
363
+ * Production VaultChainLookup over WhatsOnChain, following the exact request
364
+ * patterns already used by core/pay/rails/address.ts (getUtxosForAddress,
365
+ * the `/tx/{txid}/beef` fetch, parseWocBeefBody's response-shape checks).
366
+ *
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.
377
+ */
378
+ export function wocChainLookup(chain: AppChain): VaultChainLookup {
379
+ const woc: WocConfig = wocConfigFor(chain)
380
+ const base = `${woc.apiBase}/v1/bsv/${woc.segment}`
381
+
382
+ return {
383
+ async transactionsForLockingScript(lockingScriptHex: string): Promise<string[]> {
384
+ // The marker is always a P2PKH output; derive its address from the
385
+ // script's hash160 rather than adding a second WoC endpoint shape.
386
+ //
387
+ // The VaultChainLookup contract (see this file's interface doc) treats
388
+ // an EMPTY result as a genuine "no marker at this index" miss — so a
389
+ // failure to even ask the question (an unrecognizable script), a
390
+ // non-2xx response (rate limiting, a transient 5xx, a maintenance
391
+ // window) or a thrown exception (DNS failure, timeout, offline) must
392
+ // never collapse into that same empty array: recoverVaultFromChain's
393
+ // OWN catch around this call (never a miss, and now bounded — see
394
+ // VAULT_RECOVERY_MAX_CONSECUTIVE_PROBLEMS) is what has to handle these,
395
+ // not the miss-counting branch.
396
+ const address = p2pkhAddressFromScript(lockingScriptHex, woc.network)
397
+ if (!address) {
398
+ throw new Error('wocChainLookup: marker script is not a recognizable P2PKH script')
399
+ }
400
+ const response = await fetch(`${base}/address/${address}/history`)
401
+ if (!response.ok) {
402
+ throw new Error(`wocChainLookup: address history request failed (HTTP ${response.status})`)
403
+ }
404
+ const body = await response.json()
405
+ const rows = Array.isArray(body) ? body : Array.isArray(body?.result) ? body.result : []
406
+ const txids = rows.map((r: any) => r?.tx_hash).filter((h: unknown) => typeof h === 'string')
407
+ return [...new Set<string>(txids)]
408
+ },
409
+
410
+ async transactionForTxid(txid: string): Promise<{ beef: number[]; confirmed: boolean } | null> {
411
+ try {
412
+ const [beefResp, txResp] = await Promise.all([
413
+ fetch(`${base}/tx/${txid}/beef`),
414
+ fetch(`${base}/tx/hash/${txid}`)
415
+ ])
416
+ const beef = parseWocBeefBodyText(beefResp.ok, await beefResp.text())
417
+ if (!beef) return null
418
+ let confirmed = false
419
+ if (txResp.ok) {
420
+ const info = await txResp.json()
421
+ confirmed = Number.isInteger(info?.confirmations) && info.confirmations > 0
422
+ }
423
+ return { beef, confirmed }
424
+ } catch {
425
+ return null
426
+ }
427
+ },
428
+
429
+ async outputStatus(outpoint: { txid: string; vout: number }): Promise<'unspent' | 'spent' | 'unknown'> {
430
+ // 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.
436
+ try {
437
+ const response = await fetch(`${base}/tx/${outpoint.txid}/out/${outpoint.vout}`)
438
+ 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'
443
+ return 'unknown'
444
+ } catch {
445
+ return 'unknown'
446
+ }
447
+ }
448
+ }
449
+ }
450
+
451
+ /** Local copy of address.ts's parseWocBeefBody signature over (ok, text)
452
+ * rather than a Response, so this module does not need to import it just to
453
+ * reshape the call. */
454
+ function parseWocBeefBodyText(ok: boolean, text: string): number[] | undefined {
455
+ if (!ok) return undefined
456
+ const hex = text.trim()
457
+ if (hex.length === 0 || hex.length % 2 !== 0 || !/^[0-9a-fA-F]+$/.test(hex)) return undefined
458
+ try {
459
+ return Utils.toArray(hex, 'hex') as number[]
460
+ } catch {
461
+ return undefined
462
+ }
463
+ }
464
+
465
+ /** hash160 out of a standard P2PKH script, re-encoded as a base58check
466
+ * address for the WoC address-history endpoint, via @bsv/sdk's own public
467
+ * `Utils.toBase58Check` (already imported for toHex/toArray above) — the
468
+ * same primitive `PublicKey.prototype.toAddress()` uses internally elsewhere
469
+ * in this codebase (core/pay/rails/address.ts). Returns undefined for
470
+ * anything else (defensive — deriveVaultMarkerScript always builds P2PKH). */
471
+ function p2pkhAddressFromScript(lockingScriptHex: string, network: 'mainnet' | 'testnet'): string | undefined {
472
+ let bytes: number[]
473
+ try {
474
+ bytes = Utils.toArray(lockingScriptHex, 'hex') as number[]
475
+ } catch {
476
+ return undefined
477
+ }
478
+ if (bytes.length !== 25 || bytes[0] !== 0x76 || bytes[1] !== 0xa9 || bytes[2] !== 0x14 || bytes[23] !== 0x88 || bytes[24] !== 0xac) {
479
+ return undefined
480
+ }
481
+ const hash160 = bytes.slice(3, 23)
482
+ return Utils.toBase58Check(hash160, [network === 'mainnet' ? 0x00 : 0x6f])
483
+ }
@@ -117,8 +117,16 @@ interface NativeYubiKeyPiv {
117
117
  let injectedMock: VaultDriver | null = null
118
118
  let nativeCache: VaultDriver | null | undefined
119
119
 
120
- /** DEV/test seam: force the mock (or clear it). */
120
+ /** DEV/test seam: force the mock (or clear it).
121
+ *
122
+ * Gated on __DEV__ here, not just in devMock.ts's wrapper, so anything with
123
+ * JS execution in a nominally-production bundle (a modified/unofficial
124
+ * build, or a compromised dependency) cannot call this directly to make
125
+ * getVaultDriver() prefer a software mock over real hardware and skip native
126
+ * attestation (reviews/vault.md F-09).
127
+ */
121
128
  export function setMockDriver(driver: VaultDriver | null): void {
129
+ if (!__DEV__) return
122
130
  injectedMock = driver
123
131
  }
124
132
 
@@ -0,0 +1,150 @@
1
+ /**
2
+ * XQ-014 — device-wide registry of enrolled Vault YubiKey serials.
3
+ *
4
+ * pivReset.ts's own docstring states the residual plainly: a vault belonging
5
+ * to a DIFFERENT wallet identity on this device is invisible to it, because
6
+ * SecureStore cannot be enumerated across identities —
7
+ * vaultStore.enrolledSerialsAcrossChains only ever sees the ONE identity that
8
+ * captured its scope token. Guard 3 (the card's own occupied-slot answer) was
9
+ * the only backstop, and it was overridable by the caller-supplied
10
+ * `acknowledgeUnrecognizedVaultKey` consent — whose copy could only ever
11
+ * disclose the uncertainty, never resolve it.
12
+ *
13
+ * This module is the "device-wide serial index" that residual needed: a
14
+ * plain AsyncStorage-backed set of BARE serials — never pubkeys, nicknames,
15
+ * or identity keys, so it carries no key material and grants no spend
16
+ * authority to anything. Every identity's vaultStore writes to the SAME
17
+ * device-wide key, so pivReset can now refuse UNCONDITIONALLY (never
18
+ * overridable) when the tapped serial is one ANY identity on this device has
19
+ * ever committed as a live Vault signer — not just the currently active one.
20
+ *
21
+ * WHY NOT REFERENCE-COUNTED. A serial can legitimately be committed under
22
+ * more than one identity's vault at once (the same physical YubiKey enrolled
23
+ * twice), so `record`/`forget` are plain set add/remove, not a counter.
24
+ * `forget` is called only after the CALLING identity has independently
25
+ * confirmed, via vaultStore.enrolledSerialsAcrossChains, that no OTHER chain
26
+ * of THAT SAME identity still holds the serial — so a key genuinely shared
27
+ * only within one identity's own chains is never dropped prematurely. A
28
+ * serial shared ACROSS two different identities is a residual this module
29
+ * cannot fully resolve (proving that would need the same cross-identity
30
+ * enumeration SecureStore does not allow): if identity A fully removes its
31
+ * own copy while identity B still holds the same physical key, the registry
32
+ * forgets it and pivReset falls back to the pre-existing, honestly-worded
33
+ * `acknowledgeUnrecognizedVaultKey` consent for identity B's card — exactly
34
+ * the same protection this residual had before this module existed, never
35
+ * worse. The registry only ever makes a destructive maintenance action
36
+ * refuse MORE often; it never grants any capability.
37
+ */
38
+ import AsyncStorage from '@react-native-async-storage/async-storage'
39
+
40
+ const REGISTRY_KEY = 'vault_enrolled_serial_registry_v1'
41
+
42
+ /** Same shape as vaultStore.ts's isVaultSerial, duplicated rather than
43
+ * imported: this module deliberately has no dependency on vaultStore (or the
44
+ * expo-secure-store it pulls in) — it is a plain, storage-agnostic-of-vault
45
+ * device record every identity's vaultStore writes INTO, not a vaultStore
46
+ * extension. */
47
+ function isVaultSerial(value: unknown): value is string {
48
+ return typeof value === 'string' && /^[A-Za-z0-9._:-]{1,64}$/.test(value)
49
+ }
50
+
51
+ async function readRegistry(): Promise<Set<string>> {
52
+ try {
53
+ const raw = await AsyncStorage.getItem(REGISTRY_KEY)
54
+ if (!raw) return new Set()
55
+ const parsed: unknown = JSON.parse(raw)
56
+ if (!Array.isArray(parsed)) return new Set()
57
+ return new Set(parsed.filter((serial): serial is string => isVaultSerial(serial)))
58
+ } catch {
59
+ // Corrupt bookkeeping is never fatal, and never trusted as "empty": an
60
+ // unreadable registry answers `has` as though nothing were forgotten
61
+ // (see `has` below), so it only ever narrows what gets refused, never
62
+ // silently drops a real entry.
63
+ return new Set()
64
+ }
65
+ }
66
+
67
+ async function writeRegistry(serials: ReadonlySet<string>): Promise<void> {
68
+ await AsyncStorage.setItem(REGISTRY_KEY, JSON.stringify([...serials]))
69
+ }
70
+
71
+ export const enrolledSerialRegistry = {
72
+ /** Called whenever ANY identity's vaultStore commits `serial` as an
73
+ * enrolled Vault key (finalizeEnrollment, addVaultKey). Best-effort: a
74
+ * storage failure here must never fail the enrollment it is recording
75
+ * after — pivReset's registry check degrading to "not recognized" for
76
+ * this one serial only narrows a future refusal, it never threatens I1/I2. */
77
+ async record(serial: string): Promise<void> {
78
+ if (!isVaultSerial(serial)) return
79
+ try {
80
+ const current = await readRegistry()
81
+ if (current.has(serial)) return
82
+ current.add(serial)
83
+ await writeRegistry(current)
84
+ } catch (err) {
85
+ console.warn('[enrolledSerialRegistry] record failed:', err)
86
+ }
87
+ },
88
+
89
+ /** Called only after the caller has independently confirmed (via
90
+ * vaultStore.enrolledSerialsAcrossChains for its OWN identity) that no
91
+ * other chain of that identity still holds `serial` — see this module's
92
+ * header for the cross-identity residual this does not, and cannot,
93
+ * fully resolve. Best-effort, like `record`. */
94
+ async forget(serial: string): Promise<void> {
95
+ if (!isVaultSerial(serial)) return
96
+ try {
97
+ const current = await readRegistry()
98
+ if (!current.has(serial)) return
99
+ current.delete(serial)
100
+ await writeRegistry(current)
101
+ } catch (err) {
102
+ console.warn('[enrolledSerialRegistry] forget failed:', err)
103
+ }
104
+ },
105
+
106
+ /** Never throws: an unreadable registry answers `false`, the same
107
+ * fail-narrow behavior as a corrupt read (see readRegistry). */
108
+ async has(serial: string): Promise<boolean> {
109
+ if (!isVaultSerial(serial)) return false
110
+ try {
111
+ return (await readRegistry()).has(serial)
112
+ } catch {
113
+ return false
114
+ }
115
+ },
116
+
117
+ /** Test/maintenance only — no production caller. */
118
+ async clearAll(): Promise<void> {
119
+ await AsyncStorage.removeItem(REGISTRY_KEY)
120
+ }
121
+ }
122
+
123
+ /**
124
+ * Forget every serial in `candidates` that is no longer enrolled under any
125
+ * OTHER chain of the identity `scopeToken` was captured for. Called after a
126
+ * key (or a whole vault) has just been fully removed/disabled for that
127
+ * identity+chain, once vaultStore's own write already reflects the removal —
128
+ * so `enrolledSerialsAcrossChains`'s scan of the remaining chains answers
129
+ * correctly. See enrolledSerialRegistry's header for why this is not, and
130
+ * cannot be, a cross-IDENTITY check.
131
+ */
132
+ export async function forgetSerialsNoLongerEnrolledForIdentity(
133
+ candidates: readonly string[],
134
+ enrolledSerialsAcrossChains: () => Promise<string[]>
135
+ ): Promise<void> {
136
+ if (candidates.length === 0) return
137
+ let stillEnrolled: Set<string>
138
+ try {
139
+ stillEnrolled = new Set(await enrolledSerialsAcrossChains())
140
+ } catch (err) {
141
+ // Fail closed on the SIDE OF THE REGISTRY, not the removal that already
142
+ // committed: an unreadable cross-chain scan must not forget a serial it
143
+ // cannot prove is free elsewhere on this identity.
144
+ console.warn('[enrolledSerialRegistry] cross-chain check failed, leaving candidates registered:', err)
145
+ return
146
+ }
147
+ for (const serial of candidates) {
148
+ if (!stillEnrolled.has(serial)) await enrolledSerialRegistry.forget(serial)
149
+ }
150
+ }