@bsv/expo-wallet-toolbox 0.1.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 (240) hide show
  1. package/LICENSE.txt +28 -0
  2. package/README.md +512 -0
  3. package/assets/sounds/payment-receive.wav +0 -0
  4. package/assets/sounds/payment-send.wav +0 -0
  5. package/assets/sounds/vault-close.wav +0 -0
  6. package/assets/sounds/vault-open.wav +0 -0
  7. package/core/amountFormatHelpers.ts +330 -0
  8. package/core/backup/RemoteSyncReader.ts +94 -0
  9. package/core/backup/client.ts +111 -0
  10. package/core/backup/codec.ts +218 -0
  11. package/core/backup/constants.ts +88 -0
  12. package/core/backup/cursor.ts +138 -0
  13. package/core/backup/derive.ts +46 -0
  14. package/core/backup/deviceId.ts +33 -0
  15. package/core/backup/erase.ts +67 -0
  16. package/core/backup/preference.ts +33 -0
  17. package/core/backup/push.ts +295 -0
  18. package/core/backup/restore.ts +152 -0
  19. package/core/backup/restoreOnImport.ts +119 -0
  20. package/core/backup/status.ts +46 -0
  21. package/core/config.tsx +47 -0
  22. package/core/constants.ts +35 -0
  23. package/core/context/ExchangeRateContext.tsx +69 -0
  24. package/core/context/LocalStorageProvider.tsx +225 -0
  25. package/core/context/UserContext.tsx +129 -0
  26. package/core/context/VaultContext.tsx +79 -0
  27. package/core/context/WalletConnectionContext.tsx +454 -0
  28. package/core/context/WalletContext.tsx +2938 -0
  29. package/core/context/buildGeneration.ts +37 -0
  30. package/core/deviceTier.ts +89 -0
  31. package/core/diskSpace.ts +62 -0
  32. package/core/displayCurrencies.ts +56 -0
  33. package/core/headers/OfflineFirstChaintracks.ts +176 -0
  34. package/core/headers/checkpoints.ts +39 -0
  35. package/core/headers/fs.ts +119 -0
  36. package/core/headers/headerStore.ts +333 -0
  37. package/core/headers/prewarm.ts +36 -0
  38. package/core/headers/syncHeaders.ts +73 -0
  39. package/core/hooks/useConfirmationSound.ts +135 -0
  40. package/core/hooks/useHaptics.ts +51 -0
  41. package/core/hooks/usePermissionQueue.ts +69 -0
  42. package/core/i18n/translations.tsx +6692 -0
  43. package/core/index.ts +295 -0
  44. package/core/localpay/blePermissions.ts +32 -0
  45. package/core/localpay/build.ts +392 -0
  46. package/core/localpay/codec.ts +338 -0
  47. package/core/localpay/deviceCaps.ts +175 -0
  48. package/core/localpay/nearbyAdvisory.ts +32 -0
  49. package/core/localpay/nearbyPermissions.ts +34 -0
  50. package/core/localpay/pending.ts +385 -0
  51. package/core/localpay/pendingAborts.ts +67 -0
  52. package/core/localpay/qr.ts +16 -0
  53. package/core/localpay/session.ts +277 -0
  54. package/core/localpay/sessionPolicy.ts +5 -0
  55. package/core/localpay/transport/awdl.ts +11 -0
  56. package/core/localpay/transport/ble.ts +159 -0
  57. package/core/localpay/transport/nearby.ts +12 -0
  58. package/core/localpay/transport/race.ts +110 -0
  59. package/core/localpay/transport/select.ts +128 -0
  60. package/core/localpay/transport/socket.ts +244 -0
  61. package/core/localpay/types.ts +82 -0
  62. package/core/localpay/verify.ts +204 -0
  63. package/core/logging.config.ts +10 -0
  64. package/core/logging.ts +77 -0
  65. package/core/mnemonicWallet.ts +180 -0
  66. package/core/monitor/TaskBackupPush.ts +168 -0
  67. package/core/monitor/TaskCreditInbox.ts +116 -0
  68. package/core/monitor/TaskDrainOutbox.ts +122 -0
  69. package/core/monitor/TaskSendOffline.ts +123 -0
  70. package/core/monitor/unfailRetry.ts +116 -0
  71. package/core/net/chainMatch.ts +34 -0
  72. package/core/net/online.ts +34 -0
  73. package/core/offline/cancelParked.ts +56 -0
  74. package/core/offline/hold.ts +127 -0
  75. package/core/offline/order.ts +109 -0
  76. package/core/offline/payerHold.ts +144 -0
  77. package/core/offline/plan.ts +264 -0
  78. package/core/offline/queueGrace.ts +52 -0
  79. package/core/parsePeerPayURI.ts +119 -0
  80. package/core/pay/beefRepair.ts +106 -0
  81. package/core/pay/creditErrors.ts +46 -0
  82. package/core/pay/creditInbox.ts +202 -0
  83. package/core/pay/damagedInbox.ts +64 -0
  84. package/core/pay/proofNudge.ts +23 -0
  85. package/core/pay/provenTxFromBump.ts +31 -0
  86. package/core/pay/rails/address.ts +329 -0
  87. package/core/pay/rails/handle.ts +617 -0
  88. package/core/pay/rails/index.ts +197 -0
  89. package/core/pay/rails/nearby.ts +79 -0
  90. package/core/pay/receiveFocus.ts +13 -0
  91. package/core/pay/recordProof.ts +91 -0
  92. package/core/pay/refreshProofGuard.ts +34 -0
  93. package/core/pay/sweeper.ts +75 -0
  94. package/core/pay/tokenAmount.ts +18 -0
  95. package/core/pay/userError.ts +18 -0
  96. package/core/pay/watchlist.ts +126 -0
  97. package/core/peerpay/control.ts +122 -0
  98. package/core/peerpay/handleResendRequests.ts +475 -0
  99. package/core/peerpay/inboxAttempts.ts +33 -0
  100. package/core/peerpay/metadataDecryptor.ts +42 -0
  101. package/core/peerpay/offlineNacks.ts +96 -0
  102. package/core/peerpay/outbox.ts +209 -0
  103. package/core/peerpay/rebuildToken.ts +76 -0
  104. package/core/peerpay/resendBeef.ts +115 -0
  105. package/core/services/arcadeBroadcastProvider.ts +214 -0
  106. package/core/services/capWalletArgs.ts +99 -0
  107. package/core/services/exchangeRate.ts +63 -0
  108. package/core/services/secrets/envelope.ts +102 -0
  109. package/core/services/secrets/hkdf.ts +37 -0
  110. package/core/services/secrets/index.ts +63 -0
  111. package/core/services/secrets/kek.ts +274 -0
  112. package/core/services/secrets/migration.ts +188 -0
  113. package/core/services/secrets/policy.ts +120 -0
  114. package/core/services/secrets/storage.ts +54 -0
  115. package/core/services/secrets/store.ts +125 -0
  116. package/core/services/secrets/types.ts +85 -0
  117. package/core/services/usdFxRates.ts +101 -0
  118. package/core/services/vault/VaultKeyService.ts +312 -0
  119. package/core/services/vault/backupAttestation.ts +136 -0
  120. package/core/services/vault/ceremony.ts +972 -0
  121. package/core/services/vault/ceremonyHost.ts +46 -0
  122. package/core/services/vault/devMock.ts +22 -0
  123. package/core/services/vault/driver.ts +197 -0
  124. package/core/services/vault/guard.ts +90 -0
  125. package/core/services/vault/k1.ts +75 -0
  126. package/core/services/vault/mockYubiKey.ts +217 -0
  127. package/core/services/vault/random.ts +20 -0
  128. package/core/services/vault/sealing.ts +84 -0
  129. package/core/services/vault/session.ts +59 -0
  130. package/core/services/vault/transfers.ts +1151 -0
  131. package/core/services/vault/types.ts +109 -0
  132. package/core/services/vault/vaultDerivation.ts +152 -0
  133. package/core/services/vault/vaultPassphrase.ts +287 -0
  134. package/core/services/vault/vaultStore.ts +104 -0
  135. package/core/services/walletArgLimits.ts +234 -0
  136. package/core/services/walletServiceConfig.ts +170 -0
  137. package/core/storage/LocalStorageAdapter.ts +58 -0
  138. package/core/storage/README.md +391 -0
  139. package/core/storage/StorageExpoSQLite.ts +2008 -0
  140. package/core/storage/errors.ts +73 -0
  141. package/core/storage/index.ts +3 -0
  142. package/core/storage/methods/findSql.ts +286 -0
  143. package/core/storage/methods/historyNotes.ts +61 -0
  144. package/core/storage/methods/listActionsSql.ts +212 -0
  145. package/core/storage/methods/listOutputsSql.ts +211 -0
  146. package/core/storage/methods/offlineActions.ts +156 -0
  147. package/core/storage/methods/processOfflineActions.ts +503 -0
  148. package/core/storage/methods/reclaim.ts +135 -0
  149. package/core/storage/methods/reviewStatusSql.ts +167 -0
  150. package/core/storage/methods/unprovenWithoutReqSql.ts +26 -0
  151. package/core/storage/methods/walletBalanceSql.ts +55 -0
  152. package/core/storage/schema/createTables.ts +385 -0
  153. package/core/storage/skipQueuedAncestors.ts +29 -0
  154. package/core/storage/sqlUpdateValue.ts +12 -0
  155. package/core/stores/ConnectionStore.ts +71 -0
  156. package/core/theme/ThemeContext.tsx +182 -0
  157. package/core/theme/assertThemeContrast.ts +109 -0
  158. package/core/theme/motion.ts +50 -0
  159. package/core/theme/tokens.ts +232 -0
  160. package/core/theme/useThemeStyles.tsx +156 -0
  161. package/core/walletDbRegistry.ts +110 -0
  162. package/core/walletMonitor.ts +149 -0
  163. package/core/walletRepair/runWalletCheck.ts +195 -0
  164. package/core/walletRepair/shouldReleaseUtxo.ts +18 -0
  165. package/package.json +86 -0
  166. package/ui/backupShares.ts +367 -0
  167. package/ui/components/QRScanner.tsx +353 -0
  168. package/ui/components/pay/AddressReceive.tsx +507 -0
  169. package/ui/components/pay/AvailableBalance.tsx +61 -0
  170. package/ui/components/pay/HandleReceive.tsx +896 -0
  171. package/ui/components/pay/MessageBoxConfig.tsx +256 -0
  172. package/ui/components/pay/NearbyAdvisoryModal.tsx +111 -0
  173. package/ui/components/pay/NearbyFlow.tsx +2542 -0
  174. package/ui/components/pay/OfflineNotice.tsx +337 -0
  175. package/ui/components/pay/PayCellRow.tsx +101 -0
  176. package/ui/components/pay/PayForm.tsx +223 -0
  177. package/ui/components/pay/PaymentQrDisplay.tsx +105 -0
  178. package/ui/components/pay/PaymentSuccessOverlay.tsx +266 -0
  179. package/ui/components/pay/RecipientField.tsx +308 -0
  180. package/ui/components/pay/RequestHub.tsx +75 -0
  181. package/ui/components/pay/ResultBanner.tsx +69 -0
  182. package/ui/components/pay/UniversalSend.tsx +687 -0
  183. package/ui/components/pay/useRecipientInput.ts +270 -0
  184. package/ui/components/security/WalletLockNotice.tsx +138 -0
  185. package/ui/components/ui/AlertCard.tsx +223 -0
  186. package/ui/components/ui/AppLogo.tsx +166 -0
  187. package/ui/components/ui/BlurChrome.tsx +72 -0
  188. package/ui/components/ui/Celebration.tsx +84 -0
  189. package/ui/components/ui/ChoiceSheet.ts +69 -0
  190. package/ui/components/ui/CustomSafeArea.tsx +74 -0
  191. package/ui/components/ui/ErrorBoundary.tsx +154 -0
  192. package/ui/components/ui/GroupedList.tsx +125 -0
  193. package/ui/components/ui/IconButton.tsx +105 -0
  194. package/ui/components/ui/ListRow.tsx +197 -0
  195. package/ui/components/ui/PermissionSheet.tsx +920 -0
  196. package/ui/components/ui/PresenceRow.tsx +215 -0
  197. package/ui/components/ui/PressableScale.tsx +105 -0
  198. package/ui/components/ui/ScreenGradient.tsx +47 -0
  199. package/ui/components/ui/ScrollFade.tsx +76 -0
  200. package/ui/components/ui/Sheet.tsx +342 -0
  201. package/ui/components/ui/Toast.tsx +142 -0
  202. package/ui/components/ui/index.ts +8 -0
  203. package/ui/components/vault/EnrollWizard.tsx +627 -0
  204. package/ui/components/vault/PassphraseField.tsx +306 -0
  205. package/ui/components/vault/PhraseBackupSheet.tsx +227 -0
  206. package/ui/components/vault/VaultBackdrop.tsx +354 -0
  207. package/ui/components/vault/VaultCeremonySheet.tsx +327 -0
  208. package/ui/components/wallet/ActivityRow.tsx +408 -0
  209. package/ui/components/wallet/AmountDisplay.tsx +48 -0
  210. package/ui/components/wallet/AmountInput.tsx +256 -0
  211. package/ui/components/wallet/BackupReminderSheet.tsx +168 -0
  212. package/ui/components/wallet/Balance.tsx +144 -0
  213. package/ui/components/wallet/BiometricAdvisoryModal.tsx +133 -0
  214. package/ui/components/wallet/ImportFromBackupPrompt.tsx +93 -0
  215. package/ui/exportDatabases.ts +122 -0
  216. package/ui/exportTransactions.ts +129 -0
  217. package/ui/hooks/useOfflineNoticeActions.ts +136 -0
  218. package/ui/hooks/useOnline.ts +70 -0
  219. package/ui/hooks/useSpendableBalance.ts +58 -0
  220. package/ui/hooks/useVaultBalance.ts +50 -0
  221. package/ui/importDatabases.ts +170 -0
  222. package/ui/index.ts +136 -0
  223. package/ui/isImageUrl.ts +10 -0
  224. package/ui/printRecoveryShares.ts +93 -0
  225. package/ui/resolveIdentity.ts +125 -0
  226. package/ui/screens/ConnectionsScreen.tsx +438 -0
  227. package/ui/screens/LogsScreen.tsx +432 -0
  228. package/ui/screens/PairScreen.tsx +288 -0
  229. package/ui/screens/PayScreen.tsx +479 -0
  230. package/ui/screens/SettingsScreen.tsx +180 -0
  231. package/ui/screens/TrustScreen.tsx +831 -0
  232. package/ui/screens/VaultRecoverScreen.tsx +226 -0
  233. package/ui/screens/VaultScreen.tsx +423 -0
  234. package/ui/screens/VaultTransferScreen.tsx +293 -0
  235. package/ui/screens/WalletCheckScreen.tsx +539 -0
  236. package/ui/screens/WalletConfigScreen.tsx +1095 -0
  237. package/ui/screens/WalletHomeScreen.tsx +1597 -0
  238. package/ui/screens/homeBadges.ts +18 -0
  239. package/ui/txStatus.ts +79 -0
  240. package/ui/validateTrust.ts +44 -0
@@ -0,0 +1,214 @@
1
+ import { Beef, Transaction, Utils } from '@bsv/sdk'
2
+ import type {
3
+ PostBeefResult,
4
+ PostTxResultForTxid
5
+ } from '@bsv/wallet-toolbox-mobile/out/src/sdk'
6
+
7
+ /**
8
+ * ARC intermediate statuses that still mean "accepted for relay".
9
+ * Arcade often replies immediately with RECEIVED (HTTP 202); SEEN_* / MINED
10
+ * typically arrive later via SSE. The toolbox's built-in ARC provider treats any
11
+ * non-double-spend 2xx as success — match that so we do not fail over to WoC
12
+ * after Arcade already accepted the tx.
13
+ */
14
+ const ARC_DOUBLE_SPEND_STATUSES = new Set([
15
+ 'DOUBLE_SPEND_ATTEMPTED',
16
+ 'SEEN_IN_ORPHAN_MEMPOOL'
17
+ ])
18
+
19
+ /**
20
+ * Shared response handling for ARC-compatible services (Arcade, Taal, GorillaPool).
21
+ * Maps txStatus to the correct PostTxResultForTxid fields.
22
+ *
23
+ * Exported for unit tests.
24
+ */
25
+ export function handleArcResponse(
26
+ serviceName: string,
27
+ response: { ok: boolean; status: number },
28
+ data: { txid?: string; txStatus?: string },
29
+ txids: string[]
30
+ ): PostTxResultForTxid {
31
+ const txResult: PostTxResultForTxid = {
32
+ txid: data.txid || txids[0],
33
+ status: 'error',
34
+ notes: [{
35
+ when: new Date().toISOString(),
36
+ what: `${serviceName}PostEF`,
37
+ txStatus: data.txStatus,
38
+ httpStatus: response.status
39
+ }]
40
+ }
41
+ if (data.txStatus && ARC_DOUBLE_SPEND_STATUSES.has(data.txStatus)) {
42
+ txResult.doubleSpend = true
43
+ } else if (response.ok && data.txStatus !== 'REJECTED') {
44
+ // RECEIVED / STORED / SENT_TO_NETWORK / ACCEPTED_BY_NETWORK / SEEN_* / MINED
45
+ // all mean the broadcaster accepted the tx. Page-load 402 must not wait for
46
+ // SSE SEEN_ON_NETWORK before treating the post as successful.
47
+ txResult.status = 'success'
48
+ } else if (data.txStatus === 'REJECTED' || !response.ok) {
49
+ txResult.serviceError = true
50
+ }
51
+ return txResult
52
+ }
53
+
54
+ /**
55
+ * Convert BEEF to EF-format binary for ARC-compatible endpoints.
56
+ */
57
+ function beefToEF(beef: Beef): Uint8Array {
58
+ const tx = Transaction.fromBEEF(beef.toBinary())
59
+ return new Uint8Array(tx.toEF())
60
+ }
61
+
62
+ /**
63
+ * Create an ARC-compatible broadcast service that posts EF-format transactions.
64
+ */
65
+ function createArcBroadcastService(
66
+ name: string,
67
+ arcUrl: string,
68
+ headers: Record<string, string>
69
+ ) {
70
+ return {
71
+ name,
72
+ service: async (beef: Beef, txids: string[]): Promise<PostBeefResult> => {
73
+ const r: PostBeefResult = { name, status: 'success', txidResults: [] }
74
+ try {
75
+ const ef = beefToEF(beef)
76
+ const controller = new AbortController()
77
+ const timeout = setTimeout(() => controller.abort(), 30_000)
78
+ let response: Response
79
+ try {
80
+ response = await fetch(`${arcUrl}/tx`, {
81
+ method: 'POST',
82
+ headers: {
83
+ 'Content-Type': 'application/octet-stream',
84
+ ...headers
85
+ },
86
+ body: ef as unknown as BodyInit,
87
+ signal: controller.signal
88
+ })
89
+ } finally {
90
+ clearTimeout(timeout)
91
+ }
92
+ const data = await response.json()
93
+ console.log(`[${name}] POST /tx ${response.status}`, JSON.stringify(data))
94
+ const txResult = handleArcResponse(name, response, data, txids)
95
+ r.txidResults.push(txResult)
96
+ r.status = txResult.status
97
+ } catch (err: any) {
98
+ console.log(`[${name}] POST /tx error: ${err.message}`)
99
+ r.status = 'error'
100
+ r.txidResults.push({
101
+ txid: txids[0],
102
+ status: 'error',
103
+ serviceError: true,
104
+ data: err.message
105
+ })
106
+ }
107
+ return r
108
+ }
109
+ }
110
+ }
111
+
112
+ /**
113
+ * Arcade broadcast service — EF format with callback token for SSE updates.
114
+ */
115
+ export function createArcadeBroadcastService(arcadeUrl: string, callbackToken: string) {
116
+ return createArcBroadcastService('Arcade', arcadeUrl, {
117
+ 'X-CallbackToken': callbackToken,
118
+ 'X-FullStatusUpdates': 'true'
119
+ })
120
+ }
121
+
122
+ /**
123
+ * Taal ARC broadcast service — EF format.
124
+ */
125
+ export function createTaalBroadcastService(arcUrl: string, apiKey?: string) {
126
+ const headers: Record<string, string> = {}
127
+ if (apiKey) headers['Authorization'] = `Bearer ${apiKey}`
128
+ return createArcBroadcastService('TaalArc', arcUrl, headers)
129
+ }
130
+
131
+ /**
132
+ * GorillaPool ARC broadcast service — EF format.
133
+ */
134
+ export function createGorillaPoolBroadcastService(arcUrl: string) {
135
+ return createArcBroadcastService('GorillaPoolArc', arcUrl, {})
136
+ }
137
+
138
+ /**
139
+ * WhatsOnChain broadcast service — raw tx hex.
140
+ */
141
+ export function createWocBroadcastService(chain: string, apiKey?: string) {
142
+ const baseUrl =
143
+ chain === 'main'
144
+ ? 'https://api.whatsonchain.com/v1/bsv/main'
145
+ : chain === 'test'
146
+ ? 'https://api.whatsonchain.com/v1/bsv/test'
147
+ : chain === 'ttn'
148
+ ? 'https://api.woc-ttn.bsvblockchain.tech/v1/bsv/test'
149
+ : 'https://api.whatsonchain.com/v1/bsv/main'
150
+ const name = 'WhatsOnChain'
151
+
152
+ return {
153
+ name,
154
+ service: async (beef: Beef, txids: string[]): Promise<PostBeefResult> => {
155
+ const r: PostBeefResult = { name, status: 'success', txidResults: [] }
156
+ try {
157
+ const tx = Transaction.fromBEEF(beef.toBinary())
158
+ const rawHex = Utils.toHex(tx.toBinary())
159
+ const controller = new AbortController()
160
+ const timeout = setTimeout(() => controller.abort(), 30_000)
161
+ let response: Response
162
+ try {
163
+ const headers: Record<string, string> = {
164
+ 'Content-Type': 'application/json',
165
+ 'Accept': 'text/plain'
166
+ }
167
+ if (apiKey) headers['woc-api-key'] = apiKey
168
+ response = await fetch(`${baseUrl}/tx/raw`, {
169
+ method: 'POST',
170
+ headers,
171
+ body: JSON.stringify({ txhex: rawHex }),
172
+ signal: controller.signal
173
+ })
174
+ } finally {
175
+ clearTimeout(timeout)
176
+ }
177
+ const body = await response.text()
178
+ console.log(`[${name}] POST /tx/raw ${response.status}`, body)
179
+ const txResult: PostTxResultForTxid = {
180
+ txid: txids[0],
181
+ status: 'error',
182
+ notes: [{ when: new Date().toISOString(), what: 'wocPostRawTx', httpStatus: response.status }]
183
+ }
184
+ if (response.ok) {
185
+ txResult.status = 'success'
186
+ } else if (body.includes('already in the mempool')) {
187
+ // Idempotent same-txid rebroadcast — a conflicting DIFFERENT tx cannot
188
+ // produce this message, so it can't mask a double-spend.
189
+ txResult.status = 'success'
190
+ } else {
191
+ // Never classify from WoC body strings. "Missing inputs" is ambiguous
192
+ // (propagation lag vs mined double-spend) and a wrong terminal verdict
193
+ // cascades to reject descendants. Terminal verdicts come from Arcade's
194
+ // structured txStatus only (handleArcResponse); everything here is
195
+ // retryable, and the release engine's topological order — foreign
196
+ // ancestors included — is what prevents the orphan case at the source.
197
+ txResult.serviceError = true
198
+ }
199
+ r.txidResults.push(txResult)
200
+ r.status = txResult.status
201
+ } catch (err: any) {
202
+ console.log(`[${name}] POST /tx/raw error: ${err.message}`)
203
+ r.status = 'error'
204
+ r.txidResults.push({
205
+ txid: txids[0],
206
+ status: 'error',
207
+ serviceError: true,
208
+ data: err.message
209
+ })
210
+ }
211
+ return r
212
+ }
213
+ }
214
+ }
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Argument-size cap for wallets handed to EXTERNAL callers.
3
+ *
4
+ * Composed at each external surface exactly like guardVaultAccess: the in-tab
5
+ * CWI bridge, the desktop-pairing WalletClient, and the saved-connection
6
+ * WalletClients. Wrap outside the vault guard so a refusal costs nothing —
7
+ * neither a permission prompt nor a storage touch.
8
+ *
9
+ * WHERE THIS MUST NOT GO. Not in guardVaultAccess, not in SimpleWalletManager,
10
+ * not in WalletPermissionsManager, and not in the toolbox. The vault's K1
11
+ * traffic is ordinary-sized today — a 25-byte P2PKH locking script and a
12
+ * ~107-byte unlocking script per input — and would pass any limit here
13
+ * unmodified. The exemption is kept anyway so the vault stays insulated from
14
+ * any future tightening of these limits on the shared path.
15
+ *
16
+ * The vault is exempt STRUCTURALLY rather than by an originator comparison: it
17
+ * calls managers.permissionsManager directly and never receives a capped wallet.
18
+ * That cannot be spoofed by a caller presenting the admin originator, which
19
+ * matters because the desktop-pairing surface constructs its WalletClient over
20
+ * guardVaultAccess(manager, ADMIN_ORIGINATOR) — the admin string appears there
21
+ * for the guard's own comparison, so keying an exemption on it would be reasoning
22
+ * about the wrong thing.
23
+ */
24
+ import type { WalletInterface } from '@bsv/sdk'
25
+ import { type WalletArgLimits, checkWalletArgs, limitsForTier } from './walletArgLimits'
26
+
27
+ /**
28
+ * A refused call.
29
+ *
30
+ * `code = 6` matches WERR_INVALID_PARAMETER, which is what page-side @bsv/sdk
31
+ * consumers already read off `err.code`; the dispatcher's catch flattens a bare
32
+ * Error to code 1, so a size refusal would otherwise be indistinguishable from
33
+ * an unknown internal failure.
34
+ */
35
+ export class WalletArgTooLarge extends Error {
36
+ readonly code = 6
37
+ constructor(
38
+ readonly field: string,
39
+ message: string
40
+ ) {
41
+ super(message)
42
+ this.name = 'WalletArgTooLarge'
43
+ }
44
+ }
45
+
46
+ /**
47
+ * Device tier, read lazily.
48
+ *
49
+ * expo-device is a native module, so importing it at module load would make this
50
+ * pure wrapper unusable anywhere the native side is absent — including tests. A
51
+ * caller that supplies its own limits never touches it at all, and a failure to
52
+ * read the tier falls back to 'mid' rather than leaving the surface uncapped.
53
+ */
54
+ function tierLimits(): WalletArgLimits {
55
+ try {
56
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
57
+ const { getDeviceTier } = require('../deviceTier') as typeof import('../deviceTier')
58
+ return limitsForTier(getDeviceTier())
59
+ } catch {
60
+ return limitsForTier('mid')
61
+ }
62
+ }
63
+
64
+ /** The calls that can carry transaction bytes. */
65
+ const SIZED = new Set<keyof WalletInterface>(['createAction', 'signAction', 'internalizeAction'])
66
+
67
+ /**
68
+ * Wrap `wallet` so oversize arguments are refused before it is called.
69
+ *
70
+ * Limits default to the device tier's, which halves the aggregate on a device
71
+ * with under 3.5 GB of RAM.
72
+ */
73
+ export function capWalletArgs<T extends WalletInterface>(wallet: T, limits?: WalletArgLimits): T {
74
+ const active = limits ?? tierLimits()
75
+ return new Proxy(wallet, {
76
+ get(target, prop, receiver) {
77
+ const value = Reflect.get(target, prop, receiver)
78
+ if (typeof value !== 'function' || !SIZED.has(prop as keyof WalletInterface)) {
79
+ return typeof value === 'function' ? value.bind(target) : value
80
+ }
81
+ const bound = (value as (a: unknown, o?: string) => unknown).bind(target)
82
+ return (args: unknown, originator?: string) => {
83
+ const refusal = checkWalletArgs(String(prop), args, active)
84
+ if (refusal) {
85
+ console.log(
86
+ '[walletArgs] refused %s from %s · %s %d > %d',
87
+ String(prop),
88
+ originator ?? 'unknown',
89
+ refusal.field,
90
+ refusal.actual,
91
+ refusal.limit
92
+ )
93
+ return Promise.reject(new WalletArgTooLarge(refusal.field, refusal.message))
94
+ }
95
+ return bound(args, originator)
96
+ }
97
+ }
98
+ })
99
+ }
@@ -0,0 +1,63 @@
1
+ import type { BsvExchangeRate } from '@bsv/wallet-toolbox-mobile/out/src/sdk'
2
+ import AsyncStorage from '@react-native-async-storage/async-storage'
3
+
4
+ // Shared with context/ExchangeRateContext.tsx so a single cache serves both the
5
+ // fiat-display UI and the wallet-build seed. Same key + same { usdPerBsv } shape.
6
+ const CACHE_KEY = 'cached_exchange_rate'
7
+ const FALLBACK_RATE = 16.75
8
+ const REFRESH_TIMEOUT_MS = 4000
9
+
10
+ /**
11
+ * Fire-and-forget refresh of the cached BSV/USD rate. Timeout-guarded so it can
12
+ * NEVER hang the JS thread or the wallet build — it is never awaited by callers.
13
+ * The result is only persisted to AsyncStorage for the next cold start.
14
+ */
15
+ function refreshExchangeRateCache(): void {
16
+ ;(async () => {
17
+ const controller = new AbortController()
18
+ const timeout = setTimeout(() => controller.abort(), REFRESH_TIMEOUT_MS)
19
+ try {
20
+ const res = await fetch('https://api.whatsonchain.com/v1/bsv/main/exchangerate', {
21
+ signal: controller.signal
22
+ })
23
+ const data = await res.json()
24
+ const usdPerBsv = Number(data?.rate)
25
+ if (Number.isFinite(usdPerBsv) && usdPerBsv > 0) {
26
+ await AsyncStorage.setItem(CACHE_KEY, JSON.stringify({ usdPerBsv, timestamp: new Date().toISOString() }))
27
+ }
28
+ } catch (error) {
29
+ console.error('Error refreshing exchange rate:', error)
30
+ } finally {
31
+ clearTimeout(timeout)
32
+ }
33
+ })()
34
+ }
35
+
36
+ /**
37
+ * Return a BSV/USD seed rate for the wallet build WITHOUT blocking on the network.
38
+ *
39
+ * Previously this awaited an un-timed `fetch()` on the wallet-build critical path.
40
+ * With the web3 wallet gate holding the UI until the build resolves, a stalled
41
+ * cold-start network (≈60s NSURLSession timeout) could exceed the iOS launch
42
+ * watchdog and get the whole app killed. The rate only seeds the Services rate
43
+ * cache (refreshed periodically) and feeds fiat display — it is never read by the
44
+ * CWI provider before page JS — so a cached/hardcoded seed is fully correct.
45
+ *
46
+ * Reads the shared cache (one fast AsyncStorage get), falls back to a hardcoded
47
+ * value, and kicks off a background refresh for next time. Never hangs.
48
+ */
49
+ export async function getExchangeRate(): Promise<BsvExchangeRate> {
50
+ let rate = FALLBACK_RATE
51
+ try {
52
+ const cached = await AsyncStorage.getItem(CACHE_KEY)
53
+ if (cached) {
54
+ const { usdPerBsv } = JSON.parse(cached)
55
+ if (typeof usdPerBsv === 'number' && usdPerBsv > 0) rate = usdPerBsv
56
+ }
57
+ } catch (error) {
58
+ console.error('Error reading cached exchange rate:', error)
59
+ }
60
+ // Refresh the cache in the background — never awaited, never blocks the build.
61
+ refreshExchangeRateCache()
62
+ return { timestamp: new Date(), rate, base: 'USD' }
63
+ }
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Secret envelope crypto — pure functions, no I/O, no logging.
3
+ *
4
+ * Scheme (`bsvb-secret-envelope-v1`):
5
+ *
6
+ * seal : DEK = HKDF-SHA256(KEK, salt, "bsvb-secret-envelope-v1|<name>")
7
+ * C = AES-256-GCM(DEK, utf8(plaintext))
8
+ * open : same derivation, then AES-GCM-decrypt.
9
+ *
10
+ * The KEK never encrypts anything directly: each secret gets its own derived
11
+ * DEK, so a blob sealed as `mnemonic` cannot be opened as `recoveredKey`. That
12
+ * is the stand-in for AAD, which @bsv/sdk's SymmetricKey does not expose.
13
+ *
14
+ * SECURITY: never log inputs or outputs of these functions.
15
+ */
16
+ import { SymmetricKey, Random, Utils } from '@bsv/sdk'
17
+ import { hkdfSha256 } from './hkdf'
18
+ import { EnvelopeBlob, EnvelopeError, SecretName } from './types'
19
+
20
+ export const ENVELOPE_INFO = 'bsvb-secret-envelope-v1'
21
+
22
+ const SALT_LEN = 32
23
+ const KEK_LEN = 32
24
+ /** SymmetricKey wire format is iv(32) || ct || tag(16). */
25
+ const MIN_CIPHERTEXT_BYTES = 48
26
+
27
+ const deriveDek = (kek: number[], salt: number[], name: SecretName): number[] =>
28
+ hkdfSha256(kek, salt, `${ENVELOPE_INFO}|${name}`, 32)
29
+
30
+ /** Fresh 32-byte key-encryption key. Uses @bsv/sdk's Random, which routes to
31
+ * the platform CSPRNG — deliberately NOT services/vault/random.ts, whose
32
+ * expo-crypto path has a Math.random branch under remote debugging. */
33
+ export function generateKek(): number[] {
34
+ return Random(KEK_LEN)
35
+ }
36
+
37
+ /** Short public identifier for a KEK, so a blob can name the key that sealed
38
+ * it without revealing anything about it. */
39
+ export function generateKekId(): string {
40
+ return Utils.toHex(Random(8))
41
+ }
42
+
43
+ export function sealSecret(
44
+ kek: number[],
45
+ kekId: string,
46
+ name: SecretName,
47
+ plaintext: string
48
+ ): EnvelopeBlob {
49
+ const salt = Random(SALT_LEN)
50
+ const dek = deriveDek(kek, salt, name)
51
+ const c = new SymmetricKey(dek).encrypt(Utils.toArray(plaintext, 'utf8')) as number[]
52
+ return { v: 1, kekId, salt: Utils.toHex(salt), c: Utils.toHex(c) }
53
+ }
54
+
55
+ /**
56
+ * Open a blob. Throws EnvelopeError and never lets a bare crypto Error escape:
57
+ * SymmetricKey throws `Error('Decryption failed!')` / `Error('Ciphertext too
58
+ * short')`, which callers must not have to pattern-match on.
59
+ */
60
+ export function openSecret(kek: number[], name: SecretName, blob: unknown): string {
61
+ const b = blob as EnvelopeBlob | null
62
+ if (!b || typeof b !== 'object') {
63
+ throw new EnvelopeError('corrupt', 'envelope: not an object')
64
+ }
65
+ if (b.v !== 1) {
66
+ throw new EnvelopeError('bad-version', `envelope: unsupported version ${String(b.v)}`)
67
+ }
68
+ if (typeof b.salt !== 'string' || typeof b.c !== 'string' || typeof b.kekId !== 'string') {
69
+ throw new EnvelopeError('corrupt', 'envelope: malformed fields')
70
+ }
71
+
72
+ let salt: number[]
73
+ let ct: number[]
74
+ try {
75
+ salt = Utils.toArray(b.salt, 'hex') as number[]
76
+ ct = Utils.toArray(b.c, 'hex') as number[]
77
+ } catch {
78
+ throw new EnvelopeError('corrupt', 'envelope: bad hex')
79
+ }
80
+ if (salt.length !== SALT_LEN || ct.length < MIN_CIPHERTEXT_BYTES) {
81
+ throw new EnvelopeError('corrupt', 'envelope: bad lengths')
82
+ }
83
+
84
+ const dek = deriveDek(kek, salt, name)
85
+ let plain: number[]
86
+ try {
87
+ plain = new SymmetricKey(dek).decrypt(ct) as number[]
88
+ } catch {
89
+ // Indistinguishable by design: wrong KEK, wrong name, or tampered bytes.
90
+ throw new EnvelopeError('corrupt', 'envelope: decryption failed')
91
+ }
92
+ return Utils.toUTF8(plain)
93
+ }
94
+
95
+ /** Assert the blob was sealed by the KEK we hold, before attempting to open it.
96
+ * Separated from openSecret so a stale blob reports `kek-mismatch` rather than
97
+ * the generic `corrupt`. */
98
+ export function assertKekId(blob: EnvelopeBlob, expectedKekId: string): void {
99
+ if (blob.kekId !== expectedKekId) {
100
+ throw new EnvelopeError('kek-mismatch', 'envelope: sealed by a different KEK')
101
+ }
102
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * RFC 5869 HKDF with SHA-256.
3
+ *
4
+ * This lived in `services/vault/sealing.ts` until the vault moved to the R1-K1
5
+ * script template and stopped sealing anything. The function itself was never
6
+ * vault-specific — it is generic key derivation, and `services/secrets` is now
7
+ * its only consumer, so it lives here rather than under a module that no longer
8
+ * exists.
9
+ *
10
+ * Pinned to the RFC's own test vectors in `__tests__/secrets/hkdf.test.ts`.
11
+ */
12
+ import { Hash, Utils } from '@bsv/sdk'
13
+
14
+ const HASH_LEN = 32
15
+
16
+ /** RFC 5869 HKDF with SHA-256. `info` accepts bytes or a UTF-8 string. */
17
+ export function hkdfSha256(
18
+ ikm: number[],
19
+ salt: number[],
20
+ info: number[] | string,
21
+ length: number = 32
22
+ ): number[] {
23
+ if (length > 255 * HASH_LEN) throw new Error('hkdf: length too large')
24
+ const infoBytes: number[] = typeof info === 'string' ? Utils.toArray(info, 'utf8') : info
25
+ // Extract: PRK = HMAC(salt, IKM); zero-length salt means a hash-length zero block
26
+ const prk = Hash.sha256hmac(salt.length > 0 ? salt : Array(HASH_LEN).fill(0), ikm)
27
+ // Expand
28
+ const okm: number[] = []
29
+ let t: number[] = []
30
+ let counter = 1
31
+ while (okm.length < length) {
32
+ t = Hash.sha256hmac(prk, [...t, ...infoBytes, counter])
33
+ okm.push(...t)
34
+ counter++
35
+ }
36
+ return okm.slice(0, length)
37
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Wallet secret storage: OS-enforced at-rest protection for the mnemonic and
3
+ * the recovered key.
4
+ *
5
+ * The contract this directory exists to provide:
6
+ *
7
+ * 1. Exactly one biometric ceremony per process, at wallet instantiation.
8
+ * 2. Between ceremonies the secrets are AES-256-GCM ciphertext whose key the
9
+ * Secure Enclave / Keystore will not release without a biometric match.
10
+ *
11
+ * (2) is the part the previous design lacked. Authentication used to be a
12
+ * JavaScript boolean that the read path consulted and the OS knew nothing
13
+ * about; now the read path *is* the ceremony.
14
+ *
15
+ * peekKek is intentionally not re-exported.
16
+ */
17
+ export type {
18
+ EnvelopeBlob,
19
+ KekPolicy,
20
+ KekSentinel,
21
+ SecretName,
22
+ UnavailableReason,
23
+ UnlockState
24
+ } from './types'
25
+ export { EnvelopeError, SECRET_NAMES } from './types'
26
+
27
+ export { openSecret, sealSecret } from './envelope'
28
+
29
+ export {
30
+ biometricKind,
31
+ hasStrongBiometrics,
32
+ resolveProvisioningPolicy,
33
+ type ResolvedPolicy
34
+ } from './policy'
35
+
36
+ export {
37
+ autoUnlockKek,
38
+ destroyKek,
39
+ getUnlockState,
40
+ isUnlocked,
41
+ lockKek,
42
+ readSentinel,
43
+ subscribeUnlockState,
44
+ unlockKek
45
+ } from './kek'
46
+
47
+ export {
48
+ deleteAllSecrets,
49
+ deleteSecret,
50
+ getSecret,
51
+ hasAnySecret,
52
+ hasSecret,
53
+ putSecret
54
+ } from './store'
55
+
56
+ export {
57
+ hasLegacySecrets,
58
+ migrateLegacySecrets,
59
+ migrationAttemptsExhausted,
60
+ readLegacySecret,
61
+ sweepLegacyKeys,
62
+ type MigrationResult
63
+ } from './migration'