@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,338 @@
1
+ import { SymmetricKey } from '@bsv/sdk'
2
+
3
+ export const FRAME_VERSION = 3
4
+
5
+ export class CodecError extends Error {
6
+ constructor(message: string) {
7
+ super(message)
8
+ this.name = 'CodecError'
9
+ }
10
+ }
11
+
12
+ export type FrameKind = 'bsv' | 'token'
13
+
14
+ export interface TokenPayment {
15
+ assetId: string // "<64-hex txid>.<vout>"
16
+ overlayUrl: string
17
+ overlayIdentityKey: string // 66-hex compressed pubkey
18
+ certificates: Uint8Array[] // opaque serialized VerifiableCertificates
19
+ linkage: Array<{ txid: string; payload: Uint8Array }> // per-txid MandalaLinkagePayload bytes, whole chain
20
+ recipientLinkage: Uint8Array // JSON SpecificLinkage bytes, verifier = payee
21
+ }
22
+
23
+ export interface PaymentFrame {
24
+ version: number
25
+ kind: FrameKind
26
+ /** 66-char hex, compressed pubkey */
27
+ senderIdentityKey: string
28
+ /**
29
+ * Which output of `transaction` pays the payee.
30
+ *
31
+ * There is deliberately no `amount` beside it. `internalizeAction` credits
32
+ * the output, so a satoshi count on the frame could only ever agree with the
33
+ * transaction or lie about it — and `verifyFramePayment` has to parse the
34
+ * transaction anyway, to prove the output is one the payee can spend. That
35
+ * proof is what makes the figure it reads back worth showing as a receipt.
36
+ */
37
+ outputIndex: number
38
+ derivationPrefix: string
39
+ derivationSuffix: string
40
+ /**
41
+ * Present iff kind === 'token'. Carried opaquely: the codec validates
42
+ * shapes and lengths, never parses linkage payloads or certificates.
43
+ * `linkage` maps EVERY unbroadcast token transaction in `transaction`'s
44
+ * ancestry to the exact offChainValues bytes its issuer overlay consumes —
45
+ * forwarded verbatim on chained re-spends so whoever reconnects first can
46
+ * submit the whole chain.
47
+ */
48
+ token?: TokenPayment
49
+ /**
50
+ * AtomicBEEF, on both transports. The design originally specified a bare
51
+ * rawtx on the QR path to shrink the symbol, but ancestry is what lets the
52
+ * payee internalize offline, and the fountain removed the symbol ceiling —
53
+ * so one encoding serves both.
54
+ */
55
+ transaction: Uint8Array
56
+ }
57
+
58
+ // ── varint (LEB128, unsigned) ──
59
+
60
+ function putVarint(out: number[], n: number): void {
61
+ if (!Number.isSafeInteger(n) || n < 0) throw new CodecError(`varint out of range: ${n}`)
62
+ let v = n
63
+ while (v >= 0x80) {
64
+ out.push((v & 0x7f) | 0x80)
65
+ v = Math.floor(v / 128)
66
+ }
67
+ out.push(v)
68
+ }
69
+
70
+ function getVarint(b: Uint8Array, pos: { i: number }): number {
71
+ let result = 0
72
+ let shift = 1
73
+ for (;;) {
74
+ if (pos.i >= b.length) throw new CodecError('truncated varint')
75
+ const byte = b[pos.i++]
76
+ result += (byte & 0x7f) * shift
77
+ if ((byte & 0x80) === 0) break
78
+ shift *= 128
79
+ if (shift > 2 ** 53) throw new CodecError('varint too large')
80
+ }
81
+ return result
82
+ }
83
+
84
+ function putBytes(out: number[], bytes: Uint8Array): void {
85
+ putVarint(out, bytes.length)
86
+ for (const byte of bytes) out.push(byte)
87
+ }
88
+
89
+ function getBytes(b: Uint8Array, pos: { i: number }): Uint8Array {
90
+ const len = getVarint(b, pos)
91
+ if (pos.i + len > b.length) throw new CodecError('truncated byte field')
92
+ const slice = b.slice(pos.i, pos.i + len)
93
+ pos.i += len
94
+ return slice
95
+ }
96
+
97
+ const enc = new TextEncoder()
98
+ const dec = new TextDecoder()
99
+
100
+ function putStr(out: number[], s: string): void {
101
+ putBytes(out, enc.encode(s))
102
+ }
103
+
104
+ function getStr(b: Uint8Array, pos: { i: number }): string {
105
+ return dec.decode(getBytes(b, pos))
106
+ }
107
+
108
+ function hexToBytes(hex: string): Uint8Array {
109
+ if (hex.length % 2 !== 0) throw new CodecError('odd-length hex')
110
+ const out = new Uint8Array(hex.length / 2)
111
+ for (let i = 0; i < out.length; i++) {
112
+ const byte = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16)
113
+ if (Number.isNaN(byte)) throw new CodecError('invalid hex')
114
+ out[i] = byte
115
+ }
116
+ return out
117
+ }
118
+
119
+ function bytesToHex(b: Uint8Array): string {
120
+ return Array.from(b, x => x.toString(16).padStart(2, '0')).join('')
121
+ }
122
+
123
+ // ── frame ──
124
+
125
+ const KIND_BYTE: Record<FrameKind, number> = { bsv: 0x01, token: 0x02 }
126
+
127
+ export function encodeFrame(f: PaymentFrame): Uint8Array {
128
+ if (f.senderIdentityKey.length !== 66) {
129
+ throw new CodecError(`senderIdentityKey must be 66 hex chars, got ${f.senderIdentityKey.length}`)
130
+ }
131
+ if ((f.kind === 'token') !== (f.token !== undefined)) {
132
+ throw new CodecError(`kind ${f.kind} and token block presence disagree`)
133
+ }
134
+ const out: number[] = [f.version & 0xff, KIND_BYTE[f.kind] ?? 0]
135
+ if (out[1] === 0) throw new CodecError(`unsupported frame kind ${String(f.kind)}`)
136
+ for (const byte of hexToBytes(f.senderIdentityKey.toLowerCase())) out.push(byte)
137
+ putVarint(out, f.outputIndex)
138
+ putStr(out, f.derivationPrefix)
139
+ putStr(out, f.derivationSuffix)
140
+ if (f.token) {
141
+ const t = f.token
142
+ if (t.overlayIdentityKey.length !== 66) {
143
+ throw new CodecError(`overlayIdentityKey must be 66 hex chars, got ${t.overlayIdentityKey.length}`)
144
+ }
145
+ putStr(out, t.assetId)
146
+ putStr(out, t.overlayUrl)
147
+ for (const byte of hexToBytes(t.overlayIdentityKey.toLowerCase())) out.push(byte)
148
+ putVarint(out, t.certificates.length)
149
+ for (const cert of t.certificates) putBytes(out, cert)
150
+ putVarint(out, t.linkage.length)
151
+ for (const entry of t.linkage) {
152
+ if (entry.txid.length !== 64) throw new CodecError(`linkage txid must be 64 hex chars, got ${entry.txid.length}`)
153
+ for (const byte of hexToBytes(entry.txid.toLowerCase())) out.push(byte)
154
+ putBytes(out, entry.payload)
155
+ }
156
+ putBytes(out, t.recipientLinkage)
157
+ }
158
+ putBytes(out, f.transaction)
159
+ return new Uint8Array(out)
160
+ }
161
+
162
+ export function decodeFrame(b: Uint8Array): PaymentFrame {
163
+ if (b.length < 35) throw new CodecError('frame too short')
164
+ const version = b[0]
165
+ if (version !== FRAME_VERSION) throw new CodecError(`unsupported frame version ${version}`)
166
+ const kindByte = b[1]
167
+ const kind: FrameKind | undefined = kindByte === 0x01 ? 'bsv' : kindByte === 0x02 ? 'token' : undefined
168
+ if (kind === undefined) throw new CodecError(`unsupported frame kind ${kindByte}`)
169
+ const pos = { i: 2 }
170
+ const senderIdentityKey = bytesToHex(b.slice(pos.i, pos.i + 33))
171
+ pos.i += 33
172
+ const outputIndex = getVarint(b, pos)
173
+ const derivationPrefix = getStr(b, pos)
174
+ const derivationSuffix = getStr(b, pos)
175
+ let token: TokenPayment | undefined
176
+ if (kind === 'token') {
177
+ const assetId = getStr(b, pos)
178
+ const overlayUrl = getStr(b, pos)
179
+ if (pos.i + 33 > b.length) throw new CodecError('truncated overlayIdentityKey')
180
+ const overlayIdentityKey = bytesToHex(b.slice(pos.i, pos.i + 33))
181
+ pos.i += 33
182
+ const certificates: Uint8Array[] = []
183
+ const certCount = getVarint(b, pos)
184
+ for (let c = 0; c < certCount; c++) certificates.push(getBytes(b, pos))
185
+ const linkage: Array<{ txid: string; payload: Uint8Array }> = []
186
+ const linkCount = getVarint(b, pos)
187
+ for (let l = 0; l < linkCount; l++) {
188
+ if (pos.i + 32 > b.length) throw new CodecError('truncated linkage txid')
189
+ const txid = bytesToHex(b.slice(pos.i, pos.i + 32))
190
+ pos.i += 32
191
+ linkage.push({ txid, payload: getBytes(b, pos) })
192
+ }
193
+ const recipientLinkage = getBytes(b, pos)
194
+ token = { assetId, overlayUrl, overlayIdentityKey, certificates, linkage, recipientLinkage }
195
+ }
196
+ const transaction = getBytes(b, pos)
197
+ if (pos.i !== b.length) throw new CodecError('trailing bytes after frame')
198
+ return {
199
+ version, kind, senderIdentityKey, outputIndex, derivationPrefix, derivationSuffix,
200
+ ...(token === undefined ? {} : { token }),
201
+ transaction,
202
+ }
203
+ }
204
+
205
+ // ── Sealed envelope ──
206
+ //
207
+ // Every frame that leaves the device is sealed with the session PSK — radios
208
+ // and QR alike. On the radios this is redundant with TLS-PSK/Nearby link
209
+ // encryption and costs 49 bytes; the point is ONE wire shape, so the QR rung
210
+ // (line-of-sight readable) can never be the unsealed exception. AES-256-GCM
211
+ // via @bsv/sdk SymmetricKey: |32B IV|ciphertext|16B tag|, behind one version
212
+ // byte so an old decoder reads `1`, says `unsupported frame version 1`, and
213
+ // refuses cleanly.
214
+ //
215
+ // Only line of sight is closed: whoever photographed the PAIRING QR holds
216
+ // this PSK. That threat was noted-not-mitigated in the 07-27 design and is
217
+ // unchanged here.
218
+
219
+ export const SEAL_VERSION = 1
220
+
221
+ function pskKey(psk: Uint8Array): SymmetricKey {
222
+ if (psk.length !== 32) throw new CodecError(`psk must be 32 bytes, got ${psk.length}`)
223
+ return new SymmetricKey(Array.from(psk))
224
+ }
225
+
226
+ export function sealFrame(f: PaymentFrame, psk: Uint8Array): Uint8Array {
227
+ const ct = pskKey(psk).encrypt(Array.from(encodeFrame(f))) as number[]
228
+ return new Uint8Array([SEAL_VERSION, ...ct])
229
+ }
230
+
231
+ export function unsealFrame(b: Uint8Array, psk: Uint8Array): PaymentFrame {
232
+ if (b.length < 1 + 32 + 16) throw new CodecError('sealed frame too short')
233
+ if (b[0] !== SEAL_VERSION) throw new CodecError(`unsupported seal version ${b[0]}`)
234
+ let plain: number[]
235
+ try {
236
+ plain = pskKey(psk).decrypt(Array.from(b.slice(1))) as number[]
237
+ } catch {
238
+ // GCM tag mismatch (wrong PSK or tampering) throws a platform error;
239
+ // callers of this codec catch exactly one failure type.
240
+ throw new CodecError('sealed frame failed authentication')
241
+ }
242
+ return decodeFrame(new Uint8Array(plain))
243
+ }
244
+
245
+ // ── Frame envelope ──
246
+ //
247
+ // `bsvpayf1:` is NOT a QR wire format. Every payment code this app renders is a
248
+ // stream of `@bsv/air-gap` parts sized to FRAME_BLOCK_BYTES, and the scanner
249
+ // accepts nothing else — a second accepted shape is exactly what lets two
250
+ // implementations drift apart.
251
+ //
252
+ // What the envelope is for is storage: the payer persists one in
253
+ // `offline_actions.framePayload` so a delivered-but-unbroadcast payment can be
254
+ // re-shown later, and the renderer reads the bytes back out of it. base64url so
255
+ // the stored value is plain single-byte ASCII, behind a prefix that
256
+ // distinguishes it from a session QR (`bsvpay1:`). The envelope's payload is a
257
+ // SEALED frame: re-showing a stored payment yields ciphertext only the live
258
+ // session's PSK opens.
259
+
260
+ export const FRAME_QR_PREFIX = 'bsvpayf1:'
261
+
262
+ /**
263
+ * Source-block size for the animated payment code, in bytes.
264
+ *
265
+ * There is no single-symbol path to fall back to, so this one number decides
266
+ * symbol density for every payment. `estimatePartCharLength(1024)` is 1,404
267
+ * characters, and a part is single-byte ASCII throughout, so it occupies 1,404
268
+ * bytes of a byte-mode QR: inside the 2,331-byte capacity of a version-40
269
+ * symbol at error-correction level M, with ~40% headroom for a scanner that is
270
+ * not looking at the screen straight on. `react-native-qrcode-svg` rethrows out
271
+ * of render past capacity and takes the app down through the error boundary, so
272
+ * that headroom is not cosmetic.
273
+ *
274
+ * A frame this size or smaller is a single source block — one part carries the
275
+ * whole message — so the renderer holds `seq` at 0 and runs no timer, and an
276
+ * ordinary payment is a still QR. (Part strings are NOT equal across `seq`:
277
+ * `seq` sits in the part header. What makes it still is holding it, not the
278
+ * block count on its own.)
279
+ *
280
+ * `PaymentFrame.transaction` is AtomicBEEF — every input's source transaction
281
+ * plus its BUMP — so frame size tracks input count, not output count. The only
282
+ * remaining ceiling is air-gap's own MAX_MESSAGE_BYTES, which the send path
283
+ * checks before it builds an encoder.
284
+ */
285
+ export const FRAME_BLOCK_BYTES = 1024
286
+
287
+ function toB64url(bytes: Uint8Array): string {
288
+ let binary = ''
289
+ for (const byte of bytes) binary += String.fromCharCode(byte)
290
+ return globalThis.btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
291
+ }
292
+
293
+ function fromB64url(text: string): Uint8Array {
294
+ const padded = text.replace(/-/g, '+').replace(/_/g, '/')
295
+ let binary: string
296
+ try {
297
+ binary = globalThis.atob(padded + '='.repeat((4 - (padded.length % 4)) % 4))
298
+ } catch {
299
+ // atob throws a platform error, not a CodecError. Normalise it so callers
300
+ // see one failure type — they must still catch broadly, since a hostile QR
301
+ // can reach code paths this wrapper does not cover.
302
+ throw new CodecError('malformed base64url payload')
303
+ }
304
+ return Uint8Array.from(binary, c => c.charCodeAt(0))
305
+ }
306
+
307
+ /** Wraps a SEALED frame for storage and later re-display. Rendered as air-gap parts, never as one symbol. */
308
+ export function frameToQr(f: PaymentFrame, psk: Uint8Array): string {
309
+ return FRAME_QR_PREFIX + toB64url(sealFrame(f, psk))
310
+ }
311
+
312
+ /**
313
+ * Same envelope as `frameToQr`, but takes bytes already run through
314
+ * `sealFrame`. Callers that must know the sealed length before they can
315
+ * render it (the QR-size sanity check) would otherwise call `sealFrame`
316
+ * once to measure and `frameToQr` again to render — sealing the same frame
317
+ * twice. Seal once, size-check the bytes, then wrap the same bytes here.
318
+ */
319
+ export function sealedToQr(sealed: Uint8Array): string {
320
+ return FRAME_QR_PREFIX + toB64url(sealed)
321
+ }
322
+
323
+ /**
324
+ * The raw frame bytes behind a bsvpayf1: envelope.
325
+ *
326
+ * The encoder re-encodes exactly these bytes, and the re-show path reads them
327
+ * from a persisted framePayload — a column, so a row can be truncated, foreign
328
+ * or null. Every failure is a CodecError, including a non-string, because the
329
+ * screens that call this catch one type and must not be crashed by a bad row.
330
+ *
331
+ * Deliberately does not decode the frame: nothing reads a stored envelope back
332
+ * as a `PaymentFrame`, and a decoder for it would be a second accepted format.
333
+ */
334
+ export function frameBytesFromQr(text: string): Uint8Array {
335
+ if (typeof text !== 'string') throw new CodecError('expected a frame envelope string')
336
+ if (!text.startsWith(FRAME_QR_PREFIX)) throw new CodecError('not a nearby-payment frame envelope')
337
+ return fromB64url(text.slice(FRAME_QR_PREFIX.length))
338
+ }
@@ -0,0 +1,175 @@
1
+ /**
2
+ * What THIS device can do right now, as the hint bits the payee's session QR
3
+ * carries above the rung byte (session.ts HINT_*). The payer's ladder never
4
+ * reads these; they drive one line of copy on the payer's confirm screen
5
+ * (describeFloor) and are available to future rungs.
6
+ *
7
+ * A clear bit means "false OR unknown". Only the one asynchronous probe —
8
+ * internet reachability — gets a companion KNOWN bit, because it is the one
9
+ * that routinely cannot answer inside a minting budget.
10
+ *
11
+ * This file deliberately does NOT use getOnline() from core/net/online.ts.
12
+ * That helper collapses a `null` (not yet probed) NetInfo answer to "online",
13
+ * which is right for the home-screen banner — a wrong "offline" there hides
14
+ * the online rails from someone with signal — and wrong for a flag another
15
+ * device will act on. Here `null` must stay `null` so the QR says "unknown"
16
+ * (HINT_ONLINE_KNOWN clear) rather than asserting a reachability nobody
17
+ * established.
18
+ */
19
+ import { Platform } from 'react-native'
20
+ import NetInfo, { type NetInfoState } from '@react-native-community/netinfo'
21
+ import { getLocalPayBleTransport } from 'react-native-localpay-transport'
22
+ import {
23
+ HINT_BT,
24
+ HINT_NET,
25
+ HINT_NFC,
26
+ HINT_ONLINE,
27
+ HINT_ONLINE_KNOWN,
28
+ HINT_WIFI,
29
+ RUNG_MASK,
30
+ } from './session'
31
+
32
+ /** Mirrors LocalPayBleTransport.bluetoothState(); anything else coerces to 'unknown'. */
33
+ export type BluetoothState = 'poweredOn' | 'poweredOff' | 'unauthorized' | 'unsupported' | 'unknown'
34
+
35
+ export interface DeviceProbe {
36
+ /** NetInfo isInternetReachable; null when unknown, including "did not answer in budget". */
37
+ online: boolean | null
38
+ /** NetInfo isConnected; null when unknown. */
39
+ connected: boolean | null
40
+ /**
41
+ * Android: the Wi-Fi radio is on (isWifiEnabled). iOS has no radio-power
42
+ * API, so this is "associated with a Wi-Fi network" (type === 'wifi').
43
+ */
44
+ wifi: boolean
45
+ bluetooth: BluetoothState
46
+ /** NFC reader hardware available. Advisory only — NFC is not a transport. */
47
+ nfc: boolean
48
+ }
49
+
50
+ /** How long minting waits for NetInfo before writing "unknown" into the QR. */
51
+ export const DEFAULT_NET_BUDGET_MS = 800
52
+
53
+ /** How long minting waits for the BLE managers to settle (LocalPayBleTransport.prepare). */
54
+ export const BLE_PREPARE_TIMEOUT_MS = 1500
55
+
56
+ const BLUETOOTH_STATES: readonly BluetoothState[] = [
57
+ 'poweredOn',
58
+ 'poweredOff',
59
+ 'unauthorized',
60
+ 'unsupported',
61
+ 'unknown',
62
+ ]
63
+
64
+ /**
65
+ * Native reports Bluetooth as a plain string over Nitro. Anything outside the
66
+ * five documented values — a future CoreBluetooth case, a bridge hiccup —
67
+ * becomes 'unknown', which every caller already treats as "do not advertise".
68
+ * Shared by readBluetoothState() below and prepareBle() (added in Task 10).
69
+ */
70
+ function asBluetoothState(raw: unknown): BluetoothState {
71
+ return typeof raw === 'string' && (BLUETOOTH_STATES as readonly string[]).includes(raw)
72
+ ? (raw as BluetoothState)
73
+ : 'unknown'
74
+ }
75
+
76
+ /**
77
+ * Pure. Hint bits only: the rung byte belongs to mintSession, which ORs the
78
+ * rungs it is actually listening on with `hints & ~RUNG_MASK`. Masking here
79
+ * too keeps the invariant local, so a future hint constant that strays into
80
+ * the low byte cannot make a payer believe a radio is listening.
81
+ */
82
+ export function capsFromProbe(p: DeviceProbe): number {
83
+ let caps = 0
84
+ if (p.online === true) caps |= HINT_ONLINE
85
+ if (p.online !== null) caps |= HINT_ONLINE_KNOWN
86
+ if (p.connected === true) caps |= HINT_NET
87
+ if (p.wifi) caps |= HINT_WIFI
88
+ if (p.bluetooth === 'poweredOn') caps |= HINT_BT
89
+ if (p.nfc) caps |= HINT_NFC
90
+ return caps & ~RUNG_MASK
91
+ }
92
+
93
+ /**
94
+ * Race NetInfo against the budget. A timeout or a rejection both yield null:
95
+ * "we do not know" is the honest answer to write into the QR, and the caller
96
+ * must not be able to tell the two apart, or it would be tempted to guess.
97
+ * The timer is always cleared so a fast answer leaves nothing pending.
98
+ */
99
+ async function fetchNetWithinBudget(budgetMs: number): Promise<NetInfoState | null> {
100
+ let timer: ReturnType<typeof setTimeout> | undefined
101
+ const deadline = new Promise<null>(resolve => {
102
+ timer = setTimeout(() => resolve(null), budgetMs)
103
+ })
104
+ const answer = Promise.resolve()
105
+ .then(() => NetInfo.fetch())
106
+ .catch(() => null)
107
+ try {
108
+ return await Promise.race([answer, deadline])
109
+ } finally {
110
+ if (timer !== undefined) clearTimeout(timer)
111
+ }
112
+ }
113
+
114
+ /**
115
+ * The prompt-free Bluetooth answer, right now. Sync, never throws. The payee's
116
+ * probe reads it for HINT_BT; the payer reads it on scanning a session so
117
+ * describeFloor can say "your Bluetooth is off" without ever raising the iOS
118
+ * privacy prompt for someone who is about to pay by code anyway (spec §7).
119
+ * 'unsupported' when there is no BLE HybridObject at all (web, jest, a build
120
+ * without the native lib).
121
+ */
122
+ export function readBluetoothState(): BluetoothState {
123
+ try {
124
+ const ble = getLocalPayBleTransport()
125
+ return ble ? asBluetoothState(ble.bluetoothState()) : 'unsupported'
126
+ } catch {
127
+ return 'unknown'
128
+ }
129
+ }
130
+
131
+ function readNfcAvailable(): boolean {
132
+ try {
133
+ return getLocalPayBleTransport()?.nfcAvailable() === true
134
+ } catch {
135
+ return false
136
+ }
137
+ }
138
+
139
+ /**
140
+ * Prompt-free. bluetoothState() and nfcAvailable() are sync class-property /
141
+ * adapter reads on both platforms (spec §"Verified facts"); the one call that
142
+ * may show the iOS Bluetooth prompt is prepare(), which NearbyFlow issues
143
+ * separately (prepareBle, Task 10) and only when the user has asked to
144
+ * receive a nearby payment.
145
+ */
146
+ export async function probeDeviceCaps(opts?: { netBudgetMs?: number }): Promise<DeviceProbe> {
147
+ const net = await fetchNetWithinBudget(opts?.netBudgetMs ?? DEFAULT_NET_BUDGET_MS)
148
+ const wifi =
149
+ net !== null &&
150
+ (Platform.OS === 'android' ? net.isWifiEnabled === true : net.type === 'wifi')
151
+ return {
152
+ online: net === null ? null : net.isInternetReachable,
153
+ connected: net === null ? null : net.isConnected,
154
+ wifi,
155
+ bluetooth: readBluetoothState(),
156
+ nfc: readNfcAvailable(),
157
+ }
158
+ }
159
+
160
+ /**
161
+ * Instantiate the BLE managers and wait for them to settle. THE ONE CALL THAT
162
+ * MAY SHOW THE iOS BLUETOOTH PROMPT, so the payee's minting step is the only
163
+ * caller (spec §4). Never rejects: minting must not fail because a radio did
164
+ * not answer — the request simply advertises without CAP_BLE. 'unsupported'
165
+ * when there is no BLE HybridObject at all.
166
+ */
167
+ export async function prepareBle(timeoutMs: number = BLE_PREPARE_TIMEOUT_MS): Promise<BluetoothState> {
168
+ const ble = getLocalPayBleTransport()
169
+ if (!ble) return 'unsupported'
170
+ try {
171
+ return asBluetoothState(await ble.prepare(timeoutMs))
172
+ } catch {
173
+ return 'unknown'
174
+ }
175
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Has this device already seen the nearby-payments advisory?
3
+ *
4
+ * Nearby payments trigger OS-level prompts (iOS Local Network access, and on
5
+ * Android Bluetooth/nearby-Wi-Fi permissions) that, without warning, read as
6
+ * the app trying to profile the user. NearbyAdvisoryModal explains those
7
+ * prompts up front, once, the first time the user opens a nearby pay/get-paid
8
+ * cell. This flag is a device-level UX preference, not a security record, so
9
+ * unlike backupAttestation it is not scoped per wallet identity — there is no
10
+ * per-identity harm in a shared device remembering "already explained this."
11
+ */
12
+ import AsyncStorage from '@react-native-async-storage/async-storage'
13
+
14
+ const KEY = 'nearby_advisory_shown_v1'
15
+
16
+ export const nearbyAdvisory = {
17
+ async get(): Promise<boolean> {
18
+ try {
19
+ return (await AsyncStorage.getItem(KEY)) === 'true'
20
+ } catch {
21
+ return false
22
+ }
23
+ },
24
+
25
+ async set(): Promise<void> {
26
+ try {
27
+ await AsyncStorage.setItem(KEY, 'true')
28
+ } catch {
29
+ // Advisory only — a failed write just means the modal shows again next time.
30
+ }
31
+ }
32
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * The runtime grants Nearby Connections needs, by API level. Requested lazily
3
+ * — on entering the nearby flow — never at app start: a user who only ever
4
+ * pays over QR should never see a Bluetooth prompt. A denial is a soft
5
+ * degrade to QR, not an error.
6
+ */
7
+ import { PermissionsAndroid, Platform } from 'react-native'
8
+
9
+ export async function requestNearbyPermissions(): Promise<boolean> {
10
+ if (Platform.OS !== 'android') return false
11
+ const api = typeof Platform.Version === 'number' ? Platform.Version : parseInt(String(Platform.Version), 10)
12
+ const wanted: string[] =
13
+ api >= 33
14
+ ? [
15
+ PermissionsAndroid.PERMISSIONS.BLUETOOTH_ADVERTISE,
16
+ PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT,
17
+ PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN,
18
+ PermissionsAndroid.PERMISSIONS.NEARBY_WIFI_DEVICES
19
+ ]
20
+ : api >= 31
21
+ ? [
22
+ PermissionsAndroid.PERMISSIONS.BLUETOOTH_ADVERTISE,
23
+ PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT,
24
+ PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN,
25
+ PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION
26
+ ]
27
+ : [PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION]
28
+ try {
29
+ const results = await PermissionsAndroid.requestMultiple(wanted as never)
30
+ return wanted.every(p => results[p as keyof typeof results] === PermissionsAndroid.RESULTS.GRANTED)
31
+ } catch {
32
+ return false
33
+ }
34
+ }