@bsv/expo-wallet-toolbox 0.22.0 → 0.24.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 (137) hide show
  1. package/CHANGELOG.md +241 -0
  2. package/README.md +10 -9
  3. package/android/build.gradle +15 -0
  4. package/android/src/main/AndroidManifest.xml +3 -0
  5. package/android/src/main/java/org/bsv/boundedfetch/BoundedBody.java +19 -0
  6. package/android/src/main/java/org/bsv/boundedfetch/BoundedConnection.java +28 -0
  7. package/android/src/main/java/org/bsv/boundedfetch/BsvBoundedFetchModule.kt +114 -0
  8. package/core/backup/RemoteSyncReader.ts +71 -46
  9. package/core/backup/client.ts +6 -15
  10. package/core/backup/codec.ts +78 -13
  11. package/core/backup/constants.ts +3 -9
  12. package/core/backup/cursor.ts +8 -0
  13. package/core/backup/push.ts +26 -16
  14. package/core/backup/restore.ts +6 -5
  15. package/core/bridge/BrowserBridgeProvider.tsx +273 -0
  16. package/core/bridge/bindings.ts +459 -0
  17. package/core/bridge/conformance.ts +222 -0
  18. package/core/bridge/consent.ts +494 -0
  19. package/core/bridge/consentSheetSource.ts +98 -0
  20. package/core/bridge/dispatcher.ts +621 -0
  21. package/core/bridge/inbox.ts +569 -0
  22. package/core/bridge/index.ts +48 -0
  23. package/core/bridge/loopback/cors.ts +57 -0
  24. package/core/bridge/loopback/endpoints.ts +11 -0
  25. package/core/bridge/loopback/hostCheck.ts +25 -0
  26. package/core/bridge/loopback/index.ts +7 -0
  27. package/core/bridge/loopback/launchProof.ts +166 -0
  28. package/core/bridge/loopback/router.ts +770 -0
  29. package/core/bridge/loopback/routerTypes.ts +115 -0
  30. package/core/bridge/loopback/status.ts +52 -0
  31. package/core/bridge/memoryInboxStore.ts +231 -0
  32. package/core/bridge/permissionPolicy.ts +247 -0
  33. package/core/bridge/policy.ts +72 -0
  34. package/core/bridge/protocol/base64url.ts +64 -0
  35. package/core/bridge/protocol/connectionError.ts +79 -0
  36. package/core/bridge/protocol/constants.ts +21 -0
  37. package/core/bridge/protocol/continuity.ts +21 -0
  38. package/core/bridge/protocol/descriptor.ts +395 -0
  39. package/core/bridge/protocol/envelopes.ts +188 -0
  40. package/core/bridge/protocol/errorCodec.ts +164 -0
  41. package/core/bridge/protocol/json.ts +237 -0
  42. package/core/bridge/protocol/limits.ts +43 -0
  43. package/core/bridge/protocol/methods.ts +55 -0
  44. package/core/bridge/protocol/origin.ts +130 -0
  45. package/core/bridge/runtime.ts +642 -0
  46. package/core/bridge/runtimeFlags.ts +34 -0
  47. package/core/bridge/testing/conformanceCases.ts +149 -0
  48. package/core/bridge/testing/pageClient.ts +44 -0
  49. package/core/bridge/unverifiedManager.ts +97 -0
  50. package/core/bridge/unverifiedOriginator.ts +79 -0
  51. package/core/config.tsx +1 -16
  52. package/core/constants.ts +7 -11
  53. package/core/context/WalletConnectionContext.tsx +92 -49
  54. package/core/context/WalletContext.tsx +288 -165
  55. package/core/context/sessionTeardown.ts +46 -0
  56. package/core/context/usePairingAttempt.ts +31 -0
  57. package/core/e2e/broadcaster.ts +25 -0
  58. package/core/e2e/consentFixture.ts +46 -0
  59. package/core/e2e/mode.ts +42 -0
  60. package/core/headers/OfflineFirstChaintracks.ts +57 -107
  61. package/core/headers/headerConsensus.ts +230 -0
  62. package/core/headers/headerStore.ts +344 -122
  63. package/core/headers/prewarm.ts +4 -7
  64. package/core/headers/syncHeaders.ts +82 -12
  65. package/core/hooks/usePermissionQueue.ts +89 -34
  66. package/core/i18n/translations.tsx +958 -24
  67. package/core/identity/handleRegistry/client.ts +4 -2
  68. package/core/identity/handleRegistry/resolver.ts +7 -11
  69. package/core/index.ts +17 -0
  70. package/core/localpay/pending.ts +39 -4
  71. package/core/network/boundedFetch.ts +101 -0
  72. package/core/networks.ts +11 -13
  73. package/core/pay/rails/address.ts +5 -4
  74. package/core/pay/rails/handle.ts +3 -1
  75. package/core/pay/rails/sweep.ts +791 -0
  76. package/core/peerpay/brc29.ts +4 -0
  77. package/core/peerpay/handleResendRequests.ts +15 -2
  78. package/core/peerpay/outbox.ts +115 -2
  79. package/core/profiles/assertProfileEmpty.ts +2 -2
  80. package/core/profiles/profileStore.ts +3 -2
  81. package/core/services/arcadeBroadcastProvider.ts +260 -114
  82. package/core/services/autoApprovePolicy.ts +7 -1
  83. package/core/services/capWalletArgs.ts +2 -1
  84. package/core/services/permissionPrompts.ts +132 -0
  85. package/core/services/secrets/kek.ts +5 -0
  86. package/core/services/secrets/migration.ts +27 -2
  87. package/core/services/secrets/policy.ts +6 -0
  88. package/core/services/signingPermissionPolicy.ts +230 -2
  89. package/core/services/vault/VaultKeyService.ts +5 -2
  90. package/core/services/vault/ceremony.ts +2 -2
  91. package/core/services/vault/ceremonyHost.ts +1 -1
  92. package/core/services/vault/guard.ts +20 -0
  93. package/core/services/vault/outputAuthority.ts +76 -0
  94. package/core/services/vault/transfers.ts +52 -28
  95. package/core/services/vault/vaultStore.ts +60 -14
  96. package/core/services/walletArgLimits.ts +17 -2
  97. package/core/services/walletConnectionValidation.ts +13 -1
  98. package/core/services/walletServiceConfig.ts +8 -7
  99. package/core/storage/encryptedDbImage.ts +325 -0
  100. package/core/stores/ConnectionStore.ts +17 -0
  101. package/core/toolboxConfig.ts +78 -2
  102. package/expo-module.config.json +5 -0
  103. package/ios/BoundedBody.swift +15 -0
  104. package/ios/BsvBoundedFetch.podspec +17 -0
  105. package/ios/BsvBoundedFetchModule.swift +121 -0
  106. package/package.json +12 -8
  107. package/ui/bridgeSheet/ContextRelay.tsx +86 -0
  108. package/ui/bridgeSheet/relayedContexts.ts +21 -0
  109. package/ui/components/pay/AddressReceive.tsx +6 -2
  110. package/ui/components/pay/ImportedOutboxApproval.tsx +142 -0
  111. package/ui/components/pay/PayCellRow.tsx +3 -1
  112. package/ui/components/pay/PayForm.tsx +12 -2
  113. package/ui/components/pay/RecipientField.tsx +1 -0
  114. package/ui/components/pay/RequestHub.tsx +1 -0
  115. package/ui/components/pay/UniversalSend.tsx +110 -42
  116. package/ui/components/ui/ListRow.tsx +10 -2
  117. package/ui/components/ui/PermissionSheet.tsx +534 -158
  118. package/ui/components/ui/Sheet.tsx +59 -7
  119. package/ui/components/ui/sheetResumeSignal.ts +19 -0
  120. package/ui/components/vault/KeyChooser.tsx +1 -1
  121. package/ui/components/wallet/AmountInput.tsx +4 -1
  122. package/ui/components/wallet/BackupReminderSheet.tsx +8 -1
  123. package/ui/components/wallet/BiometricAdvisoryModal.tsx +2 -0
  124. package/ui/components/wallet/ImportFromBackupPrompt.tsx +6 -1
  125. package/ui/components/wallet/ProfileButton.tsx +1 -0
  126. package/ui/exportDatabases.ts +94 -5
  127. package/ui/hooks/useExportWalletData.ts +37 -24
  128. package/ui/importDatabases.ts +154 -34
  129. package/ui/index.ts +4 -0
  130. package/ui/screens/ConnectionsScreen.tsx +12 -3
  131. package/ui/screens/PairScreen.tsx +10 -3
  132. package/ui/screens/PayScreen.tsx +1 -0
  133. package/ui/screens/TrustScreen.tsx +6 -3
  134. package/ui/screens/VaultScreen.tsx +13 -3
  135. package/ui/screens/VaultTransferScreen.tsx +6 -3
  136. package/ui/screens/WalletConfigScreen.tsx +30 -3
  137. package/ui/screens/WalletHomeScreen.tsx +7 -1
@@ -1,5 +1,6 @@
1
- import { Beef, Transaction, Utils } from '@bsv/sdk'
2
- import type { WocEndpoints } from '../networks'
1
+ import { Beef, Transaction } from '@bsv/sdk'
2
+ import type { NetworkProfile, WocEndpoints } from '../networks'
3
+ import { trimTrailingSlashes } from '../net/trimTrailingSlashes'
3
4
  import type { PostBeefResult, PostTxResultForTxid } from '../toolboxTypes'
4
5
 
5
6
  const BROADCAST_TIMEOUT_MS = 30_000
@@ -139,6 +140,9 @@ async function fetchWithBodyDeadline(url: string, init: RequestInit, timeoutMs:
139
140
  */
140
141
  const ARC_DOUBLE_SPEND_STATUSES = new Set(['DOUBLE_SPEND_ATTEMPTED'])
141
142
 
143
+ /** WhatsOnChain bodies meaning this exact txid is already known or mined. */
144
+ const WOC_ALREADY_HAVE_TX = /already[ -](known|in[ -]the[ -]mempool|in[ -](the[ -])?block[ -]?chain)/i
145
+
142
146
  /**
143
147
  * XR-062: SEEN_IN_ORPHAN_MEMPOOL means the parent hasn't propagated yet — a
144
148
  * transport/timing condition, not a proven conflict. offline/plan.ts's
@@ -150,6 +154,19 @@ const ARC_DOUBLE_SPEND_STATUSES = new Set(['DOUBLE_SPEND_ATTEMPTED'])
150
154
  */
151
155
  const ARC_RETRYABLE_STATUSES = new Set(['SEEN_IN_ORPHAN_MEMPOOL'])
152
156
 
157
+ /**
158
+ * ARC codes (the `status` number in a BSV Broadcaster 400 body) that are a
159
+ * validator verdict about the transaction bytes: 461 (invalid unlocking
160
+ * scripts / malformed) and 464 (invalid outputs). The list is deliberately
161
+ * short. A false terminal verdict is the XR-062 cascade: offline/plan.ts
162
+ * applyOutcome releases reservations and kills every descendant of a
163
+ * terminally rejected transaction. Codes such as 460 (not EF), 462 (inputs,
164
+ * can be propagation lag), 465 (fee policy differs per instance), 466
165
+ * (conflict; double spends come only from DOUBLE_SPEND_ATTEMPTED) and 476
166
+ * (locktime not final yet) stay retryable.
167
+ */
168
+ export const ARC_INVALID_CODES = new Set([461, 464])
169
+
153
170
  /**
154
171
  * XR-064: explicit ARC statuses that mean "accepted for relay". A custom
155
172
  * (person-configured) ARC endpoint's success predicate used to be
@@ -185,7 +202,7 @@ function loggableSnippet(text: string): string {
185
202
  }
186
203
 
187
204
  /**
188
- * Shared response handling for ARC-compatible services (Arcade, Taal, GorillaPool).
205
+ * Shared response handling for ARC-compatible services (Arcade, GorillaPool).
189
206
  * Maps txStatus to the correct PostTxResultForTxid fields.
190
207
  *
191
208
  * Exported for unit tests.
@@ -193,7 +210,7 @@ function loggableSnippet(text: string): string {
193
210
  export function handleArcResponse(
194
211
  serviceName: string,
195
212
  response: { ok: boolean; status: number },
196
- data: { txid?: string; txStatus?: string },
213
+ data: { txid?: string; txStatus?: string; status?: number | string },
197
214
  txids: string[]
198
215
  ): PostTxResultForTxid {
199
216
  const txResult: PostTxResultForTxid = {
@@ -222,95 +239,227 @@ export function handleArcResponse(
222
239
  // compatibility with a status this list doesn't know yet) — but a bare
223
240
  // or unrelated response is not (XR-064).
224
241
  txResult.status = 'success'
242
+ } else if (response.status === 400 && data.txid === txids[0] && ARC_INVALID_CODES.has(Number(data.status))) {
243
+ // Final rejection: leave status 'error' with no serviceError, no doubleSpend.
225
244
  } else {
226
245
  txResult.serviceError = true
227
246
  }
228
247
  return txResult
229
248
  }
230
249
 
250
+ /** Longest the wallet waits on one provider (the Services soft timeout). */
251
+ export const BROADCAST_PROVIDER_BUDGET_MS = 30_000
252
+
231
253
  /**
232
- * Convert BEEF to EF-format binary for ARC-compatible endpoints.
254
+ * Slack kept between the end of the walk and the Services soft timeout. The
255
+ * Services timer starts before the walk, so a walk that ran to the soft timeout
256
+ * would lose the race and its per-txid results would be discarded.
233
257
  */
234
- function beefToEF(beef: Beef): Uint8Array {
235
- const tx = Transaction.fromBEEF(beef.toBinary())
236
- return new Uint8Array(tx.toEF())
258
+ const BROADCAST_WALK_SLACK_MS = 2_000
259
+
260
+ /** The walk (every post, including its in-flight request) ends by this time. */
261
+ export const BROADCAST_WALK_BUDGET_MS = BROADCAST_PROVIDER_BUDGET_MS - BROADCAST_WALK_SLACK_MS
262
+
263
+ /** No new post starts with less time than this left; it could not finish. */
264
+ const MIN_REQUEST_MS = 1_000
265
+
266
+ /**
267
+ * What to post, and in what order. `order` holds every txid in the BEEF that
268
+ * has a raw transaction and no merkle path (parents first), then any requested
269
+ * txid the BEEF does not hold. `proven` holds the requested txids whose BEEF
270
+ * entry already has a merkle path. Works on a copy, so the caller's `beef`
271
+ * keeps its order.
272
+ */
273
+ function postingPlan(beef: Beef, txids: string[]): { order: string[]; proven: Set<string> } {
274
+ const sorted = Beef.fromBinary(beef.toBinary())
275
+ sorted.sortTxs()
276
+ const wanted = new Set(txids)
277
+ const order: string[] = []
278
+ const proven = new Set<string>()
279
+ for (const btx of sorted.txs) {
280
+ if (btx.hasProof) {
281
+ if (wanted.has(btx.txid)) proven.add(btx.txid)
282
+ } else if (!btx.isTxidOnly) {
283
+ order.push(btx.txid)
284
+ }
285
+ }
286
+ const known = new Set(order)
287
+ for (const txid of txids) if (!proven.has(txid) && !known.has(txid)) order.push(txid)
288
+ return { order, proven }
237
289
  }
238
290
 
239
291
  /**
240
- * Create an ARC-compatible broadcast service that posts EF-format transactions.
241
- *
242
- * `txPath` is where the deployment serves its submit route. Arcade serves
243
- * POST /tx at the root; standard ARC (TAAL, GorillaPool) serves POST /v1/tx and
244
- * answers POST /tx with 404. Both take EF as application/octet-stream.
292
+ * Post every unconfirmed transaction of the BEEF, parents first, and return one
293
+ * result per requested txid. A transaction whose parent was not accepted is not
294
+ * posted. Each post gets only the time left in `budgetMs`, so the walk always
295
+ * ends inside the budget with its own per-txid results.
245
296
  */
246
- function createArcBroadcastService(
297
+ async function postEachTransaction(
247
298
  name: string,
248
- arcUrl: string,
249
- txPath: '/tx' | '/v1/tx',
250
- headers: Record<string, string>
251
- ) {
299
+ beef: Beef,
300
+ txids: string[],
301
+ postOne: (tx: Transaction, txid: string, timeoutMs: number) => Promise<PostTxResultForTxid>,
302
+ budgetMs: number = BROADCAST_WALK_BUDGET_MS
303
+ ): Promise<PostBeefResult> {
304
+ const retryable = (txid: string, data: string): PostTxResultForTxid => ({
305
+ txid,
306
+ status: 'error',
307
+ serviceError: true,
308
+ data
309
+ })
310
+ const work = Beef.fromBinary(beef.toBinary())
311
+ const { order, proven } = postingPlan(work, txids)
312
+ const results = new Map<string, PostTxResultForTxid>()
313
+ const notAccepted = new Set<string>()
314
+ const start = Date.now()
315
+ for (const txid of order) {
316
+ if (budgetMs - (Date.now() - start) < MIN_REQUEST_MS) break
317
+ let result: PostTxResultForTxid
318
+ try {
319
+ const tx = work.findAtomicTransaction(txid)
320
+ if (tx == null) {
321
+ result = retryable(txid, `transaction ${txid} not found in beef`)
322
+ } else {
323
+ const blockedBy = tx.inputs
324
+ .map(input => input.sourceTXID ?? input.sourceTransaction?.id('hex'))
325
+ .find(parent => parent != null && notAccepted.has(parent))
326
+ if (blockedBy != null) {
327
+ const parent = results.get(blockedBy)
328
+ const why = parent?.data ?? parent?.notes?.find(note => note.txStatus != null)?.txStatus
329
+ result = retryable(txid, `parent ${blockedBy} not accepted${why != null ? `: ${String(why)}` : ''}`)
330
+ } else {
331
+ result = await postOne(tx, txid, Math.min(BROADCAST_TIMEOUT_MS, budgetMs - (Date.now() - start)))
332
+ }
333
+ }
334
+ } catch (err: any) {
335
+ result = retryable(txid, `cannot post ${txid}: ${err?.message ?? String(err)}`)
336
+ }
337
+ if (result.status !== 'success') notAccepted.add(txid)
338
+ results.set(txid, result)
339
+ }
340
+ const txidResults = txids.map((txid): PostTxResultForTxid => {
341
+ if (proven.has(txid)) return { txid, status: 'success' }
342
+ const result = results.get(txid)
343
+ return result != null ? { ...result, txid } : retryable(txid, 'broadcast budget exceeded')
344
+ })
345
+ return {
346
+ name,
347
+ status: txidResults.every(result => result.status === 'success') ? 'success' : 'error',
348
+ txidResults
349
+ }
350
+ }
351
+
352
+ /** Drop trailing slashes so a user-entered URL joins cleanly with a path. */
353
+ function normalizeUrl(url: string): string {
354
+ return trimTrailingSlashes(url)
355
+ }
356
+
357
+ /**
358
+ * Create a BSV Broadcaster (Arcade) compatible service that posts EF-format
359
+ * transactions to `${url}/tx`. Arcade and GorillaPool's Arcade both serve
360
+ * POST /tx and take EF as application/octet-stream.
361
+ */
362
+ function createArcBroadcastService(name: string, arcUrl: string, headers: Record<string, string>) {
363
+ const txPath = '/tx'
364
+ const endpoint = `${normalizeUrl(arcUrl)}${txPath}`
252
365
  return {
253
366
  name,
254
- service: async (beef: Beef, txids: string[]): Promise<PostBeefResult> => {
255
- const r: PostBeefResult = { name, status: 'success', txidResults: [] }
256
- try {
257
- const ef = beefToEF(beef)
258
- const response = await fetchWithBodyDeadline(
259
- `${arcUrl}${txPath}`,
260
- {
261
- method: 'POST',
262
- headers: {
263
- 'Content-Type': 'application/octet-stream',
264
- ...headers
367
+ service: async (beef: Beef, txids: string[]): Promise<PostBeefResult> =>
368
+ await postEachTransaction(name, beef, txids, async (tx, txid, timeoutMs) => {
369
+ try {
370
+ const response = await fetchWithBodyDeadline(
371
+ endpoint,
372
+ {
373
+ method: 'POST',
374
+ headers: { 'Content-Type': 'application/octet-stream', ...headers },
375
+ body: new Uint8Array(tx.toEF()) as unknown as BodyInit
265
376
  },
266
- body: ef as unknown as BodyInit
267
- },
268
- BROADCAST_TIMEOUT_MS
269
- )
270
- const data = await response.json()
271
- console.log(`[${name}] POST ${txPath} ${response.status}`, loggableSnippet(JSON.stringify(data)))
272
- const txResult = handleArcResponse(name, response, data, txids)
273
- r.txidResults.push(txResult)
274
- r.status = txResult.status
275
- } catch (err: any) {
276
- console.log(`[${name}] POST ${txPath} error: ${err.message}`)
277
- r.status = 'error'
278
- r.txidResults.push({
279
- txid: txids[0],
280
- status: 'error',
281
- serviceError: true,
282
- data: err.message
283
- })
284
- }
285
- return r
286
- }
377
+ timeoutMs
378
+ )
379
+ const data = await response.json()
380
+ console.log(`[${name}] POST ${txPath} ${response.status}`, loggableSnippet(JSON.stringify(data)))
381
+ return handleArcResponse(name, response, data, [txid])
382
+ } catch (err: any) {
383
+ console.log(`[${name}] POST ${txPath} error: ${err.message}`)
384
+ return { txid, status: 'error', serviceError: true, data: err.message }
385
+ }
386
+ })
287
387
  }
288
388
  }
289
389
 
290
390
  /**
291
- * Arcade broadcast service — EF format with callback token for SSE updates.
391
+ * BSV Broadcaster (Arcade) service — EF format with callback token for SSE updates.
292
392
  */
293
393
  export function createArcadeBroadcastService(arcadeUrl: string, callbackToken: string) {
294
- return createArcBroadcastService('Arcade', arcadeUrl, '/tx', {
394
+ return createArcBroadcastService('Arcade', arcadeUrl, {
295
395
  'X-CallbackToken': callbackToken,
296
396
  'X-FullStatusUpdates': 'true'
297
397
  })
298
398
  }
299
399
 
300
400
  /**
301
- * Taal ARC broadcast service — EF format.
401
+ * GorillaPool broadcast service — EF format, posts to `${url}/tx`.
302
402
  */
303
- export function createTaalBroadcastService(arcUrl: string, apiKey?: string) {
304
- const headers: Record<string, string> = {}
305
- if (apiKey) headers['Authorization'] = `Bearer ${apiKey}`
306
- return createArcBroadcastService('TaalArc', arcUrl, '/v1/tx', headers)
403
+ export function createGorillaPoolBroadcastService(arcUrl: string) {
404
+ return createArcBroadcastService('GorillaPoolArc', arcUrl, {})
307
405
  }
308
406
 
407
+ type BroadcastProvider = { name: string; service: (beef: Beef, txids: string[]) => Promise<PostBeefResult> }
408
+
309
409
  /**
310
- * GorillaPool ARC broadcast service — EF format.
410
+ * Wrap a provider whose own verdicts we do not trust as terminal (the toolbox's
411
+ * Bitails maps node error -25 "missing inputs" to doubleSpend, and posts no
412
+ * ancestors first). Every non-success txid result becomes a retryable
413
+ * serviceError, so only Arcade's structured txStatus can be a final rejection
414
+ * (XR-062 cascade).
311
415
  */
312
- export function createGorillaPoolBroadcastService(arcUrl: string) {
313
- return createArcBroadcastService('GorillaPoolArc', arcUrl, '/v1/tx', {})
416
+ function createRetryableOnlyProvider(name: string, post: BroadcastProvider['service']): BroadcastProvider {
417
+ return {
418
+ name,
419
+ service: async (beef, txids) => {
420
+ const res = await post(beef, txids)
421
+ const txidResults = (res.txidResults ?? []).map(
422
+ (r): PostTxResultForTxid =>
423
+ r.status === 'success'
424
+ ? r
425
+ : { ...r, status: 'error', serviceError: true, doubleSpend: undefined, competingTxs: undefined }
426
+ )
427
+ return { ...res, txidResults }
428
+ }
429
+ }
430
+ }
431
+
432
+ /**
433
+ * Replace the toolbox's default broadcast providers with ours, in order:
434
+ * BSV Broadcaster (primary) -> GorillaPool -> WhatsOnChain -> Bitails. Each
435
+ * fallback is registered only where `network` says it serves the network, and
436
+ * GorillaPool is skipped when the person's primary URL already is GorillaPool.
437
+ * Returns the registered provider names, in order.
438
+ */
439
+ export function registerBroadcastProviders(
440
+ services: { postBeefServices: { add(s: BroadcastProvider): void; remove(name: string): void } },
441
+ network: NetworkProfile,
442
+ primaryUrl: string,
443
+ callbackToken: string,
444
+ whatsOnChainApiKey: string | undefined,
445
+ bitails: { postBeef: (beef: Beef, txids: string[]) => Promise<PostBeefResult> } | undefined
446
+ ): string[] {
447
+ const { postBeefServices } = services
448
+ for (const name of ['ArcadeBeef', 'GorillaPoolArcBeef', 'TaalArcBeef', 'Bitails', 'WhatsOnChain']) {
449
+ postBeefServices.remove(name)
450
+ }
451
+ const registered: string[] = []
452
+ const add = (provider: BroadcastProvider) => {
453
+ postBeefServices.add(provider)
454
+ registered.push(provider.name)
455
+ }
456
+ add(createArcadeBroadcastService(primaryUrl, callbackToken))
457
+ if (network.gorillaPoolArcUrl && normalizeUrl(network.gorillaPoolArcUrl) !== normalizeUrl(primaryUrl)) {
458
+ add(createGorillaPoolBroadcastService(network.gorillaPoolArcUrl))
459
+ }
460
+ if (network.woc) add(createWocBroadcastService(network.woc, whatsOnChainApiKey))
461
+ if (bitails && network.bitails) add(createRetryableOnlyProvider('Bitails', bitails.postBeef.bind(bitails)))
462
+ return registered
314
463
  }
315
464
 
316
465
  /**
@@ -326,60 +475,57 @@ export function createWocBroadcastService(woc: WocEndpoints, apiKey?: string) {
326
475
 
327
476
  return {
328
477
  name,
329
- service: async (beef: Beef, txids: string[]): Promise<PostBeefResult> => {
330
- const r: PostBeefResult = { name, status: 'success', txidResults: [] }
331
- try {
332
- const tx = Transaction.fromBEEF(beef.toBinary())
333
- const rawHex = Utils.toHex(tx.toBinary())
334
- const headers: Record<string, string> = {
335
- 'Content-Type': 'application/json',
336
- Accept: 'text/plain'
337
- }
338
- if (apiKey) headers['woc-api-key'] = apiKey
339
- const response = await fetchWithBodyDeadline(
340
- `${baseUrl}/tx/raw`,
341
- {
342
- method: 'POST',
343
- headers,
344
- body: JSON.stringify({ txhex: rawHex })
345
- },
346
- BROADCAST_TIMEOUT_MS
347
- )
348
- const body = await response.text()
349
- console.log(`[${name}] POST /tx/raw ${response.status}`, loggableSnippet(body))
350
- const txResult: PostTxResultForTxid = {
351
- txid: txids[0],
352
- status: 'error',
353
- notes: [{ when: new Date().toISOString(), what: 'wocPostRawTx', httpStatus: response.status }]
354
- }
355
- if (response.ok) {
356
- txResult.status = 'success'
357
- } else if (body.includes('already in the mempool')) {
358
- // Idempotent same-txid rebroadcast — a conflicting DIFFERENT tx cannot
359
- // produce this message, so it can't mask a double-spend.
360
- txResult.status = 'success'
361
- } else {
362
- // Never classify from WoC body strings. "Missing inputs" is ambiguous
363
- // (propagation lag vs mined double-spend) and a wrong terminal verdict
364
- // cascades to reject descendants. Terminal verdicts come from Arcade's
365
- // structured txStatus only (handleArcResponse); everything here is
366
- // retryable, and the release engine's topological order — foreign
367
- // ancestors included — is what prevents the orphan case at the source.
368
- txResult.serviceError = true
478
+ service: async (beef: Beef, txids: string[]): Promise<PostBeefResult> =>
479
+ await postEachTransaction(name, beef, txids, async (tx, txid, timeoutMs) => {
480
+ try {
481
+ const headers: Record<string, string> = {
482
+ 'Content-Type': 'application/json',
483
+ Accept: 'text/plain'
484
+ }
485
+ if (apiKey) headers['woc-api-key'] = apiKey
486
+ const response = await fetchWithBodyDeadline(
487
+ `${baseUrl}/tx/raw`,
488
+ {
489
+ method: 'POST',
490
+ headers,
491
+ body: JSON.stringify({ txhex: tx.toHex() })
492
+ },
493
+ timeoutMs
494
+ )
495
+ const body = await response.text()
496
+ console.log(`[${name}] POST /tx/raw ${response.status}`, loggableSnippet(body))
497
+ const txResult: PostTxResultForTxid = {
498
+ txid,
499
+ status: 'error',
500
+ notes: [{ when: new Date().toISOString(), what: 'wocPostRawTx', httpStatus: response.status }]
501
+ }
502
+ if (response.ok) {
503
+ txResult.status = 'success'
504
+ } else if (WOC_ALREADY_HAVE_TX.test(body)) {
505
+ // Idempotent same-txid rebroadcast (already in the mempool, already
506
+ // known, or already mined — an unconfirmed ancestor may have been
507
+ // mined before its proof was fetched). A conflicting DIFFERENT tx
508
+ // cannot produce these messages, so they can't mask a double-spend.
509
+ txResult.status = 'success'
510
+ } else {
511
+ // Never classify from WoC body strings. "Missing inputs" is ambiguous
512
+ // (propagation lag vs mined double-spend) and a wrong terminal verdict
513
+ // cascades to reject descendants. Terminal verdicts come from Arcade's
514
+ // structured txStatus only (handleArcResponse); everything here is
515
+ // retryable, and the release engine's topological order — foreign
516
+ // ancestors included — is what prevents the orphan case at the source.
517
+ txResult.serviceError = true
518
+ }
519
+ return txResult
520
+ } catch (err: any) {
521
+ console.log(`[${name}] POST /tx/raw error: ${err.message}`)
522
+ return {
523
+ txid,
524
+ status: 'error',
525
+ serviceError: true,
526
+ data: err.message
527
+ }
369
528
  }
370
- r.txidResults.push(txResult)
371
- r.status = txResult.status
372
- } catch (err: any) {
373
- console.log(`[${name}] POST /tx/raw error: ${err.message}`)
374
- r.status = 'error'
375
- r.txidResults.push({
376
- txid: txids[0],
377
- status: 'error',
378
- serviceError: true,
379
- data: err.message
380
- })
381
- }
382
- return r
383
- }
529
+ })
384
530
  }
385
531
  }
@@ -18,9 +18,11 @@
18
18
  * ledger to persistent storage.
19
19
  */
20
20
 
21
+ import { isUnattestedOriginator } from '../bridge/unverifiedOriginator'
22
+
21
23
  const DAY_MS = 24 * 60 * 60 * 1000
22
24
 
23
- export type AutoApproveReason = 'over-threshold' | 'cooldown' | 'daily-cap' | null
25
+ export type AutoApproveReason = 'over-threshold' | 'cooldown' | 'daily-cap' | 'unattested' | null
24
26
 
25
27
  export interface AutoApproveDecision {
26
28
  approve: boolean
@@ -70,6 +72,9 @@ export function createAutoApprovePolicy(deps: AutoApprovePolicyDeps): AutoApprov
70
72
 
71
73
  return {
72
74
  shouldAutoApprove({ originator, satoshis }) {
75
+ // An unverified origin may be a local app forging a remembered site: spending always asks.
76
+ if (isUnattestedOriginator(originator)) return { approve: false, reason: 'unattested' }
77
+
73
78
  const threshold = deps.threshold()
74
79
  if (!(threshold > 0) || satoshis > threshold) {
75
80
  return { approve: false, reason: 'over-threshold' }
@@ -89,6 +94,7 @@ export function createAutoApprovePolicy(deps: AutoApprovePolicyDeps): AutoApprov
89
94
  },
90
95
 
91
96
  record({ originator, satoshis, at }) {
97
+ if (isUnattestedOriginator(originator)) return
92
98
  lastApproveAtByOriginator.set(originator, at)
93
99
  ledger.push({ originator, satoshis, at })
94
100
  pruneLedger(at)
@@ -50,7 +50,7 @@ export class WalletArgTooLarge extends Error {
50
50
  * caller that supplies its own limits never touches it at all, and a failure to
51
51
  * read the tier falls back to 'mid' rather than leaving the surface uncapped.
52
52
  */
53
- function tierLimits(): WalletArgLimits {
53
+ export function tierLimits(): WalletArgLimits {
54
54
  try {
55
55
  // eslint-disable-next-line @typescript-eslint/no-require-imports
56
56
  const { getDeviceTier } = require('../deviceTier') as typeof import('../deviceTier')
@@ -67,6 +67,7 @@ const SIZED = new Set<keyof WalletInterface>([
67
67
  'createAction',
68
68
  'signAction',
69
69
  'internalizeAction',
70
+ 'acquireCertificate',
70
71
  'encrypt',
71
72
  'decrypt',
72
73
  'createHmac',
@@ -0,0 +1,132 @@
1
+ import type { SigningPolicyPermissionsManager } from './signingPermissionPolicy'
2
+
3
+ /** A token module's prompt function (BTMS `promptHandler`, Mandala `requestTokenAccess`). */
4
+ export type TokenPromptHandler = (originator: string, message: string) => Promise<boolean>
5
+
6
+ /**
7
+ * Ties a token-module prompt function to the build that created it. Once the
8
+ * build's manager is retired the wrapper resolves `false` without enqueueing,
9
+ * so a module call that was already inside `onRequest` (mid-lookup) when the
10
+ * wallet was replaced ends with its usual denial instead of raising a sheet
11
+ * for a wallet that is gone. The flag is set in the same synchronous step as
12
+ * `manager.retire()`. A check in the module's `onRequest` wrapper would not be
13
+ * enough: a call already inside it has passed that check.
14
+ */
15
+ export function guardTokenPromptHandlers(handlers: { btms: TokenPromptHandler; mandala: TokenPromptHandler }): {
16
+ btms: TokenPromptHandler
17
+ mandala: TokenPromptHandler
18
+ /** Hand to `manager.onRetire`. */
19
+ retire: () => void
20
+ } {
21
+ let retired = false
22
+ const guarded = (handler: TokenPromptHandler): TokenPromptHandler => {
23
+ return (originator, message) => (retired ? Promise.resolve(false) : handler(originator, message))
24
+ }
25
+ return {
26
+ btms: guarded(handlers.btms),
27
+ mandala: guarded(handlers.mandala),
28
+ retire: () => {
29
+ retired = true
30
+ }
31
+ }
32
+ }
33
+
34
+ /** The places a withdrawal empties. */
35
+ export interface PromptSinks {
36
+ /** Queues whose items are answered through a manager (protocol, basket, certificate, spending, group). */
37
+ managerQueues: Array<{ clear: () => void }>
38
+ /** Queues whose items hold a promise (BTMS, Mandala); each is resolved `false`. */
39
+ tokenQueues: Array<{ clear: (onEach: (item: { resolve: (approved: boolean) => void }) => void) => void }>
40
+ /** Anything else holding a question for the user (pending connection requests). */
41
+ others: Iterable<() => void>
42
+ }
43
+
44
+ /**
45
+ * Withdraws every prompt that belonged to wallets that have gone. The old
46
+ * managers are retired FIRST, synchronously, so a call still parked inside one
47
+ * (on a manifest fetch, the grouped lock, a token lookup) cannot raise a prompt
48
+ * after the sweep; then every request they still hold is denied and every queue
49
+ * is emptied, which also closes the modals and gives focus back.
50
+ */
51
+ export function withdrawPrompts(oldManagers: SigningPolicyPermissionsManager[], sinks: PromptSinks): void {
52
+ for (const manager of oldManagers) manager.retire()
53
+ for (const manager of oldManagers) manager.denyAllActiveRequests()
54
+ for (const queue of sinks.managerQueues) queue.clear()
55
+ for (const queue of sinks.tokenQueues) queue.clear(item => item.resolve(false))
56
+ for (const other of sinks.others) {
57
+ try {
58
+ other()
59
+ } catch (error) {
60
+ console.warn('[permissions] withdrawing a prompt failed', error)
61
+ }
62
+ }
63
+ }
64
+
65
+ export interface SpendingPromptArgs {
66
+ requestID?: string
67
+ originator: string
68
+ reason?: string
69
+ renewal?: boolean
70
+ spending?: { satoshis: number; lineItems?: any[] }
71
+ }
72
+
73
+ export interface SpendingPromptDeps<Item> {
74
+ /** Re-reads the persisted auto-approve threshold (an AsyncStorage read). */
75
+ loadThreshold: () => Promise<void>
76
+ /** The auto-approve decision for this spend. */
77
+ decide: (originator: string, satoshis: number) => { approve: boolean; reason?: string | null }
78
+ /** Records an auto-approved spend in the ledger. */
79
+ recordAutoApproved: (originator: string, satoshis: number) => void
80
+ enqueue: (item: Item) => void
81
+ /** Only for a request that arrives without the manager it was raised on. */
82
+ currentManager: () => SigningPolicyPermissionsManager | undefined
83
+ }
84
+
85
+ /**
86
+ * The wallet's reaction to a spending-authorization request: auto-grant a small
87
+ * one, otherwise queue it for the sheet. `manager` is the one the request was
88
+ * raised on (the callback is bound per manager). The threshold read is async,
89
+ * so a withdrawal can land inside it; after it, and before the ledger record,
90
+ * the auto-grant or the enqueue, the manager must still hold the request, or
91
+ * the request is gone and nothing more happens. The auto-grant also targets
92
+ * that same manager: a replacement manager restarts its `spend:…:request:N`
93
+ * counter, so the current one must never be asked to grant an old ID.
94
+ */
95
+ export async function handleSpendingPrompt<Item>(
96
+ args: SpendingPromptArgs,
97
+ manager: SigningPolicyPermissionsManager | undefined,
98
+ deps: SpendingPromptDeps<Item>
99
+ ): Promise<void> {
100
+ const { requestID, originator, reason, renewal, spending } = args
101
+ if (!requestID || !spending) return
102
+
103
+ await deps.loadThreshold()
104
+ if (manager && !manager.hasActiveRequest(requestID)) return
105
+
106
+ const decision = deps.decide(originator, spending.satoshis)
107
+ if (decision.approve) {
108
+ deps.recordAutoApproved(originator, spending.satoshis)
109
+ if (__DEV__) console.log(`[spend-auth] AUTO-APPROVING requestID=${requestID} sats=${spending.satoshis}`)
110
+ const target = manager ?? deps.currentManager()
111
+ target?.grantPermission({ requestID, ephemeral: true, amount: spending.satoshis }).catch(() => {})
112
+ return
113
+ }
114
+ if (__DEV__) {
115
+ console.log(
116
+ `[spend-auth] not eligible (${decision.reason}) → manual modal requestID=${requestID} sats=${spending.satoshis}`
117
+ )
118
+ }
119
+
120
+ deps.enqueue({
121
+ requestID,
122
+ originator,
123
+ description: reason,
124
+ transactionAmount: 0,
125
+ totalPastSpending: 0,
126
+ amountPreviouslyAuthorized: 0,
127
+ authorizationAmount: spending.satoshis,
128
+ renewal,
129
+ lineItems: spending.lineItems || [],
130
+ manager
131
+ } as Item)
132
+ }
@@ -314,6 +314,11 @@ export async function upgradeToBiometric(
314
314
  // claim THIS session's transition fully succeeded.
315
315
  const stalePlain = await SecureStore.getItemAsync(KEK_PLAIN_KEY, kekOptions(false)).catch(() => null)
316
316
  if (stalePlain !== null) return null
317
+ // Adding an ACL-protected item on iOS does not authenticate the user.
318
+ // Require a read through that ACL before the old plain KEK can become
319
+ // this session's unlocked value. A cancellation leaves it uncached.
320
+ const authenticated = await SecureStore.getItemAsync(KEK_AUTH_KEY, kekOptions(true))
321
+ if (authenticated !== Utils.toHex(pending.kek)) return null
317
322
  return { status: 'unlocked', kekId: pending.kekId, policy: 'biometric' }
318
323
  } catch {
319
324
  // Leave the install exactly as it was; the caller does not cache