@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
@@ -11,6 +11,7 @@
11
11
  */
12
12
  import { Utils } from '@bsv/sdk'
13
13
  import type { HeaderStore } from './headerStore'
14
+ import { parseHeader } from './headerConsensus'
14
15
 
15
16
  export interface HeaderSource {
16
17
  getHeaders(height: number, count: number): Promise<string>
@@ -41,10 +42,35 @@ export async function syncHeaders(args: {
41
42
  onProgress?: (tipHeight: number, presentHeight: number) => void
42
43
  shouldStop?: () => boolean
43
44
  }): Promise<SyncHeadersResult> {
45
+ return args.store.withUpdateLock(() => syncHeadersUnlocked(args))
46
+ }
47
+
48
+ async function syncHeadersUnlocked(args: Parameters<typeof syncHeaders>[0]): Promise<SyncHeadersResult> {
44
49
  const { store, client, chunkSize = 2000, onProgress, shouldStop } = args
50
+ if (!Number.isSafeInteger(chunkSize) || chunkSize < 1 || chunkSize > 100000)
51
+ throw new Error('Invalid header chunk size')
45
52
  const presentHeight = await client.getPresentHeight()
46
53
  let added = 0
47
- let rewinds = 0
54
+ if (!Number.isSafeInteger(presentHeight) || presentHeight < store.anchor.height || presentHeight > 0x7fffffff) {
55
+ throw new Error('Chain source returned an invalid present height')
56
+ }
57
+ if (store.needsContext) {
58
+ const hex = await client.getHeaders(store.contextStartHeight, store.contextCount)
59
+ if (hex.length !== store.contextCount * HEADER_BYTES * 2 || !/^[0-9a-f]+$/i.test(hex)) {
60
+ throw new Error('Header bootstrap context unavailable or malformed')
61
+ }
62
+ await store.initializeContext(new Uint8Array(Utils.toArray(hex, 'hex')))
63
+ }
64
+ // A same-height or shorter competing chain can still have more work. Do not
65
+ // use advertised height as a substitute for comparing locally computed work.
66
+ if (store.count > 0 && presentHeight <= store.tipHeight) {
67
+ const at = Math.min(presentHeight, store.tipHeight)
68
+ const hex = await client.getHeaders(at, 1)
69
+ if (hex.length !== HEADER_BYTES * 2) throw new Error('Chain tip header unavailable')
70
+ if (parseHeader(new Uint8Array(Utils.toArray(hex, 'hex'))).hash !== store.hashForHeight(at)) {
71
+ added += await reconcileBranch(store, client, presentHeight, chunkSize, shouldStop)
72
+ }
73
+ }
48
74
 
49
75
  while (store.tipHeight < presentHeight) {
50
76
  if (shouldStop?.()) break
@@ -66,19 +92,63 @@ export async function syncHeaders(args: {
66
92
  added += await store.append(bytes, from)
67
93
  onProgress?.(store.tipHeight, presentHeight)
68
94
  } catch (err) {
69
- // First-header previous-hash miss is a tip reorg: drop the orphan and
70
- // refetch. A later header in the chunk, or any other validation failure,
71
- // still propagates — a silent truncated window would look complete.
72
- if (!isFirstHeaderPrevHashError(err, from)) throw err
73
- if (store.count > 0 && rewinds < REWIND_CAP) {
74
- await store.truncateToCount(store.count - 1)
75
- rewinds++
76
- continue
77
- }
78
- await store.reset()
79
- throw err
95
+ if (!isFirstHeaderPrevHashError(err, from) || store.count === 0) throw err
96
+ added += await reconcileBranch(store, client, presentHeight, chunkSize, shouldStop)
97
+ onProgress?.(store.tipHeight, presentHeight)
80
98
  }
81
99
  }
82
100
 
83
101
  return { added, tipHeight: store.tipHeight, presentHeight }
84
102
  }
103
+
104
+ /** Find a locally authenticated ancestor, stage/validate, then compare work. */
105
+ async function reconcileBranch(
106
+ store: HeaderStore,
107
+ client: HeaderSource,
108
+ presentHeight: number,
109
+ chunkSize: number,
110
+ shouldStop?: () => boolean
111
+ ): Promise<number> {
112
+ let ancestor: number | undefined
113
+ for (
114
+ let height = Math.min(store.tipHeight, presentHeight);
115
+ height >= store.anchor.height && height >= store.tipHeight - REWIND_CAP;
116
+ height--
117
+ ) {
118
+ if (shouldStop?.()) return 0
119
+ const hex = await client.getHeaders(height, 1)
120
+ if (hex.length !== HEADER_BYTES * 2 || !/^[0-9a-f]+$/i.test(hex))
121
+ throw new Error('Reorg ancestor header unavailable')
122
+ const header = parseHeader(new Uint8Array(Utils.toArray(hex, 'hex')))
123
+ if (header.hash === store.hashForHeight(height)) {
124
+ ancestor = height
125
+ break
126
+ }
127
+ }
128
+ if (ancestor === undefined) throw new Error('No authenticated reorg ancestor within rewind limit')
129
+ let staged = new Uint8Array(0)
130
+ for (let from = ancestor + 1; from <= presentHeight;) {
131
+ if (shouldStop?.()) return 0
132
+ const want = Math.min(chunkSize, presentHeight - from + 1)
133
+ const hex = await client.getHeaders(from, want)
134
+ if (!hex || !/^[0-9a-f]+$/i.test(hex)) throw new Error('Replacement header branch unavailable')
135
+ const bytes = new Uint8Array(Utils.toArray(hex.slice(0, want * HEADER_BYTES * 2), 'hex'))
136
+ if (bytes.length === 0 || bytes.length % HEADER_BYTES !== 0) throw new Error('Malformed replacement header branch')
137
+ const merged = new Uint8Array(staged.length + bytes.length)
138
+ merged.set(staged)
139
+ merged.set(bytes, staged.length)
140
+ staged = merged
141
+ from += bytes.length / HEADER_BYTES
142
+ try {
143
+ return await store.replaceBranch(ancestor + 1, staged)
144
+ } catch (error) {
145
+ if (
146
+ !(error instanceof Error) ||
147
+ !error.message.startsWith('Replacement header branch does not have greater accumulated work')
148
+ )
149
+ throw error
150
+ if (from > presentHeight) throw error
151
+ }
152
+ }
153
+ throw new Error('Replacement header branch does not have greater accumulated work')
154
+ }
@@ -1,69 +1,124 @@
1
1
  import { useState, useCallback, useRef } from 'react'
2
2
 
3
- interface UsePermissionQueueOptions {
3
+ interface UsePermissionQueueOptions<T = unknown> {
4
4
  /** Open/close the associated modal. Omit for queues without a modal (e.g. BTMS). */
5
5
  openModal?: (open: boolean) => void
6
6
  isFocused: () => Promise<boolean>
7
7
  onFocusRequested: () => void | Promise<void>
8
8
  onFocusRelinquished: () => void | Promise<void>
9
+ /** Called synchronously for every item added, whether or not the queue was empty. */
10
+ onEnqueue?: (item: T) => void
9
11
  }
10
12
 
11
13
  interface PermissionQueue<T> {
12
14
  requests: T[]
13
15
  /** Add an item to the queue. Handles focus request and modal open on first item. */
14
16
  enqueue: (item: T) => void
15
- /** Remove the first item. Closes modal and relinquishes focus when empty. */
16
- advance: (onAdvance?: (head: T) => void) => void
17
+ /**
18
+ * Remove the first item, or with `requestID` only the item carrying that ID
19
+ * (and nothing at all if it is no longer queued). Closes modal and
20
+ * relinquishes focus when empty.
21
+ */
22
+ advance: (onAdvance?: (removed: T) => void, requestID?: string) => void
23
+ /** Remove the item with this `requestID`. Returns whether it was queued. */
24
+ removeById: (requestID: string) => boolean
25
+ /** Drop every item (handing each to `onEach`), close the modal and give focus back. */
26
+ clear: (onEach?: (item: T) => void) => void
17
27
  }
18
28
 
29
+ const idOf = (item: unknown): string | undefined => (item as { requestID?: string } | null)?.requestID
30
+
19
31
  /**
20
32
  * Generic permission request queue with focus management.
21
33
  *
22
34
  * Deduplicates the identical queue logic used by basket, certificate,
23
35
  * protocol, spending, and BTMS permission systems.
24
36
  */
25
- export function usePermissionQueue<T>(opts: UsePermissionQueueOptions): PermissionQueue<T> {
26
- const { openModal, isFocused, onFocusRequested, onFocusRelinquished } = opts
37
+ export function usePermissionQueue<T>(opts: UsePermissionQueueOptions<T>): PermissionQueue<T> {
38
+ const { openModal, isFocused, onFocusRequested, onFocusRelinquished, onEnqueue } = opts
27
39
  const [requests, setRequests] = useState<T[]>([])
40
+ // The queue's current contents, updated in the same step as the state, so a
41
+ // caller (a withdrawal, an answer by ID) can tell synchronously whether an
42
+ // item is still queued without waiting for a render.
43
+ const itemsRef = useRef<T[]>([])
28
44
  const wasOriginallyFocusedRef = useRef(false)
45
+ // Which "first item" the deferred focus/modal step belongs to. A clear or an advance to empty
46
+ // moves it on, so a step that was scheduled for a queue that has since been emptied does nothing.
47
+ const openGenRef = useRef(0)
48
+
49
+ const replace = useCallback((next: T[]) => {
50
+ itemsRef.current = next
51
+ setRequests(next)
52
+ }, [])
53
+
54
+ const emptied = useCallback(() => {
55
+ openGenRef.current += 1
56
+ openModal?.(false)
57
+ if (!wasOriginallyFocusedRef.current) onFocusRelinquished()
58
+ }, [openModal, onFocusRelinquished])
29
59
 
30
60
  const enqueue = useCallback(
31
61
  (item: T) => {
32
- // Read length before updating so the side-effect runs outside the updater.
33
- // React may double-invoke updaters in Strict Mode; this avoids double focus requests.
34
- setRequests(prev => {
35
- if (prev.length === 0) {
36
- // Schedule focus/modal on next microtask, outside the updater
37
- Promise.resolve().then(() => {
38
- isFocused().then(currentlyFocused => {
39
- wasOriginallyFocusedRef.current = currentlyFocused
40
- if (!currentlyFocused) onFocusRequested()
41
- openModal?.(true)
42
- })
62
+ const wasEmpty = itemsRef.current.length === 0
63
+ replace([...itemsRef.current, item])
64
+ try {
65
+ onEnqueue?.(item)
66
+ } catch (e) {
67
+ console.warn('[permissionQueue] onEnqueue failed', e)
68
+ }
69
+ if (wasEmpty) {
70
+ // Schedule focus/modal on next microtask, after the state is set. Both steps re-check
71
+ // that this queue is still the one that was filled: a withdrawal in between has already
72
+ // closed the modal and given focus back, and must not be undone.
73
+ const gen = ++openGenRef.current
74
+ const stale = () => gen !== openGenRef.current || itemsRef.current.length === 0
75
+ Promise.resolve().then(() => {
76
+ if (stale()) return
77
+ isFocused().then(currentlyFocused => {
78
+ if (stale()) return
79
+ wasOriginallyFocusedRef.current = currentlyFocused
80
+ if (!currentlyFocused) onFocusRequested()
81
+ openModal?.(true)
43
82
  })
44
- }
45
- return [...prev, item]
46
- })
83
+ })
84
+ }
47
85
  },
48
- [isFocused, onFocusRequested, openModal]
86
+ [isFocused, onFocusRequested, openModal, replace, onEnqueue]
49
87
  )
50
88
 
51
89
  const advance = useCallback(
52
- (onAdvance?: (head: T) => void) => {
53
- setRequests(prev => {
54
- if (prev.length > 0 && onAdvance) {
55
- onAdvance(prev[0])
56
- }
57
- const newQueue = prev.slice(1)
58
- if (newQueue.length === 0) {
59
- openModal?.(false)
60
- if (!wasOriginallyFocusedRef.current) onFocusRelinquished()
61
- }
62
- return newQueue
63
- })
90
+ (onAdvance?: (removed: T) => void, requestID?: string) => {
91
+ const prev = itemsRef.current
92
+ const index = requestID === undefined ? (prev.length > 0 ? 0 : -1) : prev.findIndex(i => idOf(i) === requestID)
93
+ if (index < 0) return
94
+ const removed = prev[index]
95
+ onAdvance?.(removed)
96
+ const next = prev.filter((_, i) => i !== index)
97
+ replace(next)
98
+ if (next.length === 0) emptied()
99
+ },
100
+ [emptied, replace]
101
+ )
102
+
103
+ const removeById = useCallback(
104
+ (requestID: string): boolean => {
105
+ if (!itemsRef.current.some(i => idOf(i) === requestID)) return false
106
+ advance(undefined, requestID)
107
+ return true
108
+ },
109
+ [advance]
110
+ )
111
+
112
+ const clear = useCallback(
113
+ (onEach?: (item: T) => void) => {
114
+ const prev = itemsRef.current
115
+ if (prev.length === 0) return
116
+ replace([])
117
+ for (const item of prev) onEach?.(item)
118
+ emptied()
64
119
  },
65
- [openModal, onFocusRelinquished]
120
+ [emptied, replace]
66
121
  )
67
122
 
68
- return { requests, enqueue, advance }
123
+ return { requests, enqueue, advance, removeById, clear }
69
124
  }