@bsv/expo-wallet-toolbox 0.23.0 → 0.24.1

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 (86) hide show
  1. package/CHANGELOG.md +147 -0
  2. package/README.md +1 -4
  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/inbox.ts +169 -64
  16. package/core/bridge/memoryInboxStore.ts +10 -1
  17. package/core/constants.ts +7 -11
  18. package/core/context/WalletConnectionContext.tsx +85 -48
  19. package/core/context/WalletContext.tsx +30 -32
  20. package/core/context/usePairingAttempt.ts +31 -0
  21. package/core/e2e/broadcaster.ts +25 -0
  22. package/core/e2e/consentFixture.ts +46 -0
  23. package/core/e2e/mode.ts +42 -0
  24. package/core/headers/OfflineFirstChaintracks.ts +57 -107
  25. package/core/headers/headerConsensus.ts +230 -0
  26. package/core/headers/headerStore.ts +344 -122
  27. package/core/headers/prewarm.ts +4 -7
  28. package/core/headers/syncHeaders.ts +82 -12
  29. package/core/i18n/translations.tsx +47 -12
  30. package/core/identity/handleRegistry/client.ts +4 -2
  31. package/core/identity/handleRegistry/resolver.ts +7 -11
  32. package/core/index.ts +2 -0
  33. package/core/localpay/pending.ts +39 -4
  34. package/core/network/boundedFetch.ts +101 -0
  35. package/core/networks.ts +11 -13
  36. package/core/pay/rails/address.ts +5 -4
  37. package/core/pay/rails/handle.ts +3 -1
  38. package/core/pay/rails/sweep.ts +791 -0
  39. package/core/peerpay/brc29.ts +4 -0
  40. package/core/peerpay/handleResendRequests.ts +15 -2
  41. package/core/peerpay/outbox.ts +115 -2
  42. package/core/profiles/assertProfileEmpty.ts +2 -2
  43. package/core/profiles/profileStore.ts +3 -2
  44. package/core/services/arcadeBroadcastProvider.ts +260 -114
  45. package/core/services/secrets/kek.ts +5 -0
  46. package/core/services/secrets/migration.ts +27 -2
  47. package/core/services/secrets/policy.ts +6 -0
  48. package/core/services/vault/VaultKeyService.ts +5 -2
  49. package/core/services/vault/ceremony.ts +2 -2
  50. package/core/services/vault/ceremonyHost.ts +1 -1
  51. package/core/services/vault/guard.ts +10 -0
  52. package/core/services/vault/outputAuthority.ts +76 -0
  53. package/core/services/vault/transfers.ts +52 -28
  54. package/core/services/vault/vaultStore.ts +60 -14
  55. package/core/services/walletConnectionValidation.ts +13 -1
  56. package/core/services/walletServiceConfig.ts +8 -7
  57. package/core/stores/ConnectionStore.ts +17 -0
  58. package/core/toolboxConfig.ts +60 -1
  59. package/expo-module.config.json +5 -0
  60. package/ios/BoundedBody.swift +15 -0
  61. package/ios/BsvBoundedFetch.podspec +17 -0
  62. package/ios/BsvBoundedFetchModule.swift +134 -0
  63. package/package.json +7 -3
  64. package/ui/components/pay/AddressReceive.tsx +6 -2
  65. package/ui/components/pay/ImportedOutboxApproval.tsx +142 -0
  66. package/ui/components/pay/PayCellRow.tsx +3 -1
  67. package/ui/components/pay/PayForm.tsx +12 -2
  68. package/ui/components/pay/RecipientField.tsx +1 -0
  69. package/ui/components/pay/RequestHub.tsx +1 -0
  70. package/ui/components/pay/UniversalSend.tsx +110 -42
  71. package/ui/components/ui/ListRow.tsx +10 -2
  72. package/ui/components/vault/KeyChooser.tsx +1 -1
  73. package/ui/components/wallet/AmountInput.tsx +4 -1
  74. package/ui/components/wallet/BackupReminderSheet.tsx +8 -1
  75. package/ui/components/wallet/BiometricAdvisoryModal.tsx +2 -0
  76. package/ui/components/wallet/ImportFromBackupPrompt.tsx +6 -1
  77. package/ui/components/wallet/ProfileButton.tsx +1 -0
  78. package/ui/importDatabases.ts +31 -6
  79. package/ui/screens/ConnectionsScreen.tsx +12 -3
  80. package/ui/screens/PairScreen.tsx +10 -3
  81. package/ui/screens/PayScreen.tsx +1 -0
  82. package/ui/screens/TrustScreen.tsx +6 -3
  83. package/ui/screens/VaultScreen.tsx +13 -3
  84. package/ui/screens/VaultTransferScreen.tsx +6 -3
  85. package/ui/screens/WalletConfigScreen.tsx +17 -2
  86. 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
  }
@@ -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
@@ -12,7 +12,8 @@ import AsyncStorage from '@react-native-async-storage/async-storage'
12
12
  import * as SecureStore from 'expo-secure-store'
13
13
  import { openSecret, sealSecret } from './envelope'
14
14
  import { destroyKek, peekKek, provisionKek, readSentinel, recordSecretName } from './kek'
15
- import { envKey, envOptions } from './storage'
15
+ import { envKey, envOptions, kekOptions } from './storage'
16
+ import { KEK_AUTH_KEY, KEK_PLAIN_KEY } from './policy'
16
17
  import { EnvelopeBlob, SECRET_NAMES, SecretName } from './types'
17
18
 
18
19
  /** Keys written by the pre-envelope LocalStorageProvider. */
@@ -112,7 +113,12 @@ export async function migrationAttemptsExhausted(): Promise<boolean> {
112
113
  export async function migrateLegacySecrets(): Promise<MigrationResult> {
113
114
  // Step 0 — idempotence. A committed sentinel means we already migrated;
114
115
  // sweeping here is what makes a crash between commit and delete harmless.
115
- const existing = await readSentinel()
116
+ let existing: Awaited<ReturnType<typeof readSentinel>>
117
+ try {
118
+ existing = await readSentinel({ strict: true })
119
+ } catch {
120
+ return { outcome: 'failed', stage: 'existing-identity', retryable: true }
121
+ }
116
122
  if (existing && existing.names.length > 0) {
117
123
  await sweepLegacyKeys()
118
124
  return { outcome: 'not-needed' }
@@ -136,6 +142,25 @@ export async function migrateLegacySecrets(): Promise<MigrationResult> {
136
142
  return { outcome: 'failed', stage: 'attempts-exhausted', retryable: false }
137
143
  }
138
144
 
145
+ // The sentinel is unauthenticated and can disappear independently of the
146
+ // protected KEK. Never interpret its absence as permission to replace an
147
+ // existing envelope identity with legacy plaintext. Read errors also fail
148
+ // closed; no destructive provisioning or rollback has started yet.
149
+ try {
150
+ for (const name of SECRET_NAMES) {
151
+ if ((await SecureStore.getItemAsync(envKey(name), envOptions)) !== null) {
152
+ return { outcome: 'failed', stage: 'existing-identity', retryable: false }
153
+ }
154
+ }
155
+ for (const [key, authenticated] of [[KEK_AUTH_KEY, true], [KEK_PLAIN_KEY, false]] as const) {
156
+ if ((await SecureStore.getItemAsync(key, kekOptions(authenticated))) !== null) {
157
+ return { outcome: 'failed', stage: 'existing-identity', retryable: false }
158
+ }
159
+ }
160
+ } catch {
161
+ return { outcome: 'failed', stage: 'existing-identity', retryable: true }
162
+ }
163
+
139
164
  // Step 3 — mint the KEK. Costs one prompt on Android, none on iOS.
140
165
  const provisioned = await provisionKek()
141
166
  if (provisioned.status !== 'unlocked') {
@@ -10,6 +10,7 @@
10
10
  * item written with requireAuthentication.
11
11
  */
12
12
  import * as LocalAuthentication from 'expo-local-authentication'
13
+ import { isE2eBuild } from '../../e2e/mode'
13
14
  import { KekPolicy } from './types'
14
15
 
15
16
  /** ALWAYS written with requireAuthentication: true. */
@@ -98,6 +99,10 @@ export async function biometricKind(): Promise<'face' | 'fingerprint' | 'iris' |
98
99
  * so it is not merely unreachable in production, it is not present.
99
100
  */
100
101
  export async function resolveProvisioningPolicy(): Promise<ResolvedPolicy> {
102
+ // The harness stores the key without a biometric ceremony so a simulator
103
+ // with nothing enrolled, and one with Face ID enrolled, take the same path.
104
+ // Production never sets the harness flag, so this branch is not taken there.
105
+ if (isE2eBuild()) return DEV_PLAIN
101
106
  const strong = await hasStrongBiometrics()
102
107
  if (strong) return BIOMETRIC
103
108
  return __DEV__ ? DEV_PLAIN : DEGRADED
@@ -114,6 +119,7 @@ export async function resolveProvisioningPolicy(): Promise<ResolvedPolicy> {
114
119
  * *can* do biometrics must be re-wrapped before the KEK is honoured.
115
120
  */
116
121
  export async function needsUpgrade(current: KekPolicy): Promise<boolean> {
122
+ if (isE2eBuild()) return false
117
123
  if (current === 'biometric') return false
118
124
  if (__DEV__) return false
119
125
  return hasStrongBiometrics()
@@ -1180,8 +1180,11 @@ export async function addVaultKey(
1180
1180
  await requireReadyEnrollmentDrafts([record], token, authority)
1181
1181
  const scope = vaultStore.getScope()
1182
1182
  if (!scope) throw new VaultError('not-enrolled', 'Wallet vault scope is not configured')
1183
- const meta = await vaultStore.addKey(record, token, next =>
1184
- computeVaultMetaAuthorityTag(authority.wallet, authority.adminOriginator, next, scope)
1183
+ const meta = await vaultStore.addKey(
1184
+ record,
1185
+ token,
1186
+ next => computeVaultMetaAuthorityTag(authority.wallet, authority.adminOriginator, next, scope),
1187
+ existing
1185
1188
  )
1186
1189
  // XQ-014: record the newly committed serial device-wide.
1187
1190
  await enrolledSerialRegistry.record(record.serial)
@@ -298,8 +298,8 @@ export class CeremonyController {
298
298
  /**
299
299
  * Report post-arm progress from the spend path.
300
300
  *
301
- * Guarded on an armed session: a note with no signer armed (a deposit, which
302
- * is hardware-free, or a caller that has already released) must not raise a
301
+ * Guarded on an armed session: a note with no signer armed (for example,
302
+ * after a deposit's possession proof has been released) must not raise a
303
303
  * sheet, and anything arriving mid-arm is ignored because the arming phases
304
304
  * own the display.
305
305
  *
@@ -46,7 +46,7 @@ export function requestVaultSigner(reason: string, chosenSerial: string): Promis
46
46
  * the ceremony sheet can show activity through the seconds-long stretches
47
47
  * where the JS thread or the network is busy, and so the retention window
48
48
  * tracks a live operation instead of expiring underneath it. A no-op when
49
- * nothing is armed — which is what keeps the hardware-free deposit sheet-free. */
49
+ * nothing is armed, such as after a deposit's possession proof is released. */
50
50
  export function noteVaultProgress(p: VaultProgress): void {
51
51
  ceremony.noteProgress(p)
52
52
  }
@@ -38,6 +38,7 @@ import {
38
38
  type WalletAction,
39
39
  type WalletInterface
40
40
  } from '@bsv/sdk'
41
+ import { DB_EXPORT_PROTOCOL } from '../../storage/encryptedDbImage'
41
42
  import { ownOriginatorLabel } from '../../storage/methods/vaultGuardSql'
42
43
  import { bakedCommitments, R1C_LOCK_LEN, R1C_MAX_KEYS } from './r1comb'
43
44
 
@@ -198,6 +199,10 @@ const PENDING_ABORT_AUTHORITY_PROTOCOL_NAMES = new Set(['pending abort authority
198
199
  * `connection authority`: a connected origin must not be able to mint or verify the tag. */
199
200
  const BRIDGE_SITE_AUTHORITY_PROTOCOL_NAMES = new Set(['bridge site authority'])
200
201
 
202
+ /** Export headers wrap the database's AES key under this ordinary self key.
203
+ * Only the admin may use it, including imports of already-created exports. */
204
+ const DB_EXPORT_PROTOCOL_NAMES = new Set([DB_EXPORT_PROTOCOL[1]])
205
+
201
206
  function matchesProtocolNamespace(args: unknown, names: Set<string>): boolean {
202
207
  if (args === null || typeof args !== 'object' || Array.isArray(args)) return false
203
208
  const protocolID = (args as { protocolID?: unknown }).protocolID
@@ -706,6 +711,10 @@ export function guardVaultAccess<T extends WalletInterface>(
706
711
 
707
712
  return async (args: any, originator?: string) => {
708
713
  if (originator === adminOriginator) return await bound(args, originator)
714
+ // Counterparty linkage reveals a root shared secret without naming a
715
+ // protocol. It cannot honor namespace reservations, including the
716
+ // export self key when a caller chooses a related public key.
717
+ if (method === 'revealCounterpartyKeyLinkage') return deny(String(method), originator)
709
718
  if (
710
719
  PRIVILEGED_CAPABLE.has(method) &&
711
720
  (args?.privileged ||
@@ -713,6 +722,7 @@ export function guardVaultAccess<T extends WalletInterface>(
713
722
  requestsConnectionAuthorityProtocol(args) ||
714
723
  requestsPendingAbortAuthorityProtocol(args) ||
715
724
  requestsBridgeSiteAuthorityProtocol(args) ||
725
+ matchesProtocolNamespace(args, DB_EXPORT_PROTOCOL_NAMES) ||
716
726
  requestsAddressRailKey(args))
717
727
  ) {
718
728
  return deny(String(method), originator)