@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
@@ -4,6 +4,15 @@
4
4
  * A failed abort is a stuck UTXO, not a lost payment. The decline still
5
5
  * stands; the reference is retried on the next wallet build.
6
6
  */
7
+ import { ADMIN_ORIGINATOR, LEGACY_ADMIN_ORIGINATOR } from '../config'
8
+ import { VAULT_ABORT_REPLAY_MARKER } from '../services/vault/guard'
9
+ import {
10
+ computePendingAbortAuthorityTag,
11
+ verifyPendingAbortAuthorityTag,
12
+ type PendingAbortTagWallet,
13
+ type PendingAbortVerifyWallet
14
+ } from './pendingAbortAuthority'
15
+
7
16
  interface StorageLike {
8
17
  getKeyValue: (key: string) => Promise<string | undefined>
9
18
  setKeyValue: (key: string, value: string) => Promise<void>
@@ -14,21 +23,232 @@ export const PENDING_ABORTS_KEY = 'pending_aborts'
14
23
  export interface PendingAbort {
15
24
  reference: string
16
25
  originator: string
26
+ /** XR-102: HMAC over `reference`, computed by `queuePendingAbort` with the
27
+ * ADMIN-scoped wallet under the reserved `pending abort authority`
28
+ * namespace (see pendingAbortAuthority.ts). Absent on a legacy pre-XR-102
29
+ * entry or a forged one — `replayPendingAborts` drops either, never
30
+ * replays them. */
31
+ tag?: string
32
+ }
33
+
34
+ function messageOf(e: unknown): string {
35
+ return e instanceof Error && e.message ? e.message : String(e)
36
+ }
37
+
38
+ // XR-088: every read-modify-write sequence on PENDING_ABORTS_KEY shares one
39
+ // storage key, so they must not interleave — a concurrent write built from a
40
+ // stale read silently drops (or resurrects) an entry. `queuePendingAbort` and
41
+ // `replayPendingAborts` each used to be a bare load-then-setKeyValue with no
42
+ // lock between them; both now run through this chain. Same pattern as
43
+ // core/localpay/pending.ts's own withQueueLock, for the identical reason.
44
+ let pendingAbortsLock: Promise<unknown> = Promise.resolve()
45
+
46
+ function withPendingAbortsLock<T>(fn: () => Promise<T>): Promise<T> {
47
+ const run = pendingAbortsLock.then(fn, fn)
48
+ pendingAbortsLock = run.catch(() => undefined)
49
+ return run
50
+ }
51
+
52
+ /** XR-088 (SEC1-026's own second, separately-named defect): a sentinel that
53
+ * distinguishes "the key is genuinely absent/empty" from "the read or parse
54
+ * itself failed" — the two used to be collapsed into the same `[]`, which let
55
+ * `queuePendingAbort` treat a transient storage hiccup as an authoritative
56
+ * empty queue and overwrite every other durable, not-yet-replayed reference
57
+ * with just the one item it was trying to add. */
58
+ const READ_FAILED = Symbol('pending-aborts-read-failed')
59
+
60
+ function parsePendingAborts(parsed: unknown): PendingAbort[] | typeof READ_FAILED {
61
+ if (!Array.isArray(parsed)) return READ_FAILED
62
+ const out: PendingAbort[] = []
63
+ for (const item of parsed) {
64
+ if (!item || typeof item !== 'object') continue
65
+ const reference = (item as { reference?: unknown }).reference
66
+ const originator = (item as { originator?: unknown }).originator
67
+ const tag = (item as { tag?: unknown }).tag
68
+ if (typeof reference === 'string' && reference && typeof originator === 'string') {
69
+ out.push({
70
+ reference,
71
+ // An abort queued before the internal label moved into hostname space
72
+ // would otherwise fail originator validation on every replay, forever.
73
+ originator: originator === LEGACY_ADMIN_ORIGINATOR ? ADMIN_ORIGINATOR : originator,
74
+ ...(typeof tag === 'string' && tag ? { tag } : {})
75
+ })
76
+ }
77
+ }
78
+ return out
79
+ }
80
+
81
+ async function loadPendingAbortsOrFail(storage: StorageLike): Promise<PendingAbort[] | typeof READ_FAILED> {
82
+ let raw: string | undefined
83
+ try {
84
+ raw = await storage.getKeyValue(PENDING_ABORTS_KEY)
85
+ } catch (e) {
86
+ console.warn('[localpay] could not read the pending-abort queue:', messageOf(e))
87
+ return READ_FAILED
88
+ }
89
+ if (!raw) return []
90
+ let parsed: unknown
91
+ try {
92
+ parsed = JSON.parse(raw)
93
+ } catch (e) {
94
+ console.warn('[localpay] the pending-abort queue is not valid JSON:', messageOf(e))
95
+ return READ_FAILED
96
+ }
97
+ return parsePendingAborts(parsed)
17
98
  }
18
99
 
19
100
  export async function loadPendingAborts(storage: StorageLike): Promise<PendingAbort[]> {
101
+ const result = await loadPendingAbortsOrFail(storage)
102
+ return result === READ_FAILED ? [] : result
103
+ }
104
+
105
+ export async function queuePendingAbort(
106
+ storage: StorageLike,
107
+ item: PendingAbort,
108
+ /** XR-102: the ADMIN-scoped wallet (and its originator) this entry's
109
+ * authenticity tag is computed with — every real call site already has
110
+ * one, since it is the same wallet `abortAction` itself is called on. */
111
+ authority: { wallet: PendingAbortTagWallet; originator: string }
112
+ ): Promise<void> {
113
+ if (!item.reference) return
114
+ return withPendingAbortsLock(async () => {
115
+ const loaded = await loadPendingAbortsOrFail(storage)
116
+ if (loaded === READ_FAILED) {
117
+ // XR-088: never overwrite on a read/parse failure — fail this queue
118
+ // call instead. Every real call site already wraps queuePendingAbort in
119
+ // its own best-effort `.catch()`, so this costs exactly one reference
120
+ // not being queued THIS attempt (the same outcome a rejected write
121
+ // would have had); what it does NOT cost is every other, unrelated,
122
+ // already-durable abort reference silently erased underneath it.
123
+ throw new Error('pending_aborts: could not read the existing queue, refusing to overwrite it')
124
+ }
125
+ if (loaded.some(a => a.reference === item.reference)) return
126
+ let tag: string | undefined
127
+ try {
128
+ tag = await computePendingAbortAuthorityTag(authority.wallet, authority.originator, item.reference)
129
+ } catch (e) {
130
+ // An untagged entry can never pass replayPendingAborts's verification
131
+ // (below) and so can never auto-release — but it is still worth
132
+ // recording durably rather than losing the reference outright: it stays
133
+ // visible, and a stuck `nosend` row remains recoverable through
134
+ // WalletHomeScreen's manual per-row abort, which does not go through
135
+ // this queue or its authority check at all.
136
+ console.warn('[localpay] could not tag a pending abort for authenticated replay:', messageOf(e))
137
+ }
138
+ await storage.setKeyValue(PENDING_ABORTS_KEY, JSON.stringify([...loaded, { ...item, ...(tag ? { tag } : {}) }]))
139
+ })
140
+ }
141
+
142
+ export interface ReplayPendingAbortsResult {
143
+ /** XR-102: entries dropped because their authority tag was missing or did
144
+ * not verify — never replayed, never called abortAction. Surfaced so the
145
+ * UI can tell the user something was ignored, in case it corresponds to a
146
+ * payment that now looks stuck (still recoverable via WalletHomeScreen's
147
+ * per-row Cancel, which does not depend on this queue). */
148
+ droppedUntrusted: number
149
+ }
150
+
151
+ export async function replayPendingAborts(args: {
152
+ wallet: {
153
+ abortAction: (
154
+ args: { reference: string; [VAULT_ABORT_REPLAY_MARKER]?: true },
155
+ originator?: string
156
+ ) => Promise<{ aborted?: boolean } | void>
157
+ } & PendingAbortVerifyWallet
158
+ storage: StorageLike
159
+ }): Promise<ReplayPendingAbortsResult> {
160
+ return withPendingAbortsLock(async () => {
161
+ const pending = await loadPendingAborts(args.storage)
162
+ if (pending.length === 0) return { droppedUntrusted: 0 }
163
+ const kept: PendingAbort[] = []
164
+ let droppedUntrusted = 0
165
+ for (const item of pending) {
166
+ // XR-102 (non-Vault residual): the vault-inventory replay marker below
167
+ // only protects a Vault reference — an ordinary localpay/PeerPay
168
+ // reference has no settlement row and no vault-inventory entry, so
169
+ // nothing else stops a forged `pending_aborts` entry naming one from
170
+ // being replayed. Authenticate first: an entry this wallet did not
171
+ // itself tag at queue time (queuePendingAbort) is dropped, never
172
+ // replayed — fail closed, since the only thing a replay ever does is
173
+ // free a reservation, and a dropped reference stays recoverable through
174
+ // WalletHomeScreen's manual per-row abort.
175
+ const authentic = await verifyPendingAbortAuthorityTag(args.wallet, ADMIN_ORIGINATOR, item.reference, item.tag)
176
+ if (!authentic) {
177
+ droppedUntrusted++
178
+ continue
179
+ }
180
+ try {
181
+ // XR-102: the persisted `originator` is never trusted here — this is a
182
+ // raw KV record, writable by anything with local storage access, and a
183
+ // forged admin-originator string used to replay straight past
184
+ // guardVaultAccess's inventory check. The ONLY originator ever used to
185
+ // replay is the real, imported constant every legitimate queued abort
186
+ // was already created under (see queuePendingAbort's call sites — all
187
+ // pass `adminOriginator`), never the field read back off disk.
188
+ //
189
+ // That alone is not enough: `assertPendingActionOriginator` requires
190
+ // this exact originator for a legitimate replay to succeed at all, and
191
+ // guardVaultAccess treats every admin-originator call as trusted. The
192
+ // marker opts this specific call OUT of that trust and into the same
193
+ // vault-inventory reference check a non-admin caller gets — so a
194
+ // reference an attacker injected that happens to name a Vault action is
195
+ // refused, while an ordinary (and authentically-tagged) localpay/
196
+ // PeerPay reference still replays.
197
+ const result = await args.wallet.abortAction(
198
+ { reference: item.reference, [VAULT_ABORT_REPLAY_MARKER]: true },
199
+ ADMIN_ORIGINATOR
200
+ )
201
+ if (result && typeof result === 'object' && result.aborted === false) {
202
+ kept.push(item)
203
+ }
204
+ } catch {
205
+ kept.push(item)
206
+ }
207
+ }
208
+ await args.storage.setKeyValue(PENDING_ABORTS_KEY, JSON.stringify(kept))
209
+ return { droppedUntrusted }
210
+ })
211
+ }
212
+
213
+ /**
214
+ * Durable watch list for a DECLINED payment (build.ts's `finalizeDelivery`)
215
+ * whose txid might, despite the decline, still reach the chain.
216
+ *
217
+ * A negative ack is the payee's own unverifiable claim that nothing was
218
+ * queued — this codebase's own abort-chain-protection only refuses an abort
219
+ * while a service is reachable AND the chain already knows the tx, so a
220
+ * decline made while offline (or a dishonest one) still releases the payer's
221
+ * inputs. Policy here is detect-and-warn, never block: the inputs are freed
222
+ * immediately either way, exactly as before this existed, and this list only
223
+ * exists so a later reappearance of that same txid on chain can be surfaced
224
+ * rather than silently missed — see `verifyDeclinedAborts`.
225
+ */
226
+ export const DECLINED_ABORT_WATCH_KEY = 'declined_abort_watch'
227
+
228
+ export interface DeclinedAbortWatch {
229
+ txid: string
230
+ reference: string
231
+ /** Best-effort; presentational only, never used to key the watch itself. */
232
+ peerIdentityKey?: string
233
+ /** `Date.now()` when the decline was recorded, for the bounded-age drop. */
234
+ at: number
235
+ }
236
+
237
+ /** How long an unresolved watch entry is kept before it is dropped unsurfaced. */
238
+ export const DECLINED_ABORT_WATCH_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000
239
+
240
+ export async function loadDeclinedAbortWatch(storage: StorageLike): Promise<DeclinedAbortWatch[]> {
20
241
  try {
21
- const raw = await storage.getKeyValue(PENDING_ABORTS_KEY)
242
+ const raw = await storage.getKeyValue(DECLINED_ABORT_WATCH_KEY)
22
243
  if (!raw) return []
23
244
  const parsed = JSON.parse(raw) as unknown
24
245
  if (!Array.isArray(parsed)) return []
25
- const out: PendingAbort[] = []
246
+ const out: DeclinedAbortWatch[] = []
26
247
  for (const item of parsed) {
27
248
  if (!item || typeof item !== 'object') continue
28
- const reference = (item as { reference?: unknown }).reference
29
- const originator = (item as { originator?: unknown }).originator
30
- if (typeof reference === 'string' && reference && typeof originator === 'string') {
31
- out.push({ reference, originator })
249
+ const { txid, reference, peerIdentityKey, at } = item as Record<string, unknown>
250
+ if (typeof txid === 'string' && txid && typeof reference === 'string' && typeof at === 'number') {
251
+ out.push({ txid, reference, at, ...(typeof peerIdentityKey === 'string' ? { peerIdentityKey } : {}) })
32
252
  }
33
253
  }
34
254
  return out
@@ -37,31 +257,51 @@ export async function loadPendingAborts(storage: StorageLike): Promise<PendingAb
37
257
  }
38
258
  }
39
259
 
40
- export async function queuePendingAbort(storage: StorageLike, item: PendingAbort): Promise<void> {
41
- if (!item.reference) return
42
- const all = await loadPendingAborts(storage)
43
- if (all.some(a => a.reference === item.reference)) return
44
- await storage.setKeyValue(PENDING_ABORTS_KEY, JSON.stringify([...all, item]))
260
+ export async function queueDeclinedAbortWatch(storage: StorageLike, item: DeclinedAbortWatch): Promise<void> {
261
+ if (!item.txid) return
262
+ const all = await loadDeclinedAbortWatch(storage)
263
+ if (all.some(a => a.txid === item.txid)) return
264
+ await storage.setKeyValue(DECLINED_ABORT_WATCH_KEY, JSON.stringify([...all, item]))
45
265
  }
46
266
 
47
- export async function replayPendingAborts(args: {
48
- wallet: {
49
- abortAction: (args: { reference: string }, originator?: string) => Promise<{ aborted?: boolean } | void>
50
- }
267
+ /**
268
+ * Asks the network about every watched txid and returns the ones it now
269
+ * reports mined or known — a declined payment that went through anyway.
270
+ * Those are removed from the watch list (surfaced once, not repeatedly); an
271
+ * unresolved one is kept, up to `DECLINED_ABORT_WATCH_MAX_AGE_MS`, after which
272
+ * it is dropped unsurfaced rather than watched forever. An honest decline,
273
+ * where the network never reports the txid, never surfaces anything.
274
+ *
275
+ * `getStatusForTxids` is the exact call this codebase already makes for the
276
+ * same question elsewhere (core/storage/methods/processOfflineActions.ts's
277
+ * `networkAlreadyHas`) — injected here rather than imported so this stays
278
+ * unit-testable without a real storage/services object.
279
+ */
280
+ export async function verifyDeclinedAborts(args: {
51
281
  storage: StorageLike
52
- }): Promise<void> {
53
- const pending = await loadPendingAborts(args.storage)
54
- if (pending.length === 0) return
55
- const kept: PendingAbort[] = []
56
- for (const item of pending) {
282
+ getStatusForTxids: (txids: string[]) => Promise<{ results?: { txid: string; status: string }[] }>
283
+ }): Promise<DeclinedAbortWatch[]> {
284
+ const watched = await loadDeclinedAbortWatch(args.storage)
285
+ if (watched.length === 0) return []
286
+ const now = Date.now()
287
+ const surfaced: DeclinedAbortWatch[] = []
288
+ const kept: DeclinedAbortWatch[] = []
289
+ for (const item of watched) {
290
+ let status: string | undefined
57
291
  try {
58
- const result = await args.wallet.abortAction({ reference: item.reference }, item.originator)
59
- if (result && typeof result === 'object' && result.aborted === false) {
60
- kept.push(item)
61
- }
292
+ const r = await args.getStatusForTxids([item.txid])
293
+ status = r.results?.find(x => x.txid === item.txid)?.status
62
294
  } catch {
63
- kept.push(item)
295
+ // Treat a failed probe as still-unknown, not as a negative result —
296
+ // the next reconnect tries again.
297
+ status = undefined
298
+ }
299
+ if (status === 'mined' || status === 'known') {
300
+ surfaced.push(item)
301
+ continue
64
302
  }
303
+ if (now - item.at < DECLINED_ABORT_WATCH_MAX_AGE_MS) kept.push(item)
65
304
  }
66
- await args.storage.setKeyValue(PENDING_ABORTS_KEY, JSON.stringify(kept))
305
+ await args.storage.setKeyValue(DECLINED_ABORT_WATCH_KEY, JSON.stringify(kept))
306
+ return surfaced
67
307
  }
@@ -44,6 +44,16 @@ export const RUNG_MASK = 0x00ff
44
44
 
45
45
  export type SessionOs = 'ios' | 'android'
46
46
 
47
+ /**
48
+ * Bound on `SessionAsset.decimals` (XR-043), mirrored at every other boundary
49
+ * that ever reads a token's decimals — `ui/tokenFormat.ts`'s formatters and
50
+ * `core/mandala/createRuntime.ts`'s asset-metadata resolution. Nothing
51
+ * token-shaped this wallet knows of uses more than a handful; an unbounded
52
+ * value here is how an extreme decimals figure from a session QR reaches
53
+ * `String(...).padStart` deep in the confirmation UI and blows up the render.
54
+ */
55
+ export const MAX_TOKEN_DECIMALS = 18
56
+
47
57
  /**
48
58
  * The asset a token request names. When present on a Session, `amount` is
49
59
  * BASE UNITS of this asset, not satoshis, and remains a binding term.
@@ -121,6 +131,16 @@ export function mintSession(args: {
121
131
  if (args.asset !== undefined && args.asset.overlayIdentityKey.length !== 66) {
122
132
  throw new CodecError('bad asset overlayIdentityKey')
123
133
  }
134
+ // XR-043: same bound `decodeSession` enforces below, checked here too for
135
+ // the same reason `amount` is — an out-of-range figure minted on THIS
136
+ // device would render (and crash) on its own screen before any decoder
137
+ // ever saw it.
138
+ if (
139
+ args.asset?.decimals !== undefined &&
140
+ (!Number.isInteger(args.asset.decimals) || args.asset.decimals < 0 || args.asset.decimals > MAX_TOKEN_DECIMALS)
141
+ ) {
142
+ throw new CodecError('bad asset decimals')
143
+ }
124
144
  return {
125
145
  version: SESSION_VERSION,
126
146
  caps:
@@ -136,7 +156,7 @@ export function mintSession(args: {
136
156
  ...(args.asset === undefined ? {} : { asset: args.asset }),
137
157
  derivationPrefix: args.derivationPrefix,
138
158
  derivationSuffix: args.derivationSuffix,
139
- ...(args.os === undefined ? {} : { os: args.os }),
159
+ ...(args.os === undefined ? {} : { os: args.os })
140
160
  }
141
161
  }
142
162
 
@@ -176,18 +196,20 @@ export function encodeSession(s: Session): string {
176
196
  i: s.identityKey,
177
197
  ...(s.os === undefined ? {} : { o: s.os === 'ios' ? 'i' : 'a' }),
178
198
  ...(s.amount === undefined ? {} : { a: s.amount }),
179
- ...(s.asset === undefined ? {} : {
180
- t: {
181
- i: s.asset.id,
182
- ...(s.asset.label === undefined ? {} : { n: s.asset.label }),
183
- ...(s.asset.ticker === undefined ? {} : { s: s.asset.ticker }),
184
- ...(s.asset.decimals === undefined ? {} : { d: s.asset.decimals }),
185
- u: s.asset.overlayUrl,
186
- k: s.asset.overlayIdentityKey,
187
- },
188
- }),
199
+ ...(s.asset === undefined
200
+ ? {}
201
+ : {
202
+ t: {
203
+ i: s.asset.id,
204
+ ...(s.asset.label === undefined ? {} : { n: s.asset.label }),
205
+ ...(s.asset.ticker === undefined ? {} : { s: s.asset.ticker }),
206
+ ...(s.asset.decimals === undefined ? {} : { d: s.asset.decimals }),
207
+ u: s.asset.overlayUrl,
208
+ k: s.asset.overlayIdentityKey
209
+ }
210
+ }),
189
211
  p: s.derivationPrefix,
190
- x: s.derivationSuffix,
212
+ x: s.derivationSuffix
191
213
  })
192
214
  return 'bsvpay1:' + toB64url(new TextEncoder().encode(body))
193
215
  }
@@ -235,17 +257,20 @@ export function decodeSession(text: string): Session {
235
257
  if (typeof ok !== 'string' || ok.length !== 66) throw new CodecError('bad overlayIdentityKey')
236
258
  if (n !== undefined && typeof n !== 'string') throw new CodecError('bad asset label')
237
259
  if (tick !== undefined && typeof tick !== 'string') throw new CodecError('bad asset ticker')
238
- if (d !== undefined && (typeof d !== 'number' || !Number.isSafeInteger(d) || d < 0)) throw new CodecError('bad asset decimals')
260
+ if (d !== undefined && (typeof d !== 'number' || !Number.isSafeInteger(d) || d < 0 || d > MAX_TOKEN_DECIMALS))
261
+ throw new CodecError('bad asset decimals')
239
262
  asset = {
240
- id: ai, overlayUrl: u, overlayIdentityKey: ok,
263
+ id: ai,
264
+ overlayUrl: u,
265
+ overlayIdentityKey: ok,
241
266
  ...(n === undefined ? {} : { label: n }),
242
267
  ...(tick === undefined ? {} : { ticker: tick }),
243
- ...(d === undefined ? {} : { decimals: d }),
268
+ ...(d === undefined ? {} : { decimals: d })
244
269
  }
245
270
  }
246
271
  return {
247
272
  version: v as number,
248
- caps: (typeof c === 'number' ? c : 0),
273
+ caps: typeof c === 'number' ? c : 0,
249
274
  sessionId,
250
275
  psk,
251
276
  identityKey: i,
@@ -253,7 +278,7 @@ export function decodeSession(text: string): Session {
253
278
  ...(asset === undefined ? {} : { asset }),
254
279
  derivationPrefix: p,
255
280
  derivationSuffix: x,
256
- ...(os === undefined ? {} : { os }),
281
+ ...(os === undefined ? {} : { os })
257
282
  }
258
283
  }
259
284
 
@@ -104,15 +104,24 @@ function hexToBytes(hex: string): Uint8Array {
104
104
  * `expectTxid` binds the payload to the transaction actually handed over: an
105
105
  * ack naming a DIFFERENT txid is somebody else's admission, replayed. It
106
106
  * verifies perfectly and proves nothing about this payment.
107
+ *
108
+ * `expectVout` binds it further, to the payee's OWN output on that
109
+ * transaction (XR-093): the overlay signs `outputsToAdmit` as a set, so a
110
+ * genuine admission of a sibling output on the same tip — the payer's own
111
+ * token change, say — verifies just as well as one that actually covers the
112
+ * payee's output. Without this check the two are indistinguishable and the
113
+ * payer's screen could claim 'sent-settled' for a payment the overlay never
114
+ * admitted.
107
115
  */
108
116
  export async function readSettlementAck(
109
117
  ack: Ack,
110
- args: { overlayIdentityKey: string; expectTxid?: string; verify: VerifyAdmissionFn }
118
+ args: { overlayIdentityKey: string; expectTxid?: string; expectVout: number; verify: VerifyAdmissionFn }
111
119
  ): Promise<AdmissionEntryWire | undefined> {
112
120
  if (!ack.ok) return undefined
113
121
  const payload = decodeSettlementAck(ack.error)
114
122
  if (!payload) return undefined
115
123
  if (args.expectTxid !== undefined && payload.txid !== args.expectTxid.toLowerCase()) return undefined
124
+ if (!payload.outputsToAdmit.includes(args.expectVout)) return undefined
116
125
 
117
126
  const entry: AdmissionEntryWire = {
118
127
  txid: payload.txid,
@@ -1,4 +1,5 @@
1
1
  import type { LocalPayTransport } from '@bsv/react-native-localpay-transport'
2
+ import { MAX_MESSAGE_BYTES } from '@bsv/air-gap'
2
3
  import { sealFrame, unsealFrame, type PaymentFrame } from '../codec'
3
4
  import { instanceName, type Session } from '../session'
4
5
  import {
@@ -10,6 +11,27 @@ import {
10
11
  type ReceivedFrame
11
12
  } from '../types'
12
13
 
14
+ /**
15
+ * XR-090. The ceiling every sealed frame this device would ever SEND already
16
+ * respects — `@bsv/air-gap`'s own limit, shared with the QR/fountain encoder
17
+ * (see codec.ts's FRAME_QR_PREFIX docs) — reused here as the ceiling on what
18
+ * this device will DECODE from a counterparty. Without it, an oversized
19
+ * radio payload reached `atob()` -> AES-GCM decrypt -> JSON.parse in full
20
+ * before anything refused it: unbounded memory/CPU per received message, on
21
+ * every transport that shares this decode layer (AWDL, Nearby JS, and BLE's
22
+ * onFrame all call `fromBase64` before anything else looks at the bytes).
23
+ */
24
+ export const MAX_INBOUND_FRAME_BYTES = MAX_MESSAGE_BYTES
25
+
26
+ /**
27
+ * An ack is `{ ok: boolean, error?: string }`, and `error` is one of a
28
+ * handful of short machine codes (see `DeclineReason`) or, at most, an
29
+ * echoed message — never anything close to a frame's size. Generous headroom
30
+ * over any real reason string, nowhere near large enough to matter for
31
+ * memory/CPU even if a counterparty sends nothing but padding.
32
+ */
33
+ export const MAX_INBOUND_ACK_BYTES = 4096
34
+
13
35
  /**
14
36
  * Whole-exchange budget: connect + transfer + the payee's save + ack. Shared
15
37
  * by every socketed rung — only the connect-phase budget is radio-specific,
@@ -44,8 +66,35 @@ export function toBase64(b: Uint8Array): string {
44
66
  return globalThis.btoa(s)
45
67
  }
46
68
 
47
- export function fromBase64(s: string): Uint8Array {
48
- return Uint8Array.from(globalThis.atob(s), c => c.charCodeAt(0))
69
+ /**
70
+ * The largest base64 STRING whose decode cannot exceed `maxBytes` — checked
71
+ * before `atob()` runs, not after. Base64 expands 3 bytes to 4 characters, so
72
+ * this is the same bound `atob()` would enforce itself if it refused rather
73
+ * than happily decoding a payload of any size handed to it.
74
+ */
75
+ function maxBase64Length(maxBytes: number): number {
76
+ return Math.ceil(maxBytes / 3) * 4
77
+ }
78
+
79
+ /**
80
+ * XR-090: `maxBytes` defaults to a full frame's ceiling since that is this
81
+ * function's most common and most sensitive caller; `parseAck` below passes
82
+ * the much smaller ack ceiling explicitly. Rejects by encoded length before
83
+ * `atob()` ever runs, so an oversized payload never reaches decode at all.
84
+ */
85
+ export function fromBase64(s: string, maxBytes: number = MAX_INBOUND_FRAME_BYTES): Uint8Array {
86
+ if (s.length > maxBase64Length(maxBytes)) {
87
+ throw new Error(`base64 payload of ${s.length} chars exceeds the ${maxBytes}-byte ceiling`)
88
+ }
89
+ const bytes = Uint8Array.from(globalThis.atob(s), c => c.charCodeAt(0))
90
+ // The length check above is a cheap, coarse circuit-breaker on the ENCODED
91
+ // string (base64 groups 3 bytes into 4 characters, so it can only bound the
92
+ // decode to within a couple of bytes of `maxBytes`). This is the precise
93
+ // one, on the actual decoded length.
94
+ if (bytes.length > maxBytes) {
95
+ throw new Error(`base64 payload decodes to ${bytes.length} bytes, exceeding the ${maxBytes}-byte ceiling`)
96
+ }
97
+ return bytes
49
98
  }
50
99
 
51
100
  /**
@@ -56,7 +105,7 @@ export function fromBase64(s: string): Uint8Array {
56
105
  export function parseAck(ackBase64: string): Ack {
57
106
  let parsed: unknown
58
107
  try {
59
- parsed = JSON.parse(new TextDecoder().decode(fromBase64(ackBase64)))
108
+ parsed = JSON.parse(new TextDecoder().decode(fromBase64(ackBase64, MAX_INBOUND_ACK_BYTES)))
60
109
  } catch {
61
110
  throw new AckError('malformed ack: invalid base64 or JSON')
62
111
  }