@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,277 @@
1
+ import { Random } from '@bsv/sdk'
2
+ import { CodecError } from './codec'
3
+
4
+ export const SESSION_VERSION = 1
5
+
6
+ /**
7
+ * The capability word `c` in the session QR.
8
+ *
9
+ * LOW BYTE — rungs the payee is LISTENING ON right now. The payer's ladder
10
+ * (transport/select.ts) reads only these bits: a set rung is a promise that a
11
+ * listener for it is live behind this QR.
12
+ */
13
+ export const CAP_AWDL = 0x01
14
+ export const CAP_NEARBY = 0x02
15
+ /** Payee is advertising bsvpay-ble/1 — now advertised by this app, and the profile Blitz adopts. */
16
+ export const CAP_BLE = 0x04
17
+ /**
18
+ * Payee is ALSO scanning for a payer that advertises this session's service
19
+ * UUID (bsvpay-ble/1 reversed role, spec 2026-09-03). Never minted without
20
+ * CAP_BLE: a scanner with no advertiser behind it would strand a payer whose
21
+ * own central role is trusted. Set by iOS payees only — Android as central is
22
+ * the role that fails against iOS.
23
+ */
24
+ export const CAP_BLE_SCAN = 0x08
25
+ // 0x10..0x80 reserved for future rungs (L2CAP, NFC, Wi-Fi Aware).
26
+
27
+ /**
28
+ * HIGH BITS — device hints. Never read for transport selection; they feed one
29
+ * line of copy on the payer's confirm screen (why this pair is on the QR
30
+ * floor) and are available to future rungs.
31
+ *
32
+ * A CLEAR bit means "false OR unknown". Only ONLINE gets a companion KNOWN
33
+ * bit, because reachability is the one probe that can time out inside the
34
+ * minting budget; every other hint is a synchronous, prompt-free read.
35
+ */
36
+ export const HINT_ONLINE = 0x0100 // internet reachable
37
+ export const HINT_ONLINE_KNOWN = 0x0200 // HINT_ONLINE is meaningful (the probe answered within budget)
38
+ export const HINT_NET = 0x0400 // any connectivity
39
+ export const HINT_WIFI = 0x0800 // Android: Wi-Fi radio on. iOS: associated with a Wi-Fi network (no radio API)
40
+ export const HINT_BT = 0x1000 // Bluetooth authorized and powered on
41
+ export const HINT_NFC = 0x2000 // NFC reader available
42
+ /** Selects the rung byte; `~RUNG_MASK` selects the hints. */
43
+ export const RUNG_MASK = 0x00ff
44
+
45
+ export type SessionOs = 'ios' | 'android'
46
+
47
+ /**
48
+ * The asset a token request names. When present on a Session, `amount` is
49
+ * BASE UNITS of this asset, not satoshis, and remains a binding term.
50
+ * label/ticker/decimals are payee-supplied display hints; overlayUrl and
51
+ * overlayIdentityKey are the issuer endpoints a payer needs to mint
52
+ * linkage blobs and (later) submit the transfer — no per-asset discovery
53
+ * protocol exists, so the request carries them.
54
+ */
55
+ export interface SessionAsset {
56
+ id: string
57
+ label?: string
58
+ ticker?: string
59
+ decimals?: number
60
+ overlayUrl: string
61
+ overlayIdentityKey: string
62
+ }
63
+
64
+ export interface Session {
65
+ version: number
66
+ caps: number
67
+ sessionId: Uint8Array
68
+ psk: Uint8Array
69
+ identityKey: string
70
+ /**
71
+ * The satoshis the payee is asking for, or undefined for an OPEN request
72
+ * where the payer chooses.
73
+ *
74
+ * Optional is a money-safety-relevant distinction, not a cosmetic one. When
75
+ * present it is a binding term of the request: the payee's settle path
76
+ * refuses any frame carrying a different figure, which is what stops a payer
77
+ * sending 1 satoshi against a 100,000 request while the payee's screen reads
78
+ * "Received 100,000". When absent there is no figure to bind, so that check
79
+ * cannot run and MUST NOT be faked — the derivation nonces are what prove the
80
+ * frame belongs to this request, and they apply either way.
81
+ */
82
+ amount?: number
83
+ asset?: SessionAsset
84
+ derivationPrefix: string
85
+ derivationSuffix: string
86
+ /**
87
+ * OS of the minting device. METADATA ONLY — copy and diagnostics. Transport
88
+ * selection reads caps, which say what the device can DO; reading this
89
+ * instead would break the moment either platform grows a second transport.
90
+ */
91
+ os?: SessionOs
92
+ }
93
+
94
+ export function mintSession(args: {
95
+ identityKey: string
96
+ /** Omit for an open request — the payer enters the amount. */
97
+ amount?: number
98
+ asset?: SessionAsset
99
+ derivationPrefix: string
100
+ derivationSuffix: string
101
+ supportsAwdl: boolean
102
+ supportsNearby?: boolean
103
+ /** True only while a bsvpay-ble/1 listener is actually advertising for this session. */
104
+ supportsBle?: boolean
105
+ /** True only while a reversed-role scan listener is live for this session. Ignored unless supportsBle. */
106
+ supportsBleScan?: boolean
107
+ /**
108
+ * HINT_* bits from deviceCaps.capsFromProbe. Masked to `~RUNG_MASK` here, so
109
+ * a hint word can never advertise a listener that was not started.
110
+ */
111
+ hints?: number
112
+ os?: SessionOs
113
+ }): Session {
114
+ if (args.identityKey.length !== 66) throw new CodecError('identityKey must be 66 hex chars')
115
+ // Validated at the mint too, not only at decode: an invalid figure minted
116
+ // here would render on the payee's own screen and be echoed to the payer as
117
+ // an authentic request before any decoder ever saw it.
118
+ if (args.amount !== undefined && !isRequestableAmount(args.amount)) {
119
+ throw new CodecError('bad amount')
120
+ }
121
+ if (args.asset !== undefined && args.asset.overlayIdentityKey.length !== 66) {
122
+ throw new CodecError('bad asset overlayIdentityKey')
123
+ }
124
+ return {
125
+ version: SESSION_VERSION,
126
+ caps:
127
+ (args.supportsAwdl ? CAP_AWDL : 0) |
128
+ (args.supportsNearby ? CAP_NEARBY : 0) |
129
+ (args.supportsBle ? CAP_BLE : 0) |
130
+ (args.supportsBle && args.supportsBleScan ? CAP_BLE_SCAN : 0) |
131
+ ((args.hints ?? 0) & ~RUNG_MASK),
132
+ sessionId: new Uint8Array(Random(16)),
133
+ psk: new Uint8Array(Random(32)),
134
+ identityKey: args.identityKey,
135
+ ...(args.amount === undefined ? {} : { amount: args.amount }),
136
+ ...(args.asset === undefined ? {} : { asset: args.asset }),
137
+ derivationPrefix: args.derivationPrefix,
138
+ derivationSuffix: args.derivationSuffix,
139
+ ...(args.os === undefined ? {} : { os: args.os }),
140
+ }
141
+ }
142
+
143
+ /**
144
+ * Satoshis: a whole, positive, exactly-representable count.
145
+ *
146
+ * A bare typeof check admits 0, negatives, NaN and fractions — and a fractional
147
+ * amount renders as a blank figure directly above a live Send button.
148
+ */
149
+ export function isRequestableAmount(a: unknown): a is number {
150
+ return typeof a === 'number' && Number.isSafeInteger(a) && a > 0
151
+ }
152
+
153
+ // Base64url, no padding — QR alphanumeric-safe and dependency-free.
154
+ function toB64url(b: Uint8Array): string {
155
+ let s = ''
156
+ for (const byte of b) s += String.fromCharCode(byte)
157
+ return globalThis.btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
158
+ }
159
+
160
+ function fromB64url(s: unknown): Uint8Array {
161
+ if (typeof s !== 'string') throw new CodecError('expected base64url string')
162
+ const pad = s.replace(/-/g, '+').replace(/_/g, '/')
163
+ const bin = globalThis.atob(pad + '='.repeat((4 - (pad.length % 4)) % 4))
164
+ return Uint8Array.from(bin, c => c.charCodeAt(0))
165
+ }
166
+
167
+ export function encodeSession(s: Session): string {
168
+ // `a` is omitted entirely for an open request rather than written as null.
169
+ // JSON.stringify already drops an undefined value, so this is explicit only
170
+ // to make the wire shape obvious: absent key === payer chooses.
171
+ const body = JSON.stringify({
172
+ v: s.version,
173
+ c: s.caps,
174
+ s: toB64url(s.sessionId),
175
+ k: toB64url(s.psk),
176
+ i: s.identityKey,
177
+ ...(s.os === undefined ? {} : { o: s.os === 'ios' ? 'i' : 'a' }),
178
+ ...(s.amount === undefined ? {} : { a: s.amount }),
179
+ ...(s.asset === undefined ? {} : {
180
+ t: {
181
+ i: s.asset.id,
182
+ ...(s.asset.label === undefined ? {} : { n: s.asset.label }),
183
+ ...(s.asset.ticker === undefined ? {} : { s: s.asset.ticker }),
184
+ ...(s.asset.decimals === undefined ? {} : { d: s.asset.decimals }),
185
+ u: s.asset.overlayUrl,
186
+ k: s.asset.overlayIdentityKey,
187
+ },
188
+ }),
189
+ p: s.derivationPrefix,
190
+ x: s.derivationSuffix,
191
+ })
192
+ return 'bsvpay1:' + toB64url(new TextEncoder().encode(body))
193
+ }
194
+
195
+ export function decodeSession(text: string): Session {
196
+ if (!text.startsWith('bsvpay1:')) throw new CodecError('not a bsvpay session QR')
197
+ let parsed: Record<string, unknown>
198
+ try {
199
+ parsed = JSON.parse(new TextDecoder().decode(fromB64url(text.slice('bsvpay1:'.length))))
200
+ } catch (e) {
201
+ if (e instanceof CodecError) throw e
202
+ throw new CodecError('malformed session payload')
203
+ }
204
+ const { v, c, s, k, i, a, p, x, o, t } = parsed as Record<string, unknown>
205
+ if (v !== SESSION_VERSION) throw new CodecError(`unsupported session version ${String(v)}`)
206
+ if (typeof i !== 'string' || i.length !== 66) throw new CodecError('bad identityKey')
207
+ // An ABSENT `a` is an OPEN request: the payer chooses.
208
+ //
209
+ // Absent means absent. An explicit `null` is refused, not read as open:
210
+ // encodeSession omits the key entirely for an open request, so no peer this
211
+ // codec talks to ever emits null, and accepting it would widen the "payer
212
+ // picks the number" path to a shape nothing legitimately produces. Every
213
+ // other value is a figure the payee is asserting, and a bad one must be
214
+ // refused rather than quietly reinterpreted as "any amount" — that would turn
215
+ // a corrupt 0 into an open request with a live Send button under it.
216
+ const open = a === undefined
217
+ if (!open && !isRequestableAmount(a)) throw new CodecError('bad amount')
218
+ if (typeof s !== 'string') throw new CodecError('bad sessionId encoding')
219
+ if (typeof k !== 'string') throw new CodecError('bad psk encoding')
220
+ if (typeof p !== 'string') throw new CodecError('bad derivationPrefix encoding')
221
+ if (typeof x !== 'string') throw new CodecError('bad derivationSuffix encoding')
222
+ if (c !== undefined && c !== null && typeof c !== 'number') throw new CodecError('bad caps')
223
+ const sessionId = fromB64url(s)
224
+ const psk = fromB64url(k)
225
+ if (sessionId.length !== 16) throw new CodecError('bad sessionId length')
226
+ if (psk.length !== 32) throw new CodecError('bad psk length')
227
+ // Tolerant on purpose: 'o' is advisory, from possibly-newer builds.
228
+ const os: SessionOs | undefined = o === 'i' ? 'ios' : o === 'a' ? 'android' : undefined
229
+ let asset: SessionAsset | undefined
230
+ if (t !== undefined) {
231
+ if (typeof t !== 'object' || t === null) throw new CodecError('bad asset block')
232
+ const { i: ai, n, s: tick, d, u, k: ok } = t as Record<string, unknown>
233
+ if (typeof ai !== 'string' || !/^[0-9a-f]{64}\.\d+$/.test(ai)) throw new CodecError('bad assetId')
234
+ if (typeof u !== 'string' || u.length === 0) throw new CodecError('bad overlayUrl')
235
+ if (typeof ok !== 'string' || ok.length !== 66) throw new CodecError('bad overlayIdentityKey')
236
+ if (n !== undefined && typeof n !== 'string') throw new CodecError('bad asset label')
237
+ if (tick !== undefined && typeof tick !== 'string') throw new CodecError('bad asset ticker')
238
+ if (d !== undefined && (typeof d !== 'number' || !Number.isSafeInteger(d) || d < 0)) throw new CodecError('bad asset decimals')
239
+ asset = {
240
+ id: ai, overlayUrl: u, overlayIdentityKey: ok,
241
+ ...(n === undefined ? {} : { label: n }),
242
+ ...(tick === undefined ? {} : { ticker: tick }),
243
+ ...(d === undefined ? {} : { decimals: d }),
244
+ }
245
+ }
246
+ return {
247
+ version: v as number,
248
+ caps: (typeof c === 'number' ? c : 0),
249
+ sessionId,
250
+ psk,
251
+ identityKey: i,
252
+ ...(open ? {} : { amount: a }),
253
+ ...(asset === undefined ? {} : { asset }),
254
+ derivationPrefix: p,
255
+ derivationSuffix: x,
256
+ ...(os === undefined ? {} : { os }),
257
+ }
258
+ }
259
+
260
+ // RFC 4648 base32, lowercase, no padding. 16 bytes → 26 chars.
261
+ const B32 = 'abcdefghijklmnopqrstuvwxyz234567'
262
+
263
+ export function instanceName(sessionId: Uint8Array): string {
264
+ let bits = 0
265
+ let value = 0
266
+ let out = ''
267
+ for (const byte of sessionId) {
268
+ value = (value << 8) | byte
269
+ bits += 8
270
+ while (bits >= 5) {
271
+ out += B32[(value >>> (bits - 5)) & 31]
272
+ bits -= 5
273
+ }
274
+ }
275
+ if (bits > 0) out += B32[(value << (5 - bits)) & 31]
276
+ return `bsvpay-${out}`
277
+ }
@@ -0,0 +1,5 @@
1
+ export type NearbyPhase = 'receive_wait' | 'failed'
2
+
3
+ export function nextPhaseAfterUnsealFailure(): NearbyPhase {
4
+ return 'receive_wait'
5
+ }
@@ -0,0 +1,11 @@
1
+ import { getLocalPayTransport } from 'react-native-localpay-transport'
2
+ import { makeSocketTransport } from './socket'
3
+
4
+ /**
5
+ * Connect-phase budget before the payer gives up and falls back to the QR.
6
+ * AWDL's Bonjour discovery over an already-established Wi-Fi link resolves
7
+ * (or doesn't) inside ~4s; a longer wait only delays the fountain.
8
+ */
9
+ export const AWDL_CONNECT_TIMEOUT_MS = 4_000
10
+
11
+ export const awdlTransport = makeSocketTransport('awdl', getLocalPayTransport, AWDL_CONNECT_TIMEOUT_MS)
@@ -0,0 +1,159 @@
1
+ import { Platform } from 'react-native'
2
+ import { getLocalPayBleTransport, type LocalPayBleTransport } from 'react-native-localpay-transport'
3
+ import { unsealFrame, sealFrame, type PaymentFrame } from '../codec'
4
+ import { instanceName, type Session } from '../session'
5
+ import type { Ack, LocalPaymentTransport, ReceivedFrame } from '../types'
6
+ import { bleRole } from './select'
7
+ import { SEND_TIMEOUT_MS, declineQuietly, fromBase64, makeConfirm, parseAck, toBase64 } from './socket'
8
+
9
+ /**
10
+ * Connect-phase budget before the payer gives up and falls back to the QR:
11
+ * scan for the session's service UUID + connect + MTU negotiation (≤ 2 s on
12
+ * Android) + service discovery + ACK subscription. The native central rejects
13
+ * "connect timeout: no route to peer" if that has not completed inside this
14
+ * budget — the string NearbyFlow already treats as radios-off / peer-gone —
15
+ * so the payer drops to the fountain instead of waiting out the whole-send
16
+ * budget (SEND_TIMEOUT_MS in socket.ts).
17
+ *
18
+ * 6 s was too tight against a real device: a captured Android(central)↔iOS
19
+ * (peripheral) failure showed the LE link physically connect, then iOS's
20
+ * radio hit a PHY-update collision (HCI status 0x2A "Instant Passed") that
21
+ * held up service discovery past the old budget — Android's own MTU request
22
+ * got no answer within 2 s either. Widened to give a slow link-layer
23
+ * renegotiation room to finish before conceding to the fountain.
24
+ */
25
+ export const BLE_CONNECT_TIMEOUT_MS = 15_000
26
+
27
+ /**
28
+ * The BLE rung. Unlike the AWDL/Nearby wrapper this one knows two roles (spec
29
+ * 2026-09-03): the payee listens on BOTH the advertised link (startListening)
30
+ * and, on iOS, the scan link (startScanning); the payer advertises instead of
31
+ * connecting when bleRole() says so. Frame decoding, the single-shot confirm
32
+ * handle and the never-stop-on-success discipline are socket.ts's, reused.
33
+ */
34
+ export function makeBleTransport(
35
+ native: () => LocalPayBleTransport | null,
36
+ connectTimeoutMs: number
37
+ ): LocalPaymentTransport {
38
+ return {
39
+ kind: 'ble',
40
+
41
+ receive(session: Session, signal: AbortSignal): Promise<ReceivedFrame> {
42
+ const backend = native()
43
+ if (!backend) return Promise.reject(new Error('ble transport unavailable'))
44
+ if (signal.aborted) return Promise.reject(new Error('cancelled'))
45
+ const name = instanceName(session.sessionId)
46
+ const psk = toBase64(session.psk)
47
+
48
+ return new Promise<ReceivedFrame>((resolve, reject) => {
49
+ let settled = false
50
+ // Same contract as socket.ts: teardown is FALSE on the success path,
51
+ // because the native side already cancelled the loser and is holding
52
+ // the winner's link open for confirmFrame().
53
+ const finish = (teardown: boolean, fn: () => void) => {
54
+ if (settled) return
55
+ settled = true
56
+ signal.removeEventListener('abort', onAbort)
57
+ if (teardown) void backend.stopListening().catch(() => {})
58
+ fn()
59
+ }
60
+ const onAbort = () => finish(true, () => reject(new Error('cancelled')))
61
+ signal.addEventListener('abort', onAbort)
62
+
63
+ // One frame handler for both links: the native latch guarantees only
64
+ // one of them ever fires it.
65
+ const onFrame = (frameBase64: string) => {
66
+ let frame: PaymentFrame
67
+ try {
68
+ frame = unsealFrame(fromBase64(frameBase64), session.psk)
69
+ } catch (e) {
70
+ declineQuietly(backend, 'decode_failed')
71
+ return finish(false, () => reject(e))
72
+ }
73
+ finish(false, () => resolve({ frame, confirm: makeConfirm(backend) }))
74
+ }
75
+ const onError = (message: string) => finish(true, () => reject(new Error(message)))
76
+
77
+ backend
78
+ .startListening(name, psk, onFrame, onError)
79
+ .then(() => {
80
+ // Reversed role: only where this device's central is trusted
81
+ // against a peer that advertises. A scan that cannot start leaves
82
+ // the advertised listener serving iOS payers, so it is logged, not
83
+ // terminal. Started AFTER startListening resolves: the native
84
+ // self-reset inside startListening would otherwise tear it down.
85
+ if (Platform.OS !== 'ios' || settled) return
86
+ return backend.startScanning(name, psk, onFrame, onError).catch((e: unknown) => {
87
+ if (settled) return
88
+ console.warn('[localpay] ble scan unavailable:', e instanceof Error ? e.message : String(e))
89
+ })
90
+ })
91
+ .catch(e => finish(true, () => reject(e)))
92
+ })
93
+ },
94
+
95
+ send(session: Session, frame: PaymentFrame, signal: AbortSignal): Promise<Ack> {
96
+ const backend = native()
97
+ if (!backend) return Promise.reject(new Error('ble transport unavailable'))
98
+ if (signal.aborted) return Promise.reject(new Error('cancelled'))
99
+
100
+ return new Promise<Ack>((resolve, reject) => {
101
+ let settled = false
102
+ const cleanup = () => signal.removeEventListener('abort', onAbort)
103
+ const onAbort = () => {
104
+ if (settled) return
105
+ settled = true
106
+ cleanup()
107
+ reject(new Error('cancelled'))
108
+ }
109
+ signal.addEventListener('abort', onAbort)
110
+ // sealFrame can throw (e.g. an oversize frame); computed inside the
111
+ // executor so that throw becomes a rejection of this Promise<Ack>
112
+ // rather than a synchronous throw out of send() (matches socket.ts).
113
+ let args: readonly [string, string, string, number, number]
114
+ try {
115
+ args = [
116
+ instanceName(session.sessionId),
117
+ toBase64(session.psk),
118
+ toBase64(sealFrame(frame, session.psk)),
119
+ SEND_TIMEOUT_MS,
120
+ connectTimeoutMs,
121
+ ] as const
122
+ } catch (e) {
123
+ settled = true
124
+ cleanup()
125
+ reject(e)
126
+ return
127
+ }
128
+ const pending =
129
+ bleRole(session) === 'peripheral' ? backend.sendFrameAdvertising(...args) : backend.sendFrame(...args)
130
+ pending.then(
131
+ ackBase64 => {
132
+ if (settled) return
133
+ settled = true
134
+ cleanup()
135
+ try {
136
+ resolve(parseAck(ackBase64))
137
+ } catch (e) {
138
+ reject(e)
139
+ }
140
+ },
141
+ e => {
142
+ if (settled) return
143
+ settled = true
144
+ cleanup()
145
+ reject(e)
146
+ }
147
+ )
148
+ })
149
+ },
150
+ }
151
+ }
152
+
153
+ /**
154
+ * A separate HybridObject from the AWDL/Nearby one. That is load-bearing for
155
+ * the payee's multi-listener: aborting this rung runs ITS native
156
+ * stopListening(), which can never touch the other radio's held ack
157
+ * connection.
158
+ */
159
+ export const bleTransport = makeBleTransport(getLocalPayBleTransport, BLE_CONNECT_TIMEOUT_MS)
@@ -0,0 +1,12 @@
1
+ import { getLocalPayTransport } from 'react-native-localpay-transport'
2
+ import { makeSocketTransport } from './socket'
3
+
4
+ /**
5
+ * Connect-phase budget before the payer gives up and falls back to the QR.
6
+ * Nearby has to do BLE discovery and then a Wi-Fi/hotspot upgrade before a
7
+ * connection even exists — AWDL's 4s would false-positive "no route to peer"
8
+ * on a link that just needed more time to come up.
9
+ */
10
+ export const NEARBY_CONNECT_TIMEOUT_MS = 10_000
11
+
12
+ export const nearbyTransport = makeSocketTransport('nearby', getLocalPayTransport, NEARBY_CONNECT_TIMEOUT_MS)
@@ -0,0 +1,110 @@
1
+ import type { Session } from '../session'
2
+ import type { LocalPaymentTransport, ReceivedFrame } from '../types'
3
+
4
+ export type RadioKind = 'awdl' | 'nearby' | 'ble'
5
+
6
+ /** The frame that won, and which radio carried it — `savePending` records the kind. */
7
+ export interface RaceWinner extends ReceivedFrame {
8
+ kind: RadioKind
9
+ }
10
+
11
+ /**
12
+ * Listen on every radio at once; the first delivered frame wins.
13
+ *
14
+ * Pure over the LocalPaymentTransport interface so the arbitration is testable
15
+ * without a screen. One AbortController per transport; on the first
16
+ * resolution the losers are aborted BEFORE the winner is handed back, so each
17
+ * loser's own native stopListening() runs while the winner's held ack
18
+ * connection — a different HybridObject on a different radio — is untouched
19
+ * (spec §6).
20
+ *
21
+ * A rejection is non-terminal: it is reported through `onError` (so the screen
22
+ * can show "Bluetooth is unavailable" while Wi-Fi keeps listening) and only
23
+ * when EVERY radio has failed does the promise reject, with the last error.
24
+ * Rejections that follow an abort — the losers' 'cancelled', or everything
25
+ * after the outer signal fires — are consequences, not failures, and are not
26
+ * reported.
27
+ *
28
+ * `qr` transports are skipped: the QR rung is driven by the UI, not by
29
+ * receive() (core/localpay/qr.ts).
30
+ */
31
+ export function raceReceivers(
32
+ transports: readonly LocalPaymentTransport[],
33
+ session: Session,
34
+ signal: AbortSignal,
35
+ onError: (kind: RadioKind, error: unknown) => void
36
+ ): Promise<RaceWinner> {
37
+ const radios = transports.filter(t => t.kind !== 'qr')
38
+ if (radios.length === 0) return Promise.reject(new Error('no radio transports to listen on'))
39
+ if (signal.aborted) return Promise.reject(new Error('cancelled'))
40
+
41
+ return new Promise<RaceWinner>((resolve, reject) => {
42
+ let settled = false
43
+ let failures = 0
44
+ let lastError: unknown = new Error('every radio listener failed')
45
+ const controllers = radios.map(() => new AbortController())
46
+
47
+ const abortAll = (except?: AbortController) => {
48
+ for (const c of controllers) if (c !== except && !c.signal.aborted) c.abort()
49
+ }
50
+ const finish = (fn: () => void) => {
51
+ if (settled) return
52
+ settled = true
53
+ signal.removeEventListener('abort', onAbort)
54
+ fn()
55
+ }
56
+ const onAbort = () =>
57
+ finish(() => {
58
+ abortAll()
59
+ reject(new Error('cancelled'))
60
+ })
61
+ signal.addEventListener('abort', onAbort)
62
+
63
+ // One radio going down, however it goes down. Shared by the rejection path
64
+ // and by the synchronous-throw path below so the two are indistinguishable.
65
+ const failed = (kind: RadioKind, controller: AbortController, error: unknown) => {
66
+ if (settled || controller.signal.aborted) return
67
+ failures += 1
68
+ lastError = error
69
+ onError(kind, error)
70
+ if (failures === radios.length) finish(() => reject(lastError))
71
+ }
72
+
73
+ radios.forEach((transport, i) => {
74
+ const controller = controllers[i]
75
+ const kind = transport.kind as RadioKind
76
+
77
+ // receive() may THROW rather than reject — a missing native accessor does
78
+ // exactly that. Unguarded, the throw escapes this executor, rejects the
79
+ // whole race, and leaves the siblings listening with nobody waiting on
80
+ // them: the payee would sit on a dead screen while a working radio held
81
+ // an open listener. Treated as that one radio failing instead, so the
82
+ // others keep the request live.
83
+ let listening: Promise<ReceivedFrame>
84
+ try {
85
+ listening = transport.receive(session, controller.signal)
86
+ } catch (e) {
87
+ failed(kind, controller, e)
88
+ return
89
+ }
90
+
91
+ listening.then(
92
+ received => {
93
+ if (settled) {
94
+ // The race was already decided (or aborted) when this frame landed.
95
+ // Nothing will ever be written for it, so it is a provable decline —
96
+ // the payer must release its inputs rather than rest on a green
97
+ // "Sent" until its own timeout.
98
+ void received.confirm(false, 'save_failed')
99
+ return
100
+ }
101
+ finish(() => {
102
+ abortAll(controller)
103
+ resolve({ kind, frame: received.frame, confirm: received.confirm })
104
+ })
105
+ },
106
+ error => failed(kind, controller, error)
107
+ )
108
+ })
109
+ })
110
+ }