@bsv/expo-wallet-toolbox 0.22.0 → 0.24.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 (137) hide show
  1. package/CHANGELOG.md +241 -0
  2. package/README.md +10 -9
  3. package/android/build.gradle +15 -0
  4. package/android/src/main/AndroidManifest.xml +3 -0
  5. package/android/src/main/java/org/bsv/boundedfetch/BoundedBody.java +19 -0
  6. package/android/src/main/java/org/bsv/boundedfetch/BoundedConnection.java +28 -0
  7. package/android/src/main/java/org/bsv/boundedfetch/BsvBoundedFetchModule.kt +114 -0
  8. package/core/backup/RemoteSyncReader.ts +71 -46
  9. package/core/backup/client.ts +6 -15
  10. package/core/backup/codec.ts +78 -13
  11. package/core/backup/constants.ts +3 -9
  12. package/core/backup/cursor.ts +8 -0
  13. package/core/backup/push.ts +26 -16
  14. package/core/backup/restore.ts +6 -5
  15. package/core/bridge/BrowserBridgeProvider.tsx +273 -0
  16. package/core/bridge/bindings.ts +459 -0
  17. package/core/bridge/conformance.ts +222 -0
  18. package/core/bridge/consent.ts +494 -0
  19. package/core/bridge/consentSheetSource.ts +98 -0
  20. package/core/bridge/dispatcher.ts +621 -0
  21. package/core/bridge/inbox.ts +569 -0
  22. package/core/bridge/index.ts +48 -0
  23. package/core/bridge/loopback/cors.ts +57 -0
  24. package/core/bridge/loopback/endpoints.ts +11 -0
  25. package/core/bridge/loopback/hostCheck.ts +25 -0
  26. package/core/bridge/loopback/index.ts +7 -0
  27. package/core/bridge/loopback/launchProof.ts +166 -0
  28. package/core/bridge/loopback/router.ts +770 -0
  29. package/core/bridge/loopback/routerTypes.ts +115 -0
  30. package/core/bridge/loopback/status.ts +52 -0
  31. package/core/bridge/memoryInboxStore.ts +231 -0
  32. package/core/bridge/permissionPolicy.ts +247 -0
  33. package/core/bridge/policy.ts +72 -0
  34. package/core/bridge/protocol/base64url.ts +64 -0
  35. package/core/bridge/protocol/connectionError.ts +79 -0
  36. package/core/bridge/protocol/constants.ts +21 -0
  37. package/core/bridge/protocol/continuity.ts +21 -0
  38. package/core/bridge/protocol/descriptor.ts +395 -0
  39. package/core/bridge/protocol/envelopes.ts +188 -0
  40. package/core/bridge/protocol/errorCodec.ts +164 -0
  41. package/core/bridge/protocol/json.ts +237 -0
  42. package/core/bridge/protocol/limits.ts +43 -0
  43. package/core/bridge/protocol/methods.ts +55 -0
  44. package/core/bridge/protocol/origin.ts +130 -0
  45. package/core/bridge/runtime.ts +642 -0
  46. package/core/bridge/runtimeFlags.ts +34 -0
  47. package/core/bridge/testing/conformanceCases.ts +149 -0
  48. package/core/bridge/testing/pageClient.ts +44 -0
  49. package/core/bridge/unverifiedManager.ts +97 -0
  50. package/core/bridge/unverifiedOriginator.ts +79 -0
  51. package/core/config.tsx +1 -16
  52. package/core/constants.ts +7 -11
  53. package/core/context/WalletConnectionContext.tsx +92 -49
  54. package/core/context/WalletContext.tsx +288 -165
  55. package/core/context/sessionTeardown.ts +46 -0
  56. package/core/context/usePairingAttempt.ts +31 -0
  57. package/core/e2e/broadcaster.ts +25 -0
  58. package/core/e2e/consentFixture.ts +46 -0
  59. package/core/e2e/mode.ts +42 -0
  60. package/core/headers/OfflineFirstChaintracks.ts +57 -107
  61. package/core/headers/headerConsensus.ts +230 -0
  62. package/core/headers/headerStore.ts +344 -122
  63. package/core/headers/prewarm.ts +4 -7
  64. package/core/headers/syncHeaders.ts +82 -12
  65. package/core/hooks/usePermissionQueue.ts +89 -34
  66. package/core/i18n/translations.tsx +958 -24
  67. package/core/identity/handleRegistry/client.ts +4 -2
  68. package/core/identity/handleRegistry/resolver.ts +7 -11
  69. package/core/index.ts +17 -0
  70. package/core/localpay/pending.ts +39 -4
  71. package/core/network/boundedFetch.ts +101 -0
  72. package/core/networks.ts +11 -13
  73. package/core/pay/rails/address.ts +5 -4
  74. package/core/pay/rails/handle.ts +3 -1
  75. package/core/pay/rails/sweep.ts +791 -0
  76. package/core/peerpay/brc29.ts +4 -0
  77. package/core/peerpay/handleResendRequests.ts +15 -2
  78. package/core/peerpay/outbox.ts +115 -2
  79. package/core/profiles/assertProfileEmpty.ts +2 -2
  80. package/core/profiles/profileStore.ts +3 -2
  81. package/core/services/arcadeBroadcastProvider.ts +260 -114
  82. package/core/services/autoApprovePolicy.ts +7 -1
  83. package/core/services/capWalletArgs.ts +2 -1
  84. package/core/services/permissionPrompts.ts +132 -0
  85. package/core/services/secrets/kek.ts +5 -0
  86. package/core/services/secrets/migration.ts +27 -2
  87. package/core/services/secrets/policy.ts +6 -0
  88. package/core/services/signingPermissionPolicy.ts +230 -2
  89. package/core/services/vault/VaultKeyService.ts +5 -2
  90. package/core/services/vault/ceremony.ts +2 -2
  91. package/core/services/vault/ceremonyHost.ts +1 -1
  92. package/core/services/vault/guard.ts +20 -0
  93. package/core/services/vault/outputAuthority.ts +76 -0
  94. package/core/services/vault/transfers.ts +52 -28
  95. package/core/services/vault/vaultStore.ts +60 -14
  96. package/core/services/walletArgLimits.ts +17 -2
  97. package/core/services/walletConnectionValidation.ts +13 -1
  98. package/core/services/walletServiceConfig.ts +8 -7
  99. package/core/storage/encryptedDbImage.ts +325 -0
  100. package/core/stores/ConnectionStore.ts +17 -0
  101. package/core/toolboxConfig.ts +78 -2
  102. package/expo-module.config.json +5 -0
  103. package/ios/BoundedBody.swift +15 -0
  104. package/ios/BsvBoundedFetch.podspec +17 -0
  105. package/ios/BsvBoundedFetchModule.swift +121 -0
  106. package/package.json +12 -8
  107. package/ui/bridgeSheet/ContextRelay.tsx +86 -0
  108. package/ui/bridgeSheet/relayedContexts.ts +21 -0
  109. package/ui/components/pay/AddressReceive.tsx +6 -2
  110. package/ui/components/pay/ImportedOutboxApproval.tsx +142 -0
  111. package/ui/components/pay/PayCellRow.tsx +3 -1
  112. package/ui/components/pay/PayForm.tsx +12 -2
  113. package/ui/components/pay/RecipientField.tsx +1 -0
  114. package/ui/components/pay/RequestHub.tsx +1 -0
  115. package/ui/components/pay/UniversalSend.tsx +110 -42
  116. package/ui/components/ui/ListRow.tsx +10 -2
  117. package/ui/components/ui/PermissionSheet.tsx +534 -158
  118. package/ui/components/ui/Sheet.tsx +59 -7
  119. package/ui/components/ui/sheetResumeSignal.ts +19 -0
  120. package/ui/components/vault/KeyChooser.tsx +1 -1
  121. package/ui/components/wallet/AmountInput.tsx +4 -1
  122. package/ui/components/wallet/BackupReminderSheet.tsx +8 -1
  123. package/ui/components/wallet/BiometricAdvisoryModal.tsx +2 -0
  124. package/ui/components/wallet/ImportFromBackupPrompt.tsx +6 -1
  125. package/ui/components/wallet/ProfileButton.tsx +1 -0
  126. package/ui/exportDatabases.ts +94 -5
  127. package/ui/hooks/useExportWalletData.ts +37 -24
  128. package/ui/importDatabases.ts +154 -34
  129. package/ui/index.ts +4 -0
  130. package/ui/screens/ConnectionsScreen.tsx +12 -3
  131. package/ui/screens/PairScreen.tsx +10 -3
  132. package/ui/screens/PayScreen.tsx +1 -0
  133. package/ui/screens/TrustScreen.tsx +6 -3
  134. package/ui/screens/VaultScreen.tsx +13 -3
  135. package/ui/screens/VaultTransferScreen.tsx +6 -3
  136. package/ui/screens/WalletConfigScreen.tsx +30 -3
  137. package/ui/screens/WalletHomeScreen.tsx +7 -1
@@ -0,0 +1,791 @@
1
+ /**
2
+ * Sweep: move coins that an EXTERNAL key controls into this wallet.
3
+ *
4
+ * Two sources of external keys:
5
+ * - a WIF private key (paper wallet, exported key), see sweepWif;
6
+ * - a BIP-39 recovery phrase from another BSV wallet, see sweepMnemonic.
7
+ *
8
+ * The address rail's sweepAddress cannot do this. It internalizes outputs the
9
+ * wallet can derive a key for itself; an external key is outside the wallet's
10
+ * key tree, so its coins must be SPENT. The spend uses the wallet's own
11
+ * createAction with the external outpoints as inputs and no outputs: the
12
+ * wallet adds change outputs into its default basket, sets the fee and
13
+ * broadcasts. This module signs only the external inputs (signAction). That
14
+ * keeps fee, change, broadcast and ledger in the wallet, where they already
15
+ * work, and matches the mnemonic-to-brc100 demo that was the model for it.
16
+ *
17
+ * Every sweep is two steps, so the app can ask before it spends:
18
+ * 1. plan (planWifSweep / scanMnemonic / decideMnemonicImport): reads
19
+ * WhatsOnChain only, returns the balance, UTXO count, estimated fee and
20
+ * what it will not spend. No wallet write, no broadcast.
21
+ * 2. execute (sweepWif / sweepMnemonic): spends the plan's inputs in batches
22
+ * of at most maxInputsPerTx, one transaction per batch.
23
+ *
24
+ * What a sweep never spends:
25
+ * - 1-satoshi outputs: these are tokens (1Sat ordinals and the like), and a
26
+ * plain spend would burn them. They are reported as `token`.
27
+ * - outputs worth less than the fee for their own input: reported as `dust`.
28
+ * - outputs whose real locking script is not plain P2PKH to the swept
29
+ * address: reported as `nonstandard`.
30
+ *
31
+ * Secret material. The WIF and the phrase are never persisted, logged, or put
32
+ * into a label or description; the plan holds addresses and derivation paths,
33
+ * never keys. Byte arrays derived from them (the decoded WIF, the BIP-39 seed)
34
+ * are filled with zeros after use. JavaScript strings are immutable and a
35
+ * PrivateKey holds a BigNumber, so this module cannot wipe the caller's input
36
+ * string or the key objects; it drops its references and that is all.
37
+ */
38
+ import {
39
+ Beef,
40
+ Hash,
41
+ HD,
42
+ Mnemonic,
43
+ P2PKH,
44
+ PrivateKey,
45
+ Transaction,
46
+ UnlockingScript,
47
+ Utils,
48
+ type CreateActionArgs,
49
+ type CreateActionResult,
50
+ type SignActionArgs,
51
+ type SignActionResult,
52
+ type AbortActionArgs
53
+ } from '@bsv/sdk'
54
+ import type { BackupChain } from '../../backup/constants'
55
+ import { deriveProfileKeys } from '../../mnemonicWallet'
56
+ import type { ProfileProbe } from '../../profiles/discovery'
57
+ import { getUtxosForAddress, parseWocBeefBody, wocFetch, WocRateLimited, type Utxo, type WocConfig } from './address'
58
+
59
+ type Network = 'mainnet' | 'testnet'
60
+
61
+ /** The three wallet calls a sweep makes. A subset of WalletInterface. */
62
+ export interface SweepWallet {
63
+ createAction(args: CreateActionArgs, originator?: string): Promise<CreateActionResult>
64
+ signAction(args: SignActionArgs, originator?: string): Promise<SignActionResult>
65
+ abortAction(args: AbortActionArgs, originator?: string): Promise<unknown>
66
+ }
67
+
68
+ // ─── Keys ────────────────────────────────────────────────────────────────────
69
+
70
+ const WIF_PREFIX: Record<number, Network> = { 0x80: 'mainnet', 0xef: 'testnet' }
71
+ const ADDRESS_VERSION: Record<Network, number> = { mainnet: 0x00, testnet: 0x6f }
72
+
73
+ export interface ParsedWif {
74
+ key: PrivateKey
75
+ /** False for an old-style (uncompressed public key) WIF, the `5…` / `9…` form. */
76
+ compressed: boolean
77
+ network: Network
78
+ }
79
+
80
+ /**
81
+ * Decode a WIF private key. Accepts mainnet (0x80) and testnet (0xef), with
82
+ * and without the compression flag. The SDK's PrivateKey.fromWif refuses the
83
+ * uncompressed form and drops the network, so the decode is done here.
84
+ */
85
+ export function parseWif(wif: string): ParsedWif {
86
+ let decoded: { prefix: number[] | string; data: number[] | string }
87
+ try {
88
+ decoded = Utils.fromBase58Check(wif.trim())
89
+ } catch {
90
+ throw new Error('Not a valid private key (WIF)')
91
+ }
92
+ const prefix = decoded.prefix as number[]
93
+ const data = decoded.data as number[]
94
+ try {
95
+ const network = prefix.length === 1 ? WIF_PREFIX[prefix[0]] : undefined
96
+ if (network === undefined) throw new Error('Not a BSV private key (unknown WIF network)')
97
+ let compressed: boolean
98
+ if (data.length === 33 && data[32] === 0x01) compressed = true
99
+ else if (data.length === 32) compressed = false
100
+ else throw new Error('Not a valid private key (WIF length)')
101
+ const key = new PrivateKey(data.slice(0, 32), 16, 'be', 'error')
102
+ return { key, compressed, network }
103
+ } finally {
104
+ wipe(data)
105
+ }
106
+ }
107
+
108
+ /** Whether a string is a WIF private key, for the app's Import screen to route on. */
109
+ export function isWif(text: string): boolean {
110
+ try {
111
+ parseWif(text)
112
+ return true
113
+ } catch {
114
+ return false
115
+ }
116
+ }
117
+
118
+ /** The P2PKH address of a key, in the compressed or uncompressed public key form. */
119
+ export function addressForKey(key: PrivateKey, compressed: boolean, network: Network): string {
120
+ const pub = key.toPublicKey().encode(compressed) as number[]
121
+ return Utils.toBase58Check(Hash.hash160(pub) as number[], [ADDRESS_VERSION[network]])
122
+ }
123
+
124
+ function wipe(bytes: number[] | Uint8Array | undefined): void {
125
+ if (bytes) bytes.fill(0)
126
+ }
127
+
128
+ // ─── Derivation paths ────────────────────────────────────────────────────────
129
+
130
+ /**
131
+ * One wallet's derivation scheme. `receive` is the chain prefix: address i is
132
+ * `${receive}/${i}`. `change` is the change chain; left out, it is
133
+ * changeChainFor(receive); `null` means the scheme has none. The change chain
134
+ * is scanned only when the receive chain has at least one used address.
135
+ */
136
+ export interface SweepPathSpec {
137
+ name: string
138
+ receive: string
139
+ change?: string | null
140
+ }
141
+
142
+ /**
143
+ * The change chain of a receive chain: a trailing non-hardened `/0` becomes
144
+ * `/1` (BIP-32/44: external chain 0, internal chain 1). Undefined when the
145
+ * receive chain does not end in `/0`.
146
+ */
147
+ export function changeChainFor(receive: string): string | undefined {
148
+ const match = /^(.*)\/0$/.exec(normalizePath(receive))
149
+ return match ? `${match[1]}/1` : undefined
150
+ }
151
+
152
+ function spec(name: string, receive: string): SweepPathSpec {
153
+ return { name, receive }
154
+ }
155
+
156
+ /**
157
+ * The default scan. A PLACEHOLDER, to be replaced by the list the product
158
+ * owner supplies; pass `paths` to override it.
159
+ *
160
+ * Taken from the mnemonic-to-brc100 demo (bsv-blockchain-demos), with one
161
+ * change: the demo appends the address index straight onto `m/44'/236'/0'`
162
+ * and `m/44'/0'/0'`, which skips the BIP-44 chain level. ElectrumSV and other
163
+ * BIP-44 wallets put address i at `m/44'/coin'/0'/0/i` (change: `/1/i`), so
164
+ * those entries carry the `/0` here.
165
+ */
166
+ export const DEFAULT_SWEEP_PATHS: readonly SweepPathSpec[] = [
167
+ spec('Centbee', "m/44'/0/0"),
168
+ spec('RockWallet', "m/0'/0"),
169
+ spec('ElectrumSV', "m/44'/236'/0'/0"),
170
+ spec('BIP-44 (coin 0)', "m/44'/0'/0'/0")
171
+ ]
172
+
173
+ /** Consecutive unused addresses that end the scan of one chain. */
174
+ export const DEFAULT_GAP_LIMIT = 20
175
+ /** Hard ceiling on the index scanned in one chain, whatever the gap rule says. */
176
+ export const MAX_SCAN_INDEX = 10_000
177
+
178
+ function normalizePath(path: string): string {
179
+ return path.trim().replace(/[’h]/g, "'")
180
+ }
181
+
182
+ function assertPath(path: string): string {
183
+ const p = normalizePath(path)
184
+ if (!/^m(\/\d+'?)+$/.test(p)) throw new Error(`Invalid derivation path: ${path}`)
185
+ return p
186
+ }
187
+
188
+ // ─── WhatsOnChain reads ──────────────────────────────────────────────────────
189
+
190
+ /**
191
+ * Space WhatsOnChain requests at least `minIntervalMs` apart. The default fits
192
+ * the anonymous limit (3 requests/s); a caller with an API key can lower it.
193
+ */
194
+ export const DEFAULT_WOC_INTERVAL_MS = 350
195
+
196
+ function pacer(minIntervalMs: number): () => Promise<void> {
197
+ let last = 0
198
+ return async () => {
199
+ const wait = last + minIntervalMs - Date.now()
200
+ if (wait > 0) await new Promise(resolve => setTimeout(resolve, wait))
201
+ last = Date.now()
202
+ }
203
+ }
204
+
205
+ /**
206
+ * Whether an address has any on-chain history: the gap rule's "used".
207
+ *
208
+ * WhatsOnChain answers an address with no history with HTTP 404 and the body
209
+ * `Not Found` (checked live, Nov 2026); an unknown route answers 404 with
210
+ * `404 page not found`. Only the first means "unused". Any other failure
211
+ * throws: a scan that cannot read the chain must not report "nothing found",
212
+ * because decideMnemonicImport then restores the phrase as this wallet's root
213
+ * and the coins of the old wallet are never looked for again.
214
+ *
215
+ * (`/address/{a}/used` is not an alternative: it answered `true` for a fresh
216
+ * address in the same check.)
217
+ */
218
+ async function addressHasHistory(woc: WocConfig, address: string): Promise<boolean> {
219
+ const response = await wocFetch(woc, `${woc.apiBase}/v1/bsv/${woc.segment}/address/${address}/history`)
220
+ if (response.status === 404) {
221
+ if ((await response.text()).trim() === 'Not Found') return false
222
+ throw new Error('WhatsOnChain history lookup is not available (404)')
223
+ }
224
+ if (!response.ok) throw new Error(`WhatsOnChain history lookup failed (${response.status})`)
225
+ const body = await response.json()
226
+ if (Array.isArray(body)) return body.length > 0
227
+ if (Array.isArray(body?.result)) return body.result.length > 0
228
+ throw new Error('WhatsOnChain history lookup returned an unexpected body')
229
+ }
230
+
231
+ // ─── Plan ────────────────────────────────────────────────────────────────────
232
+
233
+ export interface SweepInput extends Utxo {
234
+ address: string
235
+ /** Full derivation path of the key, for a mnemonic sweep. */
236
+ path?: string
237
+ }
238
+
239
+ export type SkipReason = 'token' | 'dust' | 'nonstandard'
240
+
241
+ export interface SkippedOutput extends Utxo {
242
+ address: string
243
+ reason: SkipReason
244
+ }
245
+
246
+ export interface SweepPlan {
247
+ network: Network
248
+ /** What the sweep will spend. */
249
+ inputs: SweepInput[]
250
+ /** What it will not spend, and why. */
251
+ skipped: SkippedOutput[]
252
+ /** Sum of `inputs`, as WhatsOnChain reports it (the execute step uses the real figures). */
253
+ totalSatoshis: number
254
+ utxoCount: number
255
+ estimatedFeeSatoshis: number
256
+ /** totalSatoshis minus estimatedFeeSatoshis: "Found X BSV, sweep it?" */
257
+ estimatedImportSatoshis: number
258
+ batchCount: number
259
+ }
260
+
261
+ export interface FeeOptions {
262
+ /** Rate for the preview estimate and the dust rule. Default 100, the wallet's own fee model. */
263
+ satoshisPerKilobyte?: number
264
+ /** Most inputs in one transaction. Default MAX_INPUTS_PER_TX. */
265
+ maxInputsPerTx?: number
266
+ }
267
+
268
+ export const DEFAULT_SATOSHIS_PER_KB = 100
269
+ /** About 15 kB per transaction at the compressed P2PKH input size. */
270
+ export const MAX_INPUTS_PER_TX = 100
271
+ /**
272
+ * The execute step refuses a transaction the wallet built with a higher fee
273
+ * rate than this: ten times the wallet's own model, the same 1 sat/byte ceiling
274
+ * the demo used.
275
+ */
276
+ export const MAX_SWEEP_FEE_RATE = 1000
277
+
278
+ /** Unlocking script: signature push (1 + 73 at most) and public key push (1 + 33, or 1 + 65 uncompressed). */
279
+ function unlockingScriptLength(compressed: boolean): number {
280
+ return compressed ? 108 : 140
281
+ }
282
+
283
+ /** Bytes: outpoint 36 + script length 1 + unlocking script + sequence 4. */
284
+ function inputBytes(compressed: boolean): number {
285
+ return 41 + unlockingScriptLength(compressed)
286
+ }
287
+ const TX_OVERHEAD_BYTES = 10
288
+ const CHANGE_OUTPUT_BYTES = 34
289
+
290
+ function feeFor(bytes: number, rate: number): number {
291
+ return Math.ceil((bytes * rate) / 1000)
292
+ }
293
+
294
+ /**
295
+ * Turn found UTXOs into a plan. Pure: the dust rule, the token rule and the
296
+ * batch split are all here, so they are tested without a network.
297
+ */
298
+ export function planSweep(
299
+ found: SweepInput[],
300
+ network: Network,
301
+ options: FeeOptions & { compressedFor?: (input: SweepInput) => boolean } = {}
302
+ ): SweepPlan {
303
+ const rate = options.satoshisPerKilobyte ?? DEFAULT_SATOSHIS_PER_KB
304
+ const maxInputs = Math.max(1, options.maxInputsPerTx ?? MAX_INPUTS_PER_TX)
305
+ const compressedFor = options.compressedFor ?? (() => true)
306
+
307
+ const inputs: SweepInput[] = []
308
+ const skipped: SkippedOutput[] = []
309
+ const seen = new Set<string>()
310
+ for (const utxo of found) {
311
+ const id = `${utxo.txid}.${utxo.vout}`
312
+ if (seen.has(id)) continue
313
+ seen.add(id)
314
+ if (utxo.satoshis === 1) skipped.push({ ...utxo, reason: 'token' })
315
+ else if (utxo.satoshis <= feeFor(inputBytes(compressedFor(utxo)), rate)) skipped.push({ ...utxo, reason: 'dust' })
316
+ else inputs.push(utxo)
317
+ }
318
+
319
+ let estimatedFeeSatoshis = 0
320
+ const batchCount = Math.ceil(inputs.length / maxInputs)
321
+ for (let b = 0; b < batchCount; b++) {
322
+ const batch = inputs.slice(b * maxInputs, (b + 1) * maxInputs)
323
+ const bytes = TX_OVERHEAD_BYTES + CHANGE_OUTPUT_BYTES + batch.reduce((n, i) => n + inputBytes(compressedFor(i)), 0)
324
+ estimatedFeeSatoshis += feeFor(bytes, rate)
325
+ }
326
+ const totalSatoshis = inputs.reduce((n, i) => n + i.satoshis, 0)
327
+ return {
328
+ network,
329
+ inputs,
330
+ skipped,
331
+ totalSatoshis,
332
+ utxoCount: inputs.length,
333
+ estimatedFeeSatoshis,
334
+ estimatedImportSatoshis: Math.max(0, totalSatoshis - estimatedFeeSatoshis),
335
+ batchCount
336
+ }
337
+ }
338
+
339
+ function assertNetwork(woc: WocConfig, network: Network): void {
340
+ if (woc.network !== network) {
341
+ throw new Error(`This key is for ${network}, but the wallet is on ${woc.network}`)
342
+ }
343
+ }
344
+
345
+ // ─── WIF ─────────────────────────────────────────────────────────────────────
346
+
347
+ /** Preview a WIF sweep: balance, UTXO count, fee. Reads WhatsOnChain only. */
348
+ export async function planWifSweep(args: { wif: string; woc: WocConfig } & FeeOptions): Promise<SweepPlan> {
349
+ const { key, compressed, network } = parseWif(args.wif)
350
+ assertNetwork(args.woc, network)
351
+ const address = addressForKey(key, compressed, network)
352
+ const utxos = await getUtxosForAddress(args.woc, address)
353
+ return planSweep(
354
+ utxos.map(u => ({ ...u, address })),
355
+ network,
356
+ { ...args, compressedFor: () => compressed }
357
+ )
358
+ }
359
+
360
+ export interface SweepBatchResult {
361
+ txid?: string
362
+ inputCount: number
363
+ inputSatoshis: number
364
+ importedSatoshis: number
365
+ feeSatoshis: number
366
+ error?: string
367
+ }
368
+
369
+ export interface SweepResult {
370
+ /** One per batch that went through. */
371
+ txids: string[]
372
+ importedSatoshis: number
373
+ utxoCount: number
374
+ feeSatoshis: number
375
+ batches: SweepBatchResult[]
376
+ /** The plan's skipped outputs, plus any the execute step skipped on the real transaction. */
377
+ skipped: SkippedOutput[]
378
+ /**
379
+ * Set when WhatsOnChain rate-limited the sweep: the batches after the
380
+ * limited one were not tried. Their coins are still on the external key, so
381
+ * a new plan and sweep later picks them up.
382
+ */
383
+ stoppedBy?: 'rate-limit'
384
+ }
385
+
386
+ interface ExecuteArgs {
387
+ wallet: SweepWallet
388
+ adminOriginator: string
389
+ woc: WocConfig
390
+ /** From the plan step. Build a new plan if a sweep fails on a spent input. */
391
+ plan: SweepPlan
392
+ description: string
393
+ maxInputsPerTx?: number
394
+ maxFeeRate?: number
395
+ minRequestIntervalMs?: number
396
+ }
397
+
398
+ /**
399
+ * Spend a WIF key's coins into this wallet. Pass the plan from planWifSweep
400
+ * (the one the user confirmed); without one, a plan is built here.
401
+ */
402
+ export async function sweepWif(
403
+ args: Omit<ExecuteArgs, 'plan' | 'description'> & { wif: string; plan?: SweepPlan } & FeeOptions
404
+ ): Promise<SweepResult> {
405
+ const { key, compressed, network } = parseWif(args.wif)
406
+ assertNetwork(args.woc, network)
407
+ const address = addressForKey(key, compressed, network)
408
+ const plan = args.plan ?? (await planWifSweep(args))
409
+ const { spent: _spent, ...result } = await executeSweep({
410
+ ...args,
411
+ plan,
412
+ description: 'Swept from a private key',
413
+ keyFor: input => {
414
+ if (input.address !== address) throw new Error('The plan does not belong to this key')
415
+ return { key, compressed }
416
+ }
417
+ })
418
+ return result
419
+ }
420
+
421
+ // ─── Mnemonic ────────────────────────────────────────────────────────────────
422
+
423
+ export interface PathScanSummary {
424
+ name: string
425
+ receive: string
426
+ change?: string
427
+ /** Addresses with any on-chain history, receive and change together. */
428
+ usedAddresses: number
429
+ utxoCount: number
430
+ satoshis: number
431
+ /** Whether the change chain was scanned (only after the receive chain showed use). */
432
+ changeScanned: boolean
433
+ }
434
+
435
+ export interface MnemonicScanPlan extends SweepPlan {
436
+ paths: PathScanSummary[]
437
+ }
438
+
439
+ export interface MnemonicScanArgs extends FeeOptions {
440
+ mnemonic: string
441
+ passphrase?: string
442
+ woc: WocConfig
443
+ paths?: readonly SweepPathSpec[]
444
+ gapLimit?: number
445
+ minRequestIntervalMs?: number
446
+ }
447
+
448
+ /**
449
+ * Lower case, single spaces. Use the same form to restore a phrase that
450
+ * decideMnemonicImport classified, so the backup check and the restore see
451
+ * one seed.
452
+ */
453
+ export function normalizeMnemonic(mnemonic: string): string {
454
+ return mnemonic.trim().toLowerCase().split(/\s+/).join(' ')
455
+ }
456
+
457
+ function withSeed<T>(mnemonic: string, passphrase: string, use: (root: HD) => T): T {
458
+ const seed = Mnemonic.fromString(normalizeMnemonic(mnemonic)).toSeed(passphrase)
459
+ try {
460
+ return use(HD.fromSeed(seed))
461
+ } finally {
462
+ wipe(seed)
463
+ }
464
+ }
465
+
466
+ /**
467
+ * Scan an external recovery phrase. For each path: walk the receive chain
468
+ * until `gapLimit` addresses in a row have no history; if any address was
469
+ * used, walk the change chain the same way. Collect the unspent outputs of
470
+ * every used address. Reads WhatsOnChain only.
471
+ */
472
+ export async function scanMnemonic(args: MnemonicScanArgs): Promise<MnemonicScanPlan> {
473
+ const network = args.woc.network
474
+ const gapLimit = Math.max(1, args.gapLimit ?? DEFAULT_GAP_LIMIT)
475
+ const pace = pacer(args.minRequestIntervalMs ?? DEFAULT_WOC_INTERVAL_MS)
476
+ const specs = (args.paths ?? DEFAULT_SWEEP_PATHS).map(s => {
477
+ const change = s.change === null ? undefined : (s.change ?? changeChainFor(s.receive))
478
+ return {
479
+ name: s.name,
480
+ receive: assertPath(s.receive),
481
+ change: change !== undefined ? assertPath(change) : undefined
482
+ }
483
+ })
484
+ // The PBKDF2 seed and every chain node are built up front, synchronously,
485
+ // so the seed is wiped before the first network await.
486
+ const chains = withSeed(args.mnemonic, args.passphrase ?? '', root =>
487
+ specs.map(s => ({ spec: s, receive: root.derive(s.receive), change: s.change ? root.derive(s.change) : undefined }))
488
+ )
489
+
490
+ const found: SweepInput[] = []
491
+ const summaries: PathScanSummary[] = []
492
+
493
+ const walk = async (node: HD, prefix: string): Promise<{ used: number; inputs: SweepInput[] }> => {
494
+ let used = 0
495
+ let unusedRun = 0
496
+ const inputs: SweepInput[] = []
497
+ for (let i = 0; i < MAX_SCAN_INDEX && unusedRun < gapLimit; i++) {
498
+ const address = addressForKey(node.deriveChild(i).privKey, true, network)
499
+ await pace()
500
+ if (!(await addressHasHistory(args.woc, address))) {
501
+ unusedRun++
502
+ continue
503
+ }
504
+ unusedRun = 0
505
+ used++
506
+ await pace()
507
+ const utxos = await getUtxosForAddress(args.woc, address)
508
+ inputs.push(...utxos.map(u => ({ ...u, address, path: `${prefix}/${i}` })))
509
+ }
510
+ return { used, inputs }
511
+ }
512
+
513
+ for (const chain of chains) {
514
+ const receive = await walk(chain.receive, chain.spec.receive)
515
+ let change = { used: 0, inputs: [] as SweepInput[] }
516
+ const changeScanned = receive.used > 0 && chain.change !== undefined
517
+ if (changeScanned) change = await walk(chain.change!, chain.spec.change!)
518
+ found.push(...receive.inputs, ...change.inputs)
519
+ summaries.push({
520
+ name: chain.spec.name,
521
+ receive: chain.spec.receive,
522
+ change: chain.spec.change,
523
+ usedAddresses: receive.used + change.used,
524
+ utxoCount: 0,
525
+ satoshis: 0,
526
+ changeScanned
527
+ })
528
+ }
529
+
530
+ // Per-path figures count only what the sweep will spend, not tokens or dust.
531
+ const plan = planSweep(found, network, args)
532
+ for (const input of plan.inputs) {
533
+ const owner = summaries.find(s => ownsPath(s, input.path!))
534
+ if (owner) {
535
+ owner.utxoCount++
536
+ owner.satoshis += input.satoshis
537
+ }
538
+ }
539
+ return { ...plan, paths: summaries }
540
+ }
541
+
542
+ function ownsPath(summary: { receive: string; change?: string }, path: string): boolean {
543
+ return (
544
+ path.startsWith(`${summary.receive}/`) || (summary.change !== undefined && path.startsWith(`${summary.change}/`))
545
+ )
546
+ }
547
+
548
+ export interface MnemonicSweepResult extends SweepResult {
549
+ /** Swept satoshis per path name, as spent (before the fee, which is per transaction). */
550
+ pathTotals: Record<string, number>
551
+ }
552
+
553
+ /**
554
+ * Spend the coins a scanMnemonic plan found. Keys are derived again from the
555
+ * phrase for each input's path, and each must match the input's address.
556
+ */
557
+ export async function sweepMnemonic(
558
+ args: Omit<ExecuteArgs, 'plan' | 'description'> & Omit<MnemonicScanArgs, 'woc'> & { plan?: MnemonicScanPlan }
559
+ ): Promise<MnemonicSweepResult> {
560
+ const plan = args.plan ?? (await scanMnemonic(args))
561
+ const network = args.woc.network
562
+ assertNetwork(args.woc, plan.network)
563
+ const keys = withSeed(args.mnemonic, args.passphrase ?? '', root => {
564
+ const byPath = new Map<string, PrivateKey>()
565
+ for (const input of plan.inputs) {
566
+ if (!input.path) throw new Error('The plan has an input without a derivation path')
567
+ const path = assertPath(input.path)
568
+ if (!byPath.has(path)) byPath.set(path, root.derive(path).privKey)
569
+ }
570
+ return byPath
571
+ })
572
+
573
+ const { spent, ...result } = await executeSweep({
574
+ ...args,
575
+ plan,
576
+ description: 'Swept from a recovery phrase',
577
+ keyFor: input => {
578
+ const key = keys.get(assertPath(input.path ?? ''))
579
+ if (!key || addressForKey(key, true, network) !== input.address) {
580
+ throw new Error('The plan does not belong to this recovery phrase')
581
+ }
582
+ return { key, compressed: true }
583
+ }
584
+ })
585
+ keys.clear()
586
+
587
+ const pathTotals: Record<string, number> = {}
588
+ for (const summary of plan.paths) pathTotals[summary.name] = 0
589
+ for (const input of spent) {
590
+ const owner = plan.paths.find(p => ownsPath(p, input.path!))
591
+ if (owner) pathTotals[owner.name] += input.satoshis
592
+ }
593
+ return { ...result, pathTotals }
594
+ }
595
+
596
+ // ─── Import decision ─────────────────────────────────────────────────────────
597
+
598
+ export type MnemonicImportDecision =
599
+ /** The private backup cache knows this phrase: restore it as this wallet. */
600
+ | { kind: 'restore' }
601
+ /** Not backed up, and the scan found coins: preview, then sweepMnemonic. */
602
+ | { kind: 'sweep'; plan: MnemonicScanPlan }
603
+ /** Not backed up, nothing found: restore it as this wallet's root (a new or never-backed-up wallet). */
604
+ | { kind: 'empty'; plan?: MnemonicScanPlan }
605
+
606
+ /**
607
+ * What to do with a phrase the user enters on Import, in one call:
608
+ * 1. backup cache hit for profile 0 → 'restore';
609
+ * 2. otherwise scan the external paths; coins found → 'sweep';
610
+ * 3. otherwise → 'empty'.
611
+ *
612
+ * A failed cache lookup throws rather than falling through to the scan: a
613
+ * wallet that has a backup must never be taken for an external one.
614
+ * `probe` is `backupProbe(baseUrl)` from profiles/discovery; leave it out when
615
+ * the build has no backup service. Without `woc` (a network with no
616
+ * WhatsOnChain) there is nothing to scan, so the answer is 'empty'.
617
+ */
618
+ export async function decideMnemonicImport(
619
+ args: Omit<MnemonicScanArgs, 'woc'> & {
620
+ chain: BackupChain
621
+ probe?: ProfileProbe
622
+ woc: WocConfig | undefined
623
+ }
624
+ ): Promise<MnemonicImportDecision> {
625
+ if (args.probe) {
626
+ // Profile 0 of the phrase, derived exactly as the wallet derives it (deriveProfileKeys).
627
+ const primaryKey = withSeed(args.mnemonic, args.passphrase ?? '', root => deriveProfileKeys(root, 0).primaryKey)
628
+ try {
629
+ if (await args.probe(primaryKey, args.chain)) return { kind: 'restore' }
630
+ } finally {
631
+ wipe(primaryKey)
632
+ }
633
+ }
634
+ if (!args.woc) return { kind: 'empty' }
635
+ const plan = await scanMnemonic({ ...args, woc: args.woc })
636
+ return plan.inputs.length > 0 ? { kind: 'sweep', plan } : { kind: 'empty', plan }
637
+ }
638
+
639
+ // ─── Execute ─────────────────────────────────────────────────────────────────
640
+
641
+ async function fetchSourceBeef(woc: WocConfig, txid: string): Promise<Beef> {
642
+ const response = await wocFetch(woc, `${woc.apiBase}/v1/bsv/${woc.segment}/tx/${txid}/beef`)
643
+ const bytes = parseWocBeefBody({ ok: response.ok, text: await response.text() })
644
+ if (!bytes) throw new Error(`Could not fetch the source transaction ${txid}`)
645
+ const beef = new Beef()
646
+ beef.mergeBeef(bytes)
647
+ return beef
648
+ }
649
+
650
+ async function executeSweep(
651
+ args: ExecuteArgs & { keyFor: (input: SweepInput) => { key: PrivateKey; compressed: boolean } }
652
+ ): Promise<SweepResult & { spent: SweepInput[] }> {
653
+ const { wallet, adminOriginator, woc, plan } = args
654
+ const maxInputs = Math.max(1, args.maxInputsPerTx ?? MAX_INPUTS_PER_TX)
655
+ const maxFeeRate = args.maxFeeRate ?? MAX_SWEEP_FEE_RATE
656
+ const pace = pacer(args.minRequestIntervalMs ?? DEFAULT_WOC_INTERVAL_MS)
657
+ const skipped: SkippedOutput[] = [...plan.skipped]
658
+ const batches: SweepBatchResult[] = []
659
+ const spent: SweepInput[] = []
660
+ let stoppedBy: SweepResult['stoppedBy']
661
+
662
+ // Keys are resolved before any network call, so a plan that does not belong
663
+ // to the key fails before anything is fetched or built.
664
+ const keyed = plan.inputs.map(input => ({ input, ...args.keyFor(input) }))
665
+ const sources = new Map<string, Beef>()
666
+
667
+ for (let start = 0; start < keyed.length; start += maxInputs) {
668
+ const candidates = keyed.slice(start, start + maxInputs)
669
+ const batch: SweepBatchResult = { inputCount: 0, inputSatoshis: 0, importedSatoshis: 0, feeSatoshis: 0 }
670
+ let reference: string | undefined
671
+ try {
672
+ // Verify each input against the real source transaction: its real value
673
+ // (not WhatsOnChain's figure) and its real script.
674
+ const inputBeef = new Beef()
675
+ const spend = new Map<string, (typeof keyed)[number] & { satoshis: number }>()
676
+ for (const k of candidates) {
677
+ let source = sources.get(k.input.txid)
678
+ if (!source) {
679
+ await pace()
680
+ source = await fetchSourceBeef(woc, k.input.txid)
681
+ sources.set(k.input.txid, source)
682
+ }
683
+ const output = source.findTxid(k.input.txid)?.tx?.outputs[k.input.vout]
684
+ const expected = new P2PKH().lock(k.input.address).toHex()
685
+ if (!output || output.lockingScript.toHex() !== expected) {
686
+ skipped.push({ ...k.input, reason: 'nonstandard' })
687
+ continue
688
+ }
689
+ const satoshis = output.satoshis ?? 0
690
+ if (satoshis <= 1) {
691
+ skipped.push({ ...k.input, satoshis, reason: satoshis === 1 ? 'token' : 'dust' })
692
+ continue
693
+ }
694
+ inputBeef.mergeBeef(source.toBinaryAtomic(k.input.txid))
695
+ spend.set(`${k.input.txid}.${k.input.vout}`, { ...k, satoshis })
696
+ }
697
+ if (spend.size === 0) continue
698
+ batches.push(batch)
699
+
700
+ const created = await wallet.createAction(
701
+ {
702
+ description: args.description,
703
+ inputBEEF: inputBeef.toBinary(),
704
+ inputs: [...spend.keys()].map(outpoint => ({
705
+ outpoint,
706
+ unlockingScriptLength: unlockingScriptLength(spend.get(outpoint)!.compressed),
707
+ inputDescription: 'Swept coin'
708
+ })),
709
+ labels: ['sweep', 'inbound']
710
+ },
711
+ adminOriginator
712
+ )
713
+ const signable = created.signableTransaction
714
+ if (!signable) throw new Error('The wallet did not return a transaction to sign')
715
+ reference = signable.reference
716
+ const tx = Transaction.fromAtomicBEEF(signable.tx)
717
+
718
+ // The wallet must have added nothing of its own on the input side: a
719
+ // sweep moves external coins in, it never spends this wallet's coins.
720
+ if (tx.inputs.length !== spend.size) throw new Error('The wallet added inputs to the sweep')
721
+ const spends: Record<number, { unlockingScript: string }> = {}
722
+ for (let i = 0; i < tx.inputs.length; i++) {
723
+ const input = tx.inputs[i]
724
+ const outpoint = `${input.sourceTXID ?? input.sourceTransaction?.id('hex')}.${input.sourceOutputIndex}`
725
+ const k = spend.get(outpoint)
726
+ if (!k) throw new Error('The wallet added inputs to the sweep')
727
+ let script = await new P2PKH()
728
+ .unlock(k.key, 'all', false, k.satoshis, new P2PKH().lock(k.input.address))
729
+ .sign(tx, i)
730
+ if (!k.compressed) {
731
+ const pub = k.key.toPublicKey().encode(false) as number[]
732
+ script = new UnlockingScript([script.chunks[0], { op: pub.length, data: pub }])
733
+ }
734
+ input.unlockingScript = script
735
+ spends[i] = { unlockingScript: script.toHex() }
736
+ }
737
+
738
+ const inputSatoshis = [...spend.values()].reduce((n, k) => n + k.satoshis, 0)
739
+ const outputSatoshis = tx.outputs.reduce((n, o) => n + (o.satoshis ?? 0), 0)
740
+ const fee = inputSatoshis - outputSatoshis
741
+ const rate = (fee * 1000) / tx.toBinary().length
742
+ if (fee < 0 || rate > maxFeeRate) throw new Error(`Sweep fee too high (${Math.round(rate)} sat/kB)`)
743
+
744
+ const signed = await wallet.signAction(
745
+ { reference, spends, options: { acceptDelayedBroadcast: false, returnTXIDOnly: true } },
746
+ adminOriginator
747
+ )
748
+ reference = undefined
749
+ // With acceptDelayedBroadcast false the wallet throws WERR_REVIEW_ACTIONS on a
750
+ // failed broadcast (toolbox-mobile 2.15.1); this check covers a wallet that reports instead.
751
+ const failed = signed.sendWithResults?.find(r => r.status !== 'unproven' && r.status !== 'sending')
752
+ if (failed) throw new Error(`The sweep broadcast failed (${failed.status})`)
753
+ if (!signed.txid) throw new Error('The wallet did not broadcast the sweep')
754
+ Object.assign(batch, {
755
+ txid: signed.txid,
756
+ inputCount: spend.size,
757
+ inputSatoshis,
758
+ importedSatoshis: outputSatoshis,
759
+ feeSatoshis: fee
760
+ })
761
+ for (const k of spend.values()) spent.push({ ...k.input, satoshis: k.satoshis })
762
+ } catch (error) {
763
+ if (!batches.includes(batch)) batches.push(batch)
764
+ batch.error = error instanceof Error ? error.message : String(error)
765
+ if (reference) {
766
+ try {
767
+ await wallet.abortAction({ reference }, adminOriginator)
768
+ } catch {
769
+ // The wallet expires an unsigned action on its own; the error above is what matters.
770
+ }
771
+ }
772
+ // The next batch would be refused the same way and only deepen the limit.
773
+ if (error instanceof WocRateLimited) {
774
+ stoppedBy = 'rate-limit'
775
+ break
776
+ }
777
+ }
778
+ }
779
+
780
+ const done = batches.filter(b => b.txid)
781
+ return {
782
+ ...(stoppedBy ? { stoppedBy } : {}),
783
+ txids: done.map(b => b.txid!),
784
+ importedSatoshis: done.reduce((n, b) => n + b.importedSatoshis, 0),
785
+ utxoCount: done.reduce((n, b) => n + b.inputCount, 0),
786
+ feeSatoshis: done.reduce((n, b) => n + b.feeSatoshis, 0),
787
+ batches,
788
+ skipped,
789
+ spent
790
+ }
791
+ }