@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
@@ -124,6 +124,15 @@ async function resolveMandalaAssetMetadata(assetId: string): Promise<MandalaAsse
124
124
  }
125
125
  }
126
126
 
127
+ // XR-039: same paging discipline as `core/localpay/build.ts`'s
128
+ // `listTokenBasket` and `core/mandala/createRuntime.ts`'s `listTokenOutputs`
129
+ // -- a page size generous enough that any realistic basket is one round
130
+ // trip, and a hard page ceiling so a wallet that reports a `totalOutputs` it
131
+ // never actually serves (or repeats a page forever) cannot spin
132
+ // `listMandalaTokenOutpoints` into an infinite loop.
133
+ const MANDALA_OUTPOINT_LIST_PAGE = 1000
134
+ const MANDALA_OUTPOINT_LIST_MAX_PAGES = 1000
135
+
127
136
  const DEFAULT_SETTINGS: WalletSettings = {
128
137
  ...LIB_DEFAULT_SETTINGS,
129
138
  trustSettings: {
@@ -155,23 +164,44 @@ const DEFAULT_SETTINGS: WalletSettings = {
155
164
  import type { AppChain } from '../config'
156
165
  import { DEFAULT_STORAGE_URL, DEFAULT_CHAIN, ADMIN_ORIGINATOR, toWalletChain } from '../config'
157
166
  import { getBackupUrl, getMandalaEndpoints } from '../toolboxConfig'
158
- import { DEFAULT_AUTO_APPROVE_THRESHOLD, AUTO_APPROVE_COOLDOWN_MS, AUTO_APPROVE_STORAGE_KEY } from '../constants'
167
+ import {
168
+ DEFAULT_AUTO_APPROVE_THRESHOLD,
169
+ AUTO_APPROVE_COOLDOWN_MS,
170
+ AUTO_APPROVE_STORAGE_KEY,
171
+ AUTO_APPROVE_DAILY_CAP_SATS,
172
+ AUTO_APPROVE_LEDGER_STORAGE_KEY
173
+ } from '../constants'
174
+ import { createAutoApprovePolicy } from '../services/autoApprovePolicy'
175
+ import { deriveCallbackToken } from '../services/callbackToken'
159
176
  import AsyncStorage from '@react-native-async-storage/async-storage'
160
177
  import { UserContext } from './UserContext'
161
178
  import { useLocalStorage } from './LocalStorageProvider'
162
179
  import { usePermissionQueue } from '../hooks/usePermissionQueue'
163
180
  import { configureMandala, resolveAssetMetadata } from '@bsv/mandala'
164
181
  import { MessageBoxClient } from '@bsv/message-box-client'
165
- import { MandalaTokenModule, wrapCreateActionForTokenInputs, type MandalaAssetMetadata } from '../mandala/permissionModule'
182
+ import {
183
+ MandalaTokenModule,
184
+ wrapCreateActionForTokenInputs,
185
+ listAllOutpoints,
186
+ resolveMandalaOutput,
187
+ type MandalaAssetMetadata
188
+ } from '../mandala/permissionModule'
166
189
  import { wrapAbortActionForSettlements } from '../mandala/abortGuard'
167
190
  import { migrateMandalaBasketName } from '../mandala/basketMigration'
168
- import { bindOriginator, createMandalaKvStorage, createMandalaRuntime, type MandalaMessageBox } from '../mandala/createRuntime'
191
+ import {
192
+ bindOriginator,
193
+ createMandalaKvStorage,
194
+ createMandalaRuntime,
195
+ type MandalaMessageBox
196
+ } from '../mandala/createRuntime'
169
197
  import type { MandalaRuntime } from '../mandala/runtime'
170
198
  import { MANDALA_BASKET } from '../mandala/types'
171
199
  import { mandalaSettlementDeps, type CancelParkedSettlementDeps } from '../offline/cancelParked'
172
200
  import { drainMandalaInbox } from '../pay/rails/handle'
173
201
  import { forgetSessionPsks, sealedFramePayloadDecoder } from '../offline/tokenFrames'
202
+ import { disconnectActivePairedSession } from './WalletConnectionContext'
174
203
  import { createServices, chaintracksUrlFor } from '../services/walletServiceConfig'
204
+ import { getArcApiToken } from '../services/arcTokenStorage'
175
205
  import {
176
206
  boundReviewProvenTxs,
177
207
  configureNewHeaderPolling,
@@ -194,11 +224,17 @@ import { StorageProvider, ChaintracksServiceClient } from '@bsv/wallet-toolbox-m
194
224
  import { StorageExpoSQLite } from '../storage'
195
225
  import { makeBuildGeneration } from './buildGeneration'
196
226
  import * as SQLite from 'expo-sqlite'
197
- import { getRegisteredDbs, registerDb, selectLatestDb } from '../walletDbRegistry'
227
+ import {
228
+ getRegisteredDbs,
229
+ purgeRegisteredDbFiles,
230
+ registerDb,
231
+ selectLatestDb,
232
+ unregisterDb
233
+ } from '../walletDbRegistry'
198
234
  import { AppState, AppStateStatus, InteractionManager } from 'react-native'
199
235
  import { getOnline, subscribeOnline } from '../net/online'
200
236
  import { canInternalizePending, processPending } from '../localpay/pending'
201
- import { replayPendingAborts } from '../localpay/pendingAborts'
237
+ import { replayPendingAborts, verifyDeclinedAborts } from '../localpay/pendingAborts'
202
238
  import { TaskSendOffline } from '../monitor/TaskSendOffline'
203
239
  import { MONITOR_STALL_MS, MonitorSupervisor } from '../monitor/MonitorSupervisor'
204
240
  import { TaskCreditInbox } from '../monitor/TaskCreditInbox'
@@ -206,9 +242,11 @@ import { drainUnsentEntries, TaskDrainOutbox } from '../monitor/TaskDrainOutbox'
206
242
  import { TaskBackupPush } from '../monitor/TaskBackupPush'
207
243
  import { pushOnce } from '../backup/push'
208
244
  import { restoreOnImport } from '../backup/restoreOnImport'
245
+ import { backupPseudonym } from '../backup/derive'
246
+ import type { BackupChain } from '../backup/constants'
209
247
  import { processOfflineActions } from '../storage/methods/processOfflineActions'
210
248
  import { findOfflineActions } from '../storage/methods/offlineActions'
211
- import { shouldFailUnprovenTx } from '../pay/refreshProofGuard'
249
+ import { boundedHexResponse, isChainAbsenceConfirmed, shouldFailUnprovenTx } from '../pay/refreshProofGuard'
212
250
  import { inputTxidsFromRawTx, shouldDeferSendWaiting } from '../storage/skipQueuedAncestors'
213
251
  import { provenTxFromBump } from '../pay/provenTxFromBump'
214
252
  import { recordProof } from '../pay/recordProof'
@@ -219,6 +257,9 @@ import { sounds } from '../hooks/useConfirmationSound'
219
257
  import i18n from '../i18n/translations'
220
258
  import { makeBeefRepair } from '../pay/beefRepair'
221
259
  import { shouldReleaseUtxo, type UtxoProbe } from '../walletRepair/shouldReleaseUtxo'
260
+ import { shouldMarkUnspendable } from '../walletRepair/shouldMarkUnspendable'
261
+ import { spenderConsumesOutpoint } from '../walletRepair/spenderConsumesOutpoint'
262
+ import { releaseStuckReservationsOnDb } from '../walletRepair/releaseStuckReservations'
222
263
  import {
223
264
  acceptWithRetry,
224
265
  DEFAULT_MESSAGE_BOX_URL,
@@ -229,7 +270,7 @@ import {
229
270
  retryDelivery
230
271
  } from '../pay/rails/handle'
231
272
  import { getOutboxEntries, pruneExpiredSent, unsentEntries } from '../peerpay/outbox'
232
- import { wocConfigFor } from '../pay/rails/address'
273
+ import { MAX_HEX_RESPONSE_CHARS, wocConfigFor } from '../pay/rails/address'
233
274
  import { PeerPayClient } from '@bsv/message-box-client'
234
275
  import { SWEEP_INTERVAL_MS, runSweep, shouldSweepNow, sweptTotal } from '../pay/sweeper'
235
276
  import { formatAmount } from '../amountFormatHelpers'
@@ -242,9 +283,42 @@ import { prewarmOwnRoots } from '../headers/prewarm'
242
283
  import { syncHeaders } from '../headers/syncHeaders'
243
284
  import type { HeaderSource } from '../headers/syncHeaders'
244
285
 
245
- // Global, origin-agnostic rate limit for auto-approved spending.
246
- // In-memory only — resets on app restart (intentional: more secure).
247
- let lastAutoApproveTime = 0
286
+ // Auto-approve accounting (misc-p2-04). Previously a single global cooldown
287
+ // timer let multiple paired origins accidentally throttle each other while
288
+ // placing no ceiling on a single origin's cumulative total. autoApprovePolicy
289
+ // keys the cooldown PER ORIGINATOR and adds a global rolling-24h cumulative
290
+ // cap across every originator — see services/autoApprovePolicy.ts. Module
291
+ // scope, same lifetime as the value it replaces; `threshold` reads a snapshot
292
+ // updated on every spendingAuthorizationCallback call (see below) since the
293
+ // persisted threshold is itself read fresh per-request.
294
+ let autoApproveThresholdSnapshot = 0
295
+ const autoApprovePolicy = createAutoApprovePolicy({
296
+ now: () => Date.now(),
297
+ threshold: () => autoApproveThresholdSnapshot,
298
+ cooldownMs: AUTO_APPROVE_COOLDOWN_MS,
299
+ dailyCapSats: AUTO_APPROVE_DAILY_CAP_SATS
300
+ })
301
+
302
+ // Best-effort persistence of the rolling ledger so an app restart does not
303
+ // reset the daily cap. Loaded once per process; a read/write failure never
304
+ // blocks a spend decision — the in-memory ledger stays authoritative either way.
305
+ let autoApproveLedgerLoadedOnce = false
306
+ async function loadAutoApproveLedgerOnce(): Promise<void> {
307
+ if (autoApproveLedgerLoadedOnce) return
308
+ autoApproveLedgerLoadedOnce = true
309
+ try {
310
+ const stored = await AsyncStorage.getItem(AUTO_APPROVE_LEDGER_STORAGE_KEY)
311
+ if (stored) {
312
+ const parsed = JSON.parse(stored)
313
+ if (Array.isArray(parsed)) autoApprovePolicy.loadLedger(parsed)
314
+ }
315
+ } catch {
316
+ // No persisted ledger to restore — start with an empty one, same as today.
317
+ }
318
+ }
319
+ function persistAutoApproveLedger(): void {
320
+ AsyncStorage.setItem(AUTO_APPROVE_LEDGER_STORAGE_KEY, JSON.stringify(autoApprovePolicy.getLedger())).catch(() => {})
321
+ }
248
322
 
249
323
  // -----
250
324
  // Context Types
@@ -272,6 +346,12 @@ export interface BackupRestoreState {
272
346
  /** Chunks in the generation being replayed; 0 until the log index is read. */
273
347
  total: number
274
348
  error?: string
349
+ /**
350
+ * Set alongside a `'restored'` phase, from `restoreOnImport`'s own `verified` — true
351
+ * unless the replayed generation's newest entry could not be proven complete (see
352
+ * RemoteSyncReader.verifiedComplete). Absent for every other phase.
353
+ */
354
+ verified?: boolean
275
355
  }
276
356
 
277
357
  export interface WalletBuildOptions {
@@ -282,6 +362,16 @@ export interface WalletBuildOptions {
282
362
  * to restore, and an auto-build on relaunch must not re-import over a live database.
283
363
  */
284
364
  restoreFromBackup?: boolean
365
+ /**
366
+ * Run the same spendability-reconciliation pass a backup restore runs, once local
367
+ * storage is attached — WITHOUT pulling or replaying the encrypted remote backup.
368
+ *
369
+ * Set ONLY by the raw-database-import flow (ui/importDatabases.ts): that flow already
370
+ * hands over a complete local database, so it must not also overlay a remote backup on
371
+ * top of it, but it still skipped the reconciliation review until this option existed
372
+ * (XR-079).
373
+ */
374
+ reviewImportedCoins?: boolean
285
375
  }
286
376
 
287
377
  export interface WalletContextValue {
@@ -292,8 +382,13 @@ export interface WalletContextValue {
292
382
  // Settings
293
383
  settings: WalletSettings
294
384
  updateSettings: (newSettings: WalletSettings) => Promise<void>
295
- // Logout
296
- logout: () => void
385
+ /** "Delete Wallet". Resolves to whether the secrets layer verified every
386
+ * legacy plaintext item erased (XR-107) — false means a persistent
387
+ * SecureStore delete failure left something recoverable, and the caller
388
+ * must report that as a failure (offer retry) rather than treat the
389
+ * wallet as gone: this same false also means the attestation was left
390
+ * untouched and no navigation happened. */
391
+ logout: () => Promise<boolean>
297
392
  adminOriginator: string
298
393
  basketRequests: BasketAccessRequest[]
299
394
  certificateRequests: CertificateAccessRequest[]
@@ -324,12 +419,31 @@ export interface WalletContextValue {
324
419
  * captured `backupRestore` is still the pre-build render's value. This reads the ref.
325
420
  */
326
421
  getBackupRestore: () => BackupRestoreState
422
+ /**
423
+ * This wallet's own backup-server pseudonym for `chain`, or undefined when no wallet is
424
+ * built for that chain (or none at all). Not a secret — it is exactly what the backup
425
+ * server sees as this wallet's account — but deriving it needs the primary key, so it is
426
+ * exposed this way rather than the key itself. See XR-009 / getBackupUploadState.
427
+ */
428
+ getBackupPseudonym: (chain: BackupChain) => string | undefined
429
+ /**
430
+ * The same value as `walletBuilt`, read fresh.
431
+ *
432
+ * Mirrors `getBackupRestore`'s rationale: a caller that awaits a build or rebuild
433
+ * (recoverWallet's retry loop is the motivating case) and then checks whether the
434
+ * wallet is already built must not see a React state snapshot frozen at the render
435
+ * before the await — it must see the ref, which is updated synchronously at every
436
+ * build/teardown transition.
437
+ */
438
+ getWalletBuilt: () => boolean
327
439
  switchNetwork: (network: AppChain) => Promise<void>
328
440
  /** Tear down the current wallet and re-trigger auto-build (e.g. after DB import).
329
441
  * `restoreFromBackup` threads through to the auto-build's replay, for replacing
330
442
  * an already-built wallet with an imported one (e.g. onboarding's backup-reminder
331
- * "import from backup" over an auto-created wallet). */
332
- rebuildWallet: (opts?: { restoreFromBackup?: boolean }) => Promise<void>
443
+ * "import from backup" over an auto-created wallet). `reviewImportedCoins` threads
444
+ * through to a post-storage-attach reconciliation pass (no remote replay) for a raw
445
+ * database import that already carries a complete local database (XR-079). */
446
+ rebuildWallet: (opts?: { restoreFromBackup?: boolean; reviewImportedCoins?: boolean }) => Promise<void>
333
447
  storage: StorageExpoSQLite | null
334
448
  /**
335
449
  * Mandala stablecoins, or undefined.
@@ -383,7 +497,7 @@ export const WalletContext = createContext<WalletContextValue>({
383
497
  getManagers: () => ({}),
384
498
  settings: DEFAULT_SETTINGS,
385
499
  updateSettings: async () => {},
386
- logout: () => {},
500
+ logout: async () => false,
387
501
  adminOriginator: ADMIN_ORIGINATOR,
388
502
  basketRequests: [],
389
503
  certificateRequests: [],
@@ -407,6 +521,8 @@ export const WalletContext = createContext<WalletContextValue>({
407
521
  buildWalletFromRecoveredKey: async () => {},
408
522
  backupRestore: { phase: 'idle', chunks: 0, total: 0 },
409
523
  getBackupRestore: () => ({ phase: 'idle', chunks: 0, total: 0 }),
524
+ getBackupPseudonym: () => undefined,
525
+ getWalletBuilt: () => false,
410
526
  switchNetwork: async () => {},
411
527
  rebuildWallet: async () => {},
412
528
  storage: null,
@@ -661,6 +777,22 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
661
777
  setBackupRestoreState(next)
662
778
  }, [])
663
779
  const getBackupRestore = useCallback((): BackupRestoreState => backupRestoreRef.current, [])
780
+ const getWalletBuilt = useCallback((): boolean => walletBuiltRef.current, [])
781
+ /**
782
+ * Set once buildWallet resolves this build's backup chain/pseudonym, so a screen (Wallet
783
+ * Check) can scope a backup-cursor lookup to the CURRENT identity (see XR-009) without
784
+ * ever seeing the primary key itself — the pseudonym is derived from it but is not a
785
+ * secret; it is exactly what the backup server sees as this wallet's account. Cleared on
786
+ * logout so a departed wallet's pseudonym is never read back before the next build sets
787
+ * its own; `getBackupPseudonym` also refuses to answer for any OTHER chain, so a stale
788
+ * entry from a network switch can never be misread as the current one's.
789
+ */
790
+ const backupIdentityRef = useRef<{ chain: BackupChain, pseudonym: string } | null>(null)
791
+ const getBackupPseudonym = useCallback(
792
+ (chain: BackupChain): string | undefined =>
793
+ backupIdentityRef.current?.chain === chain ? backupIdentityRef.current.pseudonym : undefined,
794
+ []
795
+ )
664
796
  /**
665
797
  * Set by an import flow immediately before it hands the primary key over, and consumed
666
798
  * (and cleared) by the buildWallet pass it triggers. A ref rather than state because
@@ -668,6 +800,17 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
668
800
  * render — a state read there would see whatever was committed, which is a race.
669
801
  */
670
802
  const restoreIntentRef = useRef(false)
803
+ /**
804
+ * Set by a raw-database-import flow (ui/importDatabases.ts, via
805
+ * rebuildWallet's `reviewImportedCoins` option) immediately before it
806
+ * triggers a rebuild, and consumed (and cleared) once local storage is
807
+ * attached in the build this triggers. Deliberately separate from
808
+ * restoreIntentRef: a raw import already carries a complete local
809
+ * database, so it must NOT also pull and replay the encrypted remote
810
+ * backup — it only needs the same spendability reconciliation pass that
811
+ * restoreIntentRef's path runs after its own replay (XR-079).
812
+ */
813
+ const reviewImportedCoinsRef = useRef(false)
671
814
  /**
672
815
  * Set by rebuildWallet right before finalizeConfig, cleared by the auto-build
673
816
  * effect once it actually starts (or determines there is nothing to build).
@@ -763,6 +906,9 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
763
906
  AsyncStorage.getItem(AUTO_APPROVE_STORAGE_KEY).then(v => {
764
907
  if (v !== null) autoApproveThresholdRef.current = Number(v) || 0
765
908
  })
909
+ // Restores the rolling auto-approve ledger so an app restart does not
910
+ // reset the daily cap (misc-p2-04). Best-effort — see loadAutoApproveLedgerOnce.
911
+ loadAutoApproveLedgerOnce()
766
912
  AsyncStorage.getItem('walletSettings').then(v => {
767
913
  if (v) setSettings(prev => ({ ...prev, ...JSON.parse(v) }))
768
914
  })
@@ -930,36 +1076,39 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
930
1076
  const { requestID, originator, reason, renewal, spending } = args
931
1077
  if (!requestID || !spending) return
932
1078
 
933
- // Auto-approve small transactions if within threshold and cooldown.
934
- // Read the persisted threshold fresh on every request so a change made
935
- // in wallet-config takes effect immediately (the mount-time ref read
936
- // alone left the old value live until app restart — felt like
937
- // auto-approve was "stuck on").
1079
+ // Auto-approve small transactions if within threshold, per-originator
1080
+ // cooldown, and the global rolling 24h cap (misc-p2-04) — accounting
1081
+ // lives in autoApprovePolicy.ts. Read the persisted threshold fresh on
1082
+ // every request so a change made in wallet-config takes effect
1083
+ // immediately (the mount-time ref read alone left the old value live
1084
+ // until app restart — felt like auto-approve was "stuck on").
938
1085
  try {
939
1086
  const stored = await AsyncStorage.getItem(AUTO_APPROVE_STORAGE_KEY)
940
1087
  if (stored !== null) autoApproveThresholdRef.current = Number(stored) || 0
941
1088
  } catch {}
942
1089
  const threshold = autoApproveThresholdRef.current
943
- const now = Date.now()
944
- const sinceLastMs = now - lastAutoApproveTime
1090
+ autoApproveThresholdSnapshot = threshold
945
1091
  // Logging gated behind __DEV__: an unconditional console.log here flushes
946
1092
  // over the JS↔native bridge on every spend request — i.e. on the payment
947
1093
  // hot path — and shows up as jank under any burst of micropayments.
948
- if (threshold > 0 && spending.satoshis <= threshold) {
949
- if (sinceLastMs >= AUTO_APPROVE_COOLDOWN_MS) {
950
- lastAutoApproveTime = now
951
- if (__DEV__) console.log(`[spend-auth] AUTO-APPROVING requestID=${requestID} sats=${spending.satoshis}`)
952
- managersRef.current.permissionsManager?.grantPermission({
953
- requestID,
954
- ephemeral: true,
955
- amount: spending.satoshis
956
- })
957
- return
958
- }
959
- if (__DEV__) console.log(`[spend-auth] cooldown blocked → manual modal requestID=${requestID}`)
960
- } else if (__DEV__) {
1094
+ const autoApproveDecision = autoApprovePolicy.shouldAutoApprove({
1095
+ originator,
1096
+ satoshis: spending.satoshis
1097
+ })
1098
+ if (autoApproveDecision.approve) {
1099
+ autoApprovePolicy.record({ originator, satoshis: spending.satoshis, at: Date.now() })
1100
+ persistAutoApproveLedger()
1101
+ if (__DEV__) console.log(`[spend-auth] AUTO-APPROVING requestID=${requestID} sats=${spending.satoshis}`)
1102
+ managersRef.current.permissionsManager?.grantPermission({
1103
+ requestID,
1104
+ ephemeral: true,
1105
+ amount: spending.satoshis
1106
+ })
1107
+ return
1108
+ }
1109
+ if (__DEV__) {
961
1110
  console.log(
962
- `[spend-auth] not eligible → manual modal requestID=${requestID} sats=${spending.satoshis} threshold=${threshold}`
1111
+ `[spend-auth] not eligible (${autoApproveDecision.reason}) → manual modal requestID=${requestID} sats=${spending.satoshis} threshold=${threshold}`
963
1112
  )
964
1113
  }
965
1114
 
@@ -1080,16 +1229,26 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1080
1229
  // the backup derivation is frozen on the app-level names.
1081
1230
  const backupChain =
1082
1231
  chain === 'main' ? ('main' as const) : chain === 'test' ? ('test' as const) : ('teratest' as const)
1232
+ // See getBackupPseudonym's own docs: this is what lets Wallet Check scope its
1233
+ // cursor lookup to THIS identity without the primary key itself leaving this scope.
1234
+ backupIdentityRef.current = { chain: backupChain, pseudonym: backupPseudonym(primaryKey, backupChain) }
1083
1235
  const keyDeriver = new KeyDeriver(new PrivateKey(primaryKey))
1084
1236
  const storageManager = new WalletStorageManager(keyDeriver.identityKey)
1085
1237
  const signer = new WalletSigner(walletChain, keyDeriver, storageManager)
1086
1238
 
1087
1239
  const bsvExchangeRate = await getExchangeRate()
1088
- const callbackToken = keyDeriver.identityKey.substring(0, 32)
1089
-
1240
+ // Derived from PRIVATE key material (misc-p2-06) — was previously the
1241
+ // first 32 chars of the PUBLIC identityKey, which any past
1242
+ // counterparty can already reconstruct. See callbackToken.ts.
1243
+ const callbackToken = deriveCallbackToken(keyDeriver)
1244
+
1245
+ // XR-106: the token half is SecureStore-backed (getArcApiToken also
1246
+ // migrates away any plaintext value a pre-fix build left in
1247
+ // AsyncStorage under this same key) — only the URL, which is not a
1248
+ // credential, still lives in plain AsyncStorage.
1090
1249
  const [arcUrlOverride, arcApiTokenOverride] = await Promise.all([
1091
1250
  AsyncStorage.getItem(`arc_custom_url_${chain}`),
1092
- AsyncStorage.getItem(`arc_custom_api_token_${chain}`)
1251
+ getArcApiToken(chain)
1093
1252
  ])
1094
1253
 
1095
1254
  // The remote client the wrapper delegates to. Built here rather than
@@ -1121,6 +1280,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1121
1280
 
1122
1281
  // Replace all default broadcast providers with EF/rawtx-only services.
1123
1282
  // Order: Arcade → Taal → GorillaPool → WoC → Bitails. UntilSuccess stops at first success.
1283
+ // Taal runs on main + test only, GorillaPool on main only; teratest has no public ARC.
1124
1284
  // 'ArcadeBeef' is the toolbox's own Arcade broadcaster, registered
1125
1285
  // because serviceOptions now carries arcadeUrl (needed for Arcade-first
1126
1286
  // proofs and SSE). Our createArcadeBroadcastService replaces it here so
@@ -1132,13 +1292,10 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1132
1292
  services.postBeefServices.remove('Bitails')
1133
1293
  services.postBeefServices.remove('WhatsOnChain')
1134
1294
  services.postBeefServices.add(createArcadeBroadcastService(serviceOptions.arcUrl!, callbackToken))
1135
- const taalArcUrl =
1136
- chain === 'main'
1137
- ? 'https://arc.taal.com'
1138
- : chain === 'test'
1139
- ? 'https://arc-test.taal.com'
1140
- : 'https://arc-teratest.taal.com'
1141
- services.postBeefServices.add(createTaalBroadcastService(taalArcUrl, serviceOptions.taalApiKey))
1295
+ if (chain === 'main' || chain === 'test') {
1296
+ const taalArcUrl = chain === 'main' ? 'https://arc.taal.com' : 'https://arc-test.taal.com'
1297
+ services.postBeefServices.add(createTaalBroadcastService(taalArcUrl, serviceOptions.taalApiKey))
1298
+ }
1142
1299
  if (chain === 'main') {
1143
1300
  services.postBeefServices.add(createGorillaPoolBroadcastService('https://arc.gorillapool.io'))
1144
1301
  }
@@ -1149,7 +1306,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1149
1306
 
1150
1307
  // Replace WoC getMerklePath with BUMP endpoint — no TSC→BUMP conversion needed.
1151
1308
  // The toolbox's 'Arcade' provider stays where Services put it: first.
1152
- // Every tx this wallet sends goes through Arcade, so GET /v1/tx/{txid}
1309
+ // Every tx this wallet sends goes through Arcade, so GET /tx/{txid}
1153
1310
  // there is the one lookup that can answer as soon as it is mined. WoC
1154
1311
  // BUMP and Bitails are re-added after it as fallbacks, in that order.
1155
1312
  const wocBumpBase =
@@ -1252,6 +1409,13 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1252
1409
  // ── Select the best database file from the registry ──
1253
1410
  let knownDbs = await getRegisteredDbs(keySuffix, chainStr)
1254
1411
 
1412
+ // Whether THIS build attempt is the one that created selectedDb below, as
1413
+ // opposed to reselecting a file that already existed before this attempt
1414
+ // started (an already-onboarded identity's real database, or a legacy file
1415
+ // discovered on disk). Only true in the "fresh user" branch — see its use at
1416
+ // the restore-failure cleanup further down (XR-017 review follow-up).
1417
+ let dbWasFreshlyCreatedThisAttempt = false
1418
+
1255
1419
  if (knownDbs.length === 0) {
1256
1420
  // First launch after update or fresh user.
1257
1421
  // Probe for a legacy (no-timestamp) database file.
@@ -1267,6 +1431,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1267
1431
  const newName = `wallet-${keySuffix}-${chainStr}net-${ts}.db`
1268
1432
  await registerDb(keySuffix, chainStr, newName)
1269
1433
  knownDbs = [newName]
1434
+ dbWasFreshlyCreatedThisAttempt = true
1270
1435
  console.log(`[WalletContext] Created new timestamped DB: ${newName}`)
1271
1436
  }
1272
1437
  }
@@ -1325,9 +1490,27 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1325
1490
  `[WalletContext] backup restore · restored=${String(restored.restored)} · ` +
1326
1491
  `chunks=${restored.chunks} · reason=${restored.reason ?? 'none'}`
1327
1492
  )
1493
+ // See P1-backup-incomplete-generation: restoreOnImport.pickTarget falls back to
1494
+ // an unverified (no seal) target rather than blocking the import, so this is a
1495
+ // warning rather than a thrown error — but it must not pass silently, since the
1496
+ // replayed generation could be a partial mid-rotation snapshot. The screens
1497
+ // that drive `recoverWallet` surface this to the user directly (restoreUnverified
1498
+ // in ui/recoveryPrompts.ts); this warn is the equivalent for the import flow,
1499
+ // which has no such prompt.
1500
+ if (restored.restored && restored.verified === false) {
1501
+ console.warn(
1502
+ `[backup] restore completed but could not be verified as a complete ` +
1503
+ `generation · deviceId=${String(restored.deviceId)} · generation=${String(restored.generation)}`
1504
+ )
1505
+ }
1328
1506
  setBackupRestore(
1329
1507
  restored.restored
1330
- ? { phase: 'restored', chunks: restored.chunks, total: restored.chunks }
1508
+ ? {
1509
+ phase: 'restored',
1510
+ chunks: restored.chunks,
1511
+ total: restored.chunks,
1512
+ verified: restored.verified
1513
+ }
1331
1514
  : { phase: 'no-backup', chunks: 0, total: 0 }
1332
1515
  )
1333
1516
  } catch (e: any) {
@@ -1339,6 +1522,32 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1339
1522
  try {
1340
1523
  await phoneStorage.destroy()
1341
1524
  } catch {}
1525
+ // restoreOnImport's precondition is that the database is freshly migrated
1526
+ // and still empty of real data — but that is only actually guaranteed when
1527
+ // THIS attempt is the one that just created selectedDb (dbWasFreshlyCreated
1528
+ // ThisAttempt). rebuildWallet({restoreFromBackup:true}) takes this same path
1529
+ // to "recover over an already-onboarded wallet" (see restoreWallet.ts), and
1530
+ // recoverWallet.ts's confirmReplace does not check whether the newly
1531
+ // supplied secret differs from the one already active — so selectedDb can
1532
+ // instead be a pre-existing, already-registered database (this identity's
1533
+ // real, live wallet, or a legacy file just discovered on disk) that this
1534
+ // attempt only SELECTED, never created. Deleting that on a restore failure
1535
+ // would destroy locally-cached change-output/BRC-29 metadata the seed cannot
1536
+ // reconstruct (see XR-017 review follow-up). Only ever discard a database
1537
+ // this exact attempt created: a later build that skips another replay
1538
+ // (recoverWallet's "skip", or any future restoreFromBackup:false call) would
1539
+ // otherwise reselect this SAME partially replayed file via selectLatestDb and
1540
+ // publish it as a working wallet. Both steps are best-effort cleanup: the
1541
+ // ORIGINAL restore failure above is what must reach the caller, not a failure
1542
+ // to tidy up after it.
1543
+ if (dbWasFreshlyCreatedThisAttempt) {
1544
+ try {
1545
+ await unregisterDb(keySuffix, chainStr, selectedDb)
1546
+ } catch {}
1547
+ try {
1548
+ await SQLite.deleteDatabaseAsync(selectedDb)
1549
+ } catch {}
1550
+ }
1342
1551
  throw e
1343
1552
  }
1344
1553
  }
@@ -1362,6 +1571,20 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1362
1571
  console.error('[WalletContext] Failed to add local storage provider:', error)
1363
1572
  }
1364
1573
 
1574
+ // A raw database import (ui/importDatabases.ts) armed this instead of
1575
+ // restoreIntentRef: the imported database is already a complete local
1576
+ // copy, so there is nothing to replay, but it never ran the same
1577
+ // spendability reconciliation an encrypted restore runs above before
1578
+ // its balance is trusted and displayed (XR-079).
1579
+ if (reviewImportedCoinsRef.current) {
1580
+ reviewImportedCoinsRef.current = false
1581
+ try {
1582
+ await wallet.reviewSpendableOutputs(false, true)
1583
+ } catch (error) {
1584
+ console.error('[WalletContext] Post-import reconciliation failed:', error)
1585
+ }
1586
+ }
1587
+
1365
1588
  let migrationUserId: number | undefined
1366
1589
  try {
1367
1590
  const auth = await storageManager.getAuth()
@@ -1427,20 +1650,53 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1427
1650
  // module's own admin pass-through branch). Shared by the module's
1428
1651
  // deps below AND by wrapCreateActionForTokenInputs's wrapper further
1429
1652
  // down, so both use the exact same listing.
1430
- const listMandalaTokenOutpoints = async (): Promise<Set<string>> => {
1431
- try {
1432
- const { outputs } = await wallet.listOutputs(
1433
- { basket: MANDALA_BASKET, includeCustomInstructions: false, limit: 10000 } as never,
1434
- adminOriginator
1435
- )
1436
- return new Set(outputs.map((o: { outpoint: string }) => o.outpoint))
1437
- } catch {
1438
- // A wallet with no Mandala basket yet, or a storage fault -- treat
1439
- // as "no known token inputs" rather than blocking createAction;
1440
- // see permissionModule.ts's doc on this dep failing open.
1441
- return new Set()
1442
- }
1443
- }
1653
+ //
1654
+ // XR-039: paginated to completion via `listAllOutpoints` (a single
1655
+ // 10,000-row page silently truncated a larger basket, and a spend of
1656
+ // an input past that page read as "not a token input" -- the same
1657
+ // balance-truncation bug `core/localpay/build.ts`'s `listTokenBasket`
1658
+ // and `createRuntime.ts`'s `listTokenOutputs` were already fixed
1659
+ // for), and a genuine listing fault now PROPAGATES instead of being
1660
+ // swallowed into an authoritative-looking empty Set -- an empty Set
1661
+ // here reads as "confirmed no token inputs" to every caller, which a
1662
+ // storage fault or a wallet with no Mandala basket are not
1663
+ // distinguishable from without this throwing. The two callers
1664
+ // (`injectMandalaLabelIfTokenInputsPresent`, `anyInputIsTokenCoin`)
1665
+ // are exactly what now fails closed on that throw.
1666
+ const listMandalaTokenOutpoints = (): Promise<Set<string>> =>
1667
+ listAllOutpoints(
1668
+ async (limit, offset) =>
1669
+ await wallet.listOutputs(
1670
+ { basket: MANDALA_BASKET, includeCustomInstructions: false, limit, offset } as never,
1671
+ adminOriginator
1672
+ ),
1673
+ MANDALA_OUTPOINT_LIST_PAGE,
1674
+ MANDALA_OUTPOINT_LIST_MAX_PAGES
1675
+ )
1676
+
1677
+ // XR-041: resolves ONE outpoint named on a `relinquishOutput` call to
1678
+ // its decoded `{assetId, amount}`, from this device's OWN current
1679
+ // MANDALA_BASKET listing — `include: 'locking scripts'` is the one
1680
+ // difference from `listMandalaTokenOutpoints` above, since naming the
1681
+ // holding needs the script, not just the outpoint. Same admin-
1682
+ // originator, zero-prompt listing; same to-completion paging.
1683
+ const resolveMandalaOutputForRelinquish = (outpoint: string) =>
1684
+ resolveMandalaOutput(
1685
+ async (limit, offset) =>
1686
+ await wallet.listOutputs(
1687
+ {
1688
+ basket: MANDALA_BASKET,
1689
+ include: 'locking scripts',
1690
+ includeCustomInstructions: false,
1691
+ limit,
1692
+ offset
1693
+ } as never,
1694
+ adminOriginator
1695
+ ),
1696
+ outpoint,
1697
+ MANDALA_OUTPOINT_LIST_PAGE,
1698
+ MANDALA_OUTPOINT_LIST_MAX_PAGES
1699
+ )
1444
1700
 
1445
1701
  // Mandala's own P-module (schemeID 'mandala', basket MANDALA_BASKET =
1446
1702
  // 'p mandala') -- same routing mechanism as BTMS above
@@ -1451,7 +1707,8 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1451
1707
  adminOriginator,
1452
1708
  requestTokenAccess: mandalaPromptHandler,
1453
1709
  resolveAssetMetadata: resolveMandalaAssetMetadata,
1454
- listTokenOutpoints: listMandalaTokenOutpoints
1710
+ listTokenOutpoints: listMandalaTokenOutpoints,
1711
+ resolveMandalaOutput: resolveMandalaOutputForRelinquish
1455
1712
  })
1456
1713
 
1457
1714
  // Setup permissions with provided callbacks and BTMS module.
@@ -1518,10 +1775,17 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1518
1775
  // admitted (and therefore broadcast) releases inputs that are spent on
1519
1776
  // chain. It reads the settlement store LATE, off `mandalaRef`, because
1520
1777
  // the runtime is built below this line and replaced on every rebuild.
1778
+ //
1779
+ // XR-034: `mandalaEndpoints` (above, static for this build) is the
1780
+ // guard's ONLY "token settlement provably not in use" signal — never
1781
+ // `mandalaRef.current`, whose `undefined` also covers a runtime that
1782
+ // threw or is mid-rebuild, both of which can leave real settlement
1783
+ // rows unreadable rather than absent.
1521
1784
  newManagers.permissionsManager = guardVaultAccess(
1522
1785
  wrapAbortActionForSettlements(
1523
1786
  wrapCreateActionForTokenInputs(permissionsManager, listMandalaTokenOutpoints, adminOriginator),
1524
- () => mandalaRef.current?.store
1787
+ () => mandalaRef.current?.store,
1788
+ () => mandalaEndpoints !== undefined
1525
1789
  ),
1526
1790
  adminOriginator
1527
1791
  )
@@ -1819,7 +2083,12 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1819
2083
  // the drain so the parent goes out first.
1820
2084
  if (phoneStorage) {
1821
2085
  const sendWaiting = monitor._tasks.find(t => t.name === 'SendWaiting') as
1822
- | { processUnsent?: (reqApis: Array<{ txid: string; rawTx?: number[] }>, indent?: number) => Promise<string> }
2086
+ | {
2087
+ processUnsent?: (
2088
+ reqApis: Array<{ txid: string; rawTx?: number[] }>,
2089
+ indent?: number
2090
+ ) => Promise<string>
2091
+ }
1823
2092
  | undefined
1824
2093
  if (sendWaiting?.processUnsent) {
1825
2094
  const orig = sendWaiting.processUnsent.bind(sendWaiting)
@@ -1828,7 +2097,8 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1828
2097
  // row is the settlement drain's to broadcast, after `/submit`,
1829
2098
  // never the monitor's. Held here and dropped from this pass.
1830
2099
  const heldTokenTxids = await phoneStorage.holdTokenReqsForDrain(allReqApis as never)
1831
- const reqApis = heldTokenTxids.size > 0 ? allReqApis.filter(r => !heldTokenTxids.has(r.txid)) : allReqApis
2100
+ const reqApis =
2101
+ heldTokenTxids.size > 0 ? allReqApis.filter(r => !heldTokenTxids.has(r.txid)) : allReqApis
1832
2102
  if (heldTokenTxids.size > 0) TaskSendOffline.requestNow()
1833
2103
  let queuedTxids = new Set<string>()
1834
2104
  try {
@@ -1849,7 +2119,8 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1849
2119
  if (deferred > 0) TaskSendOffline.requestNow()
1850
2120
  if (ready.length === 0) {
1851
2121
  const notes: string[] = []
1852
- if (heldTokenTxids.size > 0) notes.push(`held ${heldTokenTxids.size} token req(s) for the settlement drain`)
2122
+ if (heldTokenTxids.size > 0)
2123
+ notes.push(`held ${heldTokenTxids.size} token req(s) for the settlement drain`)
1853
2124
  if (deferred > 0) notes.push(`deferred ${deferred} req(s) behind queued ancestors`)
1854
2125
  return notes.length > 0 ? `${notes.join('; ')}\n` : ''
1855
2126
  }
@@ -2166,6 +2437,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2166
2437
  // rebuildWallet until buildWallet consumes it. Explicit false still
2167
2438
  // allows the import screen to continue without restoring on retry.
2168
2439
  if (opts !== undefined) restoreIntentRef.current = opts.restoreFromBackup === true
2440
+ if (opts !== undefined) reviewImportedCoinsRef.current = opts.reviewImportedCoins === true
2169
2441
 
2170
2442
  // Provide the primary key and privileged key manager to authenticate the wallet
2171
2443
  await swm.providePrimaryKey(primaryKey)
@@ -2200,6 +2472,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2200
2472
  // Never leave the intent armed: the next build on this device would otherwise be
2201
2473
  // an auto-build on relaunch, which must not re-import over a live database.
2202
2474
  restoreIntentRef.current = false
2475
+ reviewImportedCoinsRef.current = false
2203
2476
  walletBuildingRef.current = false
2204
2477
  setWalletBuilding(false)
2205
2478
  console.error('[WalletContext] Error building mnemonic wallet:', error)
@@ -2237,6 +2510,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2237
2510
  // rebuildWallet until buildWallet consumes it. Explicit false still
2238
2511
  // allows the import screen to continue without restoring on retry.
2239
2512
  if (opts !== undefined) restoreIntentRef.current = opts.restoreFromBackup === true
2513
+ if (opts !== undefined) reviewImportedCoinsRef.current = opts.reviewImportedCoins === true
2240
2514
 
2241
2515
  await swm.providePrimaryKey(primaryKey)
2242
2516
 
@@ -2254,6 +2528,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2254
2528
  logWithTimestamp(F, 'Recovered key wallet build completed')
2255
2529
  } catch (error: any) {
2256
2530
  restoreIntentRef.current = false
2531
+ reviewImportedCoinsRef.current = false
2257
2532
  walletBuildingRef.current = false
2258
2533
  setWalletBuilding(false)
2259
2534
  console.error('[WalletContext] Error building wallet from recovered key:', error)
@@ -2265,73 +2540,78 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2265
2540
 
2266
2541
  // Tear down the current wallet and re-trigger auto-build.
2267
2542
  // Used after DB import and internally by switchNetwork.
2268
- const rebuildWallet = useCallback(async (opts?: { restoreFromBackup?: boolean }) => {
2269
- logWithTimestamp(F, 'Rebuilding wallet')
2270
- // Armed before teardown so the auto-build effect this triggers (via
2271
- // finalizeConfig below) replays the backup log the same way an explicit
2272
- // buildWalletFromMnemonic({ restoreFromBackup: true }) would.
2273
- restoreIntentRef.current = opts?.restoreFromBackup === true
2274
- // Any build already in flight belongs to the configuration being replaced.
2275
- const token = buildGenRef.current.bump()
2276
- // Invalidate Vault operations before the first teardown await. Otherwise a
2277
- // signer/listing already in flight can resume against the departing wallet.
2278
- vaultStore.clearScope()
2279
- vaultCeremony.cancel()
2543
+ const rebuildWallet = useCallback(
2544
+ async (opts?: { restoreFromBackup?: boolean; reviewImportedCoins?: boolean }) => {
2545
+ logWithTimestamp(F, 'Rebuilding wallet')
2546
+ // Armed before teardown so the auto-build effect this triggers (via
2547
+ // finalizeConfig below) replays the backup log the same way an explicit
2548
+ // buildWalletFromMnemonic({ restoreFromBackup: true }) would.
2549
+ restoreIntentRef.current = opts?.restoreFromBackup === true
2550
+ // Same arming pattern, for the raw-import reconciliation pass (XR-079).
2551
+ reviewImportedCoinsRef.current = opts?.reviewImportedCoins === true
2552
+ // Any build already in flight belongs to the configuration being replaced.
2553
+ const token = buildGenRef.current.bump()
2554
+ // Invalidate Vault operations before the first teardown await. Otherwise a
2555
+ // signer/listing already in flight can resume against the departing wallet.
2556
+ vaultStore.clearScope()
2557
+ vaultCeremony.cancel()
2280
2558
 
2281
- // Stop any running monitor and let its current pass drain before the
2282
- // storage teardown below closes the connection under it.
2283
- {
2284
- const monitor = monitorRef.current
2285
- if (monitor) {
2286
- monitorRef.current = null
2287
- await stopMonitorAndDrain(monitor)
2559
+ // Stop any running monitor and let its current pass drain before the
2560
+ // storage teardown below closes the connection under it.
2561
+ {
2562
+ const monitor = monitorRef.current
2563
+ if (monitor) {
2564
+ monitorRef.current = null
2565
+ await stopMonitorAndDrain(monitor)
2566
+ }
2288
2567
  }
2289
- }
2290
- // Same convention as monitorRef above: clear so a stale deferred header
2291
- // init or reconnect handler from the old build can't pair a leftover
2292
- // store/tracker across the rebuild.
2293
- offlineChaintracksRef.current = undefined
2294
- headerStoreRef.current = undefined
2295
-
2296
- // Close the current storage connection so the new build can open
2297
- // whichever DB file the registry selects.
2298
- if (storage?.db) {
2299
- try {
2300
- await storage.destroy()
2301
- } catch {}
2302
- }
2303
- // And drop the handle with it. Leaving a destroyed storage in state kept
2304
- // the screens reading the OLD chain's database until the new build
2305
- // replaced it — which is how a testnet wallet displayed mainnet money.
2306
- setStorage(null)
2307
- // The runtime holds this build's settlement store, which is a handle on
2308
- // the database just destroyed. Dropping it here is what stops a monitor
2309
- // task or a screen draining the departed wallet's tables.
2310
- mandalaRef.current = undefined
2311
- setMandala(undefined)
2312
- forgetSessionPsks()
2313
-
2314
- // Tear down current wallet state (but keep mnemonic / config)
2315
- vaultStore.clearScope()
2316
- updateManagers({})
2317
- walletBuiltRef.current = false
2318
- setWalletBuilt(false)
2319
- walletBuildingRef.current = false
2320
- setWalletBuilding(false)
2321
-
2322
- // Re-finalize with current config — triggers auto-build effect
2323
- const config = { wabUrl: 'noWAB', method: 'mnemonic', network: selectedNetwork, storageUrl: 'local' }
2324
- pendingAutoBuildRef.current = true
2325
- finalizeConfig(config)
2326
- logWithTimestamp(F, 'Wallet rebuild triggered')
2327
- // finalizeConfig above only requests the rebuild; without this,
2328
- // rebuildWallet's promise resolved before the auto-build effect had even
2329
- // run, so `await rebuildWallet(...)` callers (e.g. the import screens
2330
- // replacing an auto-created wallet) saw pre-rebuild managers and a
2331
- // pre-rebuild walletBuilt — silently skipping anything gated on the new
2332
- // wallet actually existing, such as recording a backup attestation.
2333
- await waitForRebuild(token)
2334
- }, [selectedNetwork, storage, finalizeConfig, waitForRebuild])
2568
+ // Same convention as monitorRef above: clear so a stale deferred header
2569
+ // init or reconnect handler from the old build can't pair a leftover
2570
+ // store/tracker across the rebuild.
2571
+ offlineChaintracksRef.current = undefined
2572
+ headerStoreRef.current = undefined
2573
+
2574
+ // Close the current storage connection so the new build can open
2575
+ // whichever DB file the registry selects.
2576
+ if (storage?.db) {
2577
+ try {
2578
+ await storage.destroy()
2579
+ } catch {}
2580
+ }
2581
+ // And drop the handle with it. Leaving a destroyed storage in state kept
2582
+ // the screens reading the OLD chain's database until the new build
2583
+ // replaced it — which is how a testnet wallet displayed mainnet money.
2584
+ setStorage(null)
2585
+ // The runtime holds this build's settlement store, which is a handle on
2586
+ // the database just destroyed. Dropping it here is what stops a monitor
2587
+ // task or a screen draining the departed wallet's tables.
2588
+ mandalaRef.current = undefined
2589
+ setMandala(undefined)
2590
+ forgetSessionPsks()
2591
+
2592
+ // Tear down current wallet state (but keep mnemonic / config)
2593
+ vaultStore.clearScope()
2594
+ updateManagers({})
2595
+ walletBuiltRef.current = false
2596
+ setWalletBuilt(false)
2597
+ walletBuildingRef.current = false
2598
+ setWalletBuilding(false)
2599
+
2600
+ // Re-finalize with current config — triggers auto-build effect
2601
+ const config = { wabUrl: 'noWAB', method: 'mnemonic', network: selectedNetwork, storageUrl: 'local' }
2602
+ pendingAutoBuildRef.current = true
2603
+ finalizeConfig(config)
2604
+ logWithTimestamp(F, 'Wallet rebuild triggered')
2605
+ // finalizeConfig above only requests the rebuild; without this,
2606
+ // rebuildWallet's promise resolved before the auto-build effect had even
2607
+ // run, so `await rebuildWallet(...)` callers (e.g. the import screens
2608
+ // replacing an auto-created wallet) saw pre-rebuild managers and a
2609
+ // pre-rebuild walletBuilt — silently skipping anything gated on the new
2610
+ // wallet actually existing, such as recording a backup attestation.
2611
+ await waitForRebuild(token)
2612
+ },
2613
+ [selectedNetwork, storage, finalizeConfig, waitForRebuild]
2614
+ )
2335
2615
 
2336
2616
  // Switch network: tear down wallet, update config, and rebuild on new chain
2337
2617
  const switchNetwork = useCallback(
@@ -2487,8 +2767,47 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2487
2767
  void replayPendingAborts({
2488
2768
  wallet: managers.permissionsManager as {
2489
2769
  abortAction: (args: { reference: string }, originator?: string) => Promise<{ aborted?: boolean } | void>
2770
+ verifyHmac: NonNullable<typeof managers.permissionsManager>['verifyHmac']
2490
2771
  },
2491
2772
  storage
2773
+ }).then(result => {
2774
+ // XR-102: an entry replayPendingAborts dropped as untrusted (missing or
2775
+ // mismatching authority tag) never called abortAction at all, so
2776
+ // whatever it named — if it was even real — is unaffected; the only
2777
+ // thing to tell the user is that a stored release record was ignored,
2778
+ // in case a payment still looks stuck (Activity's manual per-row
2779
+ // Cancel remains available either way, and does not depend on this
2780
+ // queue).
2781
+ if (result.droppedUntrusted > 0) {
2782
+ setLocalPayNotification({
2783
+ message: `${t('local_pay_pending_abort_dropped_title')}. ${t('local_pay_pending_abort_dropped_body')}`,
2784
+ type: 'error'
2785
+ })
2786
+ }
2787
+ })
2788
+ // P1-3: a decline is the payee's own unverifiable claim that nothing was
2789
+ // queued (see build.ts's `watchDeclinedAbort`). Checked at the same
2790
+ // cadence as the pending-abort replay above — wallet build and every
2791
+ // reconnect — so a declined txid that reaches the chain anyway is
2792
+ // surfaced as a background notice rather than silently missed. Never
2793
+ // blocks anything: the inputs were already freed when the decline
2794
+ // was recorded.
2795
+ void verifyDeclinedAborts({
2796
+ storage,
2797
+ getStatusForTxids: async txids => {
2798
+ const services = storage.getServices() as {
2799
+ getStatusForTxids?: (txids: string[]) => Promise<{ results?: { txid: string; status: string }[] }>
2800
+ }
2801
+ if (typeof services.getStatusForTxids !== 'function') return {}
2802
+ return services.getStatusForTxids(txids)
2803
+ }
2804
+ }).then(surfaced => {
2805
+ if (surfaced.length > 0) {
2806
+ setLocalPayNotification({
2807
+ message: `${t('local_pay_decline_broadcast_title')}. ${t('local_pay_decline_broadcast_body')}`,
2808
+ type: 'error'
2809
+ })
2810
+ }
2492
2811
  })
2493
2812
 
2494
2813
  // Also run when connectivity is restored
@@ -2732,13 +3051,23 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2732
3051
  }
2733
3052
  }, [])
2734
3053
 
2735
- const logout = useCallback(() => {
3054
+ const logout = useCallback((): Promise<boolean> => {
2736
3055
  logWithTimestamp(F, 'Logout')
2737
3056
  // Synchronous on purpose: invalidate transfer tokens and release any PIN /
2738
3057
  // hardware session before monitor or storage teardown yields.
2739
3058
  vaultStore.clearScope()
2740
3059
  vaultCeremony.cancel()
2741
- ;(async () => {
3060
+ // XR-018: a live paired RPC socket otherwise outlives logout/wallet
3061
+ // deletion — the peer would keep dispatching allowlisted BRC-100 methods
3062
+ // against a wallet the user believes they've logged out of.
3063
+ disconnectActivePairedSession()
3064
+ // The IIFE's promise IS returned (unlike the old fire-and-forget version):
3065
+ // XR-107 needs the caller to await the verified outcome of the secret
3066
+ // erasure below, not just the synchronous kickoff. This does not
3067
+ // reintroduce the yield-before-first-synchronous-step problem the old
3068
+ // comment warned about — everything above this point already ran
3069
+ // synchronously before any promise existed to await.
3070
+ return (async () => {
2742
3071
  // Tear the wallet down the same way rebuildWallet does. Logout used to
2743
3072
  // skip this, which orphaned a running monitor AND left the SQLite
2744
3073
  // connection open: a re-import of the same phrase then opened a second
@@ -2754,10 +3083,26 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2754
3083
  }
2755
3084
  offlineChaintracksRef.current = undefined
2756
3085
  headerStoreRef.current = undefined
2757
- if (storage?.db) {
3086
+ backupIdentityRef.current = null
3087
+ if (storage) {
3088
+ const dbName = storage.dbName
3089
+ if (storage.db) {
3090
+ try {
3091
+ await storage.destroy()
3092
+ } catch {}
3093
+ }
3094
+ // XQ-008: destroy() only closes the connection — it never deleted the
3095
+ // underlying .db file(s) or the walletDbRegistry entry that points at
3096
+ // them, so a "deleted" wallet's complete plaintext history stayed on
3097
+ // disk indefinitely and silently reattached with everything intact if
3098
+ // the same mnemonic was ever built again on this device. dbName is a
3099
+ // plain field that survives destroy(), so it is still readable after
3100
+ // the connection is closed.
2758
3101
  try {
2759
- await storage.destroy()
2760
- } catch {}
3102
+ await purgeRegisteredDbFiles(dbName, SQLite.deleteDatabaseAsync)
3103
+ } catch (err) {
3104
+ console.warn('[logout] failed to purge wallet db file(s)/registry', err)
3105
+ }
2761
3106
  }
2762
3107
  setStorage(null)
2763
3108
  mandalaRef.current = undefined
@@ -2780,15 +3125,46 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2780
3125
  try {
2781
3126
  const keys = await AsyncStorage.getAllKeys()
2782
3127
  const stale = keys.filter(k => k.startsWith('cached_wallet_balance_'))
3128
+ // XR-058: the legacy (pre-network-scoping) `Balance` component wrote
3129
+ // an exact, unscoped `cached_wallet_balance` key with no trailing
3130
+ // underscore, which the prefix filter above never matches. Nothing
3131
+ // reads that key any more, but an install that still carries one
3132
+ // from before the fix should have it swept here too.
3133
+ if (await AsyncStorage.getItem('cached_wallet_balance')) stale.push('cached_wallet_balance')
2783
3134
  if (stale.length > 0) await AsyncStorage.multiRemove(stale)
2784
3135
  } catch (err) {
2785
3136
  console.warn('[logout] failed to clear cached balance', err)
2786
3137
  }
2787
3138
 
3139
+ // A departed wallet's push cursor must not linger to be misread as THIS device
3140
+ // already having backed up the next wallet built here — deviceId never changes
3141
+ // across a logout/re-import on the same install (see deviceId.ts and XR-009), so an
3142
+ // unscoped Wallet Check read would otherwise inherit it. Sweeps every identity's
3143
+ // cursor, not just the one just logged out of, same as the balance-cache sweep above.
3144
+ try {
3145
+ const keys = await AsyncStorage.getAllKeys()
3146
+ const stale = keys.filter(k => k.startsWith('backupCursor-'))
3147
+ if (stale.length > 0) await AsyncStorage.multiRemove(stale)
3148
+ } catch (err) {
3149
+ console.warn('[logout] failed to clear backup cursor', err)
3150
+ }
3151
+
2788
3152
  // Awaited, and it removes the KEK along with the ciphertexts: leaving the
2789
3153
  // key behind would make the next cold start prompt for a wallet that no
2790
3154
  // longer exists. Works while locked, since deleting needs no key.
2791
- await deleteAllWalletKeys()
3155
+ //
3156
+ // XR-107: its result is real, read-back-verified evidence of whether a
3157
+ // legacy plaintext mnemonic/recoveredKey/password actually got erased —
3158
+ // not a guess. A `false` here must fail closed: skip the attestation
3159
+ // clear and the navigation below (both of which tell the rest of the
3160
+ // app "this wallet is gone") and report the failure to the caller
3161
+ // instead, so the UI can show an error and let the user retry rather
3162
+ // than silently behaving as though "Delete Wallet" fully succeeded.
3163
+ const erased = await deleteAllWalletKeys()
3164
+ if (!erased) {
3165
+ console.warn('[logout] legacy secret erasure could not be verified; not reporting Delete Wallet as complete')
3166
+ return false
3167
+ }
2792
3168
 
2793
3169
  // The attestation is per wallet. "Delete Wallet" routes here, so leaving
2794
3170
  // it behind would let the NEXT wallet on this device inherit a backup it
@@ -2804,6 +3180,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2804
3180
  const { router } = loadExpoRouter()
2805
3181
  router.dismissAll()
2806
3182
  router.replace('/')
3183
+ return true
2807
3184
  })()
2808
3185
  }, [deleteAllWalletKeys, storage])
2809
3186
 
@@ -2835,7 +3212,14 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2835
3212
  const res = await fetch(`${wocBase}/v1/bsv/${chain}/tx/${txid}/proof/bump`)
2836
3213
 
2837
3214
  if (res.ok) {
2838
- const bumpHex = (await res.text()).trim()
3215
+ // XR-059 remainder: a compromised/misbehaving configured indexer must
3216
+ // not be able to force an unbounded hex-decode here just by sending
3217
+ // back an oversized (or malformed) proof body — same guard as
3218
+ // address.ts's parseWocBeefBody / beefRepair.ts's refetchAtomicBeef.
3219
+ // An oversized/invalid proof is indistinguishable from "no usable
3220
+ // proof yet", so this fails closed to 'pending', exactly like a 404.
3221
+ const bumpHex = boundedHexResponse(await res.text(), MAX_HEX_RESPONSE_CHARS)
3222
+ if (bumpHex === undefined) return 'pending'
2839
3223
  const merklePath = MerklePath.fromHex(bumpHex)
2840
3224
  const merkleRoot = merklePath.computeRoot(txid)
2841
3225
  const ct = offlineChaintracksRef.current
@@ -2867,7 +3251,13 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2867
3251
  fetchRawTx: async () => {
2868
3252
  const r = await fetch(`${wocBase}/v1/bsv/${chain}/tx/${txid}/hex`)
2869
3253
  if (!r.ok) throw new Error(`raw tx fetch failed: ${r.status}`)
2870
- return Utils.toArray((await r.text()).trim(), 'hex')
3254
+ // XR-059 remainder: same unbounded-hex-decode gap as the BUMP
3255
+ // fetch above, on the raw-tx body this time. Throwing here (like
3256
+ // the !r.ok case just above) is refreshProof's existing
3257
+ // fail-closed shape for a raw-tx read it cannot trust.
3258
+ const hex = boundedHexResponse(await r.text(), MAX_HEX_RESPONSE_CHARS)
3259
+ if (hex === undefined) throw new Error('raw tx fetch: response too large or not valid hex')
3260
+ return Utils.toArray(hex, 'hex')
2871
3261
  }
2872
3262
  })
2873
3263
  setTxStatusVersion(v => v + 1)
@@ -2881,6 +3271,9 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2881
3271
  try {
2882
3272
  const head = await fetch(`${wocBase}/v1/bsv/${chain}/tx/hash/${txid}`)
2883
3273
  onChain = head.ok
3274
+ // XR-030: any other non-OK (429/500/401/403/...) is a service
3275
+ // problem, not proof of absence — only a 404 is authoritative.
3276
+ if (!onChain && !isChainAbsenceConfirmed(head.status)) return 'pending'
2884
3277
  } catch {
2885
3278
  // Network unreachable — we cannot prove absence, so never fail the tx.
2886
3279
  return 'pending'
@@ -2897,9 +3290,14 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2897
3290
  if (!tx || tx.status === 'failed' || tx.status === 'completed') return 'pending'
2898
3291
 
2899
3292
  // A queued/posting offline payment is expected not to be on chain yet —
2900
- // failing it would release inputs the payee still holds.
3293
+ // failing it would release inputs the payee still holds. Same for an
3294
+ // 'import_hold' row (XR-085): a raw database import quarantines a
3295
+ // copied-in queued/posting row under that status precisely because it
3296
+ // may already be broadcast/handed off, so this lookup has to see it
3297
+ // too or shouldFailUnprovenTx below never learns the row is held and
3298
+ // can fail it on a stale, in-flight tx status alone.
2901
3299
  const db = storage.sqliteDb
2902
- const rows = db ? await findOfflineActions(db, { status: ['queued', 'posting'] }) : []
3300
+ const rows = db ? await findOfflineActions(db, { status: ['queued', 'posting', 'import_hold'] }) : []
2903
3301
  const offlineStatus = rows.find(r => r.txid === txid)?.status
2904
3302
  if (
2905
3303
  shouldFailUnprovenTx({
@@ -2991,20 +3389,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2991
3389
  const db = (storage as any)?.sqliteDb
2992
3390
  if (!db?.runAsync) return 'DB not available'
2993
3391
  try {
2994
- const rows = (await db.getAllAsync(
2995
- `SELECT o.outputId AS outputId, o.satoshis AS satoshis, t.txid AS txid
2996
- FROM outputs o JOIN transactions t ON t.transactionId = o.spentBy
2997
- WHERE t.status = 'failed'`
2998
- )) as { outputId: number; satoshis: number; txid: string }[]
2999
- if (!rows || rows.length === 0) return 'No stuck reservations found.'
3000
- await db.runAsync(
3001
- `UPDATE outputs SET spentBy = NULL, spendable = 1
3002
- WHERE spentBy IN (SELECT transactionId FROM transactions WHERE status = 'failed')`
3003
- )
3004
- const detail = rows
3005
- .map(r => ` • ${r.satoshis} sat (output ${r.outputId}) ← failed ${String(r.txid).slice(0, 12)}…`)
3006
- .join('\n')
3007
- return `✓ Released ${rows.length} stuck reservation(s):\n${detail}`
3392
+ return await releaseStuckReservationsOnDb(db)
3008
3393
  } catch (e: any) {
3009
3394
  return `⚠ Release failed: ${e.message}`
3010
3395
  }
@@ -3113,21 +3498,101 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3113
3498
  continue
3114
3499
  }
3115
3500
 
3116
- spentCount++
3117
- lines.push(` SPENT: ${o.txid}:${o.vout} (${o.satoshis} sat) → by ${spendingTxid}`)
3118
- await storage.updateOutput(o.outputId, { spendable: false as any })
3501
+ // Second-source corroboration (misc-p2-01): a single WoC 200-with-txid
3502
+ // response is not enough to permanently mark a UTXO unspendable — WoC
3503
+ // can be wrong, stale, or answering for the wrong network, and this
3504
+ // path never writes spentBy, so nothing can ever restore a wrong call
3505
+ // later. Require the toolbox's own configured getUtxoStatus providers
3506
+ // to ALSO report the output as no longer a UTXO before committing.
3507
+ let utxoStatus: { status: 'success' | 'error'; isUtxo?: boolean } = { status: 'error' }
3508
+ try {
3509
+ const scriptedRows = await storage.findOutputs({ partial: { outputId: o.outputId } })
3510
+ const scripted = scriptedRows[0]
3511
+ const utxoServices = storage.getServices() as {
3512
+ hashOutputScript?: (script: string) => string
3513
+ getUtxoStatus?: (
3514
+ output: string,
3515
+ outputFormat?: string,
3516
+ outpoint?: string
3517
+ ) => Promise<{ status: 'success' | 'error'; isUtxo?: boolean }>
3518
+ }
3519
+ if (scripted?.lockingScript && utxoServices.hashOutputScript && utxoServices.getUtxoStatus) {
3520
+ const scriptHash = utxoServices.hashOutputScript(Utils.toHex(scripted.lockingScript))
3521
+ const result = await utxoServices.getUtxoStatus(scriptHash, undefined, `${o.txid}.${o.vout}`)
3522
+ utxoStatus = { status: result.status, isUtxo: result.isUtxo }
3523
+ }
3524
+ } catch {
3525
+ utxoStatus = { status: 'error' }
3526
+ }
3119
3527
 
3120
- if (!spendingTxid) continue
3528
+ const markUnspendable = shouldMarkUnspendable({
3529
+ wocProbe: probe,
3530
+ wocSpendingTxid: spendingTxid,
3531
+ utxoStatus
3532
+ })
3533
+ if (!markUnspendable) {
3534
+ console.warn(
3535
+ `[walletCheck] WoC claims ${o.txid}:${o.vout} spent by ${spendingTxid || '(no txid)'} but the second source did not corroborate — leaving spendable`
3536
+ )
3537
+ lines.push(
3538
+ ` SPENT (unconfirmed by 2nd source): ${o.txid}:${o.vout} (${o.satoshis} sat) — claimed spender ${spendingTxid || '(no txid)'}, left spendable`
3539
+ )
3540
+ continue
3541
+ }
3542
+
3543
+ // XR-031: markUnspendable only means two independent chain-service
3544
+ // oracles AGREE the output is spent — neither of them is the spending
3545
+ // transaction. Fetch and parse the alleged spender's own BEEF and
3546
+ // require it to actually consume this exact outpoint BEFORE
3547
+ // committing spendable:false; a claim that fails to fetch, fails to
3548
+ // parse, hashes to a different tx, or simply doesn't reference this
3549
+ // outpoint is left spendable rather than mutated.
3550
+ if (!spendingTxid) continue // shouldMarkUnspendable already requires this; narrows the type below.
3551
+ let spenderTx: Transaction | undefined
3121
3552
  try {
3122
3553
  const beefResp = await throttledFetch(`${wocBase}/tx/${spendingTxid}/beef`)
3123
3554
  if (!beefResp.ok) {
3124
- lines.push(` ↳ BEEF fetch failed (HTTP ${beefResp.status}), skipping change recovery`)
3555
+ lines.push(
3556
+ ` SPENT (unverified, spender BEEF fetch HTTP ${beefResp.status}): ${o.txid}:${o.vout} — left spendable`
3557
+ )
3125
3558
  continue
3126
3559
  }
3127
3560
  const beefHex = await beefResp.text()
3128
3561
  const beefBytes = Utils.toArray(beefHex, 'hex')
3129
3562
  const tx = Transaction.fromBEEF(beefBytes)
3130
- const atomicBeef = tx.toAtomicBEEF()
3563
+ const confirmed = spenderConsumesOutpoint({
3564
+ parsedTxid: tx.id('hex'),
3565
+ expectedTxid: spendingTxid,
3566
+ inputs: tx.inputs,
3567
+ outpoint: { txid: o.txid, vout: o.vout }
3568
+ })
3569
+ if (!confirmed) {
3570
+ lines.push(
3571
+ ` SPENT (unverified, spender does not reference this outpoint): ${o.txid}:${o.vout} — left spendable`
3572
+ )
3573
+ continue
3574
+ }
3575
+ spenderTx = tx
3576
+ } catch (e: any) {
3577
+ lines.push(
3578
+ ` SPENT (unverified, could not parse spender BEEF: ${e.message}): ${o.txid}:${o.vout} — left spendable`
3579
+ )
3580
+ continue
3581
+ }
3582
+
3583
+ spentCount++
3584
+ lines.push(` SPENT: ${o.txid}:${o.vout} (${o.satoshis} sat) → by ${spendingTxid}`)
3585
+ // Paper trail for a repair pass: `spendingDescription` is a free-text
3586
+ // column nothing else in this app reads or writes (unlike
3587
+ // `customInstructions`, which carries live BRC-42 derivation data
3588
+ // other flows depend on), so it is safe to repurpose as a note here.
3589
+ await storage.updateOutput(o.outputId, {
3590
+ spendable: false as any,
3591
+ spendingDescription: JSON.stringify({ claimedSpender: spendingTxid, checkedAt: new Date().toISOString() })
3592
+ } as any)
3593
+
3594
+ try {
3595
+ const atomicBeef = spenderTx.toAtomicBEEF()
3131
3596
 
3132
3597
  const changeOutputs = await storage.findOutputs({
3133
3598
  partial: { change: true as any, spendable: false as any },
@@ -3222,6 +3687,8 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3222
3687
  buildWalletFromRecoveredKey,
3223
3688
  backupRestore,
3224
3689
  getBackupRestore,
3690
+ getBackupPseudonym,
3691
+ getWalletBuilt,
3225
3692
  switchNetwork,
3226
3693
  rebuildWallet,
3227
3694
  storage,
@@ -3269,6 +3736,8 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3269
3736
  buildWalletFromRecoveredKey,
3270
3737
  backupRestore,
3271
3738
  getBackupRestore,
3739
+ getBackupPseudonym,
3740
+ getWalletBuilt,
3272
3741
  switchNetwork,
3273
3742
  rebuildWallet,
3274
3743
  storage,