@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,503 @@
1
+ /**
2
+ * Releases held transactions to the network, parents first.
3
+ *
4
+ * The order comes from the BEEF, not from the queue: a received transaction's
5
+ * ancestry can contain other people's unbroadcast transactions that were never
6
+ * our queue rows, and those must go out before ours. Every held request stores
7
+ * the full AtomicBEEF it arrived in (`proven_tx_reqs.inputBEEF`, written at
8
+ * `storage/methods/internalizeAction.js:519`), so merging those beefs gives the
9
+ * whole dependency graph.
10
+ *
11
+ * Transactions we own are posted through the toolbox's own
12
+ * `attemptToPostReqsToNetwork`, which handles status transitions, history notes
13
+ * and `markStaleInputsAsSpent`. Foreign ancestors have no request here, so they
14
+ * are posted directly through `services.postBeef`.
15
+ *
16
+ * Every decision — the order, what a broadcast result means, who dies with whom
17
+ * — lives in `utils/offline/plan.ts` and is unit-tested. What is left here is
18
+ * database reads, writes and logging, which is validated on device.
19
+ */
20
+ import { Beef } from '@bsv/sdk'
21
+ import { attemptToPostReqsToNetwork } from '@bsv/wallet-toolbox-mobile/out/src/storage/methods/attemptToPostReqsToNetwork'
22
+ import { EntityProvenTxReq } from '@bsv/wallet-toolbox-mobile/out/src/storage/schema/entities'
23
+ import type { TableProvenTxReq, TableTransaction } from '@bsv/wallet-toolbox-mobile/out/src/storage/schema/tables'
24
+ import type { StorageExpoSQLite } from '../StorageExpoSQLite'
25
+ import { findOfflineActions, updateOfflineAction, type OfflineActionRow, type OfflineDb } from './offlineActions'
26
+ import {
27
+ applyOutcome,
28
+ outcomeFromReqStatus,
29
+ outcomeOfForeignPost,
30
+ outcomeOfOwnedPost,
31
+ planRelease,
32
+ undecidedReqStatuses,
33
+ type PostOutcome
34
+ } from '../../offline/plan'
35
+ import { descendantsOf, type OrderableTx } from '../../offline/order'
36
+ import { devLog } from '../../logging'
37
+ import { getOnline } from '../../net/online'
38
+
39
+ /** i18n keys for `stalledOn` — OfflineNotice translates these, never raw txids. */
40
+ export const STALL_NO_REQUEST = 'offline_stall_no_request'
41
+ export const STALL_BAD_BEEF = 'offline_stall_bad_beef'
42
+ export const STALL_FOREIGN_ANCESTOR = 'offline_stall_foreign_ancestor'
43
+
44
+ export interface ProcessOfflineActionsResult {
45
+ /** Queue rows moved to 'sent'. A foreign ancestor's broadcast is logged, not counted. */
46
+ sent: number
47
+ /** Transactions whose local records were changed to record a rejection. */
48
+ rejected: number
49
+ /**
50
+ * True if at least one subtree of the plan could not finish and was left
51
+ * queued. The run itself always walks the whole plan — a blocked subtree no
52
+ * longer aborts release of the rest — so this reports partial, not total,
53
+ * failure; there may still be more to do next pass.
54
+ */
55
+ stopped: boolean
56
+ /**
57
+ * Why the queue cannot make progress by simply being retried.
58
+ *
59
+ * Distinct from `stopped`, which is also true for the ordinary "signal went away
60
+ * again" case that the next run resolves by itself. This is set only where
61
+ * retrying changes nothing: a queued transaction whose request has gone, one
62
+ * whose beef will not parse, or an ancestor from someone else's beef that no
63
+ * service will accept. Left conservative, all three leave their rows at 'queued'
64
+ * with the received outputs still spendable and tell the user nothing — nothing
65
+ * else in the system records them, so a caller must surface this.
66
+ */
67
+ stalledOn?: string
68
+ }
69
+
70
+ /** A queued transaction paired with the request that carries its bytes. */
71
+ interface HeldAction {
72
+ row: OfflineActionRow
73
+ api: TableProvenTxReq
74
+ }
75
+
76
+ export async function processOfflineActions(args: {
77
+ storage: StorageExpoSQLite
78
+ /** Injected so tests can supply a missing ancestor without hitting the network. */
79
+ refetchBeef?: (txid: string) => Promise<number[] | undefined>
80
+ }): Promise<ProcessOfflineActionsResult> {
81
+ const { storage, refetchBeef } = args
82
+ const db = storage.sqliteDb
83
+ if (!db) return { sent: 0, rejected: 0, stopped: true, stalledOn: 'the database is not open' }
84
+
85
+ // 'posting' is included so a run interrupted mid-flight resumes rather than
86
+ // stranding its rows. Re-posting is safe: a transaction the network already has
87
+ // comes back as accepted (ARC's `SEEN_ON_NETWORK`), and a request storage has
88
+ // already recorded as delivered is not posted again at all — see `postOwned`.
89
+ const rows = await findOfflineActions(db, { status: ['queued', 'posting'] })
90
+ if (rows.length === 0) return { sent: 0, rejected: 0, stopped: false }
91
+
92
+ if (!(await probeOnline())) {
93
+ devLog(`[processOfflineActions] offline, leaving ${rows.length} action(s) queued`)
94
+ return { sent: 0, rejected: 0, stopped: true }
95
+ }
96
+
97
+ // Merge every held request's BEEF into one graph. Anything that cannot be read
98
+ // is collected rather than thrown: a row missing from the graph is simply never
99
+ // planned, which is safe but permanent, so it has to be reportable.
100
+ const merged = new Beef()
101
+ const held = new Map<string, HeldAction>()
102
+ const blocked: string[] = []
103
+ for (const row of rows) {
104
+ const api = await findReq(storage, row.txid)
105
+ if (!api) {
106
+ devLog(`[processOfflineActions] queued txid has no request, cannot release it: ${row.txid}`)
107
+ blocked.push(STALL_NO_REQUEST)
108
+ continue
109
+ }
110
+ // The request is remembered whatever happens below. Being in `held` does not
111
+ // put anything in the plan — the plan comes from the graph — so a row whose
112
+ // own beef failed can still be released properly if another row's beef
113
+ // supplied it, ordered, as an ancestor.
114
+ held.set(row.txid, { row, api })
115
+ try {
116
+ // ALL OR NOTHING, and this is why: `Beef.mergeBeef` is not atomic. It
117
+ // parses the bytes into a standalone object first, but then merges
118
+ // transaction by transaction into `this`, and `mergeBeefTx` can throw
119
+ // partway through. Merging the raw transaction straight into `merged`
120
+ // before its beef is worse still — a beef that fails to parse at all
121
+ // leaves the child in the graph with none of its ancestors.
122
+ //
123
+ // Nothing downstream can tell that apart from a child whose parents are
124
+ // already mined: `releaseOrder` finds no in-set input, calls it unblocked
125
+ // and posts it first, the network refuses it as an orphan, and the cascade
126
+ // marks it and everything spending it 'failed'. That is received money made
127
+ // permanently unspendable by our own ordering error rather than by any
128
+ // verdict the network reached — the one outcome this engine exists to
129
+ // prevent. So each row is assembled in isolation and folded in only once
130
+ // the whole of it parsed.
131
+ //
132
+ // The fold cannot itself half-succeed the way the parse can: `scratch` is
133
+ // already a live `Beef`, and `mergeBeefTx` only throws for an entry that is
134
+ // neither txid-only nor carrying bytes, which `BeefTx.isTxidOnly` makes
135
+ // unrepresentable.
136
+ const scratch = new Beef()
137
+ scratch.mergeRawTx(api.rawTx)
138
+ if (api.inputBEEF) scratch.mergeBeef(api.inputBEEF)
139
+ merged.mergeBeef(scratch)
140
+ } catch (e) {
141
+ // Without its whole beef this transaction has no place in the graph, so it
142
+ // is simply not planned and stays queued. Never guess at an order.
143
+ // Before stalling, try a network refetch — a missing ancestor that is
144
+ // already on chain can rebuild the graph.
145
+ devLog(`[processOfflineActions] could not merge the beef of ${row.txid}:`, e)
146
+ const repaired = refetchBeef ? await tryMergeRefetchedBeef(merged, row.txid, refetchBeef) : false
147
+ if (!repaired) blocked.push(STALL_BAD_BEEF)
148
+ }
149
+ }
150
+
151
+ if (refetchBeef) {
152
+ for (const t of [...merged.txs]) {
153
+ if (t.isTxidOnly) await tryMergeRefetchedBeef(merged, t.txid, refetchBeef)
154
+ }
155
+ }
156
+
157
+ const txs: OrderableTx[] = merged.txs
158
+ const plan = planRelease({ rows, txs })
159
+
160
+ let sent = 0
161
+ let rejected = 0
162
+ const resolved = new Set<string>()
163
+ const skip = new Set<string>()
164
+ const stallNotes: string[] = blocked.length > 0 ? [...blocked] : []
165
+
166
+ for (const step of plan) {
167
+ // `resolved` covers a txid the cascade already rejected earlier in this same
168
+ // pass: dependency order guarantees such a descendant's own `step` is still
169
+ // ahead in the plan, and `skip` alone never catches it because
170
+ // invalidTx/doubleSpend return `blocked: []` (a rejection is final, nothing
171
+ // deferred). Without this, the loop walks straight back into an already-
172
+ // rejected row, flips it 'posting', and re-posts a network-refused
173
+ // transaction.
174
+ if (skip.has(step.txid) || resolved.has(step.txid)) continue
175
+ const action = step.owned ? held.get(step.txid) : undefined
176
+ if (step.owned && !action) {
177
+ // Its request is gone, so it can never be posted — and nothing downstream
178
+ // of it may go out either, or it becomes an orphan. Skip the subtree and
179
+ // keep releasing independent roots: this is a local anomaly, not a
180
+ // network verdict, and 'failed' is not reversible.
181
+ skip.add(step.txid)
182
+ for (const d of descendantsOf(step.txid, txs)) skip.add(d)
183
+ stallNotes.push(STALL_NO_REQUEST)
184
+ continue
185
+ }
186
+ if (action) await updateOfflineAction(db, step.txid, { status: 'posting' })
187
+
188
+ const outcome = action ? await postOwned(storage, action.api) : await postForeign(storage, merged, step.txid)
189
+ // A cascade needs to see what spends the refused transaction, and beefs only
190
+ // reach backwards, so the graph the queue built cannot contain a spender that
191
+ // is not itself queued. Widened only when a cascade is actually about to run,
192
+ // because that widening reads every undecided request in the wallet.
193
+ const cascadeTxs = outcome === 'success' || outcome === 'serviceError' ? txs : await withLocalSpenders(storage, txs)
194
+ const result = applyOutcome({ txid: step.txid, outcome, txs: cascadeTxs, rows })
195
+
196
+ for (const txid of result.sent) {
197
+ resolved.add(txid)
198
+ if (held.has(txid)) {
199
+ await updateOfflineAction(db, txid, { status: 'sent' })
200
+ sent++
201
+ } else {
202
+ devLog(`[processOfflineActions] foreign ancestor broadcast: ${txid}`)
203
+ }
204
+ }
205
+ for (const r of result.rejected) {
206
+ resolved.add(r.txid)
207
+ try {
208
+ if (await rejectOne(storage, db, held.get(r.txid)?.row, r)) rejected++
209
+ } catch (e) {
210
+ // The walk must reach the parent. A child's failure has already released
211
+ // the parent's outputs back to spendable, so abandoning the cascade here
212
+ // would leave refused money spendable — the exact outcome children-first
213
+ // ordering exists to prevent.
214
+ devLog(`[processOfflineActions] could not record the rejection of ${r.txid}:`, e)
215
+ }
216
+ }
217
+ for (const b of result.blocked) skip.add(b)
218
+ if (result.blocked.length > 0 && !action) {
219
+ // A foreign ancestor no service would take blocks everything behind it and
220
+ // retrying will not change that, whereas our own failed post is the
221
+ // ordinary "signal went away" case the next run picks up.
222
+ stallNotes.push(STALL_FOREIGN_ANCESTOR)
223
+ }
224
+ }
225
+
226
+ await requeue(db, plan, resolved)
227
+ const uniqueStalls = [...new Set(stallNotes)]
228
+ return {
229
+ sent,
230
+ rejected,
231
+ stopped: skip.size > 0,
232
+ stalledOn: uniqueStalls.length > 0 ? uniqueStalls.join('; ') : undefined
233
+ }
234
+ }
235
+
236
+ async function tryMergeRefetchedBeef(
237
+ target: Beef,
238
+ txid: string,
239
+ refetch: (txid: string) => Promise<number[] | undefined>
240
+ ): Promise<boolean> {
241
+ try {
242
+ const bytes = await refetch(txid)
243
+ if (!bytes) return false
244
+ const scratch = new Beef()
245
+ scratch.mergeBeef(bytes)
246
+ target.mergeBeef(scratch)
247
+ return true
248
+ } catch (e) {
249
+ devLog(`[processOfflineActions] refetch of ${txid} could not be merged:`, e)
250
+ return false
251
+ }
252
+ }
253
+
254
+ /**
255
+ * A failed connectivity probe must not stop the drain: assume online and let the
256
+ * post itself be the evidence, exactly as the offline hold assumes online when
257
+ * its own probe fails.
258
+ */
259
+ async function probeOnline(): Promise<boolean> {
260
+ try {
261
+ return await getOnline()
262
+ } catch (e) {
263
+ devLog('[processOfflineActions] connectivity probe failed, assuming online:', e)
264
+ return true
265
+ }
266
+ }
267
+
268
+ /**
269
+ * The release graph plus every locally-known transaction that has not been
270
+ * decided yet, so a cascade can find the spenders of a refused transaction.
271
+ *
272
+ * These are exactly the descendants with no queue row of their own: the wallet
273
+ * re-spent money it received underground, and Task 8 leaves such an outgoing
274
+ * request to `TaskSendWaiting` rather than parking it, so nothing put it in the
275
+ * queue. They are added for the cascade only and never for release — this engine
276
+ * has no request bookkeeping to offer them, and the monitor already owns sending
277
+ * them. Which statuses count as undecided is a money decision and lives with the
278
+ * others in `utils/offline/plan.ts`.
279
+ *
280
+ * A failure to read them widens nothing rather than throwing, so a cascade still
281
+ * runs over the queue's own graph. Every error here costs rejections we should
282
+ * have made, never rejections we should not have.
283
+ */
284
+ async function withLocalSpenders(storage: StorageExpoSQLite, txs: OrderableTx[]): Promise<OrderableTx[]> {
285
+ const known = new Set(txs.map(t => t.txid))
286
+ const spenders = new Beef()
287
+ let pending: TableProvenTxReq[] = []
288
+ try {
289
+ pending = await storage.findProvenTxReqs({ partial: {}, status: undecidedReqStatuses })
290
+ } catch (e) {
291
+ devLog('[processOfflineActions] could not read undecided requests, cascading over the queue alone:', e)
292
+ return txs
293
+ }
294
+ for (const api of pending) {
295
+ if (known.has(api.txid)) continue
296
+ try {
297
+ spenders.mergeRawTx(api.rawTx)
298
+ } catch (e) {
299
+ devLog(`[processOfflineActions] could not read the raw transaction of ${api.txid}:`, e)
300
+ }
301
+ }
302
+ return [...txs, ...spenders.txs.filter(t => !known.has(t.txid))]
303
+ }
304
+
305
+ /**
306
+ * The request for a txid, or undefined if there is none or it could not be read.
307
+ *
308
+ * Guarded because every caller has something safer to do with a failed read than
309
+ * abandon the run: the merge loop leaves the row unplanned, `postOwned` falls back
310
+ * to 'serviceError' and re-holds, and `rejectOne` still records what it can.
311
+ */
312
+ async function findReq(storage: StorageExpoSQLite, txid: string): Promise<TableProvenTxReq | undefined> {
313
+ try {
314
+ return (await storage.findProvenTxReqs({ partial: { txid } }))[0]
315
+ } catch (e) {
316
+ devLog(`[processOfflineActions] could not read the request for ${txid}:`, e)
317
+ return undefined
318
+ }
319
+ }
320
+
321
+ /** Return every unresolved row we may have moved to 'posting' to 'queued'. */
322
+ async function requeue(db: OfflineDb, plan: { txid: string; owned: boolean }[], resolved: Set<string>): Promise<void> {
323
+ for (const step of plan) {
324
+ if (!step.owned || resolved.has(step.txid)) continue
325
+ await updateOfflineAction(db, step.txid, { status: 'queued' })
326
+ }
327
+ }
328
+
329
+ /**
330
+ * Post a transaction this wallet owns, reusing the toolbox's bookkeeping.
331
+ *
332
+ * The module function is imported and called directly rather than as
333
+ * `storage.attemptToPostReqsToNetwork`, so Task 8's offline override cannot
334
+ * intercept it. That matters for more than tidiness: the override returns
335
+ * `status: 'success'` for a request it merely parked, and a drain that read that
336
+ * as delivery would mark the queue row 'sent' for a transaction nobody has. The
337
+ * outcome is therefore taken from what storage records, not from what the post
338
+ * reports — see `outcomeOfOwnedPost`.
339
+ *
340
+ * The request is left at 'nosend' for the post. `attemptToPostReqsToNetwork` has
341
+ * no status gate (it screens on rawTx, notify.transactionIds and inputBEEF only,
342
+ * `attemptToPostReqsToNetwork.js:61-99`), so promoting it first would buy nothing
343
+ * and would briefly publish it at 'unsent' — the status `TaskSendWaiting` selects
344
+ * — handing the monitor a chance to broadcast it out of dependency order.
345
+ *
346
+ * On anything but success the hold is restored. A service error otherwise leaves
347
+ * the request at 'sending' with `attempts` incremented
348
+ * (`attemptToPostReqsToNetwork.js:249-253`), which is exactly the state
349
+ * `TaskSendWaiting` picks up every five minutes and `applyProofTimeout` eventually
350
+ * marks 'invalid' (`EntityProvenTxReq.js:426-433`). Leaving it there would hand
351
+ * back the very failure the hold exists to prevent, and out of dependency order at
352
+ * that.
353
+ *
354
+ * That makes the post itself throwing the dangerous case, because the toolbox
355
+ * persists the request's new status and only afterwards touches the transaction
356
+ * rows and — on a failure — runs `markStaleInputsAsSpent`, which does live chain
357
+ * queries. A throw past that first write would otherwise leave 'sending' behind
358
+ * with no re-hold. So the post is guarded and a throw simply leaves `detailStatus`
359
+ * undefined, letting the persisted status decide, which is what decides anyway.
360
+ * The drain recovers from a stalled run; it cannot recover from an out-of-order
361
+ * broadcast.
362
+ */
363
+ async function postOwned(storage: StorageExpoSQLite, api: TableProvenTxReq): Promise<PostOutcome> {
364
+ const recorded = outcomeFromReqStatus(api.status)
365
+ if (recorded !== undefined) {
366
+ devLog(`[processOfflineActions] storage already records '${api.status}' for ${api.txid}, not posting`)
367
+ return recorded
368
+ }
369
+
370
+ const attemptsBefore = api.attempts
371
+ const req = new EntityProvenTxReq(api)
372
+ // What to restore each transaction to, read before the post overwrites it.
373
+ // `holdSafeTxStatuses` admits 'nosend' as well as 'unproven', and a deliberately
374
+ // withheld transaction must not come back claiming it had been broadcast.
375
+ const txStatusBefore = new Map<number, TableTransaction['status']>()
376
+ for (const transactionId of req.notify.transactionIds ?? []) {
377
+ try {
378
+ const tx = (await storage.findTransactions({ partial: { transactionId }, noRawTx: true }))[0]
379
+ if (tx) txStatusBefore.set(transactionId, tx.status)
380
+ } catch (e) {
381
+ devLog(`[processOfflineActions] could not read the status of transaction ${transactionId}:`, e)
382
+ }
383
+ }
384
+
385
+ let detailStatus: string | undefined
386
+ try {
387
+ const posted = await attemptToPostReqsToNetwork(storage, [req])
388
+ detailStatus = posted.details.find(d => d.txid === api.txid)?.status
389
+ } catch (e) {
390
+ devLog(`[processOfflineActions] posting ${api.txid} threw:`, e)
391
+ }
392
+ // An independent read: whatever the post claimed, or failed to claim, storage is
393
+ // the witness that the transaction actually left.
394
+ const reqStatus = (await findReq(storage, api.txid))?.status
395
+ const outcome = outcomeOfOwnedPost({ detailStatus, reqStatus })
396
+ devLog(`[processOfflineActions] posted ${api.txid}: reported '${detailStatus}', stored '${reqStatus}' => ${outcome}`)
397
+ if (outcome !== 'serviceError') return outcome
398
+
399
+ // Re-hold, and put each transaction back to the hold-safe status it actually
400
+ // had, so its outputs stay spendable and nothing sweeps it while we wait for
401
+ // signal. `attempts` is restored too, so repeated releases while signal comes and
402
+ // goes cannot age a held request toward 'invalid'. The request first, because it
403
+ // is the write that keeps the monitor out and the transaction writes can throw.
404
+ await storage.updateProvenTxReq(api.provenTxReqId, { status: 'nosend', attempts: attemptsBefore })
405
+ for (const [transactionId, status] of txStatusBefore) {
406
+ try {
407
+ await storage.updateTransactionStatus(status, transactionId)
408
+ } catch (e) {
409
+ devLog(`[processOfflineActions] could not restore transaction ${transactionId} to '${status}':`, e)
410
+ }
411
+ }
412
+ return 'serviceError'
413
+ }
414
+
415
+ /**
416
+ * Post a foreign ancestor that arrived inside someone's BEEF.
417
+ *
418
+ * Only its own dependency closure is sent, not the whole merged graph, so each
419
+ * transaction reaches the network in the order this engine chose rather than in
420
+ * whatever order a service happens to unpack a batch.
421
+ *
422
+ * Services come from `storage.getServices()` rather than being passed in, so the
423
+ * owned path — which calls `getServices()` itself inside the toolbox — and this
424
+ * one cannot end up posting the same graph to two different sets of providers.
425
+ */
426
+ async function postForeign(storage: StorageExpoSQLite, merged: Beef, txid: string): Promise<PostOutcome> {
427
+ try {
428
+ const atomic = Beef.fromBinary(merged.toBinaryAtomic(txid))
429
+ const results = await storage.getServices().postBeef(atomic, [txid])
430
+ const outcome = outcomeOfForeignPost({ txid, results })
431
+ devLog(`[processOfflineActions] posted foreign ancestor ${txid} => ${outcome}`)
432
+ return outcome
433
+ } catch (e) {
434
+ devLog(`[processOfflineActions] posting foreign ancestor ${txid} threw, treating as retryable:`, e)
435
+ return 'serviceError'
436
+ }
437
+ }
438
+
439
+ /**
440
+ * Record one rejection, and report whether anything local actually changed.
441
+ *
442
+ * Every read and every write is attempted independently, so one refusal costs only
443
+ * the record it was for rather than the records after it —
444
+ * `updateTransactionStatus` throws for an already-completed or proven transaction
445
+ * (`StorageProvider.js:414-420`). What guarantees the cascade reaches the parent is
446
+ * the caller's per-entry guard, not this function: unpacking the request entity can
447
+ * still throw on corrupt stored JSON, and by then the child's failure has already
448
+ * released the parent's outputs back to spendable.
449
+ */
450
+ async function rejectOne(
451
+ storage: StorageExpoSQLite,
452
+ db: OfflineDb,
453
+ row: OfflineActionRow | undefined,
454
+ r: { txid: string; reason: string; poisonedByTxid: string }
455
+ ): Promise<boolean> {
456
+ let recorded = false
457
+ const api = await findReq(storage, r.txid)
458
+ if (api) {
459
+ const req = new EntityProvenTxReq(api)
460
+ // The attribution record: who handed us the poisoned transaction, over what
461
+ // transport, and when. This is the only durable evidence the user will have.
462
+ req.addHistoryNote({
463
+ when: new Date().toISOString(),
464
+ what: 'offlineRejected',
465
+ poisonedBy: r.poisonedByTxid,
466
+ reason: r.reason,
467
+ senderIdentityKey: row?.senderIdentityKey ?? 'unknown',
468
+ receivedVia: row?.receivedVia ?? 'unknown',
469
+ receivedAt: row?.created_at ?? 'unknown'
470
+ })
471
+ req.status = 'invalid'
472
+ try {
473
+ await req.updateStorageDynamicProperties(storage)
474
+ recorded = true
475
+ } catch (e) {
476
+ devLog(`[processOfflineActions] could not mark request ${r.txid} invalid:`, e)
477
+ }
478
+ for (const transactionId of req.notify.transactionIds ?? []) {
479
+ try {
480
+ // 'failed' releases allocated inputs and marks the outputs not spendable
481
+ // (StorageProvider.js:421-424) — the money must stop being spendable.
482
+ await storage.updateTransactionStatus('failed', transactionId)
483
+ recorded = true
484
+ } catch (e) {
485
+ devLog(`[processOfflineActions] could not fail transaction ${transactionId} of ${r.txid}:`, e)
486
+ }
487
+ }
488
+ }
489
+ if (row) {
490
+ try {
491
+ await updateOfflineAction(db, r.txid, {
492
+ status: 'rejected',
493
+ rejectedReason: r.reason,
494
+ poisonedByTxid: r.poisonedByTxid
495
+ })
496
+ recorded = true
497
+ } catch (e) {
498
+ devLog(`[processOfflineActions] could not mark the queue row of ${r.txid} rejected:`, e)
499
+ }
500
+ }
501
+ devLog(`[processOfflineActions] rejected ${r.txid} (poisoned by ${r.poisonedByTxid}): ${r.reason}`)
502
+ return recorded
503
+ }
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Measuring, and then reclaiming, wallet database space.
3
+ *
4
+ * MEASURE FIRST. The destructive half of this file touches exactly one column,
5
+ * and the report exists so that decision can be made from real device numbers
6
+ * rather than from a guess. The prediction on record is that nearly all
7
+ * reclaimable space is `transactions.inputBEEF` plus duplicated vault blobs — in
8
+ * which case nulling that one column plus the script codec is the whole feature.
9
+ *
10
+ * WHY ROW DELETION IS NOT HERE. "Drop the oldest transactions whose outputs are
11
+ * all spent" fails on three independent grounds:
12
+ *
13
+ * 1. Spent-ness is REVERSIBLE. A spend reserves its inputs by setting
14
+ * spendable = 0; if it later fails, releaseInputsAllocatedToFailedTransaction
15
+ * restores them. Prune in that window and the coin is permanently
16
+ * unspendable, because change spends run ignoreServices: true and there is
17
+ * no network recovery.
18
+ * 2. Proven-ness does not close the ancestry requirement, which is transitive
19
+ * through the outputs.spentBy graph.
20
+ * 3. The backup delta protocol carries no deletes, so pruning is invisible
21
+ * within a generation — testing shows the backup unaffected — and then the
22
+ * next rotation writes a full snapshot of the PRUNED database. The loss
23
+ * surfaces weeks later, on another device, during a recovery.
24
+ *
25
+ * WHY inputBEEF IS THE SAFE TARGET. Nothing reads it for BEEF: getProvenOrRawTx
26
+ * consults proven_txs and then proven_tx_reqs, never transactions.inputBEEF, and
27
+ * processAction already declares the intent to clear it right after signing. Its
28
+ * only reader is processAction's own pre-signing validation of a still-unsigned
29
+ * row. That is why the predicate below carries NO spent-ness term at all — the
30
+ * dangerous clauses are unnecessary precisely because this column is not part of
31
+ * the spend path.
32
+ */
33
+
34
+ /** Blob byte totals per table, computed in SQL so nothing is materialised. */
35
+ export const RECLAIM_SIZES_SQL = `
36
+ SELECT 'proven_txs' AS "table", COUNT(*) AS rows,
37
+ COALESCE(SUM(LENGTH(rawTx)), 0) + COALESCE(SUM(LENGTH(merklePath)), 0) AS blobBytes
38
+ FROM proven_txs
39
+ UNION ALL
40
+ SELECT 'proven_tx_reqs', COUNT(*),
41
+ COALESCE(SUM(LENGTH(rawTx)), 0) + COALESCE(SUM(LENGTH(inputBEEF)), 0)
42
+ FROM proven_tx_reqs
43
+ UNION ALL
44
+ SELECT 'transactions', COUNT(*),
45
+ COALESCE(SUM(LENGTH(rawTx)), 0) + COALESCE(SUM(LENGTH(inputBEEF)), 0)
46
+ FROM transactions
47
+ UNION ALL
48
+ SELECT 'outputs', COUNT(*), COALESCE(SUM(LENGTH(lockingScript)), 0) FROM outputs
49
+ `.trim()
50
+
51
+ /**
52
+ * The predicate, as a SELECT, so the report and the UPDATE cannot drift.
53
+ *
54
+ * Parameters, in order: tipHeight, cutoff.
55
+ */
56
+ const RECLAIM_PREDICATE = `
57
+ inputBEEF IS NOT NULL
58
+ AND status = 'completed'
59
+ AND provenTxId IS NOT NULL
60
+ AND EXISTS (SELECT 1 FROM proven_txs p
61
+ WHERE p.provenTxId = transactions.provenTxId AND p.height <= ? - 100)
62
+ AND NOT EXISTS (SELECT 1 FROM proven_tx_reqs r
63
+ WHERE r.txid = transactions.txid AND r.status <> 'completed')
64
+ AND NOT EXISTS (SELECT 1 FROM offline_actions a
65
+ WHERE a.txid = transactions.txid AND a.status IN ('queued','posting'))
66
+ AND updated_at < ?
67
+ `.trim()
68
+
69
+ /** Rows the predicate admits, with the bytes each would free. */
70
+ export const RECLAIM_CANDIDATES_SQL = `
71
+ SELECT txid, transactionId, LENGTH(inputBEEF) AS bytes
72
+ FROM transactions
73
+ WHERE ${RECLAIM_PREDICATE}
74
+ `.trim()
75
+
76
+ /**
77
+ * Rows holding an inputBEEF that the predicate REFUSES, and why.
78
+ *
79
+ * Reported so a near-miss is visible. A reclaim that silently frees less than
80
+ * the user expected is indistinguishable from one that failed, and the guard
81
+ * that excluded a row is the interesting part.
82
+ */
83
+ export const RECLAIM_EXCLUDED_SQL = `
84
+ SELECT
85
+ CASE
86
+ WHEN status <> 'completed' THEN 'not completed'
87
+ WHEN provenTxId IS NULL THEN 'not proven'
88
+ WHEN NOT EXISTS (SELECT 1 FROM proven_txs p
89
+ WHERE p.provenTxId = transactions.provenTxId AND p.height <= ? - 100)
90
+ THEN 'inside the reorg horizon'
91
+ WHEN EXISTS (SELECT 1 FROM proven_tx_reqs r
92
+ WHERE r.txid = transactions.txid AND r.status <> 'completed')
93
+ THEN 'broadcast still in flight'
94
+ WHEN EXISTS (SELECT 1 FROM offline_actions a
95
+ WHERE a.txid = transactions.txid AND a.status IN ('queued','posting'))
96
+ THEN 'queued for sending'
97
+ ELSE 'too recent'
98
+ END AS reason,
99
+ COUNT(*) AS rows,
100
+ COALESCE(SUM(LENGTH(inputBEEF)), 0) AS bytes
101
+ FROM transactions
102
+ WHERE inputBEEF IS NOT NULL AND NOT (${RECLAIM_PREDICATE})
103
+ GROUP BY reason
104
+ `.trim()
105
+
106
+ /**
107
+ * Null the column for every admitted row.
108
+ *
109
+ * Parameters, in order: now, tipHeight, cutoff.
110
+ *
111
+ * Raw SQL because updateTransaction cannot write NULL: sqlUpdate skips undefined
112
+ * values, so an update that means "clear this" is silently dropped.
113
+ */
114
+ export const RECLAIM_INPUT_BEEF_SQL = `
115
+ UPDATE transactions SET inputBEEF = NULL, updated_at = ?
116
+ WHERE ${RECLAIM_PREDICATE}
117
+ `.trim()
118
+
119
+ export interface ReclaimTableSize {
120
+ table: string
121
+ rows: number
122
+ blobBytes: number
123
+ }
124
+
125
+ export interface ReclaimReport {
126
+ /** Size of the database file, or null when it could not be read. */
127
+ dbBytes: number | null
128
+ /** Free space on the volume, or null when unreadable. */
129
+ freeBytes: number | null
130
+ perTable: ReclaimTableSize[]
131
+ /** What nulling inputBEEF would free right now. */
132
+ reclaimable: { rows: number; bytes: number }
133
+ /** Rows held back, by the guard that held them. */
134
+ excluded: { reason: string; rows: number; bytes: number }[]
135
+ }