@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,295 @@
1
+ /**
2
+ * One backup push pass.
3
+ *
4
+ * Reads a delta `SyncChunk` straight from the local storage provider, encrypts it, and
5
+ * appends it to the remote log.
6
+ *
7
+ * It deliberately does NOT go through `WalletStorageManager`. `updateBackups` and
8
+ * `syncToWriter` take the manager's sync lock via `runAsSync`, which blocks every read and
9
+ * write against active storage for the duration — unacceptable against the project's
10
+ * standing "chrome never JS-blocked" goal. Registering a remote as a backup store also hits
11
+ * the `_conflictingActives` trap, where a fresh remote user reports itself as the active
12
+ * storage and `updateBackups()` then throws `WERR_NOT_ACTIVE`.
13
+ *
14
+ * Reading without the lock means a chunk can be taken mid-write. That is safe here: chunks
15
+ * are `since`-based and replay is idempotent, so a torn read corrects itself on the next
16
+ * pass.
17
+ */
18
+ import type { StorageExpoSQLite } from '../storage/StorageExpoSQLite'
19
+ import type { SyncChunk } from '@bsv/wallet-toolbox-mobile/out/src/sdk/WalletStorage.interfaces'
20
+ import { BackupClient, BackupHttpError, ERR_SEQ_CONFLICT } from './client'
21
+ import { encodeChunk, estimateEncodedBytes, isEmptyChunk } from './codec'
22
+ import { GENERATION_CHUNK_THRESHOLD, MAX_ITEMS, MAX_ROUGH_SIZE, type BackupChain } from './constants'
23
+ import {
24
+ ENTITY_NAMES,
25
+ ENTITY_TO_CHUNK_ARRAY,
26
+ freshCursor,
27
+ loadCursor,
28
+ offsetsToArgs,
29
+ saveCursor,
30
+ zeroOffsets,
31
+ type PushCursor
32
+ } from './cursor'
33
+ import { backupPseudonym, deriveBackupWallet } from './derive'
34
+ import { getDeviceId } from './deviceId'
35
+ import { isBackupPushEnabled } from './preference'
36
+
37
+ export interface PushDeps {
38
+ storage: StorageExpoSQLite
39
+ /** The wallet's m/0'/0' key. The backup identity and encryption key derive from it. */
40
+ primaryKey: number[]
41
+ /**
42
+ * The network the wallet database belongs to. Folded into the derivation, so each
43
+ * network pushes to its own server account under its own encryption key — a chunk from
44
+ * a testnet database can never land in, or restore into, the mainnet log.
45
+ */
46
+ chain: BackupChain
47
+ /** The wallet's real identity key — used only for the LOCAL user lookup, never sent. */
48
+ identityKey: string
49
+ /** Supply exactly one of these. */
50
+ baseUrl?: string
51
+ client?: BackupClient
52
+ deviceId?: string
53
+ }
54
+
55
+ export interface PushResult {
56
+ /** Chunks appended this pass (0 or 1). */
57
+ pushed: number
58
+ /** Ciphertext bytes appended. */
59
+ bytes: number
60
+ /** True when the `since` window closed and the cursor advanced. */
61
+ windowClosed: boolean
62
+ /** True when a new generation was started. */
63
+ rotated: boolean
64
+ /** True when the chunk was too large for the server and nothing was sent. */
65
+ oversized?: boolean
66
+ /** True when the user has opted out of pushing; nothing was read or sent. */
67
+ optedOut?: boolean
68
+ }
69
+
70
+ /**
71
+ * Take at most one chunk and append it.
72
+ *
73
+ * One chunk per pass rather than draining in a loop: the monitor runs tasks back-to-back
74
+ * without yielding, so a long pass would stall the JS thread. Successive passes drain the
75
+ * backlog.
76
+ */
77
+ export async function pushOnce (deps: PushDeps): Promise<PushResult> {
78
+ // Checked FIRST, ahead of even reading the local database: the opt-out means no wallet
79
+ // data leaves this device, and the cheapest way to guarantee that is to do nothing at
80
+ // all. The cursor is left untouched, so opting back in resumes from where the log
81
+ // stopped instead of skipping everything written while it was off.
82
+ if (!(await isBackupPushEnabled())) {
83
+ return { pushed: 0, bytes: 0, windowClosed: false, rotated: false, optedOut: true }
84
+ }
85
+
86
+ const client = resolveClient(deps)
87
+ const pseudonym = backupPseudonym(deps.primaryKey, deps.chain)
88
+ const deviceId = deps.deviceId ?? (await getDeviceId())
89
+
90
+ let cursor = await loadCursor(deps.chain, pseudonym, deviceId)
91
+
92
+ const chunk = await deps.storage.getSyncChunk({
93
+ identityKey: deps.identityKey,
94
+ fromStorageIdentityKey: deps.identityKey,
95
+ toStorageIdentityKey: pseudonym,
96
+ since: cursor.since != null ? new Date(cursor.since) : undefined,
97
+ maxRoughSize: MAX_ROUGH_SIZE,
98
+ maxItems: MAX_ITEMS,
99
+ offsets: offsetsToArgs(cursor.offsets)
100
+ })
101
+
102
+ if (isEmptyChunk(chunk)) {
103
+ // Window exhausted. Advance `since` past everything seen and reset the offsets, as
104
+ // EntitySyncState does when its merge reports done — except that we advance PAST the
105
+ // high-water mark rather than onto it. See nextInstant.
106
+ const advanced: PushCursor = {
107
+ ...cursor,
108
+ since: nextInstant(cursor.maxUpdatedAt) ?? cursor.since,
109
+ maxUpdatedAt: undefined,
110
+ offsets: zeroOffsets()
111
+ }
112
+
113
+ const rotated = shouldRotate(advanced)
114
+ const next = rotated ? rotate(advanced) : advanced
115
+ await saveCursor(deps.chain, pseudonym, deviceId, next)
116
+ return { pushed: 0, bytes: 0, windowClosed: true, rotated }
117
+ }
118
+
119
+ // Bail BEFORE the expensive part when the chunk cannot possibly be accepted.
120
+ //
121
+ // maxRoughSize bounds what the toolbox accumulates across records; it cannot bound ONE
122
+ // record. The cap is whatever the server publishes on GET /v1/limits (200 MiB since the
123
+ // transaction-storage-capacity work; cached by the client after the first call) — with
124
+ // records compressed at rest a chunk should never approach it, so tripping this gate
125
+ // now means something is genuinely wrong rather than merely large.
126
+ //
127
+ // Ordering is still the point. Encrypting and signing a doomed payload is synchronous
128
+ // CPU work that blocked the JS thread for ~50s per attempt on device; checking here
129
+ // makes a doomed pass nearly free instead of nearly a minute.
130
+ const estimate = estimateEncodedBytes(chunk)
131
+ const { maxBlobBytes } = await client.limits()
132
+ if (estimate > maxBlobBytes) {
133
+ // Interpolated, not printf-style: React Native's console does not substitute %d, so a
134
+ // format string prints its own placeholders and pushes the numbers to the end.
135
+ console.log(
136
+ `[backup] chunk too large for the server, skipping push · estimate=${estimate} bytes · ` +
137
+ `cap=${maxBlobBytes} · nothing was encrypted or uploaded. This wallet cannot back ` +
138
+ 'up until the oversized record is handled.'
139
+ )
140
+ // Cursor deliberately untouched: advancing past this chunk would silently drop records
141
+ // from the backup, which is worse than not backing up. The pass is now cheap, so the
142
+ // monitor retrying costs nothing until the underlying limit is addressed.
143
+ return { pushed: 0, bytes: 0, windowClosed: false, rotated: false, oversized: true }
144
+ }
145
+
146
+ const wallet = deriveBackupWallet(deps.primaryKey, deps.chain)
147
+ const ciphertext = await encodeChunk(wallet, chunk, deps.chain)
148
+
149
+ const seq = cursor.seq + 1
150
+ let sha: string
151
+ try {
152
+ const r = await client.append(deviceId, cursor.generation, seq, cursor.prevSha256, ciphertext)
153
+ sha = r.sha256
154
+ } catch (e) {
155
+ if (e instanceof BackupHttpError && e.code === ERR_SEQ_CONFLICT) {
156
+ // The server and the cursor disagree about the head. Resynchronise from the server's
157
+ // view rather than retrying into the same wall — this happens after a reinstall that
158
+ // kept the log but lost the cursor, or if two devices shared a device id.
159
+ cursor = await resyncFromServer(client, pseudonym, deviceId, cursor)
160
+ await saveCursor(deps.chain, pseudonym, deviceId, cursor)
161
+ return { pushed: 0, bytes: 0, windowClosed: false, rotated: false }
162
+ }
163
+ // Anything else: leave the cursor untouched so the same chunk is retried next pass.
164
+ throw e
165
+ }
166
+
167
+ // Only advance after the append succeeded, so a failure never skips records.
168
+ await saveCursor(deps.chain, pseudonym, deviceId, {
169
+ ...cursor,
170
+ offsets: advanceOffsets(cursor, chunk),
171
+ maxUpdatedAt: maxUpdatedAt(cursor.maxUpdatedAt, chunk),
172
+ seq,
173
+ prevSha256: sha,
174
+ chunksInGeneration: cursor.chunksInGeneration + 1
175
+ })
176
+
177
+ return { pushed: 1, bytes: ciphertext.length, windowClosed: false, rotated: false }
178
+ }
179
+
180
+ /**
181
+ * One client per (server, pseudonym), reused across passes. The client caches
182
+ * the server's /v1/limits document — needed for the oversize gate and for the
183
+ * identity key every auth proof signs toward — so constructing a fresh client
184
+ * each pass would re-fetch it every minute for no reason.
185
+ */
186
+ let cachedClient: { key: string, client: BackupClient } | undefined
187
+
188
+ function resolveClient (deps: PushDeps): BackupClient {
189
+ if (deps.client != null) return deps.client
190
+ if (deps.baseUrl == null || deps.baseUrl === '') {
191
+ throw new Error('pushOnce requires either a client or a baseUrl')
192
+ }
193
+ const key = `${deps.baseUrl} ${backupPseudonym(deps.primaryKey, deps.chain)}`
194
+ if (cachedClient?.key !== key) {
195
+ cachedClient = { key, client: new BackupClient(deps.baseUrl, deps.primaryKey, deps.chain) }
196
+ }
197
+ return cachedClient.client
198
+ }
199
+
200
+ /**
201
+ * The instant after a closed window's high-water mark — where the next window starts.
202
+ *
203
+ * This is the one place our cursor deliberately DIVERGES from `EntitySyncState`, which
204
+ * sets `when = maxUpdated_at` exactly. The column comparison is `updated_at >= ?`
205
+ * (storage/methods/findSql.ts), so starting the next window ON the high-water mark
206
+ * re-reads every record sharing that timestamp. For the toolbox that is harmless: it
207
+ * syncs into a storage that merges, so a re-read record is merged again and nothing
208
+ * accumulates. Our writer is an append-only blob log, where the same re-read becomes a
209
+ * brand-new encrypted blob — so the boundary record was uploaded again on the very next
210
+ * window, forever, roughly one duplicate every two passes on a wallet that had gone
211
+ * quiet. Each duplicate also counted toward GENERATION_CHUNK_THRESHOLD, so an idle
212
+ * wallet re-uploaded its entire database about every 200 passes.
213
+ *
214
+ * Advancing by one millisecond is exact rather than approximate: SQLite stores these
215
+ * columns as `toISOString()` text, whose resolution IS one millisecond, so this is the
216
+ * next representable instant and no timestamp can hide in the gap.
217
+ *
218
+ * It cannot skip a record either. A window only closes when a chunk comes back empty,
219
+ * which means nothing at or after `since` remained beyond the offsets — so everything up
220
+ * to and including the high-water mark had already been read and appended. Anything
221
+ * written later necessarily carries a greater `updated_at`, because the closing pass runs
222
+ * at least MIN_PUSH_INTERVAL_MS after the pass that set the mark. (A device clock jumping
223
+ * backwards could still orphan a record, but that was equally true of `>=` and is not
224
+ * something a timestamp cursor can defend against.)
225
+ */
226
+ function nextInstant (iso: string | undefined): string | undefined {
227
+ if (iso == null) return undefined
228
+ const t = Date.parse(iso)
229
+ // An unparseable timestamp must not silently reset the window to the epoch; leaving it
230
+ // alone means the caller falls back to the existing `since` and re-reads at worst.
231
+ if (Number.isNaN(t)) return undefined
232
+ return new Date(t + 1).toISOString()
233
+ }
234
+
235
+ /** Per-entity consumed counts grow by what this chunk carried. */
236
+ function advanceOffsets (cursor: PushCursor, chunk: SyncChunk): PushCursor['offsets'] {
237
+ const c = chunk as unknown as Record<string, unknown[] | undefined>
238
+ const next = { ...cursor.offsets }
239
+ for (const name of ENTITY_NAMES) {
240
+ next[name] = (next[name] ?? 0) + (c[ENTITY_TO_CHUNK_ARRAY[name]]?.length ?? 0)
241
+ }
242
+ return next
243
+ }
244
+
245
+ /** Greatest `updated_at` across everything in this chunk. */
246
+ function maxUpdatedAt (current: string | undefined, chunk: SyncChunk): string | undefined {
247
+ const c = chunk as unknown as Record<string, Array<Record<string, unknown>> | undefined> // eslint-disable-line @typescript-eslint/array-type
248
+ let max = current
249
+
250
+ for (const name of ENTITY_NAMES) {
251
+ for (const item of c[ENTITY_TO_CHUNK_ARRAY[name]] ?? []) {
252
+ const raw = item.updated_at
253
+ if (raw == null) continue
254
+ const iso = raw instanceof Date ? raw.toISOString() : String(raw)
255
+ if (max == null || iso > max) max = iso
256
+ }
257
+ }
258
+ return max
259
+ }
260
+
261
+ /**
262
+ * Rotate only at a window boundary.
263
+ *
264
+ * A generation is meant to be a coherent snapshot, so starting one mid-window would leave a
265
+ * partially written generation that a restore could not trust.
266
+ */
267
+ function shouldRotate (cursor: PushCursor): boolean {
268
+ return cursor.chunksInGeneration >= GENERATION_CHUNK_THRESHOLD
269
+ }
270
+
271
+ /** Begin a new generation: a full snapshot, from sequence one, with no `since` filter. */
272
+ function rotate (cursor: PushCursor): PushCursor {
273
+ return freshCursor(cursor.generation + 1)
274
+ }
275
+
276
+ /**
277
+ * Rebuild the cursor from the server's head after a sequence conflict.
278
+ *
279
+ * The server is authoritative about what it holds. Rather than guess which records the
280
+ * remote log already covers, start a fresh generation — one extra full snapshot is cheap
281
+ * next to a restore with a hole in it.
282
+ */
283
+ async function resyncFromServer (
284
+ client: BackupClient,
285
+ _pseudonym: string,
286
+ deviceId: string,
287
+ cursor: PushCursor
288
+ ): Promise<PushCursor> {
289
+ const devices = await client.manifest()
290
+ const newest = devices
291
+ .filter(d => d.deviceId === deviceId)
292
+ .reduce<number>((max, d) => Math.max(max, d.generation), cursor.generation)
293
+
294
+ return freshCursor(newest + 1)
295
+ }
@@ -0,0 +1,152 @@
1
+ /**
2
+ * Restore orchestration.
3
+ *
4
+ * Given nothing but a recovered seed (or the primary key from printed shares), rebuild the
5
+ * wallet database from the encrypted log.
6
+ */
7
+ import type { StorageExpoSQLite } from '../storage/StorageExpoSQLite'
8
+ import { BackupClient, type DeviceSummary } from './client'
9
+ import type { BackupChain } from './constants'
10
+ import { deriveBackupWallet } from './derive'
11
+ import { RemoteSyncReader } from './RemoteSyncReader'
12
+
13
+ export interface RestoreDeps {
14
+ /** A fresh, migrated storage provider to replay into. */
15
+ storage: StorageExpoSQLite
16
+ /** The wallet's m/0'/0' key, from the mnemonic or from recovery shares. */
17
+ primaryKey: number[]
18
+ /** The network being restored. Selects the per-network pseudonym and decryption key. */
19
+ chain: BackupChain
20
+ /** The wallet's real identity key, for the local user record. */
21
+ identityKey: string
22
+ /** Supply exactly one. */
23
+ baseUrl?: string
24
+ client?: BackupClient
25
+ /** Defaults to the most recently updated device in the manifest. */
26
+ deviceId?: string
27
+ /** Defaults to the newest generation for that device. */
28
+ generation?: number
29
+ /**
30
+ * Called after each replayed chunk, with how many have landed and how many the
31
+ * generation holds. `total` is 0 until the index has been read, i.e. before the
32
+ * first chunk arrives.
33
+ */
34
+ onProgress?: (chunks: number, total: number) => void
35
+ }
36
+
37
+ export interface RestoreResult {
38
+ chunks: number
39
+ deviceId: string
40
+ generation: number
41
+ }
42
+
43
+ /** What the user can choose between when more than one device has a backup. */
44
+ export async function listBackups (deps: {
45
+ primaryKey: number[]
46
+ chain: BackupChain
47
+ baseUrl?: string
48
+ client?: BackupClient
49
+ }): Promise<DeviceSummary[]> {
50
+ return await resolveClient(deps).manifest()
51
+ }
52
+
53
+ /**
54
+ * Replay the newest complete generation into `storage`.
55
+ *
56
+ * Picks the newest generation rather than the oldest because a generation is a full
57
+ * snapshot: the newest one alone is sufficient, and it is the shortest replay.
58
+ */
59
+ export async function restoreFromBackup (deps: RestoreDeps): Promise<RestoreResult> {
60
+ const client = resolveClient(deps)
61
+ const wallet = deriveBackupWallet(deps.primaryKey, deps.chain)
62
+
63
+ const devices = await client.manifest()
64
+ if (devices.length === 0) {
65
+ throw new Error('No backup found for this wallet')
66
+ }
67
+
68
+ const chosen = pickTarget(devices, deps.deviceId, deps.generation)
69
+
70
+ const settings = await deps.storage.makeAvailable()
71
+
72
+ // processSyncChunk's preconditions, which a fresh, just-migrated database does
73
+ // not meet: it does verifyTruthy(findUserByIdentityKey(identityKey)) and then
74
+ // verifyOne(findSyncStates({storageIdentityKey: fromStorageIdentityKey, userId})).
75
+ // On a new device the restore runs BEFORE addWalletStorageProvider/getAuth ever
76
+ // create the user row, so without seeding both rows here every replay dies with
77
+ // the toolbox's bare "A truthy value is required." Both helpers are idempotent
78
+ // (find-or-insert), so a retry converges.
79
+ const { user } = await deps.storage.findOrInsertUser(deps.identityKey)
80
+ await deps.storage.findOrInsertSyncStateAuth(
81
+ { userId: user.userId, identityKey: deps.identityKey },
82
+ chosen.deviceId,
83
+ 'backup-restore'
84
+ )
85
+
86
+ const reader = new RemoteSyncReader(client, wallet, deps.chain, chosen.deviceId, chosen.generation, settings)
87
+
88
+ let chunks = 0
89
+ for (;;) {
90
+ const chunk = await reader.getSyncChunk({
91
+ identityKey: deps.identityKey,
92
+ fromStorageIdentityKey: chosen.deviceId,
93
+ toStorageIdentityKey: settings.storageIdentityKey,
94
+ maxRoughSize: 0,
95
+ maxItems: 0,
96
+ offsets: []
97
+ })
98
+
99
+ const result = await deps.storage.processSyncChunk({
100
+ identityKey: deps.identityKey,
101
+ fromStorageIdentityKey: chosen.deviceId,
102
+ toStorageIdentityKey: settings.storageIdentityKey,
103
+ maxRoughSize: 0,
104
+ maxItems: 0,
105
+ offsets: []
106
+ }, chunk)
107
+
108
+ if (result.done) break
109
+ chunks++
110
+ deps.onProgress?.(chunks, reader.length)
111
+
112
+ // The reader is finite; this guards against a processSyncChunk that never reports done.
113
+ if (chunks > reader.length) break
114
+ }
115
+
116
+ return { chunks, deviceId: chosen.deviceId, generation: chosen.generation }
117
+ }
118
+
119
+ function pickTarget (
120
+ devices: DeviceSummary[],
121
+ deviceId?: string,
122
+ generation?: number
123
+ ): { deviceId: string, generation: number } {
124
+ const candidates = deviceId != null ? devices.filter(d => d.deviceId === deviceId) : devices
125
+ if (candidates.length === 0) {
126
+ throw new Error(`No backup found for device ${String(deviceId)}`)
127
+ }
128
+
129
+ if (generation != null) {
130
+ const exact = candidates.find(d => d.generation === generation)
131
+ if (exact == null) throw new Error(`No backup found for generation ${generation}`)
132
+ return { deviceId: exact.deviceId, generation: exact.generation }
133
+ }
134
+
135
+ // Most recently written device, then its newest generation.
136
+ const newest = candidates.reduce((best, d) =>
137
+ d.updatedAt > best.updatedAt ? d : best
138
+ )
139
+ const newestGeneration = candidates
140
+ .filter(d => d.deviceId === newest.deviceId)
141
+ .reduce((best, d) => (d.generation > best.generation ? d : best))
142
+
143
+ return { deviceId: newestGeneration.deviceId, generation: newestGeneration.generation }
144
+ }
145
+
146
+ function resolveClient (deps: { primaryKey: number[], chain: BackupChain, baseUrl?: string, client?: BackupClient }): BackupClient {
147
+ if (deps.client != null) return deps.client
148
+ if (deps.baseUrl == null || deps.baseUrl === '') {
149
+ throw new Error('restore requires either a client or a baseUrl')
150
+ }
151
+ return new BackupClient(deps.baseUrl, deps.primaryKey, deps.chain)
152
+ }
@@ -0,0 +1,119 @@
1
+ /**
2
+ * The restore step of the "import an existing wallet" flow.
3
+ *
4
+ * A recovery phrase alone cannot rebuild a wallet: change outputs carry a random
5
+ * derivation suffix and BRC-29 receipts carry sender-chosen derivation data, none of it
6
+ * on-chain. The encrypted backup log holds that metadata, so an import has to replay it
7
+ * BEFORE the wallet is handed to the user.
8
+ *
9
+ * Two ordering rules are load-bearing, and both are why this runs where it does
10
+ * (WalletContext's buildWallet, straight after `migrate` and before the monitor exists):
11
+ *
12
+ * 1. **Before this device's first push.** `pushOnce` writes under this device's own
13
+ * device id, and `restoreFromBackup`'s default target is the most recently updated
14
+ * device in the manifest. Let the monitor push once and the newest entry becomes this
15
+ * device's own near-empty log — restore would then replay nothing and report success.
16
+ * Belt and braces: this module resolves the target itself and passes it explicitly, so
17
+ * the default is never consulted even if the ordering slips.
18
+ * 2. **Into a fresh database.** `restoreFromBackup` documents its storage argument as a
19
+ * fresh, migrated provider. Replay merges by record identity, so re-running it after a
20
+ * failed attempt converges rather than duplicating — but it is not a repair tool for a
21
+ * wallet that has already been transacting.
22
+ *
23
+ * Errors propagate. A partial or forked log must stop the import: a wallet that looks
24
+ * healthy while missing the outputs it needs to spend is worse than one that plainly
25
+ * failed to restore.
26
+ */
27
+ import type { StorageExpoSQLite } from '../storage/StorageExpoSQLite'
28
+ import { BackupClient, type DeviceSummary } from './client'
29
+ import type { BackupChain } from './constants'
30
+ import { listBackups, restoreFromBackup } from './restore'
31
+
32
+ export interface RestoreOnImportDeps {
33
+ /** A fresh, migrated storage provider to replay into. */
34
+ storage: StorageExpoSQLite
35
+ /** The wallet's m/0'/0' key — derives both the backup identity and the decryption key. */
36
+ primaryKey: number[]
37
+ /** The network being imported. Selects which per-network backup account to consult. */
38
+ chain: BackupChain
39
+ /** The wallet's real identity key, for the local user record. Never sent. */
40
+ identityKey: string
41
+ /** Backup server origin. Empty or absent means the feature is off for this build. */
42
+ baseUrl?: string
43
+ /** Injected transport, for tests. Takes precedence over `baseUrl`. */
44
+ client?: BackupClient
45
+ /** Chunks replayed so far, and how many this generation holds. */
46
+ onProgress?: (chunks: number, total: number) => void
47
+ /**
48
+ * After a successful replay, check that restored coins are still spendable.
49
+ * Awaited before this function resolves. Absent on a no-backup / unconfigured
50
+ * import, which has nothing to validate.
51
+ */
52
+ validateRestoredCoins?: () => Promise<void>
53
+ }
54
+
55
+ export interface RestoreOnImportResult {
56
+ restored: boolean
57
+ chunks: number
58
+ deviceId?: string
59
+ generation?: number
60
+ /** Why nothing was replayed. Absent when `restored` is true. */
61
+ reason?: 'not-configured' | 'no-backup'
62
+ }
63
+
64
+ export async function restoreOnImport (deps: RestoreOnImportDeps): Promise<RestoreOnImportResult> {
65
+ const client = deps.client ?? (hasUrl(deps.baseUrl) ? new BackupClient(deps.baseUrl!, deps.primaryKey, deps.chain) : null)
66
+ if (client == null) {
67
+ return { restored: false, chunks: 0, reason: 'not-configured' }
68
+ }
69
+
70
+ const devices = await listBackups({ primaryKey: deps.primaryKey, chain: deps.chain, client })
71
+ const target = newestTarget(devices)
72
+ if (target == null) {
73
+ // Nothing was ever pushed under this seed. An ordinary outcome — a phrase from a
74
+ // wallet that predates backups, or one that never went online — so the import
75
+ // continues with an empty history rather than failing.
76
+ return { restored: false, chunks: 0, reason: 'no-backup' }
77
+ }
78
+
79
+ const result = await restoreFromBackup({
80
+ storage: deps.storage,
81
+ primaryKey: deps.primaryKey,
82
+ chain: deps.chain,
83
+ identityKey: deps.identityKey,
84
+ client,
85
+ deviceId: target.deviceId,
86
+ generation: target.generation,
87
+ onProgress: deps.onProgress
88
+ })
89
+
90
+ if (deps.validateRestoredCoins) {
91
+ await deps.validateRestoredCoins()
92
+ }
93
+
94
+ return {
95
+ restored: true,
96
+ chunks: result.chunks,
97
+ deviceId: result.deviceId,
98
+ generation: result.generation
99
+ }
100
+ }
101
+
102
+ const hasUrl = (u?: string): boolean => u != null && u !== ''
103
+
104
+ /**
105
+ * The most recently written device, then that device's highest generation.
106
+ *
107
+ * A generation is a full snapshot, so the newest one alone is sufficient and is also the
108
+ * shortest replay. Mirrors `restoreFromBackup`'s own default deliberately: this exists to
109
+ * make the choice explicit at a point where only the other device's logs can be in the
110
+ * manifest, not to choose differently.
111
+ */
112
+ function newestTarget (devices: DeviceSummary[]): { deviceId: string, generation: number } | null {
113
+ if (devices.length === 0) return null
114
+ const newest = devices.reduce((best, d) => (d.updatedAt > best.updatedAt ? d : best))
115
+ const generation = devices
116
+ .filter(d => d.deviceId === newest.deviceId)
117
+ .reduce((best, d) => (d.generation > best.generation ? d : best)).generation
118
+ return { deviceId: newest.deviceId, generation }
119
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Has this device actually put a backup on the server?
3
+ *
4
+ * Read from the push cursor rather than by asking the server: the cursor is
5
+ * written only after chunks are appended, so a non-zero `seq` is this device's
6
+ * own record of a completed upload. It also answers offline, which matters —
7
+ * "we could not reach the server" is not the same as "you have no backup", and
8
+ * the troubleshooting list must not conflate them.
9
+ *
10
+ * Scanning the key prefix avoids needing the primary key (the pseudonym is
11
+ * derived from it) up in the UI, where it has no business being.
12
+ */
13
+ import AsyncStorage from '@react-native-async-storage/async-storage'
14
+ import { isBackupPushEnabled } from './preference'
15
+
16
+ const CURSOR_PREFIX = 'backupCursor-'
17
+
18
+ export type BackupUploadState = {
19
+ /** The user has not opted out. */
20
+ enabled: boolean
21
+ /** At least one chunk has been appended for some generation on this device. */
22
+ uploaded: boolean
23
+ }
24
+
25
+ export async function getBackupUploadState(): Promise<BackupUploadState> {
26
+ const enabled = await isBackupPushEnabled()
27
+ let uploaded = false
28
+ try {
29
+ const keys = (await AsyncStorage.getAllKeys()).filter(k => k.startsWith(CURSOR_PREFIX))
30
+ if (keys.length > 0) {
31
+ const entries = await AsyncStorage.multiGet(keys)
32
+ uploaded = entries.some(([, raw]) => {
33
+ if (!raw) return false
34
+ try {
35
+ const parsed = JSON.parse(raw) as { seq?: unknown }
36
+ return typeof parsed.seq === 'number' && parsed.seq > 0
37
+ } catch {
38
+ return false
39
+ }
40
+ })
41
+ }
42
+ } catch {
43
+ // An unreadable store is not evidence of a backup.
44
+ }
45
+ return { enabled, uploaded }
46
+ }
@@ -0,0 +1,47 @@
1
+ export type AppChain = 'main' | 'test' | 'teratest'
2
+
3
+ /**
4
+ * The wallet-toolbox `Chain` type used by @bsv/wallet-toolbox-mobile.
5
+ * Mirrors `Chain = 'main' | 'test' | 'ttn' | 'mock'` from the toolbox sdk.
6
+ */
7
+ export type WalletChain = 'main' | 'test' | 'ttn'
8
+
9
+ /**
10
+ * Map our app-level chain id to the wallet-toolbox `Chain` value.
11
+ * The app persists/displays `'teratest'`, but the toolbox (and its default
12
+ * wallet-client service paths — e.g. WhatsOnChain `api.woc-ttn.bsvblockchain.tech`)
13
+ * identify TeraTestNet as `'ttn'`. Keep `'teratest'` for AsyncStorage keys,
14
+ * env var names (`EXPO_PUBLIC_TERATEST_*`) and UI; convert only at toolbox boundaries.
15
+ */
16
+ export function toWalletChain(chain: AppChain): WalletChain {
17
+ return chain === 'teratest' ? 'ttn' : chain
18
+ }
19
+
20
+ export const DEFAULT_WAB_URL = 'noWAB'
21
+ export const DEFAULT_STORAGE_URL = 'local'
22
+ export const DEFAULT_MESSAGEBOX_URL = 'https://gmb.bsvblockchain.tech'
23
+ /**
24
+ * Encrypted wallet-backup log.
25
+ *
26
+ * Deliberately separate from DEFAULT_STORAGE_URL, which stays 'local': this service is not
27
+ * a wallet storage provider. It stores opaque ciphertext it cannot read, addressed by a
28
+ * pseudonym derived from the wallet seed.
29
+ *
30
+ * Empty disables backup entirely — no monitor task is registered and nothing is sent. That
31
+ * is what a build with no EXPO_PUBLIC_BACKUP_URL gets, including a plain local `npm run ios`
32
+ * with no .env.local: the value is not defaulted in code, so every build states its endpoint.
33
+ *
34
+ * The EAS development, dev-physical and production profiles set it to the shared server at
35
+ * https://backup.bsvblockchain.tech (see eas.json). preview-apk carries no env block at all,
36
+ * so those builds have backup disabled along with every other EXPO_PUBLIC_* default.
37
+ *
38
+ * Set EXPO_PUBLIC_BACKUP_URL to point a build at a different server. EXPO_PUBLIC_* values are
39
+ * inlined by Metro at bundle time, so changing it needs a Metro restart but not a native rebuild.
40
+ * It must be an origin with no trailing slash and no path: the BRC-103/104 handshake is
41
+ * posted to the origin root, so a path prefix makes every request fail authentication.
42
+ *
43
+ * EXPO_PUBLIC_BACKUP_URL=https://backup.example.com npm run ios
44
+ */
45
+ export const DEFAULT_BACKUP_URL = (process.env.EXPO_PUBLIC_BACKUP_URL ?? '').replace(/\/+$/, '')
46
+ export const DEFAULT_CHAIN: AppChain = 'main'
47
+ export const ADMIN_ORIGINATOR = 'admin.com'