@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,1151 @@
1
+ /**
2
+ * Vault transfers — internal movements between the `default` change basket
3
+ * and the `admin vault` basket, over plain K1 (secp256k1) P2PKH outputs.
4
+ *
5
+ * Deposit: ONE YubiKey tap. The card unwraps the vault key; the next deposit
6
+ * index derives that node's child public-key hash, which IS the P2PKH lock.
7
+ * Nothing here can produce a vault address without the tap — no xpub is
8
+ * stored anywhere, so the unwrapped node is the only source of the material.
9
+ * Funding and change stay with the toolbox, out of the default basket.
10
+ *
11
+ * Withdraw: ONE tap for the whole transaction. The same unwrapped node derives
12
+ * the child private key each selected input names, and signs it in software.
13
+ * The toolbox returns the withdrawn value (minus fee, minus any re-vaulted
14
+ * remainder) as change into the default basket — that change IS the internal
15
+ * transfer. Vault inputs carry a custom unlockingScriptLength the toolbox
16
+ * cannot itself produce, so we build each unlocking script ourselves and
17
+ * finalize with signAction.
18
+ *
19
+ * Sweep: recovery for a lost YubiKey, signed from the SAME HD node reached
20
+ * the other way — main mnemonic + vault passphrase (see vaultDerivation.ts).
21
+ * No card, no ceremony. Always empties the vault (subject to the input cap)
22
+ * and never re-vaults.
23
+ *
24
+ * One rail built for the ~960 KB R1-K1 script survives it on its own merits:
25
+ * the deferred-broadcast finish on withdrawal (see the PAST THE POINT OF NO
26
+ * ABORT comment). The other — the two-transaction deposit that staged exact
27
+ * funding so no change output was ever a sibling of the giant script — is
28
+ * retired: a K1 deposit is ONE ordinary createAction (see depositToVault).
29
+ * What remains of the staging machinery exists only to recover money the old
30
+ * flow stranded on real wallets (see reclaimStagingOutputs).
31
+ *
32
+ * The `admin vault` basket name is admin-reserved: WalletPermissionsManager
33
+ * blocks any non-admin originator (web pages) from listing, inserting into, or
34
+ * relinquishing it. All calls here use the admin originator.
35
+ *
36
+ * SECURITY: the vault HD node passes through this module for the length of ONE
37
+ * operation and is never stored. It arrives either as a VaultKeyHandle — read
38
+ * at its point of use, released in a finally — or, on the sweep, as a node the
39
+ * caller owns; neither is ever put in module state, a cache, or a closure that
40
+ * outlives the call. Nothing key-shaped is logged: not the node, not a child
41
+ * key, not a seed.
42
+ */
43
+ import { Beef, HD, Hash, LockingScript, P2PKH, PublicKey, Transaction, TransactionSignature, UnlockingScript, Utils } from '@bsv/sdk'
44
+ import { vaultStore } from './vaultStore'
45
+ import { VaultError } from './types'
46
+ import { backupAttestation } from './backupAttestation'
47
+ import { VaultKeyHandle } from './ceremony'
48
+ import { noteVaultProgress, requestVaultKey } from './ceremonyHost'
49
+ import { bip32KeyID, indexFromKeyID, depositPrivKey, depositPubKeyHash } from './vaultDerivation'
50
+ import {
51
+ K1_UNLOCK_LEN,
52
+ buildVaultLockingScript,
53
+ decodeVaultInstructions,
54
+ encodeVaultInstructions,
55
+ VaultInstructions
56
+ } from './k1'
57
+
58
+ export const VAULT_BASKET = 'admin vault'
59
+
60
+ /**
61
+ * LEGACY — the intermediate basket the retired two-transaction deposit split
62
+ * its funding into (tx1 carved out deposit + tx2 fee here; tx2 spent it into
63
+ * the vault). No new outputs are ever created in it. It survives only so that
64
+ * reclaimStagingOutputs can find and recover coins the old flow stranded on
65
+ * real wallets (tx1 landed, tx2 failed).
66
+ */
67
+ export const VAULT_STAGING_BASKET = 'vault staging'
68
+
69
+ /** LEGACY — BRC-42 protocol the staging output's P2PKH key was derived under.
70
+ * Reclaim-only: the key lives in the ordinary wallet key deriver (counterparty
71
+ * 'self'), so spending a staging coin needs no ceremony and no YubiKey. */
72
+ const STAGING_PROTOCOL: [number, string] = [2, 'vault deposit staging']
73
+
74
+ /** P2PKH unlock, worst case: push(73-byte DER+hashtype sig) + push(33-byte key). */
75
+ const STAGING_UNLOCK_LEN = 108
76
+
77
+ interface StagingInstructions {
78
+ v: 1
79
+ type: 'staging'
80
+ keyID: string
81
+ }
82
+
83
+ function decodeStagingInstructions(s: string | undefined): StagingInstructions | null {
84
+ if (!s) return null
85
+ try {
86
+ const o = JSON.parse(s)
87
+ return o && o.v === 1 && o.type === 'staging' && typeof o.keyID === 'string' ? o : null
88
+ } catch {
89
+ return null
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Storage-backed lookup of the transactions reserving a set of outpoints.
95
+ *
96
+ * Injected rather than imported so this module stays testable without a database
97
+ * — and optional, so a caller that has no storage handle keeps the original
98
+ * paged-scan heal. See findSpendingReferences in StorageExpoSQLite.
99
+ */
100
+ export type SpendingReferenceLookup = (
101
+ outpoints: string[]
102
+ ) => Promise<{ reference: string; status: string }[]>
103
+
104
+ /**
105
+ * Injected dependencies for a vault transfer.
106
+ *
107
+ * Injected rather than imported so the module stays testable without native
108
+ * modules or a database, and optional so a caller that has neither still works.
109
+ */
110
+ export interface VaultTransferOptions {
111
+ /** Storage-backed reservation heal. See SpendingReferenceLookup. */
112
+ findSpendingReferences?: SpendingReferenceLookup
113
+ /**
114
+ * The app's single online signal.
115
+ *
116
+ * Vault transfers are refused while offline. The offline queue exists for
117
+ * small casual default-basket payments: processOfflineActions holds every held
118
+ * request's full rawTx and inputBEEF in one in-memory Beef, and a held row has
119
+ * no attempt cap, no expiry and no local terminal state that releases its
120
+ * reservation — so a vault transaction landing there would freeze real money
121
+ * with no way out. Refusing up front is also what makes "no vault row ever
122
+ * reaches the offline drain" a testable invariant.
123
+ */
124
+ isOnline?: () => Promise<boolean>
125
+ }
126
+
127
+ export interface VaultSpendResult {
128
+ txid: string
129
+ /**
130
+ * Vault outputs left untouched because of the input cap.
131
+ *
132
+ * Non-zero means the withdrawal was partial: the caller should tell the user
133
+ * that funds remain and that repeating the withdrawal will move them (each
134
+ * pass also consolidates, so the next one needs fewer inputs).
135
+ */
136
+ remainingInputs: number
137
+ }
138
+
139
+ /**
140
+ * Dust-fold threshold for withdrawal remainders — not a deposit floor.
141
+ *
142
+ * The old 200,000 figure was R1 fee economics: a ~960 KB script paid for
143
+ * twice, once to create the output and once to push the preimage that spent
144
+ * it, made anything smaller not worth moving. A K1 vault output costs 25 bytes
145
+ * to create and ~107 to spend, so at the wallet's fee rate moving one is a
146
+ * couple of satoshis and the script no longer argues for any floor at all.
147
+ * Deposits are no longer capped by this constant.
148
+ *
149
+ * What remains is dust hygiene on the withdrawal side: a sub-floor remainder
150
+ * left over after a partial withdrawal is folded into the withdrawal (via the
151
+ * toolbox's own change) rather than re-vaulted, since an output this small
152
+ * isn't worth the index it would burn.
153
+ */
154
+ export const VAULT_DEPOSIT_MIN = 10_000
155
+
156
+ /**
157
+ * Vault inputs per withdrawal.
158
+ *
159
+ * Nothing about the SCRIPTS bounds this any more. The old cap of 6 was
160
+ * defending against ~1.83 MB of inputBEEF per input (a measured 146 MB Hermes
161
+ * array at 20 inputs) and Arcade's 10 MB transaction policy — both artifacts of
162
+ * the R1-K1 script. A K1 input contributes an ordinary source transaction and a
163
+ * ~107-byte unlocking script; 32 of them is a few kilobytes on the wire.
164
+ *
165
+ * What still bounds it is createAction ergonomics. Every input is one more coin
166
+ * to reserve atomically and release if anything fails, one more sighash
167
+ * preimage formatted over a transaction that itself grows with each input (the
168
+ * signing loop below is O(n²) in preimage bytes), and one more chance for a
169
+ * stuck reservation to wedge the whole withdrawal. 32 drains any realistic
170
+ * vault in one pass while staying well inside all of that; the hard ceiling is
171
+ * the value no future tuning may exceed without redoing that reasoning. (It is
172
+ * also the vault-side control services/walletArgLimits.ts refers to — the vault
173
+ * bypasses the wallet-argument caps structurally, so this IS its bound.)
174
+ *
175
+ * Consolidation is automatic: a capped withdrawal re-vaults its remainder as one
176
+ * output, so repeated withdrawals converge on a single vault UTXO.
177
+ */
178
+ export const VAULT_MAX_INPUTS = 32
179
+ export const VAULT_HARD_MAX_INPUTS = 48
180
+
181
+ /** The subset of the wallet interface transfers depends on (injected so the
182
+ * whole module is testable without the toolbox). */
183
+ export interface VaultWallet {
184
+ createAction(args: unknown, originator: string): Promise<CreateActionResult>
185
+ signAction(args: unknown, originator: string): Promise<{ txid?: string; tx?: number[] }>
186
+ listOutputs(args: unknown, originator: string): Promise<ListOutputsResult>
187
+ getPublicKey(args: unknown, originator: string): Promise<{ publicKey: string }>
188
+ /** Signs the staging input of a deposit's tx2 (BRC-42 key, counterparty 'self'). */
189
+ createSignature(args: unknown, originator: string): Promise<{ signature: number[] }>
190
+ abortAction(args: unknown, originator: string): Promise<unknown>
191
+ listActions?(args: unknown, originator: string): Promise<{ actions: VaultActionRow[] }>
192
+ }
193
+
194
+ /** The fields of a listActions row the reservation heal needs. `inputs` arrives
195
+ * only when the call asked for `includeInputs`, and a transaction that never
196
+ * reached signing has no `txid` — which is exactly the case the outpoint match
197
+ * exists to cover. */
198
+ export interface VaultActionRow {
199
+ txid?: string
200
+ status: string
201
+ reference?: string
202
+ inputs?: { sourceOutpoint?: string }[]
203
+ }
204
+
205
+ interface CreateActionResult {
206
+ txid?: string
207
+ tx?: number[]
208
+ signableTransaction?: { tx: number[]; reference: string }
209
+ }
210
+ interface ListOutputsResult {
211
+ outputs: {
212
+ outpoint: string
213
+ satoshis: number
214
+ customInstructions?: string
215
+ }[]
216
+ /** Present when `include: 'entire transactions'` was requested — the AtomicBEEF
217
+ * (well, the multi-tx BEEF) covering every listed output's source transaction.
218
+ * Forwarded verbatim as createAction's inputBEEF; see spendVaultOutputs. */
219
+ BEEF?: number[]
220
+ }
221
+
222
+ // ── helpers ───────────────────────────────────────────────────────────────
223
+
224
+ /**
225
+ * Reserve the next deposit slot: take the next BIP32 index and lock to that
226
+ * child of the vault node. Used by both depositToVault and the withdraw path's
227
+ * re-vaulted-remainder output.
228
+ *
229
+ * `hd` is caller-owned and operation-scoped — read from the armed handle at
230
+ * the call site, never held here. There is no stored xpub to fall back on:
231
+ * without a node in hand this function cannot produce an address at all, which
232
+ * is exactly the property that makes every deposit a deliberate tap.
233
+ */
234
+ async function nextDepositTarget(hd: HD): Promise<{
235
+ instructions: VaultInstructions
236
+ lockingScript: string
237
+ }> {
238
+ const index = await vaultStore.takeNextIndex()
239
+ if (index == null) throw new VaultError('not-enrolled', 'Vault is not set up')
240
+ const script = buildVaultLockingScript({ k1PublicKeyHash: depositPubKeyHash(hd, index) })
241
+ return {
242
+ instructions: { v: 3, type: 'K1', keyID: bip32KeyID(index) },
243
+ lockingScript: script.toHex()
244
+ }
245
+ }
246
+
247
+ /** True for the toolbox's WERR_REVIEW_ACTIONS — an undelayed action that needs
248
+ * review, in our case a double-spend against a vault UTXO still reserved by a
249
+ * stuck prior attempt whose reserving transaction DOES have a txid. */
250
+ function isReviewActionsError(e: unknown): boolean {
251
+ if (!e || typeof e !== 'object') return false
252
+ const anyE = e as { code?: unknown; message?: string; reviewActionResults?: unknown }
253
+ return anyE.code === 5 || 'reviewActionResults' in anyE || /require review/i.test(anyE.message ?? '')
254
+ }
255
+
256
+ /** The txids the review error blames for the double-spend — the transactions
257
+ * still reserving our vault UTXO. */
258
+ function competingTxids(e: unknown): string[] {
259
+ const rr = (e as { reviewActionResults?: unknown }).reviewActionResults
260
+ if (!Array.isArray(rr)) return []
261
+ const out: string[] = []
262
+ for (const r of rr) {
263
+ const c = (r as { competingTxs?: unknown }).competingTxs
264
+ if (Array.isArray(c)) out.push(...(c as string[]))
265
+ }
266
+ return out
267
+ }
268
+
269
+ /** One outpoint spelling. The toolbox writes `txid:vout` into error text and
270
+ * `txid.vout` into outpoint fields; both mean the same coin. */
271
+ const sameOutpoint = (outpoint: string): string => outpoint.trim().toLowerCase().replace(':', '.')
272
+
273
+ /**
274
+ * The outpoints named by the toolbox's OTHER reservation refusal:
275
+ *
276
+ * The inputs[0] parameter must be spendable output. output <txid>:0 appears
277
+ * to have been spent (spendable=false). [WERR_INVALID_PARAMETER]
278
+ *
279
+ * This is the shape a failed withdrawal actually leaves behind. createAction
280
+ * reports a double-spend review only when the output's `spentBy` transaction
281
+ * has a txid; an attempt that died before signing never got one, so the same
282
+ * check falls through to this plain WERR_INVALID_PARAMETER instead (see
283
+ * storage/methods/createAction.js). It names the OUTPOINT and no txid, which
284
+ * is why the review-actions heal below cannot see it.
285
+ *
286
+ * Matched on the message shape, deliberately narrowly: WERR_INVALID_PARAMETER
287
+ * covers most argument mistakes, and mistaking one for a stuck reservation
288
+ * would abort transactions over an unrelated bug.
289
+ */
290
+ function unspendableInputOutpoints(e: unknown): string[] {
291
+ if (!e || typeof e !== 'object') return []
292
+ const msg = (e as { message?: string }).message ?? ''
293
+ if (!/must be spendable output/i.test(msg)) return []
294
+ return [...msg.matchAll(/\b([0-9a-fA-F]{64})[.:](\d+)\b/g)].map(m => sameOutpoint(`${m[1]}.${m[2]}`))
295
+ }
296
+
297
+ /** A locally-held reservation is never in a terminal on-chain state; these are
298
+ * the states abortAction accepts, plus 'failed' which also holds inputs. */
299
+ const ABORTABLE = new Set(['unsigned', 'nosend', 'nonfinal', 'failed'])
300
+
301
+ /**
302
+ * Page ALL actions and abort every one `matches` picks out, which resets its
303
+ * inputs' `spentBy` and frees the coin. Best-effort — returns how many were
304
+ * aborted.
305
+ *
306
+ * Pages everything rather than filtering by label: the transaction reserving a
307
+ * vault UTXO may carry no vault label of its own.
308
+ */
309
+ async function abortActions(
310
+ w: VaultWallet,
311
+ adminOriginator: string,
312
+ matches: (a: VaultActionRow) => boolean,
313
+ opts: { includeInputs?: boolean; stopAfter: number }
314
+ ): Promise<number> {
315
+ if (!w.listActions) return 0
316
+ let scanned = 0
317
+ const seen: string[] = []
318
+ // By reference, so the same orphan is never aborted twice — a second
319
+ // abortAction on it would be rejected, and counting it again would report a
320
+ // heal that did not happen.
321
+ const aborted = new Set<string>()
322
+ try {
323
+ let offset = 0
324
+ for (let page = 0; page < 25 && aborted.size < opts.stopAfter; page++) {
325
+ const res = await w.listActions(
326
+ { labels: [], limit: 200, offset, ...(opts.includeInputs ? { includeInputs: true } : {}) },
327
+ adminOriginator
328
+ )
329
+ const actions = res.actions ?? []
330
+ if (actions.length === 0) break
331
+ scanned += actions.length
332
+ for (const a of actions) {
333
+ if (!matches(a)) continue
334
+ seen.push(`${a.status}${a.reference ? '' : '/no-ref'}`)
335
+ if (a.reference && ABORTABLE.has(a.status) && !aborted.has(a.reference)) {
336
+ aborted.add(a.reference)
337
+ await w.abortAction({ reference: a.reference }, adminOriginator).catch(err =>
338
+ console.log('[vault] abortAction rejected:', (err as Error)?.message)
339
+ )
340
+ }
341
+ }
342
+ offset += actions.length
343
+ }
344
+ console.log(
345
+ '[vault] abort scan · scanned=%d · matches=[%s] · aborted=%d',
346
+ scanned,
347
+ seen.join(', ') || 'NONE',
348
+ aborted.size
349
+ )
350
+ } catch (e) {
351
+ console.log('[vault] abort scan error:', (e as Error)?.message)
352
+ }
353
+ return aborted.size
354
+ }
355
+
356
+ /** Abort the orphaned transactions the review error blames, by txid. */
357
+ async function abortReservingTxids(w: VaultWallet, adminOriginator: string, txids: string[]): Promise<number> {
358
+ if (txids.length === 0) return 0
359
+ const want = new Set(txids)
360
+ return await abortActions(w, adminOriginator, a => a.txid != null && want.has(a.txid), { stopAfter: want.size })
361
+ }
362
+
363
+ /** Abort the orphaned transactions holding these outpoints, matched on each
364
+ * action's own input list — the only handle available when the reservation has
365
+ * no txid to blame. */
366
+ async function abortReservingOutpoints(
367
+ w: VaultWallet,
368
+ adminOriginator: string,
369
+ outpoints: string[],
370
+ findSpendingReferences?: SpendingReferenceLookup
371
+ ): Promise<number> {
372
+ if (outpoints.length === 0) return 0
373
+
374
+ // One indexed query when storage is reachable. The scan below answers the
375
+ // same question by paging up to 5,000 actions with includeInputs, and
376
+ // listActionsSql answers each page by loading every action's full rawTx and
377
+ // running Transaction.fromBinary on it to read a sequence number — so a vault
378
+ // retry parsed thousands of transactions to find one outpoint.
379
+ if (findSpendingReferences) {
380
+ try {
381
+ const rows = await findSpendingReferences(outpoints)
382
+ const aborted = new Set<string>()
383
+ for (const r of rows) {
384
+ if (!ABORTABLE.has(r.status) || aborted.has(r.reference)) continue
385
+ aborted.add(r.reference)
386
+ await w.abortAction({ reference: r.reference }, adminOriginator).catch(err =>
387
+ console.log('[vault] abortAction rejected:', (err as Error)?.message)
388
+ )
389
+ }
390
+ console.log('[vault] abort by outpoint · matched=%d · aborted=%d', rows.length, aborted.size)
391
+ return aborted.size
392
+ } catch (e) {
393
+ // A storage failure must not cost the retry: fall through to the scan.
394
+ console.log('[vault] spending-reference lookup failed, falling back to scan:', (e as Error)?.message)
395
+ }
396
+ }
397
+
398
+ const want = new Set(outpoints.map(sameOutpoint))
399
+ return await abortActions(
400
+ w,
401
+ adminOriginator,
402
+ a => (a.inputs ?? []).some(i => i.sourceOutpoint != null && want.has(sameOutpoint(i.sourceOutpoint))),
403
+ // No count to stop at: one orphan can hold several of our outpoints, and
404
+ // several orphans can each hold one. The 25-page cap is the bound.
405
+ { includeInputs: true, stopAfter: Number.POSITIVE_INFINITY }
406
+ )
407
+ }
408
+
409
+ /**
410
+ * Free a vault UTXO that a previous failed attempt left reserved, so the caller
411
+ * can retry once. Returns how many orphaned transactions were aborted — zero
412
+ * means "not a reservation failure, or nothing could be freed", and the caller
413
+ * must rethrow the original error rather than retry.
414
+ *
415
+ * `ours` bounds the damage: only a reservation on an outpoint THIS withdrawal
416
+ * is trying to spend justifies aborting somebody else's transaction.
417
+ */
418
+ async function freeReservedInputs(
419
+ w: VaultWallet,
420
+ adminOriginator: string,
421
+ e: unknown,
422
+ ours: string[],
423
+ findSpendingReferences?: SpendingReferenceLookup
424
+ ): Promise<number> {
425
+ if (isReviewActionsError(e)) {
426
+ return await abortReservingTxids(w, adminOriginator, competingTxids(e))
427
+ }
428
+ const mine = new Set(ours.map(sameOutpoint))
429
+ const wedged = unspendableInputOutpoints(e).filter(o => mine.has(o))
430
+ return await abortReservingOutpoints(w, adminOriginator, wedged, findSpendingReferences)
431
+ }
432
+
433
+ /**
434
+ * Refuse a vault transfer while offline.
435
+ *
436
+ * Checked before anything else: before the deposit's backup attestation, and
437
+ * before the withdrawal arms the YubiKey — an offline user must not be asked to
438
+ * present a key for a transfer that cannot proceed.
439
+ */
440
+ async function requireOnline(opts?: VaultTransferOptions): Promise<void> {
441
+ if (!opts?.isOnline) return
442
+ if (!(await opts.isOnline())) {
443
+ throw new VaultError('requires-online', 'Vault transfers need a connection')
444
+ }
445
+ }
446
+
447
+ // ── balance ─────────────────────────────────────────────────────────────
448
+
449
+ export async function getVaultBalance(w: VaultWallet, adminOriginator: string): Promise<number> {
450
+ const res = await w.listOutputs({ basket: VAULT_BASKET, limit: 1000 }, adminOriginator)
451
+ return res.outputs.reduce((sum, o) => sum + (o.satoshis ?? 0), 0)
452
+ }
453
+
454
+ // ── deposit ─────────────────────────────────────────────────────────────
455
+
456
+ /**
457
+ * Move `satoshis` from the default basket into the vault.
458
+ *
459
+ * Costs exactly one tap, and every refusal is checked BEFORE it: a user must
460
+ * never be asked to present a key for a transfer that was never going to
461
+ * proceed, and — because the tap gates the derivation, and nothing is spent
462
+ * until the single createAction below it — cancelling it moves no money.
463
+ *
464
+ * `reason` is what the ceremony sheet shows while the key is armed.
465
+ */
466
+ export async function depositToVault(
467
+ w: VaultWallet,
468
+ adminOriginator: string,
469
+ satoshis: number,
470
+ reason: string,
471
+ opts?: VaultTransferOptions
472
+ ): Promise<{ txid: string }> {
473
+ await requireOnline(opts)
474
+
475
+ // Depositing into a wallet with no recovery path would hide funds behind a
476
+ // hardware key the user cannot get past. Advisory — the wizard is the real
477
+ // gate — but it also covers the deep link straight to the transfer screen.
478
+ //
479
+ // DELIBERATELY NOT in nextDepositTarget, even though that is the single
480
+ // funnel for every vault-basket output: partial withdrawals re-vault their
481
+ // remainder through it, so a check there would block withdrawals.
482
+ //
483
+ // Checked BEFORE the tap (and so before nextDepositTarget) so a refusal
484
+ // neither raises a ceremony nor burns a deposit index.
485
+ const { publicKey: identityKey } = await w.getPublicKey({ identityKey: true }, adminOriginator)
486
+ if (!(await backupAttestation.get(identityKey))) {
487
+ throw new VaultError('backup-required', 'Back up this wallet before depositing')
488
+ }
489
+
490
+ // ── the tap ─────────────────────────────────────────────────────────────
491
+ //
492
+ // A deposit address is a child of the vault node and there is no stored
493
+ // xpub, so this is the only way to produce one. release() in the finally is
494
+ // what drops the key and (on iOS) dismisses the NFC sheet — it must fire
495
+ // whether the deposit succeeds or fails to build.
496
+ const handle = await requestVaultKey(reason)
497
+ try {
498
+ return await lockDeposit(w, adminOriginator, satoshis, handle)
499
+ } finally {
500
+ handle.release()
501
+ }
502
+ }
503
+
504
+ /**
505
+ * The deposit itself, run inside an armed ceremony: ONE ordinary createAction
506
+ * carrying the vault output, funded by the toolbox's own coin selection and
507
+ * change machinery.
508
+ *
509
+ * This used to be two chained transactions (tx1 staged exact funding into
510
+ * VAULT_STAGING_BASKET, tx2 spent only that into the vault) so that the
511
+ * ~960 KB R1-K1 script never shared a transaction with a default-basket
512
+ * change output — change born next to it dragged the whole script into the
513
+ * inputBEEF of every later payment that spent that change. A K1 vault output
514
+ * is a 25-byte P2PKH lock, so that cost is gone and the deposit is one
515
+ * transaction like any other spend. The 'vault-deposit' label still matters:
516
+ * the patched toolbox (see patches/) suppresses UTXO-pool growth for it, so
517
+ * the deposit stays minimal — at most one change output — instead of
518
+ * splitting change toward numberOfDesiredUTXOs.
519
+ *
520
+ * `handle` is operation-scoped: `hd` is read once, at its only point of use,
521
+ * and neither the handle nor the node is stored anywhere that outlives this
522
+ * call (see VaultKeyHandle). A released or relocked handle refuses there.
523
+ *
524
+ * KNOWN TRADE: the deposit index is taken BEFORE createAction, so a funding
525
+ * failure (insufficient change for deposit + fee) burns an index the old
526
+ * two-tx flow would not have (its derivation ran only after tx1 landed).
527
+ * Accepted deliberately: index holes are harmless — withdraw and sweep read
528
+ * each output's STORED keyID, nothing ever walks the index space — and the
529
+ * alternative (deriving after createAction) would spend real money before
530
+ * knowing an address exists for it.
531
+ */
532
+ async function lockDeposit(
533
+ w: VaultWallet,
534
+ adminOriginator: string,
535
+ satoshis: number,
536
+ handle: VaultKeyHandle
537
+ ): Promise<{ txid: string }> {
538
+ // Announce work before starting it: the ceremony sheet is on screen for the
539
+ // whole deposit, and this also refreshes the retention window so a slow
540
+ // createAction cannot have the key relocked out from under it.
541
+ noteVaultProgress({ phase: 'preparing' })
542
+ const target = await nextDepositTarget(handle.hd)
543
+
544
+ // One call builds, signs AND broadcasts: with no caller-supplied inputs
545
+ // there is no signableTransaction step — every funding input is toolbox
546
+ // change the toolbox signs itself. Undelayed, so a failed broadcast surfaces
547
+ // here rather than leaving the deposit looking sent while it sits in the
548
+ // monitor's queue.
549
+ noteVaultProgress({ phase: 'broadcasting' })
550
+ const created = await w.createAction(
551
+ {
552
+ description: 'Move to vault',
553
+ outputs: [
554
+ {
555
+ satoshis,
556
+ lockingScript: target.lockingScript,
557
+ outputDescription: 'Vault deposit',
558
+ basket: VAULT_BASKET,
559
+ customInstructions: encodeVaultInstructions(target.instructions),
560
+ tags: ['vault']
561
+ }
562
+ ],
563
+ labels: ['vault', 'vault-deposit'],
564
+ options: { randomizeOutputs: false, acceptDelayedBroadcast: false }
565
+ },
566
+ adminOriginator
567
+ )
568
+ const txid = created.txid ?? (created.tx ? Transaction.fromAtomicBEEF(created.tx).id('hex') : undefined)
569
+ if (!txid) throw new VaultError('no-transaction', 'Deposit produced no transaction')
570
+ return { txid }
571
+ }
572
+
573
+ // ── legacy staging reclaim ────────────────────────────────────────────────
574
+
575
+ export interface ReclaimResult {
576
+ /** Absent when there was nothing to reclaim. */
577
+ txid?: string
578
+ /** How many staging outputs the reclaim spent. */
579
+ reclaimed: number
580
+ /** Their total value (the fee comes out of it; the rest returns as change). */
581
+ satoshis: number
582
+ }
583
+
584
+ /**
585
+ * Recover money the retired two-transaction deposit stranded.
586
+ *
587
+ * The old flow could leave a funded staging output behind (tx1 landed, tx2
588
+ * failed — the 2026-08-22 device crash mid-deposit is exactly this shape),
589
+ * and that money is INVISIBLE: the main balance counts only the 'default'
590
+ * basket and the vault balance only 'admin vault', so a stranded coin shows
591
+ * up in neither. Now that deposits no longer consume staging outputs, this
592
+ * sweep is the only way that money comes back.
593
+ *
594
+ * Spends EVERY decodable staging output regardless of amount — unlike the old
595
+ * deposit-time reuse, which matched by exact satoshis — with no outputs of its
596
+ * own, so the toolbox returns the whole value (minus fee) as default-basket
597
+ * change. The staging key is an ordinary BRC-42 wallet key (counterparty
598
+ * 'self'), so no ceremony, no tap, no vault HD node is involved.
599
+ *
600
+ * Safe to call speculatively: returns {reclaimed: 0} without touching the
601
+ * wallet when the basket is empty.
602
+ */
603
+ export async function reclaimStagingOutputs(
604
+ w: VaultWallet,
605
+ adminOriginator: string,
606
+ opts?: {
607
+ /**
608
+ * Storage-backed release of staging outputs stranded by a definitively
609
+ * invalid spender. Returns how many outputs were made spendable again.
610
+ *
611
+ * Runs FIRST because a stranded coin usually sits spendable=0: when the
612
+ * old tx2 failed, the toolbox restored its inputs but then re-stranded
613
+ * them — markStaleInputsAsSpent asked the indexers whether the staging
614
+ * outpoint was a UTXO seconds after tx1 broadcast, and indexer lag
615
+ * answered "no" — and listOutputs only returns spendable coins. See
616
+ * releaseVaultStagingStrandedByInvalidTx in StorageExpoSQLite for the
617
+ * deliberately narrow predicate.
618
+ */
619
+ releaseStrandedStaging?: () => Promise<number>
620
+ /** Storage-backed reservation heal for the retry below. See SpendingReferenceLookup. */
621
+ findSpendingReferences?: SpendingReferenceLookup
622
+ }
623
+ ): Promise<ReclaimResult> {
624
+ if (opts?.releaseStrandedStaging) {
625
+ await opts.releaseStrandedStaging().catch(e => {
626
+ console.log('[vault] stranded-staging release failed:', (e as Error)?.message)
627
+ return 0
628
+ })
629
+ }
630
+
631
+ const staged = (await w.listOutputs(
632
+ { basket: VAULT_STAGING_BASKET, include: 'entire transactions', includeCustomInstructions: true, limit: 100 },
633
+ adminOriginator
634
+ )) as ListOutputsResult
635
+ const coins = staged.outputs
636
+ .map(o => ({ ...o, si: decodeStagingInstructions(o.customInstructions) }))
637
+ .filter((o): o is typeof o & { si: StagingInstructions } => o.si != null)
638
+ if (coins.length === 0) return { reclaimed: 0, satoshis: 0 }
639
+
640
+ const totalSats = coins.reduce((s, c) => s + c.satoshis, 0)
641
+ const caArgs = {
642
+ description: 'Recover vault deposit funding',
643
+ inputs: coins.map(c => ({
644
+ outpoint: c.outpoint,
645
+ unlockingScriptLength: STAGING_UNLOCK_LEN,
646
+ inputDescription: 'Stranded vault deposit funding'
647
+ })),
648
+ outputs: [],
649
+ // 'vault-deposit' is load-bearing twice: the patched toolbox suppresses
650
+ // UTXO-pool growth for it (no extra funding inputs pulled in), and the
651
+ // stranded-release predicates (both arms — spendable=0 re-strands AND
652
+ // stale spentBy on spendable=1 coins, see findSql.ts) match on it — so if
653
+ // THIS transaction fails at broadcast and re-strands the coins, the same
654
+ // heal releases them for the next attempt. 'vault-reclaim' is for
655
+ // history and forensics only.
656
+ labels: ['vault', 'vault-deposit', 'vault-reclaim'],
657
+ // Mandatory, not an optimization: these inputs carry unlockingScriptLength
658
+ // and no unlockingScript, so isSignAction is true and the signer resolves
659
+ // each input's sourceTransaction ONLY from args.inputBEEF. trustSelf just
660
+ // skips storage re-walking proof ancestry for our own coins.
661
+ inputBEEF: staged.BEEF?.length ? staged.BEEF : undefined,
662
+ options: { randomizeOutputs: false, acceptDelayedBroadcast: false, trustSelf: 'known' }
663
+ }
664
+ let created: CreateActionResult
665
+ try {
666
+ created = await w.createAction(caArgs, adminOriginator)
667
+ } catch (e) {
668
+ // A prior failed attempt (or a concurrent reclaim from a quick screen
669
+ // remount) can leave a coin reserved by an orphaned transaction, and until
670
+ // that is aborted every later reclaim is refused outright — the same
671
+ // wedge the withdraw path heals. Abort it and retry ONCE; anything else
672
+ // frees nothing and rethrows untouched.
673
+ const freed = await freeReservedInputs(
674
+ w,
675
+ adminOriginator,
676
+ e,
677
+ coins.map(c => c.outpoint),
678
+ opts?.findSpendingReferences
679
+ )
680
+ if (freed === 0) throw e
681
+ created = await w.createAction(caArgs, adminOriginator)
682
+ }
683
+
684
+ if (!created.signableTransaction) {
685
+ const txid = created.txid ?? (created.tx ? Transaction.fromAtomicBEEF(created.tx).id('hex') : undefined)
686
+ if (!txid) throw new VaultError('no-transaction', 'Reclaim produced no transaction')
687
+ return { txid, reclaimed: coins.length, satoshis: totalSats }
688
+ }
689
+
690
+ const { tx: atomic, reference } = created.signableTransaction
691
+ const spends: Record<number, { unlockingScript: string }> = {}
692
+ try {
693
+ const tx = Transaction.fromAtomicBEEF(atomic)
694
+ for (const c of coins) {
695
+ // Preimage formatting is O(tx size) per input; yield between inputs so a
696
+ // large reclaim cannot hang the JS thread (same reasoning as the
697
+ // withdraw signing loop below).
698
+ await new Promise<void>(resolve => setTimeout(resolve, 0))
699
+
700
+ // The toolbox is free to add funding inputs of its own, so each staging
701
+ // input is located by outpoint, never assumed by position — and the
702
+ // signature commits to EVERY input via otherInputs, or the nodes reject
703
+ // the spend with "false stack entry at end of script execution" (the
704
+ // 2026-08-21 production deposit failure).
705
+ const [cTxid, cVoutStr] = c.outpoint.split('.')
706
+ const cVout = Number(cVoutStr)
707
+ const inputIndex = tx.inputs.findIndex(
708
+ i =>
709
+ (i.sourceTXID ?? i.sourceTransaction?.id('hex'))?.toLowerCase() === cTxid.toLowerCase() &&
710
+ i.sourceOutputIndex === cVout
711
+ )
712
+ if (inputIndex < 0) {
713
+ throw new VaultError('no-transaction', 'Staging input missing from the signable transaction')
714
+ }
715
+ const { publicKey: stagingPub } = await w.getPublicKey(
716
+ { protocolID: STAGING_PROTOCOL, keyID: c.si.keyID, counterparty: 'self' },
717
+ adminOriginator
718
+ )
719
+ const subscript = new P2PKH().lock(PublicKey.fromString(stagingPub).toAddress())
720
+ const input = tx.inputs[inputIndex]
721
+ const scope = TransactionSignature.SIGHASH_ALL | TransactionSignature.SIGHASH_FORKID
722
+ const preimage = TransactionSignature.format({
723
+ sourceTXID: cTxid,
724
+ sourceOutputIndex: input.sourceOutputIndex,
725
+ sourceSatoshis: c.satoshis,
726
+ transactionVersion: tx.version,
727
+ otherInputs: tx.inputs.filter((_, i) => i !== inputIndex),
728
+ outputs: tx.outputs,
729
+ inputIndex,
730
+ inputSequence: input.sequence ?? 0xffffffff,
731
+ subscript,
732
+ lockTime: tx.lockTime,
733
+ scope
734
+ })
735
+ const { signature } = await w.createSignature(
736
+ {
737
+ protocolID: STAGING_PROTOCOL,
738
+ keyID: c.si.keyID,
739
+ counterparty: 'self',
740
+ hashToDirectlySign: Array.from(Hash.hash256(preimage))
741
+ },
742
+ adminOriginator
743
+ )
744
+ spends[inputIndex] = {
745
+ unlockingScript: new UnlockingScript([
746
+ { op: signature.length + 1, data: [...signature, scope] },
747
+ { op: 33, data: Utils.toArray(stagingPub, 'hex') }
748
+ ]).toHex()
749
+ }
750
+ }
751
+ } catch (e) {
752
+ // Nothing was signed: release the reservation so the coins stay listed
753
+ // for the next reclaim attempt.
754
+ await w.abortAction({ reference }, adminOriginator).catch(() => {})
755
+ throw e
756
+ }
757
+
758
+ const signed = await w.signAction(
759
+ { reference, spends, options: { acceptDelayedBroadcast: false } },
760
+ adminOriginator
761
+ )
762
+ const txid = signed.txid ?? (signed.tx ? Transaction.fromAtomicBEEF(signed.tx).id('hex') : undefined)
763
+ if (!txid) throw new VaultError('no-transaction', 'Reclaim produced no transaction')
764
+ return { txid, reclaimed: coins.length, satoshis: totalSats }
765
+ }
766
+
767
+
768
+ // ── withdraw / sweep (shared spend core) ─────────────────────────────────
769
+
770
+ /**
771
+ * How a spend reaches the vault key: a thunk, read at every point of use.
772
+ *
773
+ * There is only one key and only one script family left, so there is nothing to
774
+ * discriminate on — a withdrawal (tap-unwrapped) and a recovery sweep
775
+ * (mnemonic + passphrase) hand over the same node. What differs is REVOCABILITY,
776
+ * and that is why this is a thunk rather than the node itself.
777
+ *
778
+ * A withdrawal passes `() => handle.hd`, so every read goes back through
779
+ * VaultKeyHandle's getter — the one thing that can refuse. Dereferencing once
780
+ * up front would hand this module a raw node that outlives the ceremony's
781
+ * opinion of it: cancel(), a key detaching, and the retention ceiling
782
+ * (armedAt + 3×) would all become advisory mid-withdrawal, exactly the
783
+ * "a reference the caller already took is beyond its reach" case
784
+ * VaultKeyHandle's docblock warns about. With the thunk, a relock lands on the
785
+ * next derive and unwinds through the abort path below.
786
+ *
787
+ * The sweep wraps its caller-owned node as `() => hd`: no ceremony exists to
788
+ * revoke it, so the thunk is transparent there.
789
+ */
790
+ type VaultKeySource = () => HD
791
+
792
+ /** One selected vault input, resolved against the key that will spend it. */
793
+ interface PreparedSpend<T> {
794
+ o: T
795
+ /** BIP32 child index this output's keyID names. */
796
+ index: number
797
+ /** The output's REAL locking script, read from the listed BEEF. */
798
+ lockingScript: LockingScript
799
+ }
800
+
801
+ /**
802
+ * Resolve every selected input's derivation index and prevout script, and
803
+ * prove the key in hand actually opens it.
804
+ *
805
+ * THE WRONG-KEY CHECK, and it runs before the caller reserves, burns, or signs
806
+ * anything: not one createAction has been issued when this throws, so a
807
+ * mismatch costs no reservation to unwind and no deposit index. That matters
808
+ * twice over.
809
+ *
810
+ * - On a withdrawal it is the "wrong YubiKey" signal: a card enrolled against
811
+ * a different seed unwraps a different node, whose children hash to
812
+ * different addresses than the ones these outputs are locked to.
813
+ * - On the recovery sweep it is the PASSPHRASE-TYPO guard. A mistyped vault
814
+ * passphrase yields a valid-looking HD node that simply is not this vault's,
815
+ * so EVERY output mismatches. Without this the sweep would happily build a
816
+ * transaction signed with the wrong keys — or, worse, a future
817
+ * "skip what we can't sign" refinement would report an empty vault and let
818
+ * the user believe their funds were gone. It has to be loud.
819
+ *
820
+ * The comparison is against the script the output is ACTUALLY locked with (out
821
+ * of the BEEF the same listOutputs call returned), never a script rebuilt from
822
+ * the output's own customInstructions — a rebuild is self-consistent by
823
+ * construction and can never disagree with itself.
824
+ *
825
+ * `getHd()` is called per input rather than once: a relock partway through
826
+ * refuses on the next input instead of quietly finishing the pass with a key
827
+ * the ceremony has already declared dead. Nothing has been reserved yet, so
828
+ * that refusal costs nothing at all.
829
+ */
830
+ function prepareSpends<T extends { outpoint: string; satoshis: number; ci: VaultInstructions }>(
831
+ selected: T[],
832
+ getHd: VaultKeySource,
833
+ beefBytes?: number[]
834
+ ): PreparedSpend<T>[] {
835
+ const sources = beefBytes?.length ? Beef.fromBinary(beefBytes) : undefined
836
+ return selected.map(o => {
837
+ const index = indexFromKeyID(o.ci.keyID)
838
+ if (index == null) throw new VaultError('bad-derivation-index', `Not a BIP32 vault output: ${o.ci.keyID}`)
839
+
840
+ const [txid, voutStr] = o.outpoint.split('.')
841
+ // Beef indexes by exact txid string; storage writes lowercase, but so does
842
+ // every other txid comparison in this file — match them rather than trust it.
843
+ const lockingScript = sources?.findTxid(txid.toLowerCase())?.tx?.outputs[Number(voutStr)]?.lockingScript
844
+ if (!lockingScript) {
845
+ // Fail closed rather than sign blind: without the prevout script there is
846
+ // nothing to check the derived child against — and createAction would
847
+ // refuse this input moments later anyway (see the listOutputs comment).
848
+ throw new VaultError('no-transaction', `No source transaction for vault output ${o.outpoint}`)
849
+ }
850
+
851
+ const mine = buildVaultLockingScript({ k1PublicKeyHash: depositPubKeyHash(getHd(), index) })
852
+ if (mine.toHex() !== lockingScript.toHex()) {
853
+ throw new VaultError(
854
+ 'wrong-key',
855
+ 'This vault output was locked to a different key — wrong YubiKey, or wrong vault passphrase'
856
+ )
857
+ }
858
+ return { o, index, lockingScript }
859
+ })
860
+ }
861
+
862
+ async function spendVaultOutputs(
863
+ w: VaultWallet,
864
+ adminOriginator: string,
865
+ amount: number | 'all',
866
+ reason: string,
867
+ getHd: VaultKeySource,
868
+ opts: { revaultRemainder: boolean } & VaultTransferOptions
869
+ ): Promise<VaultSpendResult> {
870
+ // Announce work BEFORE starting it, then hand the JS thread back once so
871
+ // React can actually paint the sheet. listOutputs and createAction both cross
872
+ // the bridge and touch the database; without this yield the phase change is
873
+ // queued behind that work and the user stares at a frozen screen anyway.
874
+ noteVaultProgress({ phase: 'preparing' })
875
+ await new Promise<void>(resolve => setTimeout(resolve, 0))
876
+
877
+ // `include: 'entire transactions'` IS required, and for two reasons.
878
+ //
879
+ // The first is structural: every input here carries unlockingScriptLength but
880
+ // no unlockingScript, so @bsv/sdk's validateCreateActionArgs sets
881
+ // isSignAction=true for this createAction call. buildSignableTransaction
882
+ // then resolves each input's sourceTransaction ONLY from args.inputBEEF
883
+ // (buildSignableTransaction.js:14,101) — trustSelf and storage's own
884
+ // "known input" shortcut (storage/methods/createAction.js's
885
+ // localKnownInputTxids) are a STORAGE-side allowance to skip merkle-proof
886
+ // verification, not a substitute for the client supplying inputBEEF at all.
887
+ // Omit it and createAction.js's makeSignableTransactionBeef throws
888
+ // WERR_INTERNAL('Every signableTransaction input must have a
889
+ // sourceTransaction') on the very first input, before signing ever starts.
890
+ // (reclaimStagingOutputs is in the same boat, not exempt from it: its
891
+ // staging inputs also carry an unlockingScriptLength with no
892
+ // unlockingScript, so isSignAction is true there too. It needs no separate
893
+ // note here because it already threads `staged.BEEF` through as inputBEEF
894
+ // for exactly this reason.)
895
+ //
896
+ // The second is the wrong-key check below: the BEEF is where each vault
897
+ // output's REAL locking script comes from, which is what the derived child
898
+ // is compared against. `include` is one-of ('locking scripts' OR 'entire
899
+ // transactions' — see the SDK's validateListOutputsArgs), so this call
900
+ // cannot ask for both, and the BEEF is the one that is mandatory anyway.
901
+ //
902
+ // Under K1 the whole payload is ordinary-sized — a vault source transaction
903
+ // is a few hundred bytes, not the ~1.83 MB per input the R1-K1 script cost.
904
+ // includeCustomInstructions IS also required: listOutputs omits that field
905
+ // unless asked, and without it every output filters out as unreadable.
906
+ const list = await w.listOutputs(
907
+ { basket: VAULT_BASKET, include: 'entire transactions', includeCustomInstructions: true, limit: 1000 },
908
+ adminOriginator
909
+ )
910
+ const spendable = list.outputs
911
+ .map(o => ({ ...o, ci: decodeVaultInstructions(o.customInstructions) }))
912
+ .filter((o): o is typeof o & { ci: VaultInstructions } => o.ci != null)
913
+ .sort((a, b) => b.satoshis - a.satoshis) // largest first
914
+ if (spendable.length === 0) throw new VaultError('vault-empty', 'Vault is empty')
915
+
916
+ const total = spendable.reduce((s, o) => s + o.satoshis, 0)
917
+ if (amount !== 'all' && amount > total) {
918
+ throw new VaultError('amount-exceeds-balance', 'Withdrawal exceeds vault balance')
919
+ }
920
+
921
+ // Bounded input count — see VAULT_MAX_INPUTS for what the bound is defending
922
+ // against now that the scripts are 25/~107 bytes rather than ~960 KB.
923
+ //
924
+ // Largest first (already sorted), so the fewest inputs cover the most value.
925
+ const cap = Math.min(VAULT_MAX_INPUTS, VAULT_HARD_MAX_INPUTS)
926
+ const selected = spendable.slice(0, cap)
927
+ const acc = selected.reduce((s, o) => s + o.satoshis, 0)
928
+ const remainingInputs = spendable.length - selected.length
929
+
930
+ // 'all' means "as much as one safe transaction can carry"; the untouched
931
+ // outputs stay in the vault and the re-vaulted remainder consolidates what was
932
+ // spent, so repeating the withdrawal drains it.
933
+ const want = amount === 'all' ? acc : amount
934
+ if (want > acc) {
935
+ // The vault holds enough (checked above) but not within the input cap. Say
936
+ // so, rather than blaming the balance: the remedy is a smaller withdrawal,
937
+ // which also consolidates and makes the next one cheaper.
938
+ throw new VaultError(
939
+ 'too-many-inputs',
940
+ `Withdrawing ${want} satoshis would need more than ${cap} vault inputs; withdraw a smaller amount first`
941
+ )
942
+ }
943
+
944
+ // Resolve every selected input against the key in hand BEFORE anything is
945
+ // reserved, burned, or signed — see prepareSpends.
946
+ const prepared = prepareSpends(selected, getHd, list.BEEF)
947
+
948
+ const outputs: unknown[] = []
949
+ const remainder = acc - want
950
+ // A sub-floor remainder is folded into the withdrawal rather than re-vaulted:
951
+ // an output below VAULT_DEPOSIT_MIN is not worth what it costs to move. It
952
+ // still reaches the user — as part of the toolbox's own default-basket
953
+ // change alongside the withdrawn amount — it is just not re-vaulted.
954
+ //
955
+ // The SAME node the inputs were checked against locks it: one tap covers a
956
+ // withdrawal and its own change output, and a wrong-key failure above has
957
+ // already aborted without burning an index here. Read through the thunk (and
958
+ // BEFORE takeNextIndex, inside nextDepositTarget) so a relock at this instant
959
+ // refuses without burning an index either.
960
+ if (opts.revaultRemainder && remainder >= VAULT_DEPOSIT_MIN) {
961
+ const target = await nextDepositTarget(getHd())
962
+ outputs.push({
963
+ satoshis: remainder,
964
+ lockingScript: target.lockingScript,
965
+ outputDescription: 'Vault change',
966
+ basket: VAULT_BASKET,
967
+ customInstructions: encodeVaultInstructions(target.instructions),
968
+ tags: ['vault']
969
+ })
970
+ }
971
+
972
+ const caArgs = {
973
+ description: reason,
974
+ inputs: selected.map(o => ({
975
+ outpoint: o.outpoint,
976
+ unlockingScriptLength: K1_UNLOCK_LEN,
977
+ inputDescription: 'Vault withdrawal'
978
+ })),
979
+ outputs,
980
+ labels: ['vault', 'vault-withdraw'],
981
+ // inputBEEF, from the 'entire transactions' listOutputs call above — see
982
+ // the comment there for why this is required, not optional. trustSelf:
983
+ // 'known' is kept alongside it: it is what lets storage skip re-walking
984
+ // each source transaction's own merkle-proof ancestry for a basket this
985
+ // wallet already trusts (its own prior deposits), rather than what makes
986
+ // inputBEEF itself unnecessary.
987
+ inputBEEF: list.BEEF?.length ? list.BEEF : undefined,
988
+ options: { randomizeOutputs: false, acceptDelayedBroadcast: false, trustSelf: 'known' }
989
+ }
990
+
991
+ let created: CreateActionResult
992
+ try {
993
+ created = await w.createAction(caArgs, adminOriginator)
994
+ } catch (e) {
995
+ // A prior failed attempt can leave a vault UTXO reserved by an orphaned
996
+ // transaction, and until it is aborted every later withdrawal is refused
997
+ // outright. Two error shapes, depending on whether the orphan ever got a
998
+ // txid — see freeReservedInputs. Abort it and retry ONCE; anything else
999
+ // frees nothing and rethrows untouched.
1000
+ const freed = await freeReservedInputs(
1001
+ w,
1002
+ adminOriginator,
1003
+ e,
1004
+ selected.map(o => o.outpoint),
1005
+ opts.findSpendingReferences
1006
+ )
1007
+ if (freed === 0) throw e
1008
+ created = await w.createAction(caArgs, adminOriginator)
1009
+ }
1010
+
1011
+ if (!created.signableTransaction) {
1012
+ const txid = created.txid ?? (created.tx ? Transaction.fromAtomicBEEF(created.tx).id('hex') : undefined)
1013
+ if (!txid) throw new VaultError('no-transaction', 'Withdrawal produced no transaction')
1014
+ return { txid, remainingInputs }
1015
+ }
1016
+
1017
+ const { tx: atomic, reference } = created.signableTransaction
1018
+ let builtSpends: Record<number, { unlockingScript: string }>
1019
+ try {
1020
+ const tx = Transaction.fromAtomicBEEF(atomic)
1021
+ const spends: Record<number, { unlockingScript: string }> = {}
1022
+
1023
+ // SEQUENTIAL BY DESIGN, still — do not "simplify" this into an
1024
+ // unlockingScriptTemplate + tx.sign(). @bsv/sdk's Transaction.sign() fans
1025
+ // every template's sign() out through Promise.all
1026
+ // (dist/cjs/src/transaction/Transaction.js) and takes ownership of the
1027
+ // whole input set; this loop keeps each input's script ours to build, in a
1028
+ // known order, with the derived key never leaving the iteration that used
1029
+ // it. The yield is what keeps the JS thread from disappearing for the
1030
+ // length of the loop: one ECDSA signature is fast, but the preimage is
1031
+ // re-formatted over the entire transaction for every input, so the cost
1032
+ // grows with the square of the input count.
1033
+ //
1034
+ // getHd() per input, never hoisted: the loop yields between inputs, so a
1035
+ // cancel(), a detached key, or the retention ceiling can land BETWEEN two
1036
+ // signatures. Reading through the thunk turns that into a refusal on the
1037
+ // next input, which unwinds into the catch below and aborts the reservation
1038
+ // — a half-signed `spends` map never reaches signAction.
1039
+ for (let i = 0; i < prepared.length; i++) {
1040
+ await new Promise<void>(resolve => setTimeout(resolve, 0))
1041
+
1042
+ const { o, index, lockingScript } = prepared[i]
1043
+ const unlocker = new P2PKH().unlock(
1044
+ depositPrivKey(getHd(), index),
1045
+ 'all',
1046
+ false,
1047
+ o.satoshis,
1048
+ lockingScript
1049
+ )
1050
+ spends[i] = { unlockingScript: (await unlocker.sign(tx, i)).toHex() }
1051
+ }
1052
+
1053
+ builtSpends = spends
1054
+ } catch (e) {
1055
+ // Nothing was signed, so the reservation is worthless — release it, or the
1056
+ // vault UTXO stays spendable=false and the next withdrawal is refused
1057
+ // outright.
1058
+ await w.abortAction({ reference }, adminOriginator).catch(() => {})
1059
+ throw e
1060
+ }
1061
+
1062
+ // PAST THE POINT OF NO ABORT.
1063
+ //
1064
+ // acceptDelayedBroadcast: true hands the signed transaction to storage and
1065
+ // lets the monitor's SendWaiting task carry it to the network. A slow or
1066
+ // timing-out broadcaster therefore cannot cost the user a signed
1067
+ // transaction, and this call no longer waits on the network before the UI
1068
+ // can move on.
1069
+ //
1070
+ // Deliberately OUTSIDE the try above: once a transaction is signed, aborting
1071
+ // it is the dangerous move, not the safe one — the network may already have
1072
+ // accepted it, and abandoning it locally would leave the wallet blind to
1073
+ // funds that really moved. A failure here is reported as "we will try
1074
+ // again", never as a cancellation.
1075
+ noteVaultProgress({ phase: 'broadcasting' })
1076
+ const signed = await w.signAction(
1077
+ { reference, spends: builtSpends, options: { acceptDelayedBroadcast: true } },
1078
+ adminOriginator
1079
+ )
1080
+ const txid = signed.txid ?? (signed.tx ? Transaction.fromAtomicBEEF(signed.tx).id('hex') : undefined)
1081
+ if (!txid) throw new VaultError('no-transaction', 'Withdrawal produced no transaction')
1082
+ return { txid, remainingInputs }
1083
+ }
1084
+
1085
+ /**
1086
+ * Withdraw from the vault. ONE tap covers the whole transaction — every input
1087
+ * AND the re-vaulted remainder derive from the same unwrapped node — and the
1088
+ * key is always released in a finally: on iOS that is what dismisses the
1089
+ * system NFC sheet, and it must fire whether the withdrawal succeeds, fails to
1090
+ * build, or fails to sign.
1091
+ */
1092
+ export async function withdrawFromVault(
1093
+ w: VaultWallet,
1094
+ adminOriginator: string,
1095
+ amount: number | 'all',
1096
+ reason: string,
1097
+ opts?: VaultTransferOptions
1098
+ ): Promise<VaultSpendResult> {
1099
+ // Before the ceremony: no key prompt for a transfer that cannot proceed.
1100
+ await requireOnline(opts)
1101
+ const handle = await requestVaultKey(reason)
1102
+ try {
1103
+ // A THUNK, not `handle.hd` — see VaultKeySource. The spend reads it afresh
1104
+ // at every derive and every signature, so each read goes back through the
1105
+ // handle's getter and a relock (cancel, key detached, retention ceiling)
1106
+ // refuses on the next one. A normal withdrawal finishes inside the armed
1107
+ // window, but the ceiling makes that expected rather than guaranteed, so
1108
+ // "finishes in time" is not something this code may assume: a relock
1109
+ // mid-spend surfaces as key-removed-mid-op and unwinds through
1110
+ // spendVaultOutputs' abort path, leaving no reservation behind. Nothing is
1111
+ // stored here either way — the thunk closes over the handle, which dies
1112
+ // with this call.
1113
+ return await spendVaultOutputs(w, adminOriginator, amount, reason, () => handle.hd, {
1114
+ revaultRemainder: true,
1115
+ ...opts
1116
+ })
1117
+ } finally {
1118
+ handle.release()
1119
+ }
1120
+ }
1121
+
1122
+ /**
1123
+ * Recovery for a lost YubiKey: sweep the ENTIRE vault to the default basket,
1124
+ * signing with the HD node derived from the main mnemonic + vault passphrase.
1125
+ *
1126
+ * The same key the tap would have unwrapped, reached the other way — so this
1127
+ * needs no card, no ceremony, and no device-local vault state at all. A
1128
+ * mistyped passphrase is caught by prepareSpends, loudly. Returns null when
1129
+ * the vault is already empty.
1130
+ */
1131
+ export async function sweepVaultWithHD(
1132
+ w: VaultWallet,
1133
+ adminOriginator: string,
1134
+ hd: HD,
1135
+ reason: string,
1136
+ opts?: VaultTransferOptions
1137
+ ): Promise<VaultSpendResult | null> {
1138
+ await requireOnline(opts)
1139
+ try {
1140
+ // The node is the caller's own and no ceremony can revoke it, so the thunk
1141
+ // is transparent here — it exists for the withdrawal's handle (see
1142
+ // VaultKeySource).
1143
+ return await spendVaultOutputs(w, adminOriginator, 'all', reason, () => hd, {
1144
+ revaultRemainder: false,
1145
+ ...opts
1146
+ })
1147
+ } catch (e) {
1148
+ if (e instanceof VaultError && e.code === 'vault-empty') return null
1149
+ throw e
1150
+ }
1151
+ }