@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
@@ -1,5 +1,6 @@
1
1
  import type { SQLiteDatabase } from 'expo-sqlite'
2
2
  import type { BindValue } from '../methods/offlineActions'
3
+ import { devLog } from '../../logging'
3
4
 
4
5
  /**
5
6
  * SQL statements to create all wallet storage tables
@@ -156,6 +157,15 @@ export async function createTables(db: SQLiteDatabase): Promise<void> {
156
157
  CREATE INDEX IF NOT EXISTS idx_transactions_txid ON transactions(txid);
157
158
  `)
158
159
 
160
+ // NEW-01: a device that created this table before this migration existed
161
+ // keeps it; CREATE TABLE IF NOT EXISTS cannot add the column, so the guarded
162
+ // ALTER does (ensureTransactionsColumns, defined below — hoisted). Called
163
+ // here, inside createTables, rather than only from StorageExpoSQLite.migrate,
164
+ // so every direct createTables() caller (this schema file's own tests
165
+ // included) gets these columns too, exactly like ensureTokenSettlementColumns
166
+ // below.
167
+ await ensureTransactionsColumns(db)
168
+
159
169
  // Commissions table
160
170
  await db.execAsync(`
161
171
  CREATE TABLE IF NOT EXISTS commissions (
@@ -423,6 +433,7 @@ export async function createMandalaSettlementTables(
423
433
  overlayIdentityKey TEXT NOT NULL,
424
434
  admissionOutputsJson TEXT,
425
435
  admissionSignatureHex TEXT,
436
+ relevantVout INTEGER,
426
437
  refusedCode TEXT,
427
438
  refusedPayloadHash TEXT,
428
439
  poisonedByTxid TEXT,
@@ -511,6 +522,65 @@ export async function ensureOfflineActionsColumns(db: {
511
522
  }
512
523
  }
513
524
 
525
+ /**
526
+ * NEW-01: `@bsv/wallet-toolbox-mobile`'s BRC-177 `noSendExpiry` lifecycle
527
+ * (early-reclaim actions, `armNoSendExpiry`, `abortAction`,
528
+ * `updateTransactionStatus`) reads and writes these `transactions` columns
529
+ * unconditionally — not only when a BRC-177 action is actually used.
530
+ * `protectNoSendExpiryReclaimInputOnFailure`, the guard every 'failed'
531
+ * transition runs through, filters on `noSendExpiryReclaimTxid`: without this
532
+ * column that WHERE clause throws "no such column", not "no match", so NO
533
+ * failed-transition of a transaction with a txid can complete — `abortAction`
534
+ * of any signed action, a failed broadcast, a proof-check timeout, and
535
+ * `reviewStatus`'s own `failInvalidReqTxs` sweep all reach it. This app never
536
+ * creates a BRC-177 protected action itself (`supportsNoSendExpiryPersistence`
537
+ * is not overridden and defaults to `false`, so `armNoSendExpiry` always
538
+ * throws `WERR_NOT_IMPLEMENTED`), but the vendor's generic failure path does
539
+ * not gate on that — every row still needs these columns to exist, forever
540
+ * NULL in practice here.
541
+ *
542
+ * Types and names taken from `TableTransaction` in
543
+ * `@bsv/wallet-toolbox-mobile`'s `out/index.mobile.d.cts`. All nullable, no
544
+ * defaults: an existing row reads back every one of these as `undefined`,
545
+ * which is exactly what "this transaction never touched BRC-177" already
546
+ * means to every caller.
547
+ */
548
+ const TRANSACTIONS_COLUMNS: { name: string; ddl: string }[] = [
549
+ { name: 'noSendExpiryMode', ddl: 'ALTER TABLE transactions ADD COLUMN noSendExpiryMode TEXT' },
550
+ { name: 'noSendExpiryValue', ddl: 'ALTER TABLE transactions ADD COLUMN noSendExpiryValue INTEGER' },
551
+ { name: 'noSendExpiryDeadline', ddl: 'ALTER TABLE transactions ADD COLUMN noSendExpiryDeadline INTEGER' },
552
+ { name: 'noSendExpiryState', ddl: 'ALTER TABLE transactions ADD COLUMN noSendExpiryState TEXT' },
553
+ { name: 'noSendExpiryAnchorTxid', ddl: 'ALTER TABLE transactions ADD COLUMN noSendExpiryAnchorTxid TEXT' },
554
+ { name: 'noSendExpiryAnchorVout', ddl: 'ALTER TABLE transactions ADD COLUMN noSendExpiryAnchorVout INTEGER' },
555
+ { name: 'noSendExpiryReleasedAt', ddl: 'ALTER TABLE transactions ADD COLUMN noSendExpiryReleasedAt INTEGER' },
556
+ { name: 'noSendExpiryObservedAt', ddl: 'ALTER TABLE transactions ADD COLUMN noSendExpiryObservedAt INTEGER' },
557
+ { name: 'noSendExpiryReclaimTxid', ddl: 'ALTER TABLE transactions ADD COLUMN noSendExpiryReclaimTxid TEXT' },
558
+ { name: 'noSendExpiryReclaimRawTx', ddl: 'ALTER TABLE transactions ADD COLUMN noSendExpiryReclaimRawTx BLOB' },
559
+ {
560
+ name: 'noSendExpiryReclaimDerivationPrefix',
561
+ ddl: 'ALTER TABLE transactions ADD COLUMN noSendExpiryReclaimDerivationPrefix TEXT'
562
+ },
563
+ {
564
+ name: 'noSendExpiryReclaimDerivationSuffix',
565
+ ddl: 'ALTER TABLE transactions ADD COLUMN noSendExpiryReclaimDerivationSuffix TEXT'
566
+ },
567
+ {
568
+ name: 'noSendExpiryReclaimSatoshis',
569
+ ddl: 'ALTER TABLE transactions ADD COLUMN noSendExpiryReclaimSatoshis INTEGER'
570
+ }
571
+ ]
572
+
573
+ export async function ensureTransactionsColumns(db: {
574
+ getAllAsync(sql: string, params: BindValue[]): Promise<unknown[]>
575
+ execAsync(sql: string): Promise<unknown>
576
+ }): Promise<void> {
577
+ const info = (await db.getAllAsync('PRAGMA table_info(transactions)', [])) as { name: string }[]
578
+ const have = new Set(info.map(c => c.name))
579
+ for (const col of TRANSACTIONS_COLUMNS) {
580
+ if (!have.has(col.name)) await db.execAsync(col.ddl)
581
+ }
582
+ }
583
+
514
584
  /**
515
585
  * The same doctrine for `token_settlements`, which shipped before it had a
516
586
  * `reference` column and cannot be re-created over live rows.
@@ -522,7 +592,13 @@ export async function ensureOfflineActionsColumns(db: {
522
592
  * wallet action reference — so the backfill is simply the next hand-over.
523
593
  */
524
594
  const TOKEN_SETTLEMENT_COLUMNS: { name: string; ddl: string }[] = [
525
- { name: 'reference', ddl: 'ALTER TABLE token_settlements ADD COLUMN reference TEXT' }
595
+ { name: 'reference', ddl: 'ALTER TABLE token_settlements ADD COLUMN reference TEXT' },
596
+ // XR-038: the wallet-relevant output index, so a cached admission for some
597
+ // OTHER output of the same txid can never stand in for this one. Nullable,
598
+ // no default — an existing row reads back `relevantVout === undefined`,
599
+ // which `postTokenStep` reads as 0 (the payee's-output convention), exactly
600
+ // as it always has for every row written before this column existed.
601
+ { name: 'relevantVout', ddl: 'ALTER TABLE token_settlements ADD COLUMN relevantVout INTEGER' }
526
602
  ]
527
603
 
528
604
  export async function ensureTokenSettlementColumns(db: {
@@ -532,6 +608,54 @@ export async function ensureTokenSettlementColumns(db: {
532
608
  const info = (await db.getAllAsync('PRAGMA table_info(token_settlements)', [])) as { name: string }[]
533
609
  const have = new Set(info.map(c => c.name))
534
610
  for (const col of TOKEN_SETTLEMENT_COLUMNS) {
535
- if (!have.has(col.name)) await db.execAsync(col.ddl)
611
+ if (have.has(col.name)) continue
612
+ await db.execAsync(col.ddl)
613
+ // XR-033: this ALTER just gave every existing row a NULL `reference`, and
614
+ // the abort guard's primary check (`getSettlementByReference`) can never
615
+ // match a NULL one against any reference — so backfill it now, in the
616
+ // same migration step, rather than leaving it to "the next hand-over"
617
+ // (which never comes for a row already stuck in a blocked state).
618
+ if (col.name === 'reference') await backfillLegacyTokenSettlementReferences(db)
619
+ }
620
+ }
621
+
622
+ /**
623
+ * XR-033: resolves each pre-migration row's `reference` from `transactions`,
624
+ * the SAME table `abortAction({reference})` itself matches a reference
625
+ * against (`findTransactions({partial:{reference}})`) — so this backfills
626
+ * from the one mapping that is already authoritative, rather than guessing.
627
+ *
628
+ * Scoped to rows that both need it and can be resolved: still blocked (the
629
+ * same states `abortGuard.ts`'s `ABORT_BLOCKED_SETTLEMENT_STATES` lists —
630
+ * duplicated here, not imported, for the reason `settlementStore.ts` gives:
631
+ * this schema file is statements, not cross-module logic) and whose
632
+ * transaction row still exists to resolve from. A row that cannot be
633
+ * resolved (its transaction is gone) is left NULL; the abort guard's own
634
+ * second, coarser check (`hasUnresolvedLegacyBlockedRows`) covers that case
635
+ * without this migration needing to.
636
+ *
637
+ * Never throws: this runs inside the ADD COLUMN step of the wallet's whole
638
+ * migration ladder, and `transactions` — always present in the real app,
639
+ * created earlier in this same `createTables` — is not guaranteed by this
640
+ * function's own narrow signature. A device where the backfill itself cannot
641
+ * run is exactly what `hasUnresolvedLegacyBlockedRows` exists to catch at
642
+ * `abortAction` time instead, so a failure here costs that coarser refusal,
643
+ * never a broken migration.
644
+ */
645
+ async function backfillLegacyTokenSettlementReferences(db: {
646
+ execAsync(sql: string): Promise<unknown>
647
+ }): Promise<void> {
648
+ try {
649
+ await db.execAsync(`
650
+ UPDATE token_settlements
651
+ SET reference = (
652
+ SELECT reference FROM transactions WHERE transactions.txid = token_settlements.txid
653
+ )
654
+ WHERE reference IS NULL
655
+ AND state IN ('held','handed_over','submitting','admitted','broadcast')
656
+ AND EXISTS (SELECT 1 FROM transactions WHERE transactions.txid = token_settlements.txid)
657
+ `)
658
+ } catch (e) {
659
+ devLog('[createTables] could not backfill legacy token_settlements references:', e)
536
660
  }
537
661
  }
@@ -10,19 +10,53 @@ export interface Connection {
10
10
  protocolID: string // JSON-stringified WalletProtocol
11
11
  connectedAt: number
12
12
  status: 'active' | 'disconnected'
13
+ /** XR-027: HMAC over (origin, sessionId, protocolID, backendIdentityKey),
14
+ * computed by an ADMIN-scoped wallet under the `connection authority`
15
+ * namespace reserved in core/services/vault/guard.ts -- see
16
+ * core/services/connectionAuthority.ts. Absent on a record saved before
17
+ * this fix, or one that never got tagged; callers must treat that exactly
18
+ * like a tag that fails verification (needs re-approval), never as
19
+ * implicitly trusted. */
20
+ authorityTag?: string
13
21
  }
14
22
 
15
23
  const STORAGE_KEY = 'connections'
16
24
 
17
25
  class ConnectionStore {
18
26
  connections: Connection[] = []
27
+ /** XR-027: a tag the pairing/reconnect screens compute with their own
28
+ * admin-scoped wallet BEFORE calling connect() -- add() below (called from
29
+ * deep inside connect()'s websocket-open callback, which never sees an
30
+ * admin wallet) consumes it in the same synchronous step that creates the
31
+ * record, so a freshly approved connection is never observably tagless in
32
+ * between. Never persisted and never part of the observed connection
33
+ * list; mobx wraps it as an ObservableMap, but nothing here relies on
34
+ * that reactivity. */
35
+ private pendingAuthorityTags = new Map<string, string>()
19
36
 
20
37
  constructor() {
21
38
  makeAutoObservable(this)
22
39
  void this.load()
23
40
  }
24
41
 
42
+ stageAuthorityTag(sessionId: string, tag: string) {
43
+ this.pendingAuthorityTags.set(sessionId, tag)
44
+ }
45
+
46
+ /** A staged tag that never gets consumed (approval abandoned, connect()
47
+ * failed before its record was ever added) would otherwise sit in memory
48
+ * forever. Screens call this from their own catch block; harmless to call
49
+ * for a sessionId with nothing staged. */
50
+ discardStagedAuthorityTag(sessionId: string) {
51
+ this.pendingAuthorityTags.delete(sessionId)
52
+ }
53
+
25
54
  add(connection: Connection) {
55
+ const tag = this.pendingAuthorityTags.get(connection.sessionId)
56
+ if (tag !== undefined) {
57
+ this.pendingAuthorityTags.delete(connection.sessionId)
58
+ connection = { ...connection, authorityTag: tag }
59
+ }
26
60
  const idx = this.connections.findIndex(c => c.sessionId === connection.sessionId)
27
61
  if (idx >= 0) {
28
62
  this.connections[idx] = connection
@@ -125,6 +125,33 @@ const NOT_CONFIGURED =
125
125
  'from the host app entry point, before rendering WalletContextProvider. ' +
126
126
  'Pass backupUrl: null to disable backup deliberately.'
127
127
 
128
+ /**
129
+ * Hosts a development build may reach over plain http: the simulator's own
130
+ * machine, the Android emulator's alias for it, and RFC 1918 space. Everything
131
+ * else must be https — which key owns a handle (or holds a backup, or admits
132
+ * a Mandala settlement) is precisely what a reader on the path would want to
133
+ * change.
134
+ */
135
+ const PRIVATE_HOST =
136
+ /^(localhost|127\.0\.0\.1|10\.\d{1,3}\.\d{1,3}\.\d{1,3}|192\.168\.\d{1,3}\.\d{1,3}|172\.(1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3})$/
137
+
138
+ /**
139
+ * XR-065 (SEC2-074): the https-except-private-network policy
140
+ * `getHandleRegistryConfig` already applied to the paymail registry origin,
141
+ * shared here so `normalizeBackupUrl` and `getMandalaEndpoints` stop
142
+ * accepting a plain http: or credential-bearing origin with no policy at
143
+ * all. A host's own backup service, Mandala overlay, and Mandala MessageBox
144
+ * are each configuration-time, host-trusted values, not remote/runtime
145
+ * input — but a misconfigured or copy-pasted http: URL, or one carrying a
146
+ * bearer credential, still exposes every request this package makes over
147
+ * that origin to an on-path attacker.
148
+ */
149
+ export function isAllowedServiceOrigin(parsed: URL): boolean {
150
+ if (parsed.username || parsed.password) return false
151
+ if (parsed.protocol === 'https:') return true
152
+ return parsed.protocol === 'http:' && PRIVATE_HOST.test(parsed.hostname)
153
+ }
154
+
128
155
  function normalizeBackupUrl(raw: string): string {
129
156
  const trimmed = raw.trim().replace(/\/+$/, '')
130
157
  if (trimmed === '') return ''
@@ -143,6 +170,11 @@ function normalizeBackupUrl(raw: string): string {
143
170
  if (parsed.search !== '' || parsed.hash !== '') {
144
171
  throw new Error(`configureToolbox: backupUrl must be a bare origin, with no query or fragment: ${raw}`)
145
172
  }
173
+ if (!isAllowedServiceOrigin(parsed)) {
174
+ throw new Error(
175
+ `configureToolbox: backupUrl must be https (plain http is allowed only for a local-dev host): ${raw}`
176
+ )
177
+ }
146
178
  return trimmed
147
179
  }
148
180
 
@@ -208,6 +240,18 @@ export function getMandalaEndpoints(chain: AppChain): MandalaEndpointConfig | un
208
240
  const messageBoxUrl = entry.messageBoxUrl?.trim().replace(/\/+$/, '') ?? ''
209
241
  if (overlayUrl === '' || messageBoxUrl === '') return undefined
210
242
  if (!COMPRESSED_KEY.test(overlayIdentityKey)) return undefined
243
+ // XR-065 (SEC2-074): neither URL had a scheme policy at all before this --
244
+ // a plain http: overlay or MessageBox origin (or one carrying embedded
245
+ // credentials) resolved to a fully populated, "working" config.
246
+ for (const url of [overlayUrl, messageBoxUrl]) {
247
+ let parsed: URL
248
+ try {
249
+ parsed = new URL(url)
250
+ } catch {
251
+ return undefined
252
+ }
253
+ if (!isAllowedServiceOrigin(parsed)) return undefined
254
+ }
211
255
  return { overlayUrl, overlayIdentityKey, messageBoxUrl }
212
256
  }
213
257
 
@@ -219,14 +263,6 @@ export function getMandalaEndpoints(chain: AppChain): MandalaEndpointConfig | un
219
263
  * this accepts and that one rejects is a configured registry nothing resolves.
220
264
  */
221
265
  const REGISTRY_DOMAIN = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)+$/
222
- /**
223
- * Hosts a development build may reach over plain http: the simulator's own
224
- * machine, the Android emulator's alias for it, and RFC 1918 space. Everything
225
- * else must be https — which key owns a handle is precisely what a reader on
226
- * the path would want to change.
227
- */
228
- const PRIVATE_HOST =
229
- /^(localhost|127\.0\.0\.1|10\.\d{1,3}\.\d{1,3}\.\d{1,3}|192\.168\.\d{1,3}\.\d{1,3}|172\.(1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3})$/
230
266
 
231
267
  /**
232
268
  * The handle registry for a chain, or undefined when this build has none.
@@ -255,9 +291,7 @@ export function getHandleRegistryConfig(chain: AppChain): HandleRegistryConfig |
255
291
  }
256
292
  if (parsed.search !== '' || parsed.hash !== '') return undefined
257
293
  if (parsed.pathname !== '' && parsed.pathname !== '/') return undefined
258
- if (parsed.protocol === 'https:') return { domain, url }
259
- if (parsed.protocol === 'http:' && PRIVATE_HOST.test(parsed.hostname)) return { domain, url }
260
- return undefined
294
+ return isAllowedServiceOrigin(parsed) ? { domain, url } : undefined
261
295
  }
262
296
 
263
297
  /**
@@ -122,3 +122,66 @@ export async function registerDb(keySuffix: string, chain: string, filename: str
122
122
  existing.push(filename)
123
123
  await getAsyncStorage().setItem(registryKey(keySuffix, chain), JSON.stringify(existing))
124
124
  }
125
+
126
+ /**
127
+ * Remove a filename from the registry (no-op if not present).
128
+ *
129
+ * Used when a database this registry pointed at turns out to be unsafe to reuse — e.g. a
130
+ * failed import-time restore left it only partially replayed (see XR-017) — so a later
131
+ * `selectLatestDb` can never select it again. Removing the registry entry alone is enough
132
+ * for that; deleting the underlying file is the caller's separate decision.
133
+ */
134
+ export async function unregisterDb(keySuffix: string, chain: string, filename: string): Promise<void> {
135
+ const existing = await getRegisteredDbs(keySuffix, chain)
136
+ const next = existing.filter(f => f !== filename)
137
+ if (next.length === existing.length) return
138
+ await getAsyncStorage().setItem(registryKey(keySuffix, chain), JSON.stringify(next))
139
+ }
140
+
141
+ /**
142
+ * XQ-008: "Delete Wallet" only ever closed the SQLite connection
143
+ * (`storage.destroy()`) — it never deleted the underlying `.db` file(s) or
144
+ * cleared this registry's entry for them, so a "deleted" wallet's complete
145
+ * plaintext transaction/output/contact/note history stayed on disk
146
+ * indefinitely and silently reattached with everything intact the next time
147
+ * the same mnemonic was built on the same device.
148
+ *
149
+ * Deletes every filename this identity+chain's registry knows about (not
150
+ * just `dbName`, in case an earlier build left a stale entry pointing at a
151
+ * different file) via the host-supplied `deleteFile` — kept as a parameter
152
+ * rather than a static `expo-sqlite` import so this stays a plain leaf module
153
+ * a non-native host (e.g. Jest) can load without pulling in a native module,
154
+ * same reasoning as `getAsyncStorage` above — and clears each one's registry
155
+ * entry. `dbName` itself is always included even if the registry never
156
+ * recorded it, so the file actually open at logout time can never be the one
157
+ * left behind.
158
+ *
159
+ * Best-effort per file: one file's delete or unregister failing must not stop
160
+ * the rest from being attempted, and a `dbName` that does not parse as a
161
+ * wallet DB filename is treated as nothing to do rather than an error — this
162
+ * runs during logout, after the decision to erase the wallet has already
163
+ * been made elsewhere, and a cleanup failure here must never surface as (or
164
+ * be mistaken for) that erasure failing.
165
+ */
166
+ export async function purgeRegisteredDbFiles(
167
+ dbName: string,
168
+ deleteFile: (filename: string) => Promise<void>
169
+ ): Promise<void> {
170
+ const parsed = parseDbFilename(dbName)
171
+ if (!parsed) return
172
+ const { keySuffix, chain } = parsed
173
+ const registered = await getRegisteredDbs(keySuffix, chain)
174
+ const filenames = registered.includes(dbName) ? registered : [...registered, dbName]
175
+ for (const filename of filenames) {
176
+ try {
177
+ await deleteFile(filename)
178
+ } catch {
179
+ // Best-effort — see doc comment above.
180
+ }
181
+ try {
182
+ await unregisterDb(keySuffix, chain, filename)
183
+ } catch {
184
+ // Best-effort — see doc comment above.
185
+ }
186
+ }
187
+ }
@@ -96,6 +96,17 @@ export function reviewProvenTxsStartHeight(
96
96
  return Math.max(0, unbounded, floor)
97
97
  }
98
98
 
99
+ /** A `{fromHeight, toHeight}` window `boundReviewProvenTxs` had to skip because
100
+ * last-reviewed was more than `maxSpan` behind the tip. Kept so diagnostics
101
+ * can surface ranges that will never be audited by TaskReviewProvenTxs
102
+ * (reviews/misc-p2.md misc-p2-09) — process-local and cleared only by
103
+ * `resetSkippedReviewRanges` (used by tests). */
104
+ export const skippedReviewRanges: { fromHeight: number; toHeight: number }[] = []
105
+
106
+ export function resetSkippedReviewRanges(): void {
107
+ skippedReviewRanges.length = 0
108
+ }
109
+
99
110
  interface ReviewProvenTxsLike {
100
111
  trigger: (nowMsecsSinceEpoch: number) => { run: boolean }
101
112
  remainingHeightSpan?: number
@@ -148,7 +159,12 @@ export function boundReviewProvenTxs(task: ReviewProvenTxsLike, opts?: BoundRevi
148
159
  const start = reviewProvenTxsStartHeight(last, maxEligible, maxSpan)
149
160
  const unbounded = last === undefined ? 0 : last + 1
150
161
  task.remainingHeightSpan = Math.max(0, maxEligible - start + 1)
151
- if (start > unbounded) return start - 1
162
+ if (start > unbounded) {
163
+ const skipped = { fromHeight: unbounded, toHeight: start - 1 }
164
+ skippedReviewRanges.push(skipped)
165
+ console.warn('[walletMonitor] skipped proven-tx review heights', skipped)
166
+ return start - 1
167
+ }
152
168
  return last
153
169
  }
154
170
  }
@@ -0,0 +1,72 @@
1
+ import {
2
+ REVIEW_REQ_STATUSES_SQL,
3
+ collectFailedTransactionIds,
4
+ type ReviewFailedTx
5
+ } from '../storage/methods/reviewStatusSql'
6
+
7
+ export type ReleaseStuckDb = {
8
+ getAllAsync(sql: string, params?: unknown[]): Promise<unknown[]>
9
+ runAsync(sql: string, params?: unknown[]): Promise<unknown>
10
+ }
11
+
12
+ type StuckRow = { outputId: number; satoshis: number; txid: string; failedTransactionId: number }
13
+
14
+ const STUCK_RESERVATIONS_SQL = `
15
+ SELECT o.outputId AS outputId, o.satoshis AS satoshis, t.txid AS txid, t.transactionId AS failedTransactionId
16
+ FROM outputs o JOIN transactions t ON t.transactionId = o.spentBy
17
+ WHERE t.status = 'failed'
18
+ `.trim()
19
+
20
+ /**
21
+ * A FAILED transaction never confirms, but the toolbox leaves the inputs it
22
+ * had reserved marked `spentBy` that dead txid — so the coin reads as an
23
+ * unresolvable double-spend forever (WERR_REVIEW_ACTIONS on every new spend,
24
+ * even though the output is still `spendable`). Null out spentBy and restore
25
+ * spendable for every output still reserved by a failed tx.
26
+ *
27
+ * XR-032: the local `status = 'failed'` alone is not proof the reservation is
28
+ * safe to release — the same status is left behind by a transaction that was
29
+ * actually broadcast/delivered (a stale/imported row, or an interrupted
30
+ * send), and resurrecting its inputs lets the wallet build a conflicting
31
+ * second payment from already-spent coins. Reuse the exact proven_tx_reqs
32
+ * gate `StorageExpoSQLite.reviewStatus`/`reviewStatusOnDb` already apply
33
+ * before restoring an input: only release a reservation when every
34
+ * proven_tx_req row for the spender's txid (if any) is itself a terminal,
35
+ * safe-to-discard status (invalid/doubleSpend). Pure local SQL — no network.
36
+ */
37
+ export async function releaseStuckReservationsOnDb(db: ReleaseStuckDb): Promise<string> {
38
+ const rows = (await db.getAllAsync(STUCK_RESERVATIONS_SQL)) as StuckRow[]
39
+ if (!rows || rows.length === 0) return 'No stuck reservations found.'
40
+
41
+ const failedTxs: ReviewFailedTx[] = []
42
+ const seen = new Set<number>()
43
+ for (const row of rows) {
44
+ if (seen.has(row.failedTransactionId)) continue
45
+ seen.add(row.failedTransactionId)
46
+ failedTxs.push({ transactionId: row.failedTransactionId, txid: row.txid })
47
+ }
48
+
49
+ const reqStatusesByTxid = new Map<string, string[]>()
50
+ for (const tx of failedTxs) {
51
+ if (!tx.txid || reqStatusesByTxid.has(tx.txid)) continue
52
+ const reqs = (await db.getAllAsync(REVIEW_REQ_STATUSES_SQL, [tx.txid])) as { status: string }[]
53
+ reqStatusesByTxid.set(
54
+ tx.txid,
55
+ reqs.map(r => r.status)
56
+ )
57
+ }
58
+
59
+ const { safeFailedTransactionIds } = collectFailedTransactionIds(failedTxs, reqStatusesByTxid, new Set())
60
+ const safeRows = rows.filter(row => safeFailedTransactionIds.has(row.failedTransactionId))
61
+ if (safeRows.length === 0) return 'No stuck reservations found.'
62
+
63
+ const placeholders = safeRows.map(() => '?').join(',')
64
+ await db.runAsync(
65
+ `UPDATE outputs SET spentBy = NULL, spendable = 1 WHERE outputId IN (${placeholders})`,
66
+ safeRows.map(r => r.outputId)
67
+ )
68
+ const detail = safeRows
69
+ .map(r => ` • ${r.satoshis} sat (output ${r.outputId}) ← failed ${String(r.txid).slice(0, 12)}…`)
70
+ .join('\n')
71
+ return `✓ Released ${safeRows.length} stuck reservation(s):\n${detail}`
72
+ }
@@ -0,0 +1,20 @@
1
+ export type SecondSourceProbe = { status: 'success' | 'error'; isUtxo?: boolean }
2
+
3
+ /**
4
+ * A single WoC "spent" endpoint 200-with-txid response is not enough to
5
+ * permanently mark a UTXO unspendable (misc-p2-01) — WoC can be wrong,
6
+ * stale, or answering for the wrong network, and checkUtxoSpendability never
7
+ * writes `spentBy`, so nothing can ever restore a wrong call. Require a
8
+ * second, independent source (the toolbox's own configured getUtxoStatus
9
+ * providers) to also report the output as no longer a UTXO before committing
10
+ * to spendable:false.
11
+ */
12
+ export function shouldMarkUnspendable(args: {
13
+ wocProbe: SecondSourceProbe
14
+ wocSpendingTxid: string | undefined
15
+ utxoStatus: SecondSourceProbe
16
+ }): boolean {
17
+ if (args.wocProbe.status !== 'success' || args.wocProbe.isUtxo !== false) return false
18
+ if (!args.wocSpendingTxid) return false
19
+ return args.utxoStatus.status === 'success' && args.utxoStatus.isUtxo === false
20
+ }
@@ -0,0 +1,29 @@
1
+ export type ParsedSpenderInput = {
2
+ sourceTXID?: string
3
+ sourceOutputIndex?: number
4
+ sourceTransaction?: { id(enc: 'hex'): string }
5
+ }
6
+
7
+ /**
8
+ * XR-031: neither the WhatsOnChain "spent" probe nor the toolbox's
9
+ * second-source `getUtxoStatus` corroboration ever look at the alleged
10
+ * spending transaction itself — they are both bare claims. Before Wallet
11
+ * Check commits `spendable:false` against a UTXO, require the claimed
12
+ * spender's own parsed BEEF to (a) actually hash to the txid the chain
13
+ * services named, and (b) contain an input that references the exact
14
+ * outpoint being marked spent. A BEEF that fails to fetch/parse, hashes to a
15
+ * different tx, or doesn't reference this outpoint is not proof of spend —
16
+ * the caller must leave the output spendable rather than mutate it.
17
+ */
18
+ export function spenderConsumesOutpoint(args: {
19
+ parsedTxid: string
20
+ expectedTxid: string
21
+ inputs: ParsedSpenderInput[]
22
+ outpoint: { txid: string; vout: number }
23
+ }): boolean {
24
+ if (args.parsedTxid !== args.expectedTxid) return false
25
+ return args.inputs.some(input => {
26
+ const inTxid = input.sourceTXID ?? input.sourceTransaction?.id('hex')
27
+ return inTxid === args.outpoint.txid && input.sourceOutputIndex === args.outpoint.vout
28
+ })
29
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bsv/expo-wallet-toolbox",
3
- "version": "0.7.0",
3
+ "version": "0.9.0",
4
4
  "private": false,
5
5
  "description": "Wallet screens and P2P local-payment backend for Expo/React Native apps, extracted from BSV Wallet.",
6
6
  "license": "SEE LICENSE IN LICENSE.txt",
@@ -37,7 +37,7 @@
37
37
  "@bsv/react-native-localpay-transport": "*",
38
38
  "@bsv/sdk": "^2.8.2",
39
39
  "@bsv/templates": "^1.10.3",
40
- "@bsv/wallet-toolbox-mobile": "^2.14.0",
40
+ "@bsv/wallet-toolbox-mobile": "^2.14.3",
41
41
  "@expo/vector-icons": "^15.0.3",
42
42
  "@noble/curves": "^2.3.0",
43
43
  "@react-native-async-storage/async-storage": "^2.2.0",