@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
@@ -1,5 +1,6 @@
1
1
  import { PublicKey, type WalletProtocol } from '@bsv/sdk'
2
2
  import { parseExternalOrigin, type ExternalOrigin } from './externalOrigin'
3
+ import { isPrivateNetworkHost } from '../net/publicDestination'
3
4
 
4
5
  const KB = 1024
5
6
  const MB = 1024 * KB
@@ -25,6 +26,20 @@ export const MAX_RPC_CIPHERTEXT_BYTES = MAX_RPC_PLAINTEXT_BYTES + 256
25
26
  export const MAX_RPC_CIPHERTEXT_CHARS = Math.ceil(MAX_RPC_CIPHERTEXT_BYTES * 4 / 3)
26
27
  export const MAX_RPC_WIRE_CHARS = MAX_RPC_CIPHERTEXT_CHARS + 1024
27
28
  export const MAX_IN_FLIGHT_RPC = 4
29
+ /**
30
+ * XR-026: MAX_IN_FLIGHT_RPC bounds the COUNT of concurrent messages, but each
31
+ * can independently be up to MAX_RPC_PLAINTEXT_BYTES — so up to
32
+ * MAX_IN_FLIGHT_RPC of them decrypting at once multiplies that ceiling by up
33
+ * to 4x before the ~20-30x native amplification documented in
34
+ * walletArgLimits.ts (a single ~5 MiB call is already ~100-150 MB of peak
35
+ * RSS). This bounds the SUM of estimated plaintext bytes across every
36
+ * message currently being decrypted or dispatched on one connection, to no
37
+ * worse than today's already-accepted single-message ceiling — a message
38
+ * that would push the running total over it is dropped, exactly like the
39
+ * existing MAX_IN_FLIGHT_RPC count gate, rather than allowed to add to an
40
+ * unbounded concurrent total.
41
+ */
42
+ export const MAX_IN_FLIGHT_RPC_BYTES = MAX_RPC_PLAINTEXT_BYTES
28
43
 
29
44
  export interface ConnectParams {
30
45
  topic: string
@@ -42,18 +57,48 @@ export interface ValidatedConnectParams {
42
57
  expiry: number
43
58
  }
44
59
 
45
- export const PAIRING_SIGNATURE_DOMAIN = 'bsv-wallet-pairing-v1'
60
+ /** XR-027: the protocol namespace an admin-scoped wallet derives the saved-
61
+ * pairing authority tag under (reserved in core/services/vault/guard.ts so a
62
+ * paired peer's own, site-scoped WalletClient can never mint or verify it),
63
+ * and the versioned transcript that tag is computed over. `expiry`/`sig` are
64
+ * the QR's own one-time proof and are not part of what a saved, reusable
65
+ * connection record needs to keep authentic. */
66
+ export const CONNECTION_AUTHORITY_PROTOCOL_ID: WalletProtocol = [2, 'connection authority']
67
+ export const CONNECTION_AUTHORITY_SIGNATURE_DOMAIN = 'bsv-wallet-connection-authority-v1'
68
+ /** HMAC-SHA256 output, base64url-encoded without padding (32 bytes -> 43 chars). */
69
+ export const CONNECTION_AUTHORITY_TAG_CHARS = 43
46
70
 
47
- /** Exact transcript signed by the desktop pairing peer. Every field that
48
- * chooses the transport endpoint or its BRC-42 key namespace is included. */
71
+ export interface ConnectionAuthorityTuple {
72
+ origin: string
73
+ topic: string
74
+ protocolID: string
75
+ backendIdentityKey: string
76
+ }
77
+
78
+ /** Exact transcript MAC'd over the tuple a user approved. Every field that
79
+ * chooses the transport endpoint, its BRC-42 key namespace, or which backend
80
+ * it talks to is included -- an attacker who can flip any one of them without
81
+ * knowing the admin wallet's key can no longer produce a tag that verifies. */
82
+ export function buildConnectionAuthorityMessage(tuple: ConnectionAuthorityTuple): string {
83
+ return [
84
+ CONNECTION_AUTHORITY_SIGNATURE_DOMAIN,
85
+ tuple.origin,
86
+ tuple.topic,
87
+ tuple.protocolID,
88
+ tuple.backendIdentityKey
89
+ ].join('|')
90
+ }
91
+
92
+ /** Exact transcript signed by the desktop pairing peer, matching
93
+ * @bsv/wallet-relay 0.5.x (`topic|backendIdentityKey|origin|expiry`).
94
+ * protocolID is not signed by the library; changing this format must be
95
+ * coordinated with wallet-relay and every backend that uses it. */
49
96
  export function buildPairingSignatureMessage(
50
- params: Pick<Required<ConnectParams>, 'topic' | 'backendIdentityKey' | 'protocolID' | 'origin' | 'expiry'>
97
+ params: Pick<Required<ConnectParams>, 'topic' | 'backendIdentityKey' | 'origin' | 'expiry'>
51
98
  ): string {
52
99
  return [
53
- PAIRING_SIGNATURE_DOMAIN,
54
100
  params.topic,
55
101
  params.backendIdentityKey,
56
- params.protocolID,
57
102
  params.origin,
58
103
  params.expiry
59
104
  ].join('|')
@@ -193,6 +238,24 @@ export function validateStoredConnectionFields(raw: {
193
238
  return { topic, backendIdentityKey, mobileIdentityKey, protocolIDRaw: protocol.raw, protocolID: protocol.value, external }
194
239
  }
195
240
 
241
+ /** XR-027: a stored connection's authority tag is untrusted AsyncStorage data
242
+ * like every other field above -- absent (undefined/null) means a legacy or
243
+ * never-tagged record, which callers must treat as "needs re-approval", the
244
+ * same outcome as a tag that fails verification. Anything present but not a
245
+ * canonical, correctly-sized base64url string is rejected outright rather
246
+ * than handed to verifyHmac. */
247
+ export function validateStoredConnectionAuthorityTag(raw: unknown): string | undefined {
248
+ if (raw === undefined || raw === null) return undefined
249
+ if (
250
+ typeof raw !== 'string' ||
251
+ raw.length !== CONNECTION_AUTHORITY_TAG_CHARS ||
252
+ !/^[A-Za-z0-9_-]+$/.test(raw)
253
+ ) {
254
+ throw new Error('Stored connection authority tag is invalid')
255
+ }
256
+ return raw
257
+ }
258
+
196
259
  /** SecureStore data can be corrupted or restored independently of the
197
260
  * connection database. Only canonical sequence values that can be incremented
198
261
  * safely for the next authenticated message are accepted. */
@@ -221,6 +284,13 @@ export function validateRelayUrl(raw: unknown): string {
221
284
  if (url.pathname !== '/' || url.search || url.hash) {
222
285
  throw new Error('Relay URL must be a bare WSS origin')
223
286
  }
287
+ // XR-024 (SEC2-055): the origin server's relay URL is exactly as untrusted
288
+ // as the pairing origin it came from (see parseExternalOrigin) -- nothing
289
+ // stopped it from naming a loopback/private/link-local literal and sending
290
+ // the device's WebSocket connection into its own local network.
291
+ if (isPrivateNetworkHost(url.hostname)) {
292
+ throw new Error('Relay URL must not name a loopback or private-network destination')
293
+ }
224
294
  return url.origin
225
295
  }
226
296
 
@@ -1,10 +1,7 @@
1
1
  import type { AppChain } from '../config'
2
2
  import { toWalletChain } from '../config'
3
3
  import { getServiceConfig } from '../toolboxConfig'
4
- import {
5
- ChaintracksServiceClient,
6
- Services
7
- } from '@bsv/wallet-toolbox-mobile'
4
+ import { ChaintracksServiceClient, Services } from '@bsv/wallet-toolbox-mobile'
8
5
  import type { ChaintracksClientApi } from '@bsv/wallet-toolbox-mobile'
9
6
  import type { ChainTracker } from '@bsv/sdk'
10
7
  import type { BsvExchangeRate, WalletServicesOptions } from '../toolboxTypes'
@@ -81,7 +78,7 @@ export function createServiceOptions(
81
78
  // toolbox's generic ARC slot (broadcast fallback, `services.arcTaal`).
82
79
  // `arcadeUrl` is what makes `Services` construct its `Arcade` provider —
83
80
  // and that provider is the only `getMerklePath` source that can answer for
84
- // a transaction the moment Arcade sees it mined (GET /v1/tx/{txid} carries
81
+ // a transaction the moment Arcade sees it mined (GET /tx/{txid} carries
85
82
  // the BUMP), and the only thing `TaskArcadeSSE` will subscribe to. Without
86
83
  // it every proof lookup went straight to WhatsOnChain/Bitails, and the
87
84
  // monitor logged "no arcadeUrl configured; SSE disabled" on every start —
@@ -103,6 +100,11 @@ export function createServiceOptions(
103
100
  }
104
101
  const arcade = { arcUrl: arcadeUrl, arcConfig, arcadeUrl, arcadeConfig: arcConfig }
105
102
 
103
+ // XR-066: taalApiKey must never fall back to whatsOnChainApiKey. TAAL and
104
+ // WhatsOnChain are different origins (createTaalBroadcastService sends
105
+ // this key as a Bearer token to arc.taal.com et al. on every ordinary
106
+ // broadcast) — a host that scoped a key to WhatsOnChain must not have it
107
+ // silently disclosed to TAAL just because it left taalApiKey unset.
106
108
  if (network === 'main') {
107
109
  return {
108
110
  ...base,
@@ -110,7 +112,7 @@ export function createServiceOptions(
110
112
  bsvUpdateMsecs: 60 * 60 * 1000,
111
113
  fiatUpdateMsecs: 60 * 60 * 1000,
112
114
  whatsOnChainApiKey: svc.whatsOnChainApiKey ?? '',
113
- taalApiKey: svc.taalApiKey ?? svc.whatsOnChainApiKey ?? '',
115
+ taalApiKey: svc.taalApiKey ?? '',
114
116
  chaintracks: chaintracksOverride ?? new ChaintracksServiceClient(walletChain, chaintracksUrlFor(network))
115
117
  }
116
118
  }
@@ -122,7 +124,7 @@ export function createServiceOptions(
122
124
  bsvUpdateMsecs: 60 * 60 * 1000000,
123
125
  fiatUpdateMsecs: 60 * 60 * 1000000,
124
126
  whatsOnChainApiKey: svc.whatsOnChainApiKey ?? '',
125
- taalApiKey: svc.taalApiKey ?? svc.whatsOnChainApiKey ?? '',
127
+ taalApiKey: svc.taalApiKey ?? '',
126
128
  chaintracks: chaintracksOverride ?? new ChaintracksServiceClient(walletChain, chaintracksUrlFor(network))
127
129
  }
128
130
  }
@@ -134,7 +136,7 @@ export function createServiceOptions(
134
136
  bsvUpdateMsecs: 60 * 60 * 1000000,
135
137
  fiatUpdateMsecs: 60 * 60 * 1000000,
136
138
  whatsOnChainApiKey: svc.whatsOnChainApiKey ?? '',
137
- taalApiKey: svc.taalApiKey ?? svc.whatsOnChainApiKey ?? '',
139
+ taalApiKey: svc.taalApiKey ?? '',
138
140
  chaintracks: chaintracksOverride ?? new ChaintracksServiceClient(walletChain, chaintracksUrlFor(network))
139
141
  }
140
142
  }
@@ -1166,7 +1166,9 @@ export class StorageExpoSQLite extends StorageProvider {
1166
1166
  args,
1167
1167
  'transactionId',
1168
1168
  extraConditions.length > 0 ? { conditions: extraConditions, params: extraParams } : undefined,
1169
- args.noRawTx ? columnsExcluding('transactions', ['rawTx', 'inputBEEF']) : undefined
1169
+ // NEW-01: noSendExpiryReclaimRawTx is the other large blob TABLE_COLUMNS
1170
+ // now lists for this table — exclude it too, or noRawTx stops being cheap.
1171
+ args.noRawTx ? columnsExcluding('transactions', ['rawTx', 'inputBEEF', 'noSendExpiryReclaimRawTx']) : undefined
1170
1172
  )
1171
1173
 
1172
1174
  const results = this.validateEntities(rows, undefined, ['isOutgoing'])
@@ -2104,12 +2106,21 @@ export class StorageExpoSQLite extends StorageProvider {
2104
2106
  }
2105
2107
 
2106
2108
  /**
2107
- * Which of these txids the Mandala settlement drain owns.
2109
+ * Which of these txids the Mandala settlement drain owns — THROWS if the
2110
+ * read itself could not be answered.
2108
2111
  *
2109
- * A missing table (a device that has not yet run the additive migration) or
2110
- * any other read failure yields the empty set, which is exactly the
2111
- * pre-feature behaviour — logged, never thrown, because a broken read here
2112
- * must not take down every broadcast in the wallet.
2112
+ * XR-045: this used to collapse "the read failed" into the same empty set as
2113
+ * "no token requests here", which is exactly what "treat it as plain BSV"
2114
+ * means to every caller — so a transient SQLite fault (busy/locked, a
2115
+ * corrupt page) on a table that had just been written to successfully
2116
+ * looked identical to "this feature does not apply", and an unadmitted token
2117
+ * request went straight to broadcast. Never swallowed here any more: each
2118
+ * caller already decides what a failure costs it — `holdTokenReqsForDrain`
2119
+ * withholds its whole batch on any exception, and `attemptToPostReqsToNetwork`
2120
+ * (guard #2, the one that can actually broadcast) does the same rather than
2121
+ * deciding off an incomplete answer. `heldTokenTxidsIn` (guard #2's result
2122
+ * half, reporting only) already documented "read failures propagate; the one
2123
+ * caller decides" — this is what makes that true.
2113
2124
  */
2114
2125
  private async tokenSettlementTxids(txids: string[]): Promise<Set<string>> {
2115
2126
  if (txids.length === 0 || !this.db) return new Set()
@@ -2120,8 +2131,8 @@ export class StorageExpoSQLite extends StorageProvider {
2120
2131
  )) as { txid: string }[]
2121
2132
  return new Set(rows.map(r => r.txid))
2122
2133
  } catch (e) {
2123
- devLog('[StorageExpoSQLite] could not read token_settlements, treating every req as plain BSV:', e)
2124
- return new Set()
2134
+ devLog('[StorageExpoSQLite] could not read token_settlements:', e)
2135
+ throw e
2125
2136
  }
2126
2137
  }
2127
2138
 
@@ -2228,10 +2239,20 @@ export class StorageExpoSQLite extends StorageProvider {
2228
2239
  try {
2229
2240
  heldTokenTxids = await this.heldTokenTxidsIn(swr.map(s => s.txid))
2230
2241
  } catch (e) {
2231
- // A read fault here must not change what the wallet reports; the guard in
2232
- // front of the broadcast has already done the load-bearing work.
2233
- devLog('[StorageExpoSQLite] could not check held token reqs for sendWithResults:', e)
2234
- return r
2242
+ // XR-045/SEC2-070: a read fault here means this call cannot tell which of
2243
+ // these txids are held token requests — "could not determine" must not
2244
+ // resolve to "report as delivered", which is exactly the false 'unproven'
2245
+ // signal that let @bsv/mandala's broadcastAcceptedTx clear an 'accepted'
2246
+ // journal entry for a transaction nothing had broadcast on 2026-09-15.
2247
+ // Mirror the fail-closed policy already applied to the broadcast guard
2248
+ // (attemptToPostReqsToNetwork holds the WHOLE batch on this identical
2249
+ // fault): treat every txid here as if it were held, so every entry is
2250
+ // omitted below rather than any of them being reported as sent.
2251
+ devLog(
2252
+ '[StorageExpoSQLite] could not check held token reqs for sendWithResults; omitting all rather than reporting a possibly-false delivery:',
2253
+ e
2254
+ )
2255
+ heldTokenTxids = new Set(swr.map(s => s.txid))
2235
2256
  }
2236
2257
  if (heldTokenTxids.size === 0) return r
2237
2258
 
@@ -2266,7 +2287,20 @@ export class StorageExpoSQLite extends StorageProvider {
2266
2287
  ): Promise<PostReqsToNetworkResult> {
2267
2288
  if (reqs.length === 0) return await super.attemptToPostReqsToNetwork(reqs, trx, logger)
2268
2289
 
2269
- const tokenTxids = await this.tokenSettlementTxids(reqs.map(r => r.txid))
2290
+ let tokenTxids: Set<string>
2291
+ try {
2292
+ tokenTxids = await this.tokenSettlementTxids(reqs.map(r => r.txid))
2293
+ } catch (e) {
2294
+ // XR-045: the read could not be answered, so this call does not know
2295
+ // which of `reqs` are token requests — and "I could not tell" must never
2296
+ // resolve to "post them", the exact fail-open this guard exists to
2297
+ // prevent. Hold the WHOLE batch, as if every txid in it needed the
2298
+ // drain: a plain BSV req held this way is not lost, only delayed until
2299
+ // `processOfflineActions` (or a later, healthy read) finds no settlement
2300
+ // row for it and posts it normally.
2301
+ devLog('[StorageExpoSQLite] could not read token_settlements; holding the whole batch rather than guessing:', e)
2302
+ tokenTxids = new Set(reqs.map(r => r.txid))
2303
+ }
2270
2304
  const tokenReqs = tokenTxids.size > 0 ? reqs.filter(r => tokenTxids.has(r.txid)) : []
2271
2305
  const rest = tokenTxids.size > 0 ? reqs.filter(r => !tokenTxids.has(r.txid)) : reqs
2272
2306
 
@@ -67,7 +67,23 @@ export const TABLE_COLUMNS: Record<string, string[]> = {
67
67
  'txid',
68
68
  'inputBEEF',
69
69
  'rawTx',
70
- 'provenTxId'
70
+ 'provenTxId',
71
+ // NEW-01: BRC-177 lifecycle columns (core/storage/schema/createTables.ts's
72
+ // ensureTransactionsColumns) — without these here, a noRawTx-projected
73
+ // findTransactions() silently drops them even though the table has them.
74
+ 'noSendExpiryMode',
75
+ 'noSendExpiryValue',
76
+ 'noSendExpiryDeadline',
77
+ 'noSendExpiryState',
78
+ 'noSendExpiryAnchorTxid',
79
+ 'noSendExpiryAnchorVout',
80
+ 'noSendExpiryReleasedAt',
81
+ 'noSendExpiryObservedAt',
82
+ 'noSendExpiryReclaimTxid',
83
+ 'noSendExpiryReclaimRawTx',
84
+ 'noSendExpiryReclaimDerivationPrefix',
85
+ 'noSendExpiryReclaimDerivationSuffix',
86
+ 'noSendExpiryReclaimSatoshis'
71
87
  ],
72
88
  outputs: [
73
89
  'outputId',
@@ -113,7 +129,10 @@ export const TABLE_COLUMNS: Record<string, string[]> = {
113
129
  export const BLOB_COLUMNS: Record<string, string[]> = {
114
130
  proven_txs: ['merklePath', 'rawTx'],
115
131
  proven_tx_reqs: ['rawTx', 'inputBEEF'],
116
- transactions: ['inputBEEF', 'rawTx'],
132
+ // NEW-01: noSendExpiryReclaimRawTx is a BLOB (the signed reclaim tx bytes)
133
+ // exactly like rawTx/inputBEEF — declared here so writes go through the same
134
+ // explicit bytesForColumn() path as every other blob column.
135
+ transactions: ['inputBEEF', 'rawTx', 'noSendExpiryReclaimRawTx'],
117
136
  outputs: ['lockingScript'],
118
137
  commissions: ['lockingScript']
119
138
  }
@@ -11,8 +11,17 @@
11
11
  * 'queued'/'posting', so a parked row is inert by construction — it exists to
12
12
  * keep the frame (for re-showing the code) and to keep the transaction
13
13
  * cancellable.
14
+ *
15
+ * `import_hold` is the same kind of deliberately-inert status, written only by
16
+ * ui/importDatabases.ts: a raw database import downgrades every 'queued'/
17
+ * 'posting' row it copies in to this status so the automatic post-build drain
18
+ * (WalletContext's TaskSendOffline) cannot rebroadcast an already-signed
19
+ * payment the user may have aborted, without a renewed review (XR-085). No
20
+ * query anywhere promotes a row out of 'import_hold' — until that review UI
21
+ * exists, an imported queue row stays held rather than being silently dropped
22
+ * or silently resumed.
14
23
  */
15
- export type OfflineActionStatus = 'queued' | 'posting' | 'sent' | 'rejected' | 'acknowledged' | 'parked'
24
+ export type OfflineActionStatus = 'queued' | 'posting' | 'sent' | 'rejected' | 'acknowledged' | 'parked' | 'import_hold'
16
25
  export type OfflineActionRole = 'received' | 'sent'
17
26
 
18
27
  export interface OfflineActionRow {
@@ -18,7 +18,7 @@
18
18
  * database reads, writes and logging, which is validated on device.
19
19
  */
20
20
  import { Beef } from '@bsv/sdk'
21
- import { attemptToPostReqsToNetwork, EntityProvenTxReq } from '@bsv/wallet-toolbox-mobile'
21
+ import { attemptToPostReqsToNetwork, EntityProvenTx, EntityProvenTxReq } from '@bsv/wallet-toolbox-mobile'
22
22
  import type { TableProvenTxReq, TableTransaction } from '@bsv/wallet-toolbox-mobile'
23
23
  import type { StorageExpoSQLite } from '../StorageExpoSQLite'
24
24
  import { findOfflineActions, updateOfflineAction, type OfflineActionRow, type OfflineDb } from './offlineActions'
@@ -33,13 +33,7 @@ import {
33
33
  } from '../../offline/plan'
34
34
  import { descendantsOf, type OrderableTx } from '../../offline/order'
35
35
  import { postTokenStep, reconcileSettlements, type TokenFrameSource } from '../../mandala/drain'
36
- import type {
37
- AdmissionVerifier,
38
- CoverFn,
39
- SettlementStore,
40
- SubmitFn,
41
- TokenSettlementRow
42
- } from '../../mandala/types'
36
+ import type { AdmissionVerifier, CoverFn, SettlementStore, SubmitFn, TokenSettlementRow } from '../../mandala/types'
43
37
  import { devLog } from '../../logging'
44
38
  import { getOnline } from '../../net/online'
45
39
 
@@ -51,7 +45,13 @@ export const STALL_FOREIGN_ANCESTOR = 'offline_stall_foreign_ancestor'
51
45
  export interface ProcessOfflineActionsResult {
52
46
  /** Queue rows moved to 'sent'. A foreign ancestor's broadcast is logged, not counted. */
53
47
  sent: number
54
- /** Transactions whose local records were changed to record a rejection. */
48
+ /**
49
+ * Transactions whose local records were changed to record a rejection.
50
+ * Includes both a rejection this pass's own cascade decided and a stale
51
+ * 'sent' row this pass reconciled against a since-invalidated request
52
+ * (XQ-009 remainder) — both are "a local record changed to record a
53
+ * rejection", and neither needs its own counter.
54
+ */
55
55
  rejected: number
56
56
  /**
57
57
  * True if at least one subtree of the plan could not finish and was left
@@ -152,12 +152,28 @@ export async function processOfflineActions(args: {
152
152
  }
153
153
  }
154
154
 
155
+ // XQ-009 remainder: a row this device once honestly marked 'sent' (real
156
+ // proof, or a real broadcast) can still have its backing request later
157
+ // reclaimed by the toolbox's own proof-timeout machinery
158
+ // (`EntityProvenTxReq`'s `applyProofTimeout`, reached from `TaskSendWaiting`
159
+ // once `attempts` runs out) if the transaction never actually confirms — a
160
+ // reorg, or a rarer race. When that happens the toolbox's OWN request row
161
+ // already reflects it (`status: 'invalid'`) and has already reclaimed the
162
+ // spendable inputs; this queue's own 'sent' row just never learns about it,
163
+ // leaving the activity list and any resend logic reading a stale success
164
+ // forever. Purely local and read-only against the toolbox's own tables —
165
+ // it never re-broadcasts, aborts, or writes a transaction/request row
166
+ // itself, only brings this queue's bookkeeping in line with a decision the
167
+ // toolbox already made — so it runs unconditionally, before the
168
+ // connectivity probe and even when there is nothing else to do this pass.
169
+ const staleReconciled = await reconcileStaleSentActions(storage, db)
170
+
155
171
  // 'posting' is included so a run interrupted mid-flight resumes rather than
156
172
  // stranding its rows. Re-posting is safe: a transaction the network already has
157
173
  // comes back as accepted (ARC's `SEEN_ON_NETWORK`), and a request storage has
158
174
  // already recorded as delivered is not posted again at all — see `postOwned`.
159
175
  const queued = await findOfflineActions(db, { status: ['queued', 'posting'] })
160
- if (queued.length === 0) return { sent: 0, rejected: 0, stopped: false }
176
+ if (queued.length === 0) return { sent: 0, rejected: staleReconciled, stopped: false }
161
177
 
162
178
  // BEFORE the connectivity probe, because it needs none: a row whose request
163
179
  // storage already records as delivered ('unmined', 'completed', …) has
@@ -181,11 +197,11 @@ export async function processOfflineActions(args: {
181
197
  rows.push(row)
182
198
  }
183
199
  }
184
- if (rows.length === 0) return { sent, rejected: 0, stopped: false }
200
+ if (rows.length === 0) return { sent, rejected: staleReconciled, stopped: false }
185
201
 
186
202
  if (!(await probeOnline())) {
187
203
  devLog(`[processOfflineActions] offline, leaving ${rows.length} action(s) queued`)
188
- return { sent, rejected: 0, stopped: true }
204
+ return { sent, rejected: staleReconciled, stopped: true }
189
205
  }
190
206
 
191
207
  // Merge every held request's BEEF into one graph. Anything that cannot be read
@@ -251,7 +267,7 @@ export async function processOfflineActions(args: {
251
267
  const txs: OrderableTx[] = merged.txs
252
268
  const plan = planRelease({ rows, txs })
253
269
 
254
- let rejected = 0
270
+ let rejected = staleReconciled
255
271
  const resolved = new Set<string>()
256
272
  const skip = new Set<string>()
257
273
  const stallNotes: string[] = blocked.length > 0 ? [...blocked] : []
@@ -469,6 +485,53 @@ async function findReq(storage: StorageExpoSQLite, txid: string): Promise<TableP
469
485
  }
470
486
  }
471
487
 
488
+ /**
489
+ * XQ-009 remainder: bring a 'sent' queue row back in line once its backing
490
+ * request has since been invalidated.
491
+ *
492
+ * A row only ever reaches 'sent' from either a real, verified proof
493
+ * (`postOwned`/`postForeign`'s Merkle-path-checked `networkAlreadyHas`) or
494
+ * this device's own successful broadcast — never from a bare, unauthenticated
495
+ * status claim (that is exactly what XQ-009's own fix closed). What this
496
+ * reconciles is the narrower case left after that: a transaction that really
497
+ * did look delivered at the time can still fail to confirm — a reorg, or a
498
+ * rarer race — and the toolbox's OWN monitor eventually notices on its own
499
+ * timeline (`EntityProvenTxReq`'s proof-timeout marks the request `invalid`
500
+ * once its retry budget is exhausted, `TaskSendWaiting` reclaiming the
501
+ * spendable inputs as part of that). Nothing here decides any of that, or
502
+ * touches a proven_tx_req/transaction row at all — it only reads what the
503
+ * toolbox already decided and updates this queue's OWN bookkeeping table to
504
+ * match, so the activity list and any resend logic stop reading a stale
505
+ * 'sent' as reality. Never re-broadcasts, never releases or aborts anything.
506
+ *
507
+ * Read-only against `findOfflineActions`/`findReq`, both already
508
+ * fault-tolerant (a read failure there returns nothing, not a throw), so a
509
+ * failure here costs only a skipped row for one pass, not the rest of the
510
+ * run — errors are still caught around the one write, for the same reason.
511
+ */
512
+ async function reconcileStaleSentActions(storage: StorageExpoSQLite, db: OfflineDb): Promise<number> {
513
+ let sentRows: OfflineActionRow[]
514
+ try {
515
+ sentRows = await findOfflineActions(db, { status: ['sent'] })
516
+ } catch (e) {
517
+ devLog('[processOfflineActions] could not read sent rows to reconcile:', e)
518
+ return 0
519
+ }
520
+ let reconciled = 0
521
+ for (const row of sentRows) {
522
+ const api = await findReq(storage, row.txid)
523
+ if (api?.status !== 'invalid') continue
524
+ try {
525
+ await updateOfflineAction(db, row.txid, { status: 'rejected', rejectedReason: 'proof_timeout' })
526
+ devLog(`[processOfflineActions] reconciled stale 'sent' row ${row.txid}: its request is now 'invalid'`)
527
+ reconciled++
528
+ } catch (e) {
529
+ devLog(`[processOfflineActions] could not reconcile stale 'sent' row ${row.txid}:`, e)
530
+ }
531
+ }
532
+ return reconciled
533
+ }
534
+
472
535
  /** Return every unresolved row we may have moved to 'posting' to 'queued'. */
473
536
  async function requeue(db: OfflineDb, plan: { txid: string; owned: boolean }[], resolved: Set<string>): Promise<void> {
474
537
  for (const step of plan) {
@@ -526,7 +589,7 @@ async function postOwned(storage: StorageExpoSQLite, api: TableProvenTxReq): Pro
526
589
  // can only read as serviceError: re-held, re-queued, and stuck on every tick
527
590
  // while the activity list says settled (2026-09-16). Asking first costs one
528
591
  // status lookup and lets storage record what already happened.
529
- if (await networkAlreadyHas(storage, api.txid)) {
592
+ if (await networkAlreadyHas(storage, api.txid, api.rawTx)) {
530
593
  devLog(`[processOfflineActions] the network already has ${api.txid}; recording delivery without a post`)
531
594
  await recordDeliveredElsewhere(storage, api)
532
595
  return 'success'
@@ -605,21 +668,47 @@ export async function postOwnedByTxid(storage: StorageExpoSQLite, txid: string):
605
668
  return await postOwned(storage, api)
606
669
  }
607
670
 
671
+ /** Whatever `EntityProvenTx.fromTxid` actually needs — extracted rather than
672
+ * importing the (unexported) `WalletServices` type by name. */
673
+ type ProvenTxServices = Parameters<typeof EntityProvenTx.fromTxid>[1]
674
+
608
675
  /**
609
- * Whether the network already has `txid`, by the services' own status lookup
610
- * ('mined' or 'known'). Every failure — no such service, a transport fault, an
611
- * unexpected shape — is `false`: the answer then falls back to the ordinary
612
- * post, whose own result decides. Never a reason to stall.
676
+ * Whether the network already has `txid`, PROVEN.
677
+ *
678
+ * XQ-009: a bare `getStatusForTxids` 'mined'/'known' string costs nothing for
679
+ * an attacker who controls, or MITMs, the status endpoint — and both callers
680
+ * below treat a `true` answer as licence to skip this device's own broadcast
681
+ * and record the transaction as durably delivered, with no reconciliation
682
+ * path if that later turns out to be wrong. So the status string is only the
683
+ * cheap first check; a positive answer must still be confirmed by the same
684
+ * chain-tracker-validated proof the toolbox's own `TaskCheckForProofs`
685
+ * already trusts (`EntityProvenTx.fromTxid`) — this device's OWN `rawTx`
686
+ * (never fetched from the network) plus a Merkle path whose root validates
687
+ * against this wallet's independently-maintained chain tracker. Forging a
688
+ * status string is free; forging a Merkle path that validates against a real
689
+ * chain tracker would require actually getting the transaction mined.
690
+ *
691
+ * `rawTx` is optional only so a caller with no local copy of the candidate
692
+ * transaction (a foreign ancestor whose beef entry is txid-only) degrades to
693
+ * the pre-existing "no proof, no shortcut" answer rather than skipping proof
694
+ * entirely — it never widens what counts as proof.
695
+ *
696
+ * Every failure — no such service, a transport fault, an unexpected shape, no
697
+ * valid proof — is `false`: the answer then falls back to the ordinary post,
698
+ * whose own result decides. Never a reason to stall.
613
699
  */
614
- async function networkAlreadyHas(storage: StorageExpoSQLite, txid: string): Promise<boolean> {
700
+ async function networkAlreadyHas(storage: StorageExpoSQLite, txid: string, rawTx?: number[]): Promise<boolean> {
615
701
  try {
616
- const services = storage.getServices() as {
702
+ const services = storage.getServices() as ProvenTxServices & {
617
703
  getStatusForTxids?: (txids: string[]) => Promise<{ results?: { txid: string; status: string }[] }>
618
704
  }
619
705
  if (typeof services.getStatusForTxids !== 'function') return false
620
706
  const r = await services.getStatusForTxids([txid])
621
707
  const status = r.results?.find(x => x.txid === txid)?.status
622
- return status === 'mined' || status === 'known'
708
+ if (status !== 'mined' && status !== 'known') return false
709
+ if (!rawTx) return false
710
+ const { proven } = await EntityProvenTx.fromTxid(txid, services, rawTx)
711
+ return proven !== undefined
623
712
  } catch (e) {
624
713
  devLog(`[processOfflineActions] could not ask the network whether it has ${txid}:`, e)
625
714
  return false
@@ -675,8 +764,12 @@ async function closeSettlementAsBroadcast(store: SettlementStore, txid: string):
675
764
  async function postForeign(storage: StorageExpoSQLite, merged: Beef, txid: string): Promise<PostOutcome> {
676
765
  // Same witness as `postOwned`: an ancestor that arrived inside a counterparty's
677
766
  // BEEF was usually broadcast by that counterparty already, and a failed
678
- // re-post of it would block every owned transaction behind it.
679
- if (await networkAlreadyHas(storage, txid)) {
767
+ // re-post of it would block every owned transaction behind it. The
768
+ // candidate rawTx for the proof check comes from the merged graph itself
769
+ // (a counterparty's own bytes) rather than the network — absent only when
770
+ // that entry is txid-only, in which case `networkAlreadyHas` degrades to
771
+ // its pre-existing "no proof, no shortcut" answer.
772
+ if (await networkAlreadyHas(storage, txid, merged.findTxid(txid)?.tx?.toBinary())) {
680
773
  devLog(`[processOfflineActions] the network already has foreign ancestor ${txid}; not posting`)
681
774
  return 'success'
682
775
  }