@bsv/expo-wallet-toolbox 0.7.0 → 0.10.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 (154) hide show
  1. package/CHANGELOG.md +1790 -0
  2. package/README.md +54 -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 +653 -175
  21. package/core/headers/OfflineFirstChaintracks.ts +48 -4
  22. package/core/headers/headerStore.ts +26 -4
  23. package/core/headers/headerSyncTriggers.ts +65 -0
  24. package/core/headers/syncHeaders.ts +12 -1
  25. package/core/i18n/translations.tsx +1001 -25
  26. package/core/identity/handleRegistry/client.ts +31 -2
  27. package/core/identity/handleRegistry/keyPinStore.ts +70 -0
  28. package/core/identity/handleRegistry/resolver.ts +71 -3
  29. package/core/index.ts +33 -3
  30. package/core/localpay/build.ts +225 -24
  31. package/core/localpay/pending.ts +110 -7
  32. package/core/localpay/pendingAbortAuthority.ts +95 -0
  33. package/core/localpay/pendingAborts.ts +264 -28
  34. package/core/localpay/session.ts +42 -17
  35. package/core/localpay/settlementAck.ts +10 -1
  36. package/core/localpay/transport/socket.ts +52 -3
  37. package/core/localpay/types.ts +9 -1
  38. package/core/localpay/verify.ts +143 -16
  39. package/core/mandala/abortGuard.ts +96 -20
  40. package/core/mandala/createRuntime.ts +206 -33
  41. package/core/mandala/drain.ts +89 -11
  42. package/core/mandala/inboxPrehold.ts +186 -0
  43. package/core/mandala/permissionModule.ts +202 -20
  44. package/core/mandala/settlementStore.ts +24 -2
  45. package/core/mandala/types.ts +40 -5
  46. package/core/monitor/TaskBackupPush.ts +14 -0
  47. package/core/monitor/TaskDrainOutbox.ts +14 -0
  48. package/core/monitor/TaskSendOffline.ts +14 -0
  49. package/core/net/publicDestination.ts +91 -0
  50. package/core/net/validateArcUrl.ts +22 -0
  51. package/core/offline/cancelParked.ts +134 -13
  52. package/core/offline/payerHold.ts +100 -24
  53. package/core/offline/plan.ts +36 -7
  54. package/core/pay/beefRepair.ts +6 -2
  55. package/core/pay/damagedInbox.ts +24 -0
  56. package/core/pay/rails/address.ts +107 -12
  57. package/core/pay/rails/handle.ts +117 -22
  58. package/core/pay/rails/index.ts +45 -7
  59. package/core/pay/rails/nativeIntent.ts +61 -0
  60. package/core/pay/rails/nearby.ts +1 -0
  61. package/core/pay/receiveHistory.ts +93 -0
  62. package/core/pay/recordProof.ts +19 -1
  63. package/core/pay/refreshProofGuard.ts +42 -1
  64. package/core/pay/watchlist.ts +5 -2
  65. package/core/peerpay/control.ts +17 -18
  66. package/core/peerpay/handleResendRequests.ts +58 -4
  67. package/core/peerpay/outbox.ts +3 -1
  68. package/core/recovery/backupMaterial.ts +61 -0
  69. package/core/recovery/createWallet.ts +95 -0
  70. package/core/recovery/recoverWallet.ts +120 -0
  71. package/core/recovery/restoreWallet.ts +170 -0
  72. package/core/recovery/secret.ts +92 -0
  73. package/core/recovery/shareCollector.ts +71 -0
  74. package/core/recovery/shareParsing.ts +87 -0
  75. package/core/recovery/shares.ts +116 -0
  76. package/core/recovery/useRecoveryDeps.ts +70 -0
  77. package/core/services/arcTokenStorage.ts +52 -0
  78. package/core/services/arcadeBroadcastProvider.ts +232 -48
  79. package/core/services/autoApprovePolicy.ts +105 -0
  80. package/core/services/callbackToken.ts +19 -0
  81. package/core/services/capWalletArgs.ts +14 -2
  82. package/core/services/connectionAuthority.ts +98 -0
  83. package/core/services/exchangeRate.ts +35 -12
  84. package/core/services/externalOrigin.ts +11 -0
  85. package/core/services/secrets/kek.ts +126 -29
  86. package/core/services/secrets/migration.ts +16 -4
  87. package/core/services/secrets/store.ts +42 -14
  88. package/core/services/vault/VaultKeyService.ts +228 -45
  89. package/core/services/vault/chainRecovery.ts +483 -0
  90. package/core/services/vault/driver.ts +9 -1
  91. package/core/services/vault/enrolledSerialRegistry.ts +150 -0
  92. package/core/services/vault/guard.ts +218 -32
  93. package/core/services/vault/hardwareLease.ts +19 -0
  94. package/core/services/vault/metaAuthority.ts +210 -0
  95. package/core/services/vault/pivReset.ts +64 -23
  96. package/core/services/vault/r1comb.ts +139 -3
  97. package/core/services/vault/session.ts +25 -4
  98. package/core/services/vault/transfers.ts +866 -170
  99. package/core/services/vault/types.ts +19 -4
  100. package/core/services/vault/vaultStore.ts +256 -29
  101. package/core/services/walletArgLimits.ts +45 -2
  102. package/core/services/walletConnectionValidation.ts +76 -6
  103. package/core/services/walletServiceConfig.ts +10 -8
  104. package/core/storage/StorageExpoSQLite.ts +47 -13
  105. package/core/storage/methods/findSql.ts +21 -2
  106. package/core/storage/methods/offlineActions.ts +10 -1
  107. package/core/storage/methods/processOfflineActions.ts +116 -23
  108. package/core/storage/schema/createTables.ts +126 -2
  109. package/core/stores/ConnectionStore.ts +34 -0
  110. package/core/toolboxConfig.ts +45 -11
  111. package/core/walletDbRegistry.ts +63 -0
  112. package/core/walletMonitor.ts +17 -1
  113. package/core/walletRepair/releaseStuckReservations.ts +72 -0
  114. package/core/walletRepair/shouldMarkUnspendable.ts +20 -0
  115. package/core/walletRepair/spenderConsumesOutpoint.ts +29 -0
  116. package/package.json +2 -2
  117. package/ui/backupShares.ts +26 -169
  118. package/ui/components/pay/AddressReceive.tsx +13 -6
  119. package/ui/components/pay/AssetPicker.tsx +30 -9
  120. package/ui/components/pay/MessageBoxConfig.tsx +16 -0
  121. package/ui/components/pay/NearbyFlow.tsx +511 -251
  122. package/ui/components/pay/PaymentSuccessOverlay.tsx +39 -4
  123. package/ui/components/pay/UniversalSend.tsx +167 -73
  124. package/ui/components/ui/AlertCard.tsx +38 -5
  125. package/ui/components/ui/PermissionSheet.tsx +197 -66
  126. package/ui/components/vault/EnrollWizard.tsx +61 -13
  127. package/ui/components/vault/vaultErrorCopy.ts +3 -1
  128. package/ui/components/wallet/ActivityRow.tsx +5 -3
  129. package/ui/components/wallet/AmountInput.tsx +8 -2
  130. package/ui/components/wallet/AssetSwitcherDropdown.tsx +22 -2
  131. package/ui/components/wallet/Balance.tsx +42 -23
  132. package/ui/components/wallet/BiometricAdvisoryModal.tsx +16 -3
  133. package/ui/exportTransactions.ts +36 -4
  134. package/ui/hooks/useExportWalletData.ts +25 -2
  135. package/ui/importDatabases.ts +339 -24
  136. package/ui/index.ts +9 -3
  137. package/ui/isImageUrl.ts +6 -0
  138. package/ui/printRecoveryShares.ts +9 -10
  139. package/ui/recoveryPrompts.ts +91 -0
  140. package/ui/resolveIdentity.ts +31 -9
  141. package/ui/screens/ConnectionsScreen.tsx +86 -19
  142. package/ui/screens/IdentifierScreen.tsx +30 -8
  143. package/ui/screens/PairScreen.tsx +74 -2
  144. package/ui/screens/SettingsScreen.tsx +10 -4
  145. package/ui/screens/TrustScreen.tsx +99 -4
  146. package/ui/screens/VaultScreen.tsx +410 -61
  147. package/ui/screens/VaultTransferScreen.tsx +59 -7
  148. package/ui/screens/WalletCheckScreen.tsx +17 -6
  149. package/ui/screens/WalletConfigScreen.tsx +82 -28
  150. package/ui/screens/WalletHomeScreen.tsx +179 -88
  151. package/ui/screens/detailActionKeys.ts +55 -0
  152. package/ui/tokenFormat.ts +44 -4
  153. package/ui/txStatus.ts +5 -0
  154. package/core/storage/LocalStorageAdapter.ts +0 -58
@@ -48,6 +48,11 @@ export class TaskDrainOutbox extends WalletMonitorTask {
48
48
  static hasPending = false
49
49
  static backoffMs = TaskDrainOutbox.BASE_BACKOFF_MS
50
50
  static nextDueAt = 0
51
+ /** A drain pass is in flight. Guards against MonitorSupervisor's watchdog
52
+ * restart overlapping an old generation's still-running runOnce() with a
53
+ * new generation's — without this, both could concurrently retry the same
54
+ * outbox entry (reviews/misc-p2.md misc-p2-08). */
55
+ static running = false
51
56
 
52
57
  static noteConnectivity(online: boolean): void {
53
58
  TaskDrainOutbox.onlineNow = online
@@ -77,6 +82,7 @@ export class TaskDrainOutbox extends WalletMonitorTask {
77
82
  TaskDrainOutbox.hasPending = false
78
83
  TaskDrainOutbox.backoffMs = TaskDrainOutbox.BASE_BACKOFF_MS
79
84
  TaskDrainOutbox.nextDueAt = 0
85
+ TaskDrainOutbox.running = false
80
86
  }
81
87
 
82
88
  constructor(
@@ -102,6 +108,12 @@ export class TaskDrainOutbox extends WalletMonitorTask {
102
108
  }
103
109
 
104
110
  async runTask(): Promise<string> {
111
+ // A watchdog restart can spawn a new generation's runOnce() while an old
112
+ // generation's own runOnce() is still executing (it is not cancelled,
113
+ // only stopped from looping again). Without this guard both could
114
+ // concurrently retry the same outbox entry.
115
+ if (TaskDrainOutbox.running) return ''
116
+ TaskDrainOutbox.running = true
105
117
  TaskDrainOutbox.checkNow = false
106
118
  try {
107
119
  const r = await this.drain()
@@ -117,6 +129,8 @@ export class TaskDrainOutbox extends WalletMonitorTask {
117
129
  } catch (e) {
118
130
  this.scheduleRetry()
119
131
  return `DrainOutbox failed: ${e instanceof Error ? e.message : String(e)}\n`
132
+ } finally {
133
+ TaskDrainOutbox.running = false
120
134
  }
121
135
  }
122
136
  }
@@ -42,6 +42,11 @@ export class TaskSendOffline extends WalletMonitorTask {
42
42
  * alone will not help, and nothing else in the system records it.
43
43
  */
44
44
  static lastStall: string | undefined
45
+ /** A release pass is in flight. Guards against MonitorSupervisor's watchdog
46
+ * restart overlapping an old generation's still-running runOnce() with a
47
+ * new generation's — without this, both could concurrently release the
48
+ * same offline queue (XR-105; same pattern as TaskDrainOutbox.running). */
49
+ static running = false
45
50
 
46
51
  static noteConnectivity(online: boolean): void {
47
52
  TaskSendOffline.onlineNow = online
@@ -73,6 +78,7 @@ export class TaskSendOffline extends WalletMonitorTask {
73
78
  TaskSendOffline.backoffMs = TaskSendOffline.BASE_BACKOFF_MS
74
79
  TaskSendOffline.nextDueAt = 0
75
80
  TaskSendOffline.lastStall = undefined
81
+ TaskSendOffline.running = false
76
82
  }
77
83
 
78
84
  constructor(
@@ -97,6 +103,12 @@ export class TaskSendOffline extends WalletMonitorTask {
97
103
  }
98
104
 
99
105
  async runTask(): Promise<string> {
106
+ // A watchdog restart can spawn a new generation's runOnce() while an old
107
+ // generation's own runOnce() is still executing (it is not cancelled,
108
+ // only stopped from looping again). Without this guard both could
109
+ // concurrently release the same offline queue (XR-105).
110
+ if (TaskSendOffline.running) return ''
111
+ TaskSendOffline.running = true
100
112
  TaskSendOffline.checkNow = false
101
113
  try {
102
114
  const r = await this.release()
@@ -118,6 +130,8 @@ export class TaskSendOffline extends WalletMonitorTask {
118
130
  // a failed drain, so it earns a retry rather than silence.
119
131
  this.scheduleRetry()
120
132
  return `SendOffline failed: ${e instanceof Error ? e.message : String(e)}\n`
133
+ } finally {
134
+ TaskSendOffline.running = false
121
135
  }
122
136
  }
123
137
  }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Whether a URL is safe to hand to a native fetch/prefetch as a destination
3
+ * this app does not control.
4
+ *
5
+ * There is no synchronous DNS resolution available on this runtime, so this
6
+ * cannot catch a hostname that only *resolves* to a private address (DNS
7
+ * rebinding) — that needs a redirect/connect-time check on the platform's
8
+ * networking stack, which this codebase does not have. What it DOES catch,
9
+ * cheaply and up front, is the concrete class of report this closes: a
10
+ * foreign paymail registry, a user-typed trust-provider domain, or a search
11
+ * result that names a loopback/private/link-local address or IP literal
12
+ * directly (XR-073 / SEC2-057, SEC2-076). A hostname is otherwise accepted
13
+ * without being resolved — this is a floor, not a firewall.
14
+ */
15
+ const IPV4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/
16
+
17
+ function isPrivateIPv4(host: string): boolean {
18
+ const m = IPV4.exec(host)
19
+ if (!m) return false
20
+ const parts = m.slice(1, 5).map(Number)
21
+ if (parts.some(n => n > 255)) return false
22
+ const [a, b] = parts
23
+ if (a === 127) return true // loopback
24
+ if (a === 10) return true // RFC1918
25
+ if (a === 172 && b >= 16 && b <= 31) return true // RFC1918
26
+ if (a === 192 && b === 168) return true // RFC1918
27
+ if (a === 169 && b === 254) return true // link-local
28
+ if (a === 100 && b >= 64 && b <= 127) return true // CGNAT (RFC6598)
29
+ if (a === 0) return true // "this network"
30
+ if (a >= 224) return true // multicast + reserved
31
+ return false
32
+ }
33
+
34
+ /** Also catches the bracketed literal a URL's `hostname` gives back, e.g. `[::1]`. */
35
+ function isPrivateIPv6(host: string): boolean {
36
+ const h = host.replace(/^\[|\]$/g, '').toLowerCase()
37
+ if (h === '::1' || h === '::') return true
38
+ if (h.startsWith('fe8') || h.startsWith('fe9') || h.startsWith('fea') || h.startsWith('feb')) return true // link-local fe80::/10
39
+ if (h.startsWith('fc') || h.startsWith('fd')) return true // unique local fc00::/7
40
+ // IPv4-mapped/compatible — judge the embedded address. A URL's `.hostname`
41
+ // canonicalises the literal to hex groups (`::ffff:a.b.c.d` becomes
42
+ // `::ffff:7f00:1`), so the last two 16-bit groups are read back as bytes
43
+ // rather than matched against the dotted form.
44
+ if (h.includes('ffff')) {
45
+ const groups = h.split(':')
46
+ const last = groups.slice(-2)
47
+ if (last.length === 2 && last.every(g => /^[0-9a-f]{1,4}$/.test(g))) {
48
+ const hi = parseInt(last[0], 16)
49
+ const lo = parseInt(last[1], 16)
50
+ const ipv4 = `${(hi >> 8) & 0xff}.${hi & 0xff}.${(lo >> 8) & 0xff}.${lo & 0xff}`
51
+ if (isPrivateIPv4(ipv4)) return true
52
+ }
53
+ }
54
+ return false
55
+ }
56
+
57
+ /**
58
+ * The address-class half of `isPublicHttpsUrl`, exposed on its own for
59
+ * validators that enforce a different scheme themselves (e.g. `wss://`
60
+ * relay URLs, or the `https://` pairing origin's own reserved-`.invalid`
61
+ * check) and only need "is this hostname loopback/private/link-local/
62
+ * reserved/a bare local-network literal" (XR-024 / SEC2-055). Takes a URL's
63
+ * already-punycoded `.hostname` — bracketed IPv6 included.
64
+ */
65
+ export function isPrivateNetworkHost(rawHost: string): boolean {
66
+ const host = rawHost.toLowerCase().replace(/\.$/, '')
67
+ if (!host) return true
68
+ if (host === 'localhost' || host.endsWith('.localhost')) return true
69
+ if (host === 'local' || host.endsWith('.local')) return true
70
+ if (host === 'internal' || host.endsWith('.internal')) return true
71
+ if (host.startsWith('[') || host.includes(':')) return isPrivateIPv6(host)
72
+ return isPrivateIPv4(host)
73
+ }
74
+
75
+ /**
76
+ * A parseable, credential-free `https://` URL whose host is not a loopback,
77
+ * private-use, link-local, CGNAT, multicast/reserved, or `.local`/`localhost`/
78
+ * `.internal` address. The path/query is not otherwise restricted — this is a
79
+ * host-class check, not a full origin policy.
80
+ */
81
+ export function isPublicHttpsUrl(raw: string): boolean {
82
+ let url: URL
83
+ try {
84
+ url = new URL(raw)
85
+ } catch {
86
+ return false
87
+ }
88
+ if (url.protocol !== 'https:') return false
89
+ if (url.username || url.password) return false
90
+ return !isPrivateNetworkHost(url.hostname)
91
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * XR-064: a custom ARC broadcast endpoint carries the signed transaction (and
3
+ * any configured API token) over the wire. Restrict it to https, with a
4
+ * narrow explicit exception for local development against a loopback
5
+ * broadcaster (http://localhost / http://127.0.0.1) — so an on-path
6
+ * attacker on a person-chosen plaintext host cannot observe the transaction
7
+ * and callback token, or return a bare success that suppresses the real
8
+ * HTTPS fallback chain, while the legitimate local-dev workflow keeps
9
+ * working.
10
+ */
11
+ export function validateArcUrl(url: string): boolean {
12
+ const trimmed = url.trim()
13
+ if (!trimmed) return true // empty clears the override back to the default
14
+ let parsed: URL
15
+ try {
16
+ parsed = new URL(trimmed)
17
+ } catch {
18
+ return false
19
+ }
20
+ if (parsed.protocol === 'https:') return true
21
+ return parsed.protocol === 'http:' && (parsed.hostname === 'localhost' || parsed.hostname === '127.0.0.1')
22
+ }
@@ -21,7 +21,7 @@ import type { MandalaRuntime } from '../mandala/runtime'
21
21
 
22
22
  const CANCELLABLE = new Set(['nosend', 'unsigned', 'unprocessed'])
23
23
 
24
- export type CancelParkedOutcome = 'cancelled' | 'already-sent' | 'not-found'
24
+ export type CancelParkedOutcome = 'cancelled' | 'already-sent' | 'not-found' | 'unverifiable-offline'
25
25
 
26
26
  export interface CancelParkedStorage {
27
27
  readonly sqliteDb: unknown
@@ -29,6 +29,16 @@ export interface CancelParkedStorage {
29
29
  partial: { txid: string }
30
30
  noRawTx?: boolean
31
31
  }): Promise<{ reference?: string; status?: string }[]>
32
+ /**
33
+ * Optional only so every existing test double (and the token-only overlay
34
+ * path, which never needed it) keeps compiling; the real StorageExpoSQLite
35
+ * always has it. Absent, or a services object with no `getStatusForTxids`,
36
+ * is treated exactly like "the network doesn't know this txid" — see
37
+ * `chainAlreadyKnows`.
38
+ */
39
+ getServices?(): {
40
+ getStatusForTxids?: (txids: string[]) => Promise<{ results?: { txid: string; status: string }[] }>
41
+ }
32
42
  }
33
43
 
34
44
  export interface CancelParkedWallet {
@@ -85,8 +95,27 @@ export async function cancelParkedPayment(args: {
85
95
  txid: string
86
96
  /** Token settlement. Absent for a plain BSV payment. */
87
97
  settlement?: CancelParkedSettlementDeps
98
+ /**
99
+ * P1-3: the connectivity probe for the chain-status check below, independent
100
+ * of `settlement` (which may be entirely absent on the BSV rail). Defaults
101
+ * to the real probe; a failed probe is treated as online, not offline —
102
+ * same direction as every other `getOnline` guard in this codebase
103
+ * (build.ts's `finalizeDelivery`) — because the network call the "online"
104
+ * branch makes fails harmlessly on its own if the device really has no
105
+ * connection, and defaulting to "offline" here would instead start
106
+ * blocking cancels on a transient probe hiccup.
107
+ */
108
+ isOnline?: () => Promise<boolean>
109
+ /**
110
+ * The payer has already been shown, and accepted, the "cannot verify this
111
+ * payment while offline" warning (t('local_pay_cancel_unverifiable_title'
112
+ * / '_body')) and still wants to cancel. Skips the offline refusal below;
113
+ * never skips the online chain-status check itself.
114
+ */
115
+ acknowledgedUnverifiable?: boolean
88
116
  }): Promise<CancelParkedOutcome> {
89
- const { storage, wallet, originator, txid, settlement } = args
117
+ const { storage, wallet, originator, txid, settlement, acknowledgedUnverifiable } = args
118
+ const isOnlineProbe = args.isOnline ?? getOnline
90
119
  const db = storage.sqliteDb
91
120
  if (!db) throw new Error('the database is not open, cannot cancel this payment')
92
121
 
@@ -99,17 +128,48 @@ export async function cancelParkedPayment(args: {
99
128
  // landed (rule 3: the RECIPIENT settles the hop), in which case aborting
100
129
  // would release inputs the overlay has already marked spent and hand the
101
130
  // payer a double-spend against the person they just paid.
102
- if (settlement && (await isOnline(settlement))) {
131
+ //
132
+ // XR-100: a settlement ROW is the signal that this txid was genuinely
133
+ // handed over — once one exists, "cannot ask the overlay" (offline, or a
134
+ // `fetchAdmission` that comes back `unavailable`) must not be read as "the
135
+ // overlay says no". Only a txid with NO row at all (never locally tracked
136
+ // as a token hand-over) is safe to fall through with no admission check.
137
+ if (settlement) {
103
138
  const row = await settlement.settlements.getSettlement(txid)
104
139
  if (row) {
105
- const verdict = await fetchAdmissionSafely(settlement, row.overlayUrl, txid)
106
- if (verdict?.kind === 'admitted') return 'already-sent'
140
+ if (await isOnline(settlement)) {
141
+ const verdict = await fetchAdmissionSafely(settlement, row.overlayUrl, txid)
142
+ if (verdict?.kind === 'admitted') return 'already-sent'
143
+ if (verdict?.kind === 'unavailable' && !acknowledgedUnverifiable) return 'unverifiable-offline'
144
+ } else if (!acknowledgedUnverifiable) {
145
+ // Cannot ask the overlay at all while offline. Same refusal as the
146
+ // BSV-rail check below, and the same escape hatch: the caller shows
147
+ // the destructive confirm and retries with `acknowledgedUnverifiable`.
148
+ return 'unverifiable-offline'
149
+ }
107
150
  }
108
151
  }
109
152
 
110
153
  if (!tx.status || !CANCELLABLE.has(tx.status)) return 'already-sent'
111
154
  if (!tx.reference) return 'not-found'
112
155
 
156
+ // P1-3-localpay-cancelparked-bsv: the check above is token-only (it is
157
+ // skipped entirely for a plain BSV payment, or a token txid with no
158
+ // settlement row yet). Ask the network directly, regardless of settlement,
159
+ // before trusting the local `nosend` status — a payee holding a scanned
160
+ // static QR may already have broadcast their copy while both devices were
161
+ // offline, and this device has no interactive ack that would have told it.
162
+ const online = await probeConnectivity(isOnlineProbe)
163
+ if (online) {
164
+ if (await chainAlreadyKnows(storage, txid)) return 'already-sent'
165
+ } else if (!acknowledgedUnverifiable) {
166
+ // Genuinely offline: cannot rule out the payee having already broadcast.
167
+ // Refuse to cancel silently — the caller shows the destructive confirm
168
+ // and retries with `acknowledgedUnverifiable: true` if the user accepts
169
+ // the risk.
170
+ return 'unverifiable-offline'
171
+ }
172
+
113
173
  const r = await wallet.abortAction({ reference: tx.reference }, originator)
114
174
  if (r && r.aborted === false) throw new Error('the wallet refused to cancel this payment')
115
175
 
@@ -119,10 +179,60 @@ export async function cancelParkedPayment(args: {
119
179
  return 'cancelled'
120
180
  }
121
181
 
182
+ /**
183
+ * The UI-facing glue for `cancelParkedPayment`'s `unverifiable-offline`
184
+ * outcome, extracted so it is unit-testable without mounting a screen: call
185
+ * `cancel()` once; only when that comes back `unverifiable-offline` does it
186
+ * show the destructive confirm, and only on acceptance does it call
187
+ * `cancel(true)` to retry with the acknowledgement. Any other outcome (or a
188
+ * declined confirm) is returned as-is, with no second call.
189
+ */
190
+ export async function runCancelParkedFlow(deps: {
191
+ cancel: (acknowledgedUnverifiable?: boolean) => Promise<CancelParkedOutcome>
192
+ /** Shows t('local_pay_cancel_unverifiable_title'/'_body'); resolves true only on the destructive confirm. */
193
+ confirmUnverifiable: () => Promise<boolean>
194
+ }): Promise<CancelParkedOutcome> {
195
+ const outcome = await deps.cancel(undefined)
196
+ if (outcome !== 'unverifiable-offline') return outcome
197
+ const proceed = await deps.confirmUnverifiable()
198
+ if (!proceed) return outcome
199
+ return deps.cancel(true)
200
+ }
201
+
202
+ /** Same "assume online" direction as build.ts's `finalizeDelivery` probe. */
203
+ async function probeConnectivity(isOnlineProbe: () => Promise<boolean>): Promise<boolean> {
204
+ try {
205
+ return await isOnlineProbe()
206
+ } catch (e) {
207
+ devLog('[cancelParkedPayment] connectivity probe failed, assuming online:', e)
208
+ return true
209
+ }
210
+ }
211
+
212
+ /**
213
+ * Mirrors core/storage/methods/processOfflineActions.ts's `networkAlreadyHas`.
214
+ * Exported (XR-095) so build.ts's `finalizeDelivery` can run the identical
215
+ * check before releasing inputs on a decline, instead of re-implementing it.
216
+ */
217
+ export async function chainAlreadyKnows(storage: CancelParkedStorage, txid: string): Promise<boolean> {
218
+ try {
219
+ const services = storage.getServices?.()
220
+ if (!services || typeof services.getStatusForTxids !== 'function') return false
221
+ const r = await services.getStatusForTxids([txid])
222
+ const status = r.results?.find(x => x.txid === txid)?.status
223
+ return status === 'mined' || status === 'known'
224
+ } catch (e) {
225
+ devLog(`[cancelParkedPayment] could not ask the network about ${txid}, treating as unknown:`, e)
226
+ return false
227
+ }
228
+ }
229
+
122
230
  /**
123
231
  * A probe that throws must not strand the user on a screen they cannot leave.
124
- * Treating the failure as offline falls back to the local `nosend` check, which
125
- * is the behaviour every build before this feature had.
232
+ * Treating the failure as offline routes it through the same
233
+ * `acknowledgedUnverifiable` gate as a genuinely offline device (XR-100) when
234
+ * a settlement row exists — it is not the "safe to fall through" case, only a
235
+ * different way of not being able to ask.
126
236
  */
127
237
  async function isOnline(deps: CancelParkedSettlementDeps): Promise<boolean> {
128
238
  try {
@@ -134,16 +244,27 @@ async function isOnline(deps: CancelParkedSettlementDeps): Promise<boolean> {
134
244
  }
135
245
 
136
246
  /**
137
- * Only a 200/admitted refuses the cancel. Anything else — a 404 for a txid the
138
- * overlay has never seen, a persisted refusal, an unreachable overlay — leaves
139
- * the decision to the local check: the payment was not admitted, so cancelling
140
- * it cannot double-spend anyone.
247
+ * Only a 200/admitted refuses the cancel outright, and only a definite
248
+ * non-admission — `undefined` (a 404 for a txid the overlay has never seen,
249
+ * or a mismatched/unverifiable answer, per FIX H) or a terminal `refused`/
250
+ * `evicted` — leaves the decision to the local check safely: the overlay
251
+ * affirmatively said this payment was never admitted, so cancelling it cannot
252
+ * double-spend anyone.
253
+ *
254
+ * XR-100: "the overlay could not be asked" is a THIRD answer, not a synonym
255
+ * for either of those. The real runtime's `fetchAdmission` already returns a
256
+ * distinct `{ kind: 'unavailable' }` verdict for an unreachable overlay
257
+ * rather than throwing (`createRuntime.ts`) — the try/catch here exists only
258
+ * for a caller/dependency that fails outright, and folds that failure into
259
+ * the SAME `unavailable` verdict rather than swallowing it into `undefined`,
260
+ * so `cancelParkedPayment` cannot mistake "could not ask" for "asked, and the
261
+ * answer was no".
141
262
  */
142
263
  async function fetchAdmissionSafely(deps: CancelParkedSettlementDeps, overlayUrl: string, txid: string) {
143
264
  try {
144
265
  return await deps.fetchAdmission(overlayUrl, txid)
145
266
  } catch (e) {
146
- devLog(`[cancelParkedPayment] could not reach ${overlayUrl} for ${txid}, falling back to the local check:`, e)
147
- return undefined
267
+ devLog(`[cancelParkedPayment] could not reach ${overlayUrl} for ${txid}:`, e)
268
+ return { kind: 'unavailable', code: 'ERR_LOCAL_FETCH_FAILED', retryable: true } as const
148
269
  }
149
270
  }
@@ -119,20 +119,23 @@ async function advanceToHandedOver(storage: StorageExpoSQLite, txid: string): Pr
119
119
 
120
120
  /**
121
121
  * Persist what the plaintext frame carries, for the state this call just put
122
- * the payment in. Never throws: the queue row is already durable by the time
123
- * this runs, and a payment that IS queued must not be reported as un-queued
124
- * because a cache write failed.
122
+ * the payment in. Never throws — the caller decides what a failed journal
123
+ * costs, from the boolean this returns, rather than finding out from a thrown
124
+ * exception. `true` for a plain BSV hold (nothing to journal) and for a token
125
+ * hold whose write landed; `false` only when a token hold's write did not.
125
126
  */
126
127
  async function journalHandover(
127
128
  deps: TokenHandoverDeps,
128
129
  txid: string,
129
130
  state: 'parked' | 'handed_over'
130
- ): Promise<void> {
131
- if (!deps.frame?.token || !deps.onTokenHandedOver) return
131
+ ): Promise<boolean> {
132
+ if (!deps.frame?.token || !deps.onTokenHandedOver) return true
132
133
  try {
133
134
  await deps.onTokenHandedOver(deps.frame, txid, state, deps.reference)
135
+ return true
134
136
  } catch (e) {
135
137
  devLog(`[payerHold] could not journal the ${state} settlement for ${txid}:`, e)
138
+ return false
136
139
  }
137
140
  }
138
141
 
@@ -148,6 +151,20 @@ async function journalHandover(
148
151
  */
149
152
  const ADVANCEABLE_TO_QUEUED = new Set(['parked', 'queued'])
150
153
 
154
+ /**
155
+ * XR-036: whether this hold has a settlement row to wait for at all.
156
+ *
157
+ * `processOfflineActions.ts`'s `readSettlement` tells "ordinary BSV" from
158
+ * "token, needs overlay admission first" by whether ANY `token_settlements`
159
+ * row exists for the txid — so a token hold's queue row may not be promoted
160
+ * to 'queued' (which wakes the drain) until `journalHandover` has actually
161
+ * written that row. A plain BSV hold has no such row to wait for and keeps
162
+ * its old, immediate promotion.
163
+ */
164
+ function isTokenHold(deps: TokenHandoverDeps): boolean {
165
+ return !!(deps.frame?.token && deps.onTokenHandedOver)
166
+ }
167
+
151
168
  export async function holdSentPaymentOffline(
152
169
  args: TokenHandoverDeps & {
153
170
  storage: StorageExpoSQLite
@@ -189,11 +206,25 @@ export async function holdSentPaymentOffline(
189
206
  devLog(`[holdSentPaymentOffline] ${txid} is already '${existing.status}', leaving it alone`)
190
207
  return
191
208
  }
192
- // Same two writes and the same order as the insert path: the durable row
193
- // first, the promotion after.
194
- await updateOfflineAction(db, txid, { status: 'queued' })
195
- TaskSendOffline.noteEnqueued()
196
- await journalHandover(args, txid, 'handed_over')
209
+ if (isTokenHold(args)) {
210
+ // XR-036: do NOT wake the drain until the settlement row is durable —
211
+ // leave the row exactly where a park would (non-drainable) if the write
212
+ // fails, rather than handing the drain a 'queued' row with nothing in
213
+ // `token_settlements` to stop it reading this as plain BSV.
214
+ const journaled = await journalHandover(args, txid, 'handed_over')
215
+ if (journaled) {
216
+ await updateOfflineAction(db, txid, { status: 'queued' })
217
+ TaskSendOffline.noteEnqueued()
218
+ } else {
219
+ devLog(`[holdSentPaymentOffline] ${txid} left '${existing.status}': its settlement could not be journaled`)
220
+ }
221
+ } else {
222
+ // Same two writes and the same order as before: the durable row first,
223
+ // the promotion after — unchanged for the plain BSV rail, which has no
224
+ // settlement row to wait for.
225
+ await updateOfflineAction(db, txid, { status: 'queued' })
226
+ TaskSendOffline.noteEnqueued()
227
+ }
197
228
  await advanceToHandedOver(storage, txid)
198
229
  // Only while still withheld: if the payee already broadcast and this device
199
230
  // saw it, the transaction has moved on and this write would be a lie.
@@ -201,19 +232,33 @@ export async function holdSentPaymentOffline(
201
232
  return
202
233
  }
203
234
 
204
- // Insert before promote — see the ORDER MATTERS note above.
205
- await insertOfflineAction(db, { userId: tx.userId, txid, role: 'sent', framePayload })
206
- TaskSendOffline.noteEnqueued()
207
- // Queue row first, settlement second, for the reason the ORDER MATTERS note
208
- // gives: the queue row is what the drain finds, and it is durable. The
209
- // advance is issued even on this path because a row may already exist at
210
- // `parked` from a park that never got its queue row written.
211
- await journalHandover(args, txid, 'handed_over')
235
+ if (isTokenHold(args)) {
236
+ // XR-036: insert at 'parked' — durable (`findOfflineActions` never reads
237
+ // it, so the drain leaves it alone), and NOT promoted to 'queued' until
238
+ // `journalHandover`'s write to `token_settlements` has actually landed.
239
+ // Without this, a process kill or a transient write fault right here left
240
+ // a 'queued' row with no settlement to match it, and
241
+ // `processOfflineActions`'s `readSettlement` reads that absence as "this
242
+ // is an ordinary BSV transaction" and posts it straight past overlay
243
+ // admission (§4.3).
244
+ await insertOfflineAction(db, { userId: tx.userId, txid, role: 'sent', framePayload }, 'parked')
245
+ const journaled = await journalHandover(args, txid, 'handed_over')
246
+ if (journaled) {
247
+ await updateOfflineAction(db, txid, { status: 'queued' })
248
+ TaskSendOffline.noteEnqueued()
249
+ } else {
250
+ devLog(`[holdSentPaymentOffline] ${txid} left 'parked': its settlement could not be journaled`)
251
+ }
252
+ } else {
253
+ // Insert before promote — see the ORDER MATTERS note above. Unchanged for
254
+ // the plain BSV rail.
255
+ await insertOfflineAction(db, { userId: tx.userId, txid, role: 'sent', framePayload })
256
+ TaskSendOffline.noteEnqueued()
257
+ }
212
258
  await advanceToHandedOver(storage, txid)
213
259
  await storage.updateTransactionStatus('unproven', tx.transactionId)
214
260
  }
215
261
 
216
-
217
262
  /**
218
263
  * Keep a handed-over payment WITHOUT releasing it for broadcast.
219
264
  *
@@ -235,7 +280,7 @@ export async function parkSentPaymentOffline(
235
280
  txid: string
236
281
  framePayload?: string
237
282
  }
238
- ): Promise<void> {
283
+ ): Promise<boolean> {
239
284
  const { storage, txid, framePayload } = args
240
285
  const db = storage.sqliteDb
241
286
  if (!db) throw new Error('the database is not open, cannot park this payment')
@@ -251,10 +296,15 @@ export async function parkSentPaymentOffline(
251
296
  // `attemptToPostReqsToNetwork` both key their token branch on. That is the
252
297
  // durability this call buys and the sealed `framePayload` cannot: after a
253
298
  // restart the session PSK is gone and these bytes can no longer be opened.
254
- await journalHandover(args, txid, 'parked')
299
+ //
300
+ // XR-036 review follow-up: this used to discard journalHandover's result,
301
+ // so nothing downstream could tell a landed token journal from a silently
302
+ // failed one. Returned now so a caller (and `releaseParkedPayment`'s own
303
+ // settlement check) has something to act on. A plain BSV park still
304
+ // resolves `true` (there is nothing to journal).
305
+ return journalHandover(args, txid, 'parked')
255
306
  }
256
307
 
257
-
258
308
  /**
259
309
  * Release a parked payment: the payer showed the code again and this time
260
310
  * confirmed the hand-over.
@@ -262,15 +312,41 @@ export async function parkSentPaymentOffline(
262
312
  * The same two writes `holdSentPaymentOffline` makes, minus the insert — the
263
313
  * row already exists from parking, so it is flipped to 'queued' instead. Same
264
314
  * order for the same reason: the durable row moves first, the promotion after.
315
+ *
316
+ * XR-036 review follow-up: no frame is threaded here (the row already exists
317
+ * from the park), so this cannot re-attempt `journalHandover` the way a second
318
+ * `holdSentPaymentOffline` confirm can. What it CAN and must do is refuse to
319
+ * repeat XR-036's own defect through this second entry point: a token-bearing
320
+ * park whose `journalHandover(..., 'parked')` write silently failed (see
321
+ * `parkSentPaymentOffline`) has no `token_settlements` row, and
322
+ * `processOfflineActions`'s `readSettlement` reads that absence as "ordinary
323
+ * BSV" and posts it straight past overlay admission. `isTokenHold` is the
324
+ * caller's own knowledge of which rail this txid took (WalletHomeScreen.tsx's
325
+ * resend flow already derives it from the action's 'mandala' label); when set,
326
+ * the row is only promoted once a settlement row proves the park-time journal
327
+ * actually landed, otherwise it is left at 'parked' exactly like a fresh
328
+ * journal failure in `holdSentPaymentOffline`.
265
329
  */
266
- export async function releaseParkedPayment(args: { storage: StorageExpoSQLite; txid: string }): Promise<void> {
267
- const { storage, txid } = args
330
+ export async function releaseParkedPayment(args: {
331
+ storage: StorageExpoSQLite
332
+ txid: string
333
+ isTokenHold?: boolean
334
+ }): Promise<void> {
335
+ const { storage, txid, isTokenHold } = args
268
336
  const db = storage.sqliteDb
269
337
  if (!db) throw new Error('the database is not open, cannot release this payment')
270
338
 
271
339
  const tx = (await storage.findTransactions({ partial: { txid }, noRawTx: true }))[0]
272
340
  if (!tx) throw new Error(`no transaction record for ${txid}, cannot release it`)
273
341
 
342
+ if (isTokenHold) {
343
+ const settlement = await createSettlementStore(db as unknown as SettlementDb).getSettlement(txid)
344
+ if (!settlement) {
345
+ devLog(`[releaseParkedPayment] ${txid} left 'parked': no settlement row to release a token hold from`)
346
+ return
347
+ }
348
+ }
349
+
274
350
  await updateOfflineAction(db, txid, { status: 'queued' })
275
351
  TaskSendOffline.noteEnqueued()
276
352
  // The settlement twin of the line above (§4.4). No frame is threaded here —
@@ -230,6 +230,15 @@ export interface PostedTxidResult {
230
230
  /** The service already had this transaction, which its own docs say to read as success. */
231
231
  alreadyKnown?: boolean
232
232
  doubleSpend?: boolean
233
+ /**
234
+ * The toolbox's own distinction between "the network told us this exact
235
+ * transaction is invalid" (`false`) and "we could not tell" (`true` or
236
+ * absent) — set by the ARC adapter to exactly `false` for INVALID/
237
+ * MALFORMED/REJECTED verdicts, and `true` for transport/rate-limit/timeout
238
+ * issues. Absent (a provider that never sets it) must read the same as
239
+ * `true`: no signal is no verdict, not an invalidity claim.
240
+ */
241
+ serviceError?: boolean
233
242
  }
234
243
 
235
244
  /** One service's reply. Structurally satisfied by `PostBeefResult`. */
@@ -244,21 +253,41 @@ export interface PostedResult {
244
253
  * A double spend outranks a success, matching the toolbox's own aggregate
245
254
  * (`attemptToPostReqsToNetwork.js:174-181`) so the codebase has one rule for it.
246
255
  *
247
- * A plain error is never read as invalidity. This ancestor arrived inside a BEEF
248
- * that `internalizeAction` had already verified — scripts and SPV both — so a
249
- * bare rejection is far more likely to mean our merged BEEF is missing bytes
250
- * this service needed than that the transaction is bad, and rejecting it would
251
- * cascade into money the user legitimately holds. Left retryable, the drain
252
- * simply stalls, which loses nothing.
256
+ * An UNMARKED error is never read as invalidity. Verification here relies on
257
+ * `internalizeAction`'s own gate having already checked this ancestor, but
258
+ * that gate is AtomicBEEF structure and SPV (merkle-proof) validity only — it
259
+ * does not execute or verify the transaction's unlocking/locking scripts — so
260
+ * a bare rejection with no further signal is far more likely to mean our
261
+ * merged BEEF is missing bytes this service needed than that the transaction
262
+ * is bad, and rejecting it would cascade into money the user legitimately
263
+ * holds. Left retryable, the drain simply stalls, which loses nothing.
264
+ *
265
+ * A MARKED error is different: `serviceError === false` is the toolbox's own
266
+ * structured signal, already computed by the broadcaster adapter (e.g. ARC's
267
+ * INVALID/MALFORMED/REJECTED), that the network looked at this exact
268
+ * transaction and refused it — not merely that we could not reach anyone.
269
+ * Reading it is what lets a forged foreign ancestor (the P0-1 gap this rail
270
+ * also has to defend against, until every payee upgrades) cascade to the
271
+ * descendant it poisoned instead of stalling the drain forever. The full
272
+ * condition is the exact triple `status==='error' && doubleSpend!==true &&
273
+ * serviceError===false` — the `doubleSpend!==true` half of it is enforced
274
+ * above by returning early, so the two checks together are never both live
275
+ * at once, but the exactness still matters for `serviceError`: absent or
276
+ * `true` — including from a broadcaster that never sets the field at all —
277
+ * must fall through to the safe `serviceError` outcome, never get swept in
278
+ * by a loose `!serviceError`.
253
279
  */
254
280
  export function outcomeOfForeignPost(args: { txid: string; results: PostedResult[] }): PostOutcome {
255
281
  let success = false
282
+ let invalid = false
256
283
  for (const result of args.results) {
257
284
  for (const r of result.txidResults) {
258
285
  if (r.txid !== args.txid) continue
259
286
  if (r.doubleSpend === true) return 'doubleSpend'
260
287
  if (r.status === 'success' || r.alreadyKnown === true) success = true
288
+ else if (r.status === 'error' && r.serviceError === false) invalid = true
261
289
  }
262
290
  }
263
- return success ? 'success' : 'serviceError'
291
+ if (success) return 'success'
292
+ return invalid ? 'invalidTx' : 'serviceError'
264
293
  }