@bsv/expo-wallet-toolbox 0.5.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 (200) hide show
  1. package/CHANGELOG.md +2000 -0
  2. package/README.md +66 -1
  3. package/core/amountFormatHelpers.ts +258 -36
  4. package/core/backup/RemoteSyncReader.ts +133 -24
  5. package/core/backup/appData.ts +157 -0
  6. package/core/backup/client.ts +15 -1
  7. package/core/backup/codec.ts +149 -11
  8. package/core/backup/constants.ts +30 -1
  9. package/core/backup/cursor.ts +31 -2
  10. package/core/backup/push.ts +71 -5
  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/config.tsx +12 -5
  15. package/core/constants.ts +14 -1
  16. package/core/contacts/contactActivity.ts +153 -0
  17. package/core/contacts/contactCache.ts +41 -0
  18. package/core/contacts/contactsStore.ts +183 -0
  19. package/core/context/ExchangeRateContext.tsx +34 -27
  20. package/core/context/LocalStorageProvider.tsx +43 -40
  21. package/core/context/UserContext.tsx +18 -7
  22. package/core/context/VaultContext.tsx +49 -2
  23. package/core/context/WalletConnectionContext.tsx +203 -11
  24. package/core/context/WalletContext.tsx +685 -171
  25. package/core/demo/demoAssets.ts +60 -0
  26. package/core/demo/demoLedger.ts +240 -0
  27. package/core/demo/demoMandalaRuntime.ts +96 -0
  28. package/core/demo/demoMode.ts +38 -0
  29. package/core/demo/demoWallet.ts +25 -0
  30. package/core/demo/index.ts +26 -0
  31. package/core/demo/useDemo.ts +59 -0
  32. package/core/headers/OfflineFirstChaintracks.ts +99 -17
  33. package/core/headers/headerStore.ts +33 -14
  34. package/core/headers/syncHeaders.ts +12 -1
  35. package/core/i18n/translations.tsx +2186 -98
  36. package/core/identity/contactLink.ts +36 -0
  37. package/core/identity/handleRegistry/client.ts +314 -0
  38. package/core/identity/handleRegistry/keyPinStore.ts +70 -0
  39. package/core/identity/handleRegistry/profileCert.ts +254 -0
  40. package/core/identity/handleRegistry/registration.ts +559 -0
  41. package/core/identity/handleRegistry/resolver.ts +315 -0
  42. package/core/identity/handleRegistry/rules.ts +104 -0
  43. package/core/index.ts +53 -5
  44. package/core/localpay/build.ts +225 -24
  45. package/core/localpay/pending.ts +110 -7
  46. package/core/localpay/pendingAbortAuthority.ts +95 -0
  47. package/core/localpay/pendingAborts.ts +266 -26
  48. package/core/localpay/session.ts +42 -17
  49. package/core/localpay/settlementAck.ts +10 -1
  50. package/core/localpay/transport/socket.ts +52 -3
  51. package/core/localpay/verify.ts +100 -10
  52. package/core/mandala/abortGuard.ts +96 -20
  53. package/core/mandala/createRuntime.ts +206 -33
  54. package/core/mandala/drain.ts +89 -11
  55. package/core/mandala/inboxPrehold.ts +186 -0
  56. package/core/mandala/permissionModule.ts +202 -20
  57. package/core/mandala/settlementStore.ts +24 -2
  58. package/core/mandala/types.ts +40 -5
  59. package/core/monitor/MonitorSupervisor.ts +121 -0
  60. package/core/monitor/TaskBackupPush.ts +15 -1
  61. package/core/monitor/TaskCreditInbox.ts +1 -1
  62. package/core/monitor/TaskDrainOutbox.ts +15 -1
  63. package/core/monitor/TaskSendOffline.ts +15 -1
  64. package/core/net/online.ts +49 -0
  65. package/core/net/publicDestination.ts +91 -0
  66. package/core/net/validateArcUrl.ts +22 -0
  67. package/core/numberFormat.ts +19 -0
  68. package/core/offline/cancelParked.ts +134 -13
  69. package/core/offline/payerHold.ts +100 -24
  70. package/core/offline/plan.ts +37 -8
  71. package/core/pay/beefRepair.ts +6 -2
  72. package/core/pay/damagedInbox.ts +24 -0
  73. package/core/pay/rails/address.ts +107 -12
  74. package/core/pay/rails/handle.ts +117 -22
  75. package/core/pay/rails/index.ts +45 -7
  76. package/core/pay/rails/nativeIntent.ts +61 -0
  77. package/core/pay/receiveHistory.ts +93 -0
  78. package/core/pay/recordProof.ts +21 -7
  79. package/core/pay/refreshProofGuard.ts +42 -1
  80. package/core/pay/watchlist.ts +5 -2
  81. package/core/peerpay/control.ts +17 -18
  82. package/core/peerpay/handleResendRequests.ts +58 -4
  83. package/core/peerpay/outbox.ts +3 -1
  84. package/core/recovery/backupMaterial.ts +61 -0
  85. package/core/recovery/createWallet.ts +95 -0
  86. package/core/recovery/recoverWallet.ts +120 -0
  87. package/core/recovery/restoreWallet.ts +170 -0
  88. package/core/recovery/secret.ts +92 -0
  89. package/core/recovery/shareCollector.ts +71 -0
  90. package/core/recovery/shareParsing.ts +87 -0
  91. package/core/recovery/shares.ts +116 -0
  92. package/core/recovery/useRecoveryDeps.ts +70 -0
  93. package/core/services/arcTokenStorage.ts +52 -0
  94. package/core/services/arcadeBroadcastProvider.ts +233 -52
  95. package/core/services/autoApprovePolicy.ts +105 -0
  96. package/core/services/callbackToken.ts +19 -0
  97. package/core/services/capWalletArgs.ts +14 -2
  98. package/core/services/connectionAuthority.ts +98 -0
  99. package/core/services/exchangeRate.ts +36 -13
  100. package/core/services/externalOrigin.ts +16 -2
  101. package/core/services/secrets/kek.ts +126 -29
  102. package/core/services/secrets/migration.ts +16 -4
  103. package/core/services/secrets/store.ts +42 -14
  104. package/core/services/vault/VaultKeyService.ts +228 -45
  105. package/core/services/vault/chainRecovery.ts +483 -0
  106. package/core/services/vault/driver.ts +9 -1
  107. package/core/services/vault/enrolledSerialRegistry.ts +150 -0
  108. package/core/services/vault/guard.ts +218 -32
  109. package/core/services/vault/hardwareLease.ts +19 -0
  110. package/core/services/vault/metaAuthority.ts +210 -0
  111. package/core/services/vault/pivReset.ts +64 -23
  112. package/core/services/vault/r1comb.ts +139 -3
  113. package/core/services/vault/session.ts +25 -4
  114. package/core/services/vault/transfers.ts +868 -172
  115. package/core/services/vault/types.ts +19 -4
  116. package/core/services/vault/vaultStore.ts +256 -29
  117. package/core/services/walletArgLimits.ts +45 -2
  118. package/core/services/walletConnectionValidation.ts +76 -6
  119. package/core/services/walletServiceConfig.ts +40 -27
  120. package/core/storage/StorageExpoSQLite.ts +88 -47
  121. package/core/storage/methods/findSql.ts +24 -2
  122. package/core/storage/methods/listActionsSql.ts +8 -5
  123. package/core/storage/methods/listOutputsSql.ts +2 -2
  124. package/core/storage/methods/offlineActions.ts +10 -1
  125. package/core/storage/methods/processOfflineActions.ts +117 -25
  126. package/core/storage/methods/reviewStatusSql.ts +7 -2
  127. package/core/storage/schema/createTables.ts +155 -2
  128. package/core/stores/ConnectionStore.ts +34 -0
  129. package/core/toolboxConfig.ts +104 -0
  130. package/core/toolboxTypes.ts +40 -0
  131. package/core/userAvatar.ts +79 -0
  132. package/core/walletDbRegistry.ts +63 -0
  133. package/core/walletMonitor.ts +25 -4
  134. package/core/walletRepair/releaseStuckReservations.ts +72 -0
  135. package/core/walletRepair/shouldMarkUnspendable.ts +20 -0
  136. package/core/walletRepair/spenderConsumesOutpoint.ts +29 -0
  137. package/package.json +7 -7
  138. package/ui/activityFilter.ts +115 -0
  139. package/ui/backupShares.ts +26 -169
  140. package/ui/components/pay/AddressReceive.tsx +13 -6
  141. package/ui/components/pay/AssetPicker.tsx +30 -9
  142. package/ui/components/pay/MessageBoxConfig.tsx +16 -0
  143. package/ui/components/pay/NearbyFlow.tsx +480 -243
  144. package/ui/components/pay/PaymentSuccessOverlay.tsx +85 -10
  145. package/ui/components/pay/RecipientField.tsx +84 -70
  146. package/ui/components/pay/StepBar.tsx +32 -0
  147. package/ui/components/pay/UniversalSend.tsx +827 -205
  148. package/ui/components/ui/AlertCard.tsx +38 -5
  149. package/ui/components/ui/PencilEditField.tsx +109 -0
  150. package/ui/components/ui/PermissionSheet.tsx +197 -66
  151. package/ui/components/ui/SlideOverFromRight.tsx +86 -0
  152. package/ui/components/vault/EnrollWizard.tsx +61 -13
  153. package/ui/components/vault/vaultErrorCopy.ts +3 -1
  154. package/ui/components/wallet/ActivityRow.tsx +227 -123
  155. package/ui/components/wallet/AmountInput.tsx +26 -8
  156. package/ui/components/wallet/AssetSwitcherDropdown.tsx +22 -2
  157. package/ui/components/wallet/Balance.tsx +42 -23
  158. package/ui/components/wallet/BiometricAdvisoryModal.tsx +16 -3
  159. package/ui/components/wallet/ContactActivityList.tsx +149 -0
  160. package/ui/components/wallet/ContactSigil.tsx +49 -0
  161. package/ui/components/wallet/EditPictureSheet.tsx +99 -0
  162. package/ui/components/wallet/FitAmount.tsx +148 -0
  163. package/ui/components/wallet/IconPickerSheet.tsx +168 -0
  164. package/ui/components/wallet/IdentifierRow.tsx +69 -0
  165. package/ui/components/wallet/ImportFromBackupPrompt.tsx +35 -13
  166. package/ui/components/wallet/ProfileButton.tsx +62 -0
  167. package/ui/components/wallet/UserAvatar.tsx +85 -0
  168. package/ui/components/wallet/avatarIcons.ts +122 -0
  169. package/ui/exportTransactions.ts +36 -4
  170. package/ui/hooks/useContactsStore.ts +10 -0
  171. package/ui/hooks/useExportWalletData.ts +25 -2
  172. package/ui/hooks/useMandala.ts +18 -1
  173. package/ui/hooks/useOnline.ts +65 -20
  174. package/ui/importDatabases.ts +339 -24
  175. package/ui/index.ts +33 -2
  176. package/ui/isImageUrl.ts +6 -0
  177. package/ui/printRecoveryShares.ts +9 -10
  178. package/ui/recoveryPrompts.ts +91 -0
  179. package/ui/resolveIdentity.ts +31 -9
  180. package/ui/screens/ConnectionsScreen.tsx +86 -19
  181. package/ui/screens/ContactScreen.tsx +289 -0
  182. package/ui/screens/ContactsScreen.tsx +373 -0
  183. package/ui/screens/IdentifierScreen.tsx +256 -0
  184. package/ui/screens/NewContactScreen.tsx +362 -0
  185. package/ui/screens/PairScreen.tsx +74 -2
  186. package/ui/screens/PayScreen.tsx +20 -7
  187. package/ui/screens/ProfileScreen.tsx +783 -0
  188. package/ui/screens/SettingsScreen.tsx +10 -4
  189. package/ui/screens/TransactionDetailScreen.tsx +419 -0
  190. package/ui/screens/TrustScreen.tsx +100 -5
  191. package/ui/screens/VaultScreen.tsx +410 -61
  192. package/ui/screens/VaultTransferScreen.tsx +59 -7
  193. package/ui/screens/WalletCheckScreen.tsx +17 -6
  194. package/ui/screens/WalletConfigScreen.tsx +124 -28
  195. package/ui/screens/WalletHomeScreen.tsx +640 -104
  196. package/ui/screens/detailActionKeys.ts +55 -0
  197. package/ui/tokenFormat.ts +44 -4
  198. package/ui/tokenStatus.ts +21 -0
  199. package/ui/txStatus.ts +48 -5
  200. package/core/storage/LocalStorageAdapter.ts +0 -58
@@ -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 —
@@ -9,7 +9,7 @@
9
9
  */
10
10
  import { dependencyOrder, descendantsOf, releaseOrder, type OrderableTx } from './order'
11
11
  import type { OfflineActionRow } from '../storage/methods/offlineActions'
12
- import type { ProvenTxReqStatus } from '@bsv/wallet-toolbox-mobile/out/src/sdk/types'
12
+ import type { ProvenTxReqStatus } from '../toolboxTypes'
13
13
 
14
14
  export type PostOutcome = 'success' | 'serviceError' | 'invalidTx' | 'doubleSpend'
15
15
 
@@ -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
  }
@@ -23,7 +23,7 @@
23
23
  * and `makeBeefRepair` declines rather than burning an attempt on it.
24
24
  */
25
25
  import { Beef, Utils } from '@bsv/sdk'
26
- import type { WocConfig } from './rails/address'
26
+ import { MAX_HEX_RESPONSE_CHARS, type WocConfig } from './rails/address'
27
27
 
28
28
  /** Injectable for tests; production uses global fetch. */
29
29
  export type FetchLike = (url: string) => Promise<{ ok: boolean; status: number; text: () => Promise<string> }>
@@ -53,7 +53,11 @@ export async function refetchAtomicBeef(args: {
53
53
  // a code path the user never asked for.
54
54
  if (!resp.ok) return undefined
55
55
  const hex = (await resp.text()).trim()
56
- if (hex.length === 0 || hex.length % 2 !== 0 || !/^[0-9a-fA-F]+$/.test(hex)) return undefined
56
+ // XR-059: reject an oversized body before it is ever hex-decoded or
57
+ // merged into a Beef — a compromised/misbehaving indexer must not be able
58
+ // to force that work with an arbitrarily large response.
59
+ if (hex.length === 0 || hex.length > MAX_HEX_RESPONSE_CHARS || hex.length % 2 !== 0 || !/^[0-9a-fA-F]+$/.test(hex))
60
+ return undefined
57
61
  bytes = Utils.toArray(hex, 'hex')
58
62
  } catch {
59
63
  return undefined
@@ -1,3 +1,5 @@
1
+ import { limitsForTier } from '../services/walletArgLimits'
2
+
1
3
  export type DamagedInboxReason = 'unparseable' | 'bad_shape'
2
4
 
3
5
  export interface DamagedInboxMessage {
@@ -6,6 +8,22 @@ export interface DamagedInboxMessage {
6
8
  reason: DamagedInboxReason
7
9
  }
8
10
 
11
+ /**
12
+ * XR-047: a poisoned inbox message stays in the box indefinitely — nothing
13
+ * here acknowledges or removes it — and is re-fetched and re-shape-checked on
14
+ * every 5s `HandleReceive` poll and every background `TaskCreditInbox` pass.
15
+ * With no ceiling, a `transaction` array (or a derivation string) sized to the
16
+ * message-box client's own much larger limit could make every one of those
17
+ * passes do an expensive `.every()` scan, indefinitely, and could reach
18
+ * `wallet.internalizeAction` were it ever credited.
19
+ *
20
+ * `internalizeTx`/`customInstructions` (walletArgLimits.ts) do not vary by
21
+ * device tier — only `aggregate` does — so `'mid'` here is just a stable way
22
+ * to read those shared constants, not a device probe; this module stays pure
23
+ * and needs no device-tier context.
24
+ */
25
+ const LIMITS = limitsForTier('mid')
26
+
9
27
  /** True when body looks like a PeerPay payment token. */
10
28
  export function isPaymentTokenShape(body: unknown): boolean {
11
29
  if (body === null || typeof body !== 'object') return false
@@ -16,8 +34,14 @@ export function isPaymentTokenShape(body: unknown): boolean {
16
34
  derivationSuffix?: unknown
17
35
  }
18
36
  if (typeof derivationPrefix !== 'string' || typeof derivationSuffix !== 'string') return false
37
+ if (derivationPrefix.length > LIMITS.customInstructions || derivationSuffix.length > LIMITS.customInstructions) {
38
+ return false
39
+ }
19
40
  const transaction = (body as { transaction?: unknown }).transaction
20
41
  if (!Array.isArray(transaction)) return false
42
+ // Length check BEFORE the O(n) scan below: an oversized array must never
43
+ // pay for its own rejection on every poll.
44
+ if (transaction.length > LIMITS.internalizeTx) return false
21
45
  return transaction.every(n => typeof n === 'number')
22
46
  }
23
47