@bsv/expo-wallet-toolbox 0.23.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 (86) hide show
  1. package/CHANGELOG.md +133 -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 +121 -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
@@ -21,7 +21,8 @@ import {
21
21
  validatePairingTopic,
22
22
  validateStoredConnectionSequence,
23
23
  validateStoredConnectionFields,
24
- type ConnectParams
24
+ type ConnectParams,
25
+ type OriginSessionTuple
25
26
  } from '../services/walletConnectionValidation'
26
27
 
27
28
  export type { ConnectParams } from '../services/walletConnectionValidation'
@@ -172,19 +173,26 @@ async function readBoundedRelayResponse(res: Response): Promise<string> {
172
173
  return text
173
174
  }
174
175
 
175
- export async function fetchRelay(origin: string, topic: string): Promise<string> {
176
+ export async function fetchRelay(origin: string, topic: string, expected?: OriginSessionTuple): Promise<string> {
176
177
  const validatedTopic = validatePairingTopic(topic)
177
178
  const external = validateCanonicalExternalOrigin(origin)
179
+ const sessionUrl = `${external.origin}/api/session/${encodeURIComponent(validatedTopic)}`
178
180
  const controller = new AbortController()
179
181
  const timer = setTimeout(() => controller.abort(), 10_000)
180
182
  try {
181
- const res = await fetch(`${external.origin}/api/session/${encodeURIComponent(validatedTopic)}`, {
183
+ const res = await fetch(sessionUrl, {
182
184
  signal: controller.signal,
183
185
  redirect: 'error'
184
186
  })
185
187
  if (!res.ok) throw new Error(`Could not fetch session from origin: HTTP ${res.status}`)
188
+ // React Native's XHR fetch polyfill can ignore redirect: 'error'. Only
189
+ // the exact requested HTTPS endpoint may supply this authority proof;
190
+ // missing final-URL metadata must fail closed too.
191
+ if (res.url !== sessionUrl || res.redirected === true) {
192
+ throw new Error('Origin session response URL does not match the requested endpoint')
193
+ }
186
194
  const raw = await readBoundedRelayResponse(res)
187
- return parseRelayResponse(raw)
195
+ return parseRelayResponse(raw, expected)
188
196
  } finally {
189
197
  clearTimeout(timer)
190
198
  }
@@ -252,6 +260,9 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
252
260
  // still reach handleRpc and dispatch privileged RPC after the app has
253
261
  // already moved on to a different (or no) session.
254
262
  const connectionGenerationRef = useRef(0)
263
+ // Keep sequence commits serialized across replacement sockets as well as
264
+ // concurrent messages. A closing session can still have a native write pending.
265
+ const sequenceCommitRef = useRef<Promise<boolean>>(Promise.resolve(true))
255
266
  // Snapshot of sessionMeta for use inside async WS callbacks
256
267
  const sessionMetaRef = useRef<SessionMeta | null>(null)
257
268
  useEffect(() => {
@@ -292,7 +303,6 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
292
303
  const supersedeExistingSocket = useCallback(() => {
293
304
  const topic = sessionMetaRef.current?.topic
294
305
  if (topic) {
295
- void SecureStore.setItemAsync(lastSeqKey(topic), String(lastSeqRef.current))
296
306
  connectionStore.setStatus(topic, 'disconnected')
297
307
  }
298
308
  closeAndDetachSocket(wsRef.current)
@@ -323,8 +333,9 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
323
333
  return () => {
324
334
  unregister()
325
335
  if (activeDisconnect === disconnect) activeDisconnect = null
336
+ closeAndDetachSocket(wsRef.current)
326
337
  }
327
- }, [disconnect])
338
+ }, [disconnect, closeAndDetachSocket])
328
339
 
329
340
  // ── Nav timer (pair screen lifecycle) ─────────────────────────────────────
330
341
 
@@ -417,13 +428,9 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
417
428
  wallet: WalletClient,
418
429
  meta: SessionMeta,
419
430
  initialSeq: number,
420
- // XR-018: this socket's own identity for the generation check below —
421
- // the caller (connect()/reconnect()) allocates it right after
422
- // supersedeExistingSocket() and before opening `ws`, and reuses the same
423
- // value to guard its own onopen handler, so a stale in-flight onopen
424
- // from a socket superseded in the meantime is guarded exactly like
425
- // onmessage/onerror/onclose below.
426
- myGeneration: number,
431
+ // Captured at attempt start, before any asynchronous work. Includes both
432
+ // the provider generation and this topic's explicit revocation version.
433
+ isCurrent: () => boolean,
427
434
  onFirstMessage: () => void
428
435
  ) {
429
436
  wsRef.current = ws
@@ -433,14 +440,13 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
433
440
  let inFlightBytes = 0
434
441
  // XR-021 review follow-up: MAX_IN_FLIGHT_RPC lets several messages
435
442
  // decrypt concurrently, so the sequence check-then-durable-write-then-
436
- // advance below is chained through this promise — each message's commit
443
+ // advance below is chained through the provider-wide promise — each message's commit
437
444
  // only runs once the previous one has fully resolved (write landed, ref
438
445
  // advanced), and re-checks the watermark at that point. Without this,
439
446
  // two concurrent messages can both pass the check against the same stale
440
447
  // watermark and have their durable writes resolve out of order,
441
448
  // regressing the watermark and letting an already-executed higher-
442
449
  // sequence ciphertext be replayed immediately (no crash needed).
443
- let seqCommitChain: Promise<boolean> = Promise.resolve(true)
444
450
 
445
451
  ws.onmessage = async event => {
446
452
  // XR-018: this socket may have already been superseded (a concurrent
@@ -448,7 +454,7 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
448
454
  // the relay delivering this event and this handler running — closing
449
455
  // a socket cannot cancel an event already queued for it. Drop it
450
456
  // before touching any in-flight counters.
451
- if (connectionGenerationRef.current !== myGeneration) return
457
+ if (!isCurrent()) return
452
458
  if (inFlightRpc >= MAX_IN_FLIGHT_RPC) {
453
459
  console.warn('[WalletConnection] dropping message: too many requests in flight')
454
460
  return
@@ -507,18 +513,23 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
507
513
  // the durable write itself fails, drop the message rather than
508
514
  // dispatching with no durable record of having accepted it.
509
515
  //
510
- // Chained through seqCommitChain (review follow-up): re-checks the
516
+ // Chained through sequenceCommitRef (review follow-up): re-checks the
511
517
  // watermark once it's this message's turn, so a concurrent message
512
518
  // that already committed a higher sequence in the meantime causes
513
519
  // this one to be dropped instead of regressing the watermark.
514
- const accepted = await (seqCommitChain = seqCommitChain.then(async () => {
515
- if (sequence <= lastSeqRef.current) return false
520
+ const accepted = await (sequenceCommitRef.current = sequenceCommitRef.current.then(async () => {
521
+ if (!isCurrent()) return false
516
522
  try {
523
+ const stored = validateStoredConnectionSequence(await SecureStore.getItemAsync(lastSeqKey(meta.topic)))
524
+ if (!isCurrent() || sequence <= Math.max(lastSeqRef.current, stored)) {
525
+ return false
526
+ }
517
527
  await SecureStore.setItemAsync(lastSeqKey(meta.topic), String(sequence))
518
528
  } catch (err) {
519
529
  console.warn('[WalletConnection] dropping message: failed to persist sequence', err)
520
530
  return false
521
531
  }
532
+ if (!isCurrent()) return false
522
533
  lastSeqRef.current = sequence
523
534
  return true
524
535
  }))
@@ -533,7 +544,7 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
533
544
  // this socket while this invocation was still awaiting them —
534
545
  // detaching handlers at that point cannot cancel this already-
535
546
  // running invocation, so the dispatch itself must also check.
536
- if (connectionGenerationRef.current !== myGeneration) {
547
+ if (!isCurrent()) {
537
548
  console.warn('[WalletConnection] dropping message: connection superseded before dispatch')
538
549
  return
539
550
  }
@@ -562,7 +573,7 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
562
573
  }
563
574
 
564
575
  ws.onerror = () => {
565
- if (connectionGenerationRef.current !== myGeneration) return
576
+ if (!isCurrent()) return
566
577
  setErrorMsg('WebSocket connection failed')
567
578
  setStatus('error')
568
579
  }
@@ -574,7 +585,7 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
574
585
  // before calling close() for every controlled teardown path, so this
575
586
  // is defense in depth for anything that still holds a reference to
576
587
  // this closure directly.
577
- if (connectionGenerationRef.current !== myGeneration) return
588
+ if (!isCurrent()) return
578
589
  const wasIntentional = intentionalCloseRef.current
579
590
  intentionalCloseRef.current = false
580
591
 
@@ -586,11 +597,12 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
586
597
  if (!wasIntentional) {
587
598
  const topic = sessionMetaRef.current?.topic
588
599
  if (topic) {
589
- void SecureStore.setItemAsync(lastSeqKey(topic), String(lastSeqRef.current))
590
600
  connectionStore.setStatus(topic, 'disconnected')
591
601
  }
592
602
  }
593
- wsRef.current = null
603
+ // Remote close revokes handlers already awaiting decrypt or persistence,
604
+ // just as an explicit disconnect does.
605
+ closeAndDetachSocket(ws)
594
606
  lastSeqRef.current = 0
595
607
  if (navTimerRef.current) {
596
608
  clearTimeout(navTimerRef.current)
@@ -618,10 +630,18 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
618
630
 
619
631
  const connect = useCallback(
620
632
  async (params: ConnectParams, wallet: WalletClient) => {
633
+ // Allocate authority before waits so teardown can revoke this attempt.
634
+ supersedeExistingSocket()
635
+ const myGeneration = ++connectionGenerationRef.current
636
+ const revocation = connectionStore.revocationVersion(params.topic)
637
+ const isCurrent = () =>
638
+ connectionGenerationRef.current === myGeneration &&
639
+ connectionStore.revocationVersion(params.topic) === revocation
621
640
  setStatus('connecting')
622
641
  setErrorMsg(null)
623
642
 
624
643
  let relay: string
644
+ let initialSeq: number
625
645
  let validated: ReturnType<typeof validateConnectParams>
626
646
  try {
627
647
  // This provider is a public embedding boundary. Validate every field here
@@ -629,10 +649,19 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
629
649
  validated = validateConnectParams(params)
630
650
  // Verify QR signature before trusting the origin or opening any connection
631
651
  await verifyQrSignature(validated.params)
652
+ if (!isCurrent()) return
632
653
 
633
654
  // Fetch relay URL from origin over HTTPS — TLS cert is the trust anchor
634
- relay = await fetchRelay(validated.external.origin, validated.params.topic)
655
+ relay = await fetchRelay(validated.external.origin, validated.params.topic, validated.params)
656
+ if (!isCurrent()) return
657
+ // Re-approval does not rotate the topic's encryption key. Previously
658
+ // accepted ciphertexts must remain consumed when this QR is scanned again.
659
+ initialSeq = validateStoredConnectionSequence(
660
+ await SecureStore.getItemAsync(lastSeqKey(validated.params.topic))
661
+ )
662
+ if (!isCurrent()) return
635
663
  } catch (err) {
664
+ if (!isCurrent()) return
636
665
  setErrorMsg(err instanceof Error ? err.message : 'Connection failed')
637
666
  setStatus('error')
638
667
  throw err
@@ -640,14 +669,15 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
640
669
 
641
670
  const protocolID = validated.protocolID
642
671
  const identityResult = await wallet.getPublicKey({ identityKey: true })
672
+ if (!isCurrent()) return
643
673
  const mobileIdentityKey = validateBackendIdentityKey(identityResult.publicKey)
644
674
 
645
- // XR-018: tear down any live socket for a DIFFERENT prior session before
646
- // wiring this one — see supersedeExistingSocket for why. myGeneration is
647
- // allocated right after, so this connection's onopen AND wireSocket's
648
- // handlers all guard against the same supersede event.
649
- supersedeExistingSocket()
650
- const myGeneration = ++connectionGenerationRef.current
675
+ // The current socket can accept requests while the stored floor and
676
+ // identity are being read. Preserve its newer floor when re-pairing the
677
+ // same topic, with no await between this snapshot and replacing it.
678
+ if (sessionMetaRef.current?.topic === validated.params.topic) {
679
+ initialSeq = Math.max(initialSeq, lastSeqRef.current)
680
+ }
651
681
 
652
682
  const meta: SessionMeta = {
653
683
  topic: validated.params.topic,
@@ -666,11 +696,11 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
666
696
  // a later connect()/reconnect()/disconnect() while relay/verify above
667
697
  // were in flight — a stale send here must not touch the new session's
668
698
  // state, and must not fire on an already-detached socket.
669
- if (connectionGenerationRef.current !== myGeneration) return
699
+ if (!isCurrent()) return
670
700
  try {
671
701
  const payload = JSON.stringify({
672
702
  id: crypto.randomUUID(),
673
- seq: 1,
703
+ seq: initialSeq + 1,
674
704
  method: 'pairing_approved',
675
705
  params: {
676
706
  mobileIdentityKey,
@@ -686,18 +716,18 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
686
716
  validated.params.backendIdentityKey,
687
717
  payload
688
718
  )
689
- if (connectionGenerationRef.current !== myGeneration) return
719
+ if (!isCurrent()) return
690
720
  ws.send(
691
721
  JSON.stringify({ topic: validated.params.topic, mobileIdentityKey, ciphertext } satisfies WireEnvelope)
692
722
  )
693
723
  } catch {
694
- if (connectionGenerationRef.current !== myGeneration) return
724
+ if (!isCurrent()) return
695
725
  setErrorMsg('Failed to send pairing message')
696
726
  setStatus('error')
697
727
  }
698
728
  }
699
729
 
700
- wireSocket(ws, wallet, meta, 0, myGeneration, () => {
730
+ wireSocket(ws, wallet, meta, initialSeq, isCurrent, () => {
701
731
  connectionStore.add({
702
732
  sessionId: validated.params.topic,
703
733
  origin: validated.external.origin,
@@ -718,30 +748,37 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
718
748
 
719
749
  const reconnect = useCallback(
720
750
  async (connection: Connection, wallet: WalletClient) => {
751
+ // Allocate authority before waits so teardown can revoke this attempt.
752
+ supersedeExistingSocket()
753
+ const myGeneration = ++connectionGenerationRef.current
754
+ const revocation = connectionStore.revocationVersion(connection.sessionId)
755
+ const isCurrent = () =>
756
+ connectionGenerationRef.current === myGeneration &&
757
+ connectionStore.revocationVersion(connection.sessionId) === revocation
721
758
  setStatus('connecting')
722
759
  setErrorMsg(null)
723
760
 
724
761
  // Stored connection data is untrusted after import or database tampering.
725
762
  const validated = validateStoredConnectionFields(connection)
726
763
  const identityResult = await wallet.getPublicKey({ identityKey: true })
764
+ if (!isCurrent()) return
727
765
  const currentMobileIdentityKey = validateBackendIdentityKey(identityResult.publicKey)
728
766
  if (currentMobileIdentityKey !== validated.mobileIdentityKey) {
729
767
  throw new Error('Stored connection belongs to a different wallet identity')
730
768
  }
731
769
  // Fetch relay URL from origin over HTTPS — relay may have moved since last connection
732
- const relay = await fetchRelay(validated.external.origin, validated.topic)
770
+ const relay = await fetchRelay(validated.external.origin, validated.topic, {
771
+ topic: validated.topic,
772
+ backendIdentityKey: validated.backendIdentityKey,
773
+ protocolID: validated.protocolIDRaw
774
+ })
775
+ if (!isCurrent()) return
733
776
 
734
777
  const protocolID = validated.protocolID
735
778
  const storedSeq = await SecureStore.getItemAsync(lastSeqKey(validated.topic))
779
+ if (!isCurrent()) return
736
780
  const initialSeq = validateStoredConnectionSequence(storedSeq)
737
781
 
738
- // XR-018: tear down any live socket for a DIFFERENT prior session before
739
- // wiring this one — see supersedeExistingSocket for why. myGeneration is
740
- // allocated right after, so this connection's onopen AND wireSocket's
741
- // handlers all guard against the same supersede event.
742
- supersedeExistingSocket()
743
- const myGeneration = ++connectionGenerationRef.current
744
-
745
782
  const meta: SessionMeta = {
746
783
  topic: validated.topic,
747
784
  origin: validated.external.origin,
@@ -756,7 +793,7 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
756
793
 
757
794
  ws.onopen = async () => {
758
795
  // XR-018: see the identical guard in connect()'s onopen.
759
- if (connectionGenerationRef.current !== myGeneration) return
796
+ if (!isCurrent()) return
760
797
  try {
761
798
  const payload = JSON.stringify({
762
799
  id: crypto.randomUUID(),
@@ -776,7 +813,7 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
776
813
  validated.backendIdentityKey,
777
814
  payload
778
815
  )
779
- if (connectionGenerationRef.current !== myGeneration) return
816
+ if (!isCurrent()) return
780
817
  ws.send(
781
818
  JSON.stringify({
782
819
  topic: validated.topic,
@@ -785,13 +822,13 @@ export function WalletConnectionProvider({ children, walletName = 'App' }: Walle
785
822
  } satisfies WireEnvelope)
786
823
  )
787
824
  } catch {
788
- if (connectionGenerationRef.current !== myGeneration) return
825
+ if (!isCurrent()) return
789
826
  setErrorMsg('Failed to send reconnect message')
790
827
  setStatus('error')
791
828
  }
792
829
  }
793
830
 
794
- wireSocket(ws, wallet, meta, initialSeq, myGeneration, () => {
831
+ wireSocket(ws, wallet, meta, initialSeq, isCurrent, () => {
795
832
  connectionStore.setStatus(validated.topic, 'active')
796
833
  setStatus('connected')
797
834
  })
@@ -139,6 +139,7 @@ import { buildUnverifiedPermissionsManager } from '../bridge/unverifiedManager'
139
139
  import { DEFAULT_STORAGE_URL, DEFAULT_CHAIN, ADMIN_ORIGINATOR, toWalletChain } from '../config'
140
140
  import { NETWORKS, isAppChain } from '../networks'
141
141
  import { getBackupUrl, getHandleRegistryConfig, getMandalaEndpoints, getPushAdapter } from '../toolboxConfig'
142
+ import { e2eSafeChain } from '../e2e/mode'
142
143
  import { inboxSeenStore } from '../directpay/receive'
143
144
  import {
144
145
  DEFAULT_AUTO_APPROVE_THRESHOLD,
@@ -180,12 +181,7 @@ import {
180
181
  createWalletMonitorOptions
181
182
  } from '../walletMonitor'
182
183
  import { runBoundedUnfail } from '../monitor/unfailRetry'
183
- import {
184
- createArcadeBroadcastService,
185
- createTaalBroadcastService,
186
- createGorillaPoolBroadcastService,
187
- createWocBroadcastService
188
- } from '../services/arcadeBroadcastProvider'
184
+ import { registerBroadcastProviders } from '../services/arcadeBroadcastProvider'
189
185
  import { getExchangeRate } from '../services/exchangeRate'
190
186
  import { devLog, logWithTimestamp } from '../logging'
191
187
  import { recoverMnemonicWallet } from '../mnemonicWallet'
@@ -1407,7 +1403,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1407
1403
 
1408
1404
  // ---- WAB + network + storage configuration ----
1409
1405
  const [selectedMethod, setSelectedMethod] = useState<string>('')
1410
- const [selectedNetwork, setSelectedNetwork] = useState<AppChain>(DEFAULT_CHAIN)
1406
+ const [selectedNetwork, setSelectedNetwork] = useState<AppChain>(e2eSafeChain(DEFAULT_CHAIN))
1411
1407
  /**
1412
1408
  * The network a build should use, readable without a closure.
1413
1409
  *
@@ -1417,7 +1413,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1417
1413
  * and published it, leaving a mainnet label over a testnet wallet. The state
1418
1414
  * is what the UI renders; this ref is what the build reads.
1419
1415
  */
1420
- const selectedNetworkRef = useRef<AppChain>(DEFAULT_CHAIN)
1416
+ const selectedNetworkRef = useRef<AppChain>(e2eSafeChain(DEFAULT_CHAIN))
1421
1417
  selectedNetworkRef.current = selectedNetwork
1422
1418
  const [selectedStorageUrl, setSelectedStorageUrl] = useState<string>(DEFAULT_STORAGE_URL)
1423
1419
  // Wallet profiles (one mnemonic, many wallets). The store is module state so
@@ -1463,8 +1459,9 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1463
1459
  console.error('Network selection is required')
1464
1460
  return false
1465
1461
  }
1462
+ const chain = e2eSafeChain(network)
1466
1463
  setSelectedMethod(method || 'mnemonic')
1467
- setSelectedNetwork(network)
1464
+ setSelectedNetwork(chain)
1468
1465
  setSelectedStorageUrl(storageUrl || 'local')
1469
1466
  setConfigStatus('configured')
1470
1467
  return true
@@ -1519,7 +1516,12 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1519
1516
  })
1520
1517
  await setItem(
1521
1518
  'finalConfig',
1522
- JSON.stringify({ wabUrl: 'noWAB', method: 'mnemonic', network: DEFAULT_CHAIN, storageUrl: 'local' })
1519
+ JSON.stringify({
1520
+ wabUrl: 'noWAB',
1521
+ method: 'mnemonic',
1522
+ network: e2eSafeChain(DEFAULT_CHAIN),
1523
+ storageUrl: 'local'
1524
+ })
1523
1525
  )
1524
1526
  }
1525
1527
  } else {
@@ -1532,7 +1534,12 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1532
1534
  })
1533
1535
  await setItem(
1534
1536
  'finalConfig',
1535
- JSON.stringify({ wabUrl: 'noWAB', method: 'mnemonic', network: DEFAULT_CHAIN, storageUrl: 'local' })
1537
+ JSON.stringify({
1538
+ wabUrl: 'noWAB',
1539
+ method: 'mnemonic',
1540
+ network: e2eSafeChain(DEFAULT_CHAIN),
1541
+ storageUrl: 'local'
1542
+ })
1536
1543
  )
1537
1544
  }
1538
1545
  })()
@@ -1637,33 +1644,22 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1637
1644
  )
1638
1645
 
1639
1646
  // Replace all default broadcast providers with EF/rawtx-only services.
1640
- // Order: Arcade → Taal → GorillaPool → WoC → Bitails. UntilSuccess stops at first success.
1647
+ // Order: BSV Broadcaster → GorillaPool → WoC → Bitails. UntilSuccess stops at first success.
1641
1648
  // Each fallback is registered only where NETWORKS says it serves the
1642
- // network: Taal on main + test, GorillaPool on main, WhatsOnChain where
1649
+ // network: GorillaPool on main + test, WhatsOnChain where
1643
1650
  // one exists, Bitails on main + test.
1644
1651
  // 'ArcadeBeef' is the toolbox's own Arcade broadcaster, registered
1645
1652
  // because serviceOptions now carries arcadeUrl (needed for Arcade-first
1646
1653
  // proofs and SSE). Our createArcadeBroadcastService replaces it here so
1647
1654
  // the same tx is not posted to Arcade twice with two header sets.
1648
- const bitailsService = (services as any).bitails
1649
- services.postBeefServices.remove('ArcadeBeef')
1650
- services.postBeefServices.remove('GorillaPoolArcBeef')
1651
- services.postBeefServices.remove('TaalArcBeef')
1652
- services.postBeefServices.remove('Bitails')
1653
- services.postBeefServices.remove('WhatsOnChain')
1654
- services.postBeefServices.add(createArcadeBroadcastService(serviceOptions.arcUrl!, callbackToken))
1655
- if (network.taalArcUrl) {
1656
- services.postBeefServices.add(createTaalBroadcastService(network.taalArcUrl, serviceOptions.taalApiKey))
1657
- }
1658
- if (network.gorillaPoolArcUrl) {
1659
- services.postBeefServices.add(createGorillaPoolBroadcastService(network.gorillaPoolArcUrl))
1660
- }
1661
- if (network.woc) {
1662
- services.postBeefServices.add(createWocBroadcastService(network.woc, serviceOptions.whatsOnChainApiKey))
1663
- }
1664
- if (bitailsService && network.bitails) {
1665
- services.postBeefServices.add({ name: 'Bitails', service: bitailsService.postBeef.bind(bitailsService) })
1666
- }
1655
+ registerBroadcastProviders(
1656
+ services,
1657
+ network,
1658
+ serviceOptions.arcUrl!,
1659
+ callbackToken,
1660
+ serviceOptions.whatsOnChainApiKey,
1661
+ (services as any).bitails
1662
+ )
1667
1663
 
1668
1664
  // Replace WoC getMerklePath with BUMP endpoint — no TSC→BUMP conversion needed.
1669
1665
  // The toolbox's 'Arcade' provider stays where Services put it: first.
@@ -3261,6 +3257,8 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3261
3257
  // strands the user on an unusable wallet. Switching again retries.
3262
3258
  const switchNetwork = useCallback(
3263
3259
  async (network: AppChain, opts: { fallback?: boolean } = {}) => {
3260
+ // The harness cannot be moved onto mainnet, whatever asked.
3261
+ if (e2eSafeChain(network) !== network) return
3264
3262
  // The ref, not the state: the fallback below runs inside the same call.
3265
3263
  const from = selectedNetworkRef.current
3266
3264
  if (network === from || switchInFlightRef.current) return
@@ -0,0 +1,31 @@
1
+ import { useCallback, useEffect, useRef } from 'react'
2
+ import connectionStore from '../stores/ConnectionStore'
3
+ import { registerSessionTeardown } from './sessionTeardown'
4
+
5
+ /** Cancels screen-side authority checks that run before connect/reconnect begins. */
6
+ export function usePairingAttempt() {
7
+ const generation = useRef(0)
8
+ const mounted = useRef(true)
9
+ const cancel = useCallback(() => {
10
+ generation.current++
11
+ }, [])
12
+
13
+ useEffect(() => {
14
+ mounted.current = true
15
+ const unregister = registerSessionTeardown(['logout', 'profile'], cancel)
16
+ return () => {
17
+ mounted.current = false
18
+ cancel()
19
+ unregister()
20
+ }
21
+ }, [cancel])
22
+
23
+ const begin = useCallback((topic?: string) => {
24
+ const attempt = ++generation.current
25
+ const revocation = connectionStore.revocationVersion(topic)
26
+ return () =>
27
+ mounted.current && generation.current === attempt && connectionStore.revocationVersion(topic) === revocation
28
+ }, [])
29
+
30
+ return { begin, cancel }
31
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Posts a pay-review to the E2E mock broadcaster.
3
+ *
4
+ * This is the send path an E2E build uses instead of `sendAddress`. The mock
5
+ * never forwards the body to a network, and this function refuses to run
6
+ * unless the harness is on, so a production bundle cannot reach it: the host
7
+ * only sets the mode from `EXPO_PUBLIC_E2E`.
8
+ */
9
+ import { getE2eBroadcasterUrl, isE2eBuild } from './mode'
10
+
11
+ export async function postE2eBroadcast(to: string, satoshis: number): Promise<string> {
12
+ if (!isE2eBuild()) throw new Error('E2E broadcaster is only available in an E2E build')
13
+ const url = getE2eBroadcasterUrl()
14
+ if (!url) throw new Error('E2E broadcaster is not configured')
15
+ const res = await fetch(`${url}/e2e/broadcast`, {
16
+ method: 'POST',
17
+ headers: { 'content-type': 'application/json', accept: 'application/json' },
18
+ body: JSON.stringify({ chain: 'test', to, satoshis })
19
+ })
20
+ const body = (await res.json().catch(() => null)) as { txid?: string; error?: string } | null
21
+ if (!res.ok || !body?.txid) {
22
+ throw new Error(body?.error || 'Test broadcaster refused the payment')
23
+ }
24
+ return body.txid
25
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Raises one BRC-100-style connection prompt on the wallet's PermissionSheet.
3
+ *
4
+ * The in-app browser that would normally raise this lives in the sibling
5
+ * apps. This fixture is how the wallet's own sheet is exercised. It refuses
6
+ * to register anything unless the E2E harness is on.
7
+ */
8
+ import type { PendingConsent } from '../bridge/consent'
9
+ import { setConsentSheetSource } from '../bridge/consentSheetSource'
10
+ import { isE2eBuild } from './mode'
11
+
12
+ const FIXTURE: PendingConsent = {
13
+ requestId: 'e2e-consent',
14
+ origin: 'https://e2e.example',
15
+ attestation: 'unattested',
16
+ transportId: 'e2e',
17
+ connectedBefore: false,
18
+ walletRevision: 1,
19
+ profileKey: 'e2e'
20
+ }
21
+
22
+ export function presentE2eConsentFixture(): void {
23
+ if (!isE2eBuild()) return
24
+ let pending: PendingConsent[] = [FIXTURE]
25
+ const listeners = new Set<() => void>()
26
+ const emit = () => {
27
+ for (const fn of listeners) fn()
28
+ }
29
+ setConsentSheetSource({
30
+ store: {
31
+ listPending: () => pending,
32
+ answerConsent: async requestId => {
33
+ pending = pending.filter(p => p.requestId !== requestId)
34
+ emit()
35
+ return undefined
36
+ },
37
+ onChange: fn => {
38
+ listeners.add(fn)
39
+ return () => {
40
+ listeners.delete(fn)
41
+ }
42
+ }
43
+ },
44
+ context: () => ({ walletRevision: 1, profileKey: 'e2e' })
45
+ })
46
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * End-to-end harness switch.
3
+ *
4
+ * Off unless the host passes `e2e` to `configureToolbox`. Production builds
5
+ * never do. The flag lives here, a leaf, so profile storage and the key
6
+ * policy can read it without importing the rest of the toolbox.
7
+ *
8
+ * When it is on, `main` is not a chain this process will open. The public
9
+ * test vector used by the suite must not be able to reach mainnet.
10
+ */
11
+ import type { AppChain } from '../config'
12
+
13
+ let broadcasterUrl: string | undefined
14
+
15
+ export function setE2eMode(url: string | undefined): void {
16
+ broadcasterUrl = url
17
+ }
18
+
19
+ export function isE2eBuild(): boolean {
20
+ return broadcasterUrl !== undefined
21
+ }
22
+
23
+ /** The mock broadcaster origin, or undefined when this is not an E2E build. */
24
+ export function getE2eBroadcasterUrl(): string | undefined {
25
+ return broadcasterUrl
26
+ }
27
+
28
+ /**
29
+ * The chain a build is allowed to open.
30
+ *
31
+ * An E2E build that was asked for mainnet gets testnet instead. Every other
32
+ * chain, and every chain in a normal build, is returned unchanged.
33
+ */
34
+ export function e2eSafeChain(chain: AppChain): AppChain {
35
+ if (broadcasterUrl !== undefined && chain === 'main') return 'test'
36
+ return chain
37
+ }
38
+
39
+ /** Test-only. */
40
+ export function resetE2eMode(): void {
41
+ broadcasterUrl = undefined
42
+ }