@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,123 @@
1
+ /**
2
+ * Releases held offline transactions when the device has signal.
3
+ *
4
+ * Two triggers, both gated on the app's single online signal:
5
+ *
6
+ * · `checkNow` — an immediate pass, set by reconnect (`noteConnectivity`),
7
+ * by the manual "Send now" control (`requestNow`), and by app foreground.
8
+ * · a periodic retry — while `hasPending` says the queue may hold releasable
9
+ * rows, fire every `backoffMs`, starting at 10 s and doubling to a 5 min
10
+ * cap. Rationale: users do not keep the app open for long, and once there
11
+ * IS network the first attempt almost always succeeds, so a short first
12
+ * gap is cheap; the doubling keeps a genuinely stuck queue from spamming
13
+ * services.
14
+ *
15
+ * All state is static and process-global BY DESIGN: the monitor is torn down
16
+ * and rebuilt on network switches and wallet rebuilds, and a pending queue
17
+ * must survive that. The previous one-shot version of this task lost its one
18
+ * trigger whenever the first drain after reconnect failed — NetInfo often
19
+ * reports online seconds before routes actually work — which is exactly the
20
+ * "payments sit at nosend forever" bug this rewrite removes.
21
+ */
22
+ import { WalletMonitorTask } from '@bsv/wallet-toolbox-mobile/out/src/monitor/tasks/WalletMonitorTask'
23
+ import type { Monitor } from '@bsv/wallet-toolbox-mobile'
24
+ import type { ProcessOfflineActionsResult } from '../storage/methods/processOfflineActions'
25
+
26
+ export class TaskSendOffline extends WalletMonitorTask {
27
+ static taskName = 'SendOffline'
28
+
29
+ static readonly BASE_BACKOFF_MS = 10_000
30
+ static readonly MAX_BACKOFF_MS = 300_000
31
+
32
+ /** An immediate pass has been requested. Consumed at the top of runTask. */
33
+ static checkNow = false
34
+ /** Last observation from the app's single online listener. Gates trigger. */
35
+ static onlineNow = false
36
+ /** The queue may hold releasable rows. Set pessimistically; a clean run clears it. */
37
+ static hasPending = false
38
+ static backoffMs = TaskSendOffline.BASE_BACKOFF_MS
39
+ static nextDueAt = 0
40
+ /**
41
+ * The most recent run's stalledOn, kept for the UI: a stall means retrying
42
+ * alone will not help, and nothing else in the system records it.
43
+ */
44
+ static lastStall: string | undefined
45
+
46
+ static noteConnectivity(online: boolean): void {
47
+ TaskSendOffline.onlineNow = online
48
+ if (online) {
49
+ TaskSendOffline.checkNow = true
50
+ TaskSendOffline.backoffMs = TaskSendOffline.BASE_BACKOFF_MS
51
+ TaskSendOffline.nextDueAt = 0
52
+ }
53
+ }
54
+
55
+ /** New work exists. Cheap to over-call: one idle drain clears it. */
56
+ static noteEnqueued(): void {
57
+ TaskSendOffline.hasPending = true
58
+ TaskSendOffline.backoffMs = TaskSendOffline.BASE_BACKOFF_MS
59
+ TaskSendOffline.nextDueAt = 0
60
+ }
61
+
62
+ /** The user's "Send now". */
63
+ static requestNow(): void {
64
+ TaskSendOffline.checkNow = true
65
+ TaskSendOffline.backoffMs = TaskSendOffline.BASE_BACKOFF_MS
66
+ TaskSendOffline.nextDueAt = 0
67
+ }
68
+
69
+ static resetForTests(): void {
70
+ TaskSendOffline.checkNow = false
71
+ TaskSendOffline.onlineNow = false
72
+ TaskSendOffline.hasPending = false
73
+ TaskSendOffline.backoffMs = TaskSendOffline.BASE_BACKOFF_MS
74
+ TaskSendOffline.nextDueAt = 0
75
+ TaskSendOffline.lastStall = undefined
76
+ }
77
+
78
+ constructor(
79
+ monitor: Monitor,
80
+ private readonly release: () => Promise<ProcessOfflineActionsResult>,
81
+ private readonly now: () => number = () => Date.now()
82
+ ) {
83
+ super(monitor, TaskSendOffline.taskName)
84
+ }
85
+
86
+ trigger(nowMsecsSinceEpoch: number): { run: boolean } {
87
+ if (!TaskSendOffline.onlineNow) return { run: false }
88
+ return {
89
+ run: TaskSendOffline.checkNow || (TaskSendOffline.hasPending && nowMsecsSinceEpoch >= TaskSendOffline.nextDueAt)
90
+ }
91
+ }
92
+
93
+ private scheduleRetry(): void {
94
+ TaskSendOffline.hasPending = true
95
+ TaskSendOffline.nextDueAt = this.now() + TaskSendOffline.backoffMs
96
+ TaskSendOffline.backoffMs = Math.min(TaskSendOffline.backoffMs * 2, TaskSendOffline.MAX_BACKOFF_MS)
97
+ }
98
+
99
+ async runTask(): Promise<string> {
100
+ TaskSendOffline.checkNow = false
101
+ try {
102
+ const r = await this.release()
103
+ TaskSendOffline.lastStall = r.stalledOn
104
+ if (r.stopped) {
105
+ this.scheduleRetry()
106
+ } else {
107
+ TaskSendOffline.hasPending = false
108
+ TaskSendOffline.backoffMs = TaskSendOffline.BASE_BACKOFF_MS
109
+ }
110
+ if (r.sent === 0 && r.rejected === 0 && !r.stalledOn) return ''
111
+ let log = `sent ${r.sent}, rejected ${r.rejected}${r.stopped ? ', stopped early' : ''}`
112
+ // A stall is distinct from the ordinary "signal went away again" stop: it
113
+ // means retrying alone will not help, so it must not go unnoticed.
114
+ if (r.stalledOn) log += ` — stalled: ${r.stalledOn}`
115
+ return `${log}\n`
116
+ } catch (e) {
117
+ // A throw would take down the monitor's whole run loop — and it is also
118
+ // a failed drain, so it earns a retry rather than silence.
119
+ this.scheduleRetry()
120
+ return `SendOffline failed: ${e instanceof Error ? e.message : String(e)}\n`
121
+ }
122
+ }
123
+ }
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Which `invalid` proof requests are still worth another lookup.
3
+ *
4
+ * The app patches TaskUnFail to re-examine `invalid` reqs, because the library
5
+ * only ever looks at `unfail` and nothing promotes one to the other — so a
6
+ * transaction invalidated by a service outage (a WoC 401, chaintracks down)
7
+ * would stay invalid for good. That patch was unbounded: it took every invalid
8
+ * req on every pass, forever.
9
+ *
10
+ * Two things make it terminate.
11
+ *
12
+ * The transaction is already resolved. `reviewStatus` fails the transaction
13
+ * behind an invalid req and releases its inputs; once that has happened there
14
+ * is nothing left for a merkle path to rescue, and asking the network for one
15
+ * every ten minutes is pure noise — which is exactly how this surfaced, as the
16
+ * same three txids reporting "returned to status 'invalid'" forever.
17
+ *
18
+ * It has been asked enough times. The library's failure path does not touch
19
+ * `attempts` (only its success path does, resetting them), so nothing aged out
20
+ * on its own. Counting failures here gives a genuinely unmineable transaction
21
+ * somewhere to stop.
22
+ */
23
+
24
+ /** Consecutive failed proof lookups before an invalid req is left alone. */
25
+ export const MAX_UNFAIL_RETRIES = 6
26
+
27
+ export type InvalidReq = { provenTxReqId: number; txid: string; attempts?: number | null }
28
+
29
+ /** Transaction statuses per txid, as the transactions table holds them. */
30
+ export type TxStatusesByTxid = Map<string, string[]>
31
+
32
+ /**
33
+ * A txid whose every transaction row is terminal has nothing to recover. No row
34
+ * at all counts as resolved too: the req outlived whatever referenced it.
35
+ */
36
+ export function isResolved(statuses: string[] | undefined): boolean {
37
+ if (!statuses || statuses.length === 0) return true
38
+ return statuses.every(s => s === 'failed' || s === 'completed')
39
+ }
40
+
41
+ export function selectRetryableInvalidReqs<T extends InvalidReq>(reqs: T[], statuses: TxStatusesByTxid): T[] {
42
+ return reqs.filter(r => !isResolved(statuses.get(r.txid)) && (r.attempts ?? 0) < MAX_UNFAIL_RETRIES)
43
+ }
44
+
45
+ /**
46
+ * The two storage surfaces this needs, named apart on purpose.
47
+ *
48
+ * A monitor task's `storage` is the WalletStorageManager, which exposes only a
49
+ * narrow slice: `findProvenTxReqs` is there, `findTransactions` and
50
+ * `updateProvenTxReq` are not. Reaching for one of the missing ones threw at
51
+ * runtime and took the whole UnFail task down with it — including the
52
+ * library's own handling. Declaring both surfaces means the compiler now
53
+ * refuses that mistake instead of the device finding it.
54
+ */
55
+ export interface UnfailProvider {
56
+ findTransactions(args: { partial: { txid: string }; noRawTx?: boolean }): Promise<{ status: string }[]>
57
+ updateProvenTxReq(id: number, update: { attempts: number }): Promise<unknown>
58
+ }
59
+
60
+ export interface UnfailStorage {
61
+ findProvenTxReqs(args: {
62
+ partial: Record<string, unknown>
63
+ status: string[]
64
+ paged: { limit: number; offset: number }
65
+ }): Promise<InvalidReq[]>
66
+ runAsStorageProvider<T>(fn: (sp: UnfailProvider) => Promise<T>): Promise<T>
67
+ }
68
+
69
+ const PAGE = { limit: 100, offset: 0 }
70
+
71
+ /**
72
+ * One bounded pass over the `invalid` reqs, returning what to append to the
73
+ * task's log. Empty when there was nothing worth asking about — which, once a
74
+ * wallet's dead transactions have been failed, is every pass.
75
+ */
76
+ export async function runBoundedUnfail(args: {
77
+ storage: UnfailStorage
78
+ unfail: (reqs: InvalidReq[], indent: number) => Promise<{ log: string }>
79
+ }): Promise<string> {
80
+ const { storage, unfail } = args
81
+ const invalidReqs = await storage.findProvenTxReqs({ partial: {}, status: ['invalid'], paged: PAGE })
82
+ if (invalidReqs.length === 0) return ''
83
+
84
+ const byTxid = await storage.runAsStorageProvider(async sp => {
85
+ const map: TxStatusesByTxid = new Map()
86
+ for (const req of invalidReqs) {
87
+ if (map.has(req.txid)) continue
88
+ const rows = await sp.findTransactions({ partial: { txid: req.txid }, noRawTx: true })
89
+ map.set(
90
+ req.txid,
91
+ rows.map(r => r.status)
92
+ )
93
+ }
94
+ return map
95
+ })
96
+
97
+ const retryable = selectRetryableInvalidReqs(invalidReqs, byTxid)
98
+ if (retryable.length === 0) return ''
99
+
100
+ let log = `\n${retryable.length} invalid reqs — retrying proof lookup\n`
101
+ log += (await unfail(retryable, 2)).log
102
+
103
+ // The library's failure path leaves `attempts` untouched (only its success
104
+ // path writes it, resetting to 0), so without this nothing ages out and the
105
+ // bound could never be reached.
106
+ const stillInvalid = await storage.findProvenTxReqs({ partial: {}, status: ['invalid'], paged: PAGE })
107
+ const stillById = new Map(stillInvalid.map(q => [q.provenTxReqId, q]))
108
+ await storage.runAsStorageProvider(async sp => {
109
+ for (const req of retryable) {
110
+ const current = stillById.get(req.provenTxReqId)
111
+ if (!current) continue
112
+ await sp.updateProvenTxReq(req.provenTxReqId, { attempts: (current.attempts ?? 0) + 1 })
113
+ }
114
+ })
115
+ return log
116
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Is the mounted storage the one this network's screens should be reading?
3
+ *
4
+ * A network switch tears the wallet down and rebuilds it, and for the length of
5
+ * that rebuild the previous chain's storage is still mounted. Anything that
6
+ * reads it in that window answers with the OLD chain's money: the balance, the
7
+ * activity list, and the per-network balance cache the screen writes on the way
8
+ * past — which is how a testnet wallet came to display a mainnet balance and a
9
+ * mainnet list of payments.
10
+ *
11
+ * The app's chain names and the toolbox's do not match ('teratest' is 'ttn' to
12
+ * the toolbox, and both testnets share the 'test' storage chain), so the
13
+ * comparison goes through the same mapping the wallet build uses.
14
+ */
15
+
16
+ export type AppChain = 'main' | 'test' | 'teratest'
17
+
18
+ /** The storage chain an app-level network is expected to be backed by. */
19
+ export function storageChainFor(network: AppChain | string): string {
20
+ return network === 'main' ? 'main' : 'test'
21
+ }
22
+
23
+ /**
24
+ * True only when `storage` is present AND belongs to `network`. A null storage
25
+ * is not a match: there is nothing to read, which is different from — and
26
+ * safer than — reading whatever was there before.
27
+ */
28
+ export function storageMatchesNetwork(
29
+ storage: { chain?: string } | null | undefined,
30
+ network: AppChain | string
31
+ ): boolean {
32
+ if (!storage?.chain) return false
33
+ return storage.chain === storageChainFor(network)
34
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * The single definition of "online" for the whole app.
3
+ *
4
+ * BOTH fields are tri-state: NetInfo reports `null` for each while it has not
5
+ * finished probing, and at cold start `isConnected` is routinely `null` for a
6
+ * beat. Only an explicit `false` counts against us — anything else is "not
7
+ * known yet", which must not read as offline.
8
+ *
9
+ * Requiring `isConnected === true` here (the old rule) is what put the offline
10
+ * banner on the home screen of phones that were online the whole time: the
11
+ * first NetInfo emission arrives before the native probe has an answer, so the
12
+ * app announced a state it had not established. Unknown is optimistic for the
13
+ * same reason it is everywhere else in this codebase — a wrong "online" costs a
14
+ * retry, a wrong "offline" hides the online rails from someone who has signal.
15
+ */
16
+ import NetInfo from '@react-native-community/netinfo'
17
+
18
+ export interface OnlineState {
19
+ isConnected: boolean | null
20
+ isInternetReachable: boolean | null
21
+ }
22
+
23
+ export function isOnlineState(state: OnlineState): boolean {
24
+ return state.isConnected !== false && state.isInternetReachable !== false
25
+ }
26
+
27
+ export async function getOnline(): Promise<boolean> {
28
+ return isOnlineState(await NetInfo.fetch())
29
+ }
30
+
31
+ /** Returns the unsubscribe function. */
32
+ export function subscribeOnline(cb: (online: boolean) => void): () => void {
33
+ return NetInfo.addEventListener(state => cb(isOnlineState(state)))
34
+ }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Cancel a parked nearby payment: one that was built, shown as a QR code, and
3
+ * deliberately never released for broadcast.
4
+ *
5
+ * Parked is the honest state after the payer leaves the code screen without
6
+ * confirming the hand-over: we cannot see whether the other phone scanned the
7
+ * frame, so the transaction stays `nosend` and its inputs stay reserved. This
8
+ * is the exit from that state for the "they never got it" case — abort the
9
+ * action so the coins come back, and retire the offline row.
10
+ *
11
+ * Refuses once the transaction has left `nosend`. If it has been promoted, the
12
+ * counterparty did broadcast (or is about to), and releasing the inputs would
13
+ * hand the payer a double-spend against the person they just paid.
14
+ */
15
+
16
+ import { updateOfflineAction } from '../storage/methods/offlineActions'
17
+
18
+ const CANCELLABLE = new Set(['nosend', 'unsigned', 'unprocessed'])
19
+
20
+ export type CancelParkedOutcome = 'cancelled' | 'already-sent' | 'not-found'
21
+
22
+ export interface CancelParkedStorage {
23
+ readonly sqliteDb: unknown
24
+ findTransactions(args: {
25
+ partial: { txid: string }
26
+ noRawTx?: boolean
27
+ }): Promise<{ reference?: string; status?: string }[]>
28
+ }
29
+
30
+ export interface CancelParkedWallet {
31
+ abortAction(args: { reference: string }, originator?: string): Promise<{ aborted?: boolean } | void>
32
+ }
33
+
34
+ export async function cancelParkedPayment(args: {
35
+ storage: CancelParkedStorage
36
+ wallet: CancelParkedWallet
37
+ originator?: string
38
+ txid: string
39
+ }): Promise<CancelParkedOutcome> {
40
+ const { storage, wallet, originator, txid } = args
41
+ const db = storage.sqliteDb
42
+ if (!db) throw new Error('the database is not open, cannot cancel this payment')
43
+
44
+ const tx = (await storage.findTransactions({ partial: { txid }, noRawTx: true }))[0]
45
+ if (!tx) return 'not-found'
46
+ if (!tx.status || !CANCELLABLE.has(tx.status)) return 'already-sent'
47
+ if (!tx.reference) return 'not-found'
48
+
49
+ const r = await wallet.abortAction({ reference: tx.reference }, originator)
50
+ if (r && r.aborted === false) throw new Error('the wallet refused to cancel this payment')
51
+
52
+ // Only after the abort landed: a retained parked row is recoverable, a
53
+ // retired row over a live reservation is not.
54
+ await updateOfflineAction(db as never, txid, { status: 'acknowledged' })
55
+ return 'cancelled'
56
+ }
@@ -0,0 +1,127 @@
1
+ /*
2
+ * Deciding whether a request may be held for later delivery, and what to report
3
+ * when it is.
4
+ *
5
+ * `status: 'success'` from a hold means "accepted for delivery", not "the
6
+ * network has it". Nothing in the stored state claims otherwise: the request
7
+ * sits at `nosend` rather than `unmined`, `wasBroadcast` stays false, and a row
8
+ * in `offline_actions` records that it still needs sending.
9
+ * `aggregateActionResults` maps this to a notDelayedResult of `success`
10
+ * (`utility/aggregateResults.js:17-21`), which is what stops `internalizeAction`
11
+ * from rolling back the payment it just verified.
12
+ *
13
+ * Pure by design: no I/O belongs in this file. The caller does the database
14
+ * reads and hands the rows in, so the rules that decide whether money may be
15
+ * parked — and under whose name — are unit-testable rather than device-only.
16
+ */
17
+ import type { OfflineActionRole } from '../storage/methods/offlineActions'
18
+
19
+ export interface HeldReq {
20
+ txid: string
21
+ }
22
+
23
+ export interface OfflineHoldResult<T extends HeldReq> {
24
+ status: 'success'
25
+ details: { txid: string; req: T; status: 'success' }[]
26
+ }
27
+
28
+ /**
29
+ * The result shape `shareReqsWithWorld` expects back from
30
+ * `attemptToPostReqsToNetwork` when a request was parked instead of broadcast.
31
+ *
32
+ * Generic over the request type so the caller's own request objects pass
33
+ * straight through: `attemptToPostReqsToNetwork` returns `EntityProvenTxReq` in
34
+ * `details[].req`, and callers (`TaskSendWaiting`'s logging, for one) read
35
+ * fields off it. Rebuilding a bare `{ txid }` stand-in here would satisfy the
36
+ * type but hand back a different object than every other code path does.
37
+ */
38
+ export function buildOfflineHoldResult<T extends HeldReq>(reqs: T[]): OfflineHoldResult<T> {
39
+ return {
40
+ status: 'success',
41
+ details: reqs.map(req => ({ txid: req.txid, req, status: 'success' as const }))
42
+ }
43
+ }
44
+
45
+ /**
46
+ * The transaction-row facts a hold decision needs. Structurally satisfied by
47
+ * `TableTransaction`, so the caller passes rows straight in.
48
+ */
49
+ export interface HoldTx {
50
+ userId: number
51
+ isOutgoing: boolean
52
+ status: string
53
+ }
54
+
55
+ export interface OfflineHoldGroup {
56
+ userId: number
57
+ role: OfflineActionRole
58
+ reqs: { txid: string }[]
59
+ }
60
+
61
+ /**
62
+ * Transaction statuses that survive having their request parked at 'nosend'.
63
+ *
64
+ * Holding a request stops the broadcast but writes nothing to the transaction
65
+ * row, so that row's existing status must already be one no monitor task acts on
66
+ * and that keeps the coins usable:
67
+ *
68
+ * - 'unproven' — what `internalizeAction` sets
69
+ * (`storage/methods/internalizeAction.js:352`). Ignored by `TaskFailAbandoned`
70
+ * and accepted by `allocateChangeInput`, so the received outputs stay
71
+ * spendable while the broadcast waits. This is the case the feature needs.
72
+ * - 'nosend' — a deliberately withheld transaction, likewise swept by nothing.
73
+ *
74
+ * Everything else is refused, and 'unprocessed' is why this list exists. A
75
+ * non-delayed `createAction` leaves its transaction at 'unprocessed'
76
+ * (`storage/methods/processAction.js:156-159`) and relies on
77
+ * `updateReqsFromAggregateResults` — which a hold skips — to promote it to
78
+ * 'unproven' via `postStatus`. Held at 'unprocessed' it would instead be failed
79
+ * by `TaskFailAbandoned` within `abandonedMsecs` (5 minutes,
80
+ * `monitor/Monitor.js:39`; it selects `['unprocessed','unsigned']` at
81
+ * `monitor/tasks/TaskFailAbandoned.js:35`), which restores its inputs to
82
+ * spendable while the `offline_actions` row still reads 'queued' — leaving a
83
+ * drain to broadcast a transaction the wallet has already failed and may have
84
+ * re-spent the inputs of.
85
+ *
86
+ * Refusing instead returns that request to the behaviour it has today: a
87
+ * `serviceError` leaves the request at 'sending', which `TaskSendWaiting`
88
+ * already retries on its own.
89
+ */
90
+ export const holdSafeTxStatuses: readonly string[] = ['unproven', 'nosend']
91
+
92
+ /**
93
+ * Decide whether every request in a call may be held, and group those that may
94
+ * by the `(userId, role)` their `offline_actions` row needs.
95
+ *
96
+ * All-or-nothing: returns undefined if **any** pair is unattributable or sits on
97
+ * a transaction status that is not hold-safe, which tells the caller to refuse
98
+ * the whole call and let the ordinary broadcast run. A partial hold is not
99
+ * offered, because the result the caller must return covers every txid it was
100
+ * given — reporting 'success' for a held subset while the rest went nowhere
101
+ * would be exactly the false claim holding is careful to avoid — and because a
102
+ * `sendWith` batch has its merged BEEF verified as a unit and is released as a
103
+ * unit.
104
+ *
105
+ * `role` follows the money: `isOutgoing` is true for the wallet's own sends
106
+ * (`storage/methods/createAction.js:377`) and false for what it receives
107
+ * (`storage/methods/internalizeAction.js:364`).
108
+ *
109
+ * Grouped per pair rather than resolved from the first one: a single non-delayed
110
+ * call can carry a whole `options.sendWith` batch, and such a batch can mix a
111
+ * released incoming transaction with the user's own outgoing one, so the role
112
+ * genuinely varies within a call.
113
+ */
114
+ export function groupOfflineHolds<T extends HeldReq>(
115
+ pairs: { req: T; tx: HoldTx | undefined }[]
116
+ ): Map<string, OfflineHoldGroup> | undefined {
117
+ const groups = new Map<string, OfflineHoldGroup>()
118
+ for (const { req, tx } of pairs) {
119
+ if (!tx || !holdSafeTxStatuses.includes(tx.status)) return undefined
120
+ const role: OfflineActionRole = tx.isOutgoing ? 'sent' : 'received'
121
+ const key = `${tx.userId} ${role}`
122
+ const group = groups.get(key) ?? { userId: tx.userId, role, reqs: [] }
123
+ group.reqs.push({ txid: req.txid })
124
+ groups.set(key, group)
125
+ }
126
+ return groups
127
+ }
@@ -0,0 +1,109 @@
1
+ /**
2
+ * The order in which held transactions may be released, and who dies with whom
3
+ * when one is rejected.
4
+ *
5
+ * Pure on purpose. Ordering is the difference between a chain of offline
6
+ * payments landing and a child being rejected as an orphan, so it gets
7
+ * exhaustive unit tests rather than device-only confidence.
8
+ *
9
+ * `OrderableTx` is the shape `BeefTx` already has, so the driver passes
10
+ * `beef.txs` in directly and there is exactly one ordering rule in the codebase.
11
+ */
12
+ export interface OrderableTx {
13
+ txid: string
14
+ /** True once a merkle path is attached — already mined, nothing to send. */
15
+ hasProof: boolean
16
+ /** True for a bare txid reference with no transaction bytes. */
17
+ isTxidOnly: boolean
18
+ inputTxids: string[]
19
+ }
20
+
21
+ /**
22
+ * Dependency order over exactly the transactions given: each is emitted once every
23
+ * input it takes from inside the set has been emitted.
24
+ *
25
+ * Inputs outside the set are ignored — they are either already on chain or someone
26
+ * else's problem, and in both cases they impose no ordering on us. A cycle
27
+ * (impossible in real transactions, possible in corrupt data) is dropped rather
28
+ * than allowed to spin.
29
+ *
30
+ * Membership is deliberately the caller's decision, because the two callers
31
+ * disagree about it. Releasing orders only what needs broadcasting. A cascade must
32
+ * order **every** member, mined and txid-only included: those need no broadcast,
33
+ * but their `failed` write still touches their neighbours' spendability, so leaving
34
+ * them out of the ordering leaves them unplaced — and no end of the list is the
35
+ * right place for a transaction that is both somebody's child and somebody's
36
+ * parent.
37
+ */
38
+ export function dependencyOrder(txs: OrderableTx[]): string[] {
39
+ const inSet = new Set(txs.map(t => t.txid))
40
+ const remaining = new Map(txs.map(t => [t.txid, t]))
41
+ const emitted = new Set<string>()
42
+ const order: string[] = []
43
+
44
+ // Repeated insertion-ordered passes rather than recursion. Exactly two things
45
+ // are guaranteed, and they are the two that matter: nothing is emitted before
46
+ // an input it takes from inside the set, and the result is deterministic for a
47
+ // given input array.
48
+ //
49
+ // Independent transactions do NOT keep their arrival order. A pass emits as it
50
+ // scans, so an entry checked while its parent is still unemitted waits for the
51
+ // next pass and loses its place to a sibling checked later in the same one:
52
+ //
53
+ // releaseOrder([C1(spends P), P, C2(spends P)]) -> ['P', 'C2', 'C1']
54
+ //
55
+ // C1 is examined first and blocked, P is emitted next, and C2 — reached later
56
+ // in that same pass — is by then unblocked. Left as it is on purpose: a parent
57
+ // can never end up after its child, so the tie-break between two unrelated
58
+ // siblings has no consequence for money, while making it stable means replacing
59
+ // the scan with a Kahn FIFO ready-queue and re-establishing the order every
60
+ // existing caller and test depends on.
61
+ let progressed = true
62
+ while (progressed && remaining.size > 0) {
63
+ progressed = false
64
+ for (const t of [...remaining.values()]) {
65
+ const blocked = t.inputTxids.some(i => inSet.has(i) && !emitted.has(i))
66
+ if (blocked) continue
67
+ order.push(t.txid)
68
+ emitted.add(t.txid)
69
+ remaining.delete(t.txid)
70
+ progressed = true
71
+ }
72
+ }
73
+ return order
74
+ }
75
+
76
+ /**
77
+ * Dependency order over the transactions that still need broadcasting.
78
+ *
79
+ * Mined and txid-only entries are excluded: the first needs nothing, the second
80
+ * has nothing to send.
81
+ */
82
+ export function releaseOrder(txs: OrderableTx[]): string[] {
83
+ return dependencyOrder(txs.filter(t => !t.hasProof && !t.isTxidOnly))
84
+ }
85
+
86
+ /**
87
+ * Every transaction in the set that depends on `txid`, directly or through
88
+ * other members. Used to cascade a rejection: if a parent is refused, no child
89
+ * of it can ever be valid.
90
+ */
91
+ export function descendantsOf(txid: string, txs: OrderableTx[]): string[] {
92
+ const childrenOf = new Map<string, string[]>()
93
+ for (const t of txs) {
94
+ for (const input of t.inputTxids) {
95
+ const list = childrenOf.get(input)
96
+ if (list) list.push(t.txid)
97
+ else childrenOf.set(input, [t.txid])
98
+ }
99
+ }
100
+ const found = new Set<string>()
101
+ const queue = [...(childrenOf.get(txid) ?? [])]
102
+ while (queue.length > 0) {
103
+ const next = queue.shift() as string
104
+ if (next === txid || found.has(next)) continue
105
+ found.add(next)
106
+ queue.push(...(childrenOf.get(next) ?? []))
107
+ }
108
+ return [...found]
109
+ }