@bsv/expo-wallet-toolbox 0.24.3 → 0.25.1

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.
@@ -0,0 +1,310 @@
1
+ /**
2
+ * Production VaultChainLookup over WhatsOnChain (moved out of
3
+ * chainRecovery.ts; chainRecovery.ts re-exports it).
4
+ */
5
+ import { Utils } from '@bsv/sdk'
6
+ import { wocConfigFor, type WocConfig } from '../../pay/rails/address'
7
+ import { wocLimitedFetch } from '../../net/wocLimiter'
8
+ import type { AppChain } from '../../config'
9
+ import type { MarkerHistory, MarkerUnknownReason, VaultChainLookup } from './markerLookup'
10
+
11
+ /** Rows per confirmed-history page. */
12
+ export const VAULT_HISTORY_PAGE = 1000
13
+ /** Row cap of the plain /history endpoint. A confirmed page of exactly this
14
+ * length with no token is read as cut off (fail closed), because the live
15
+ * limit and token field names were not verifiable offline. */
16
+ export const VAULT_HISTORY_LEGACY_CAP = 100
17
+ /** Pages read before the window counts as full (5,000 confirmed rows). */
18
+ export const VAULT_HISTORY_MAX_PAGES = 5
19
+
20
+ /** Merge two HeadersInit values (plain object, Headers instance or array of
21
+ * pairs) into a plain object. Later names win on a clash. */
22
+ function mergeHeaders(base?: HeadersInit, over?: HeadersInit): Record<string, string> {
23
+ const out: Record<string, string> = {}
24
+ for (const part of [base, over]) {
25
+ if (!part) continue
26
+ new Headers(part).forEach((value, name) => {
27
+ out[name] = value
28
+ })
29
+ }
30
+ return out
31
+ }
32
+
33
+ /**
34
+ * Production VaultChainLookup over WhatsOnChain, following the exact request
35
+ * patterns already used by core/pay/rails/address.ts (getUtxosForAddress,
36
+ * the `/tx/{txid}/beef` fetch, parseWocBeefBody's response-shape checks).
37
+ *
38
+ * Response shapes checked against live mainnet WhatsOnChain on 2026-09-27:
39
+ * `/address/{address}/history` answers `[{tx_hash, height}]`, or 404 "Not
40
+ * Found" for an address with no history; `/tx/{txid}/out/{index}` answers
41
+ * 502 for every output, so spent status comes from `POST /utxos/spent`,
42
+ * which returns one row per outpoint (see outputStatus).
43
+ */
44
+ export function wocChainLookup(chain: AppChain, requestInit?: RequestInit): VaultChainLookup {
45
+ const woc: WocConfig | undefined = wocConfigFor(chain)
46
+ // Vault is mainnet-only, so this only fires on a misrouted call. Refuse it
47
+ // rather than answer "no marker": an empty answer is a genuine miss here.
48
+ if (!woc) throw new Error(`Vault chain recovery needs WhatsOnChain, which ${chain} does not have`)
49
+ const base = `${woc.apiBase}/v1/bsv/${woc.segment}`
50
+
51
+ // `requestInit` (for example the app's WhatsOnChain key header) is merged
52
+ // into every request. Headers given per call win on a name clash.
53
+ // Every request goes through the shared WhatsOnChain limiter: a scan sends
54
+ // several requests per index, back to back.
55
+ const doFetch = (url: string, init?: RequestInit): Promise<Response> => {
56
+ if (!requestInit) return wocLimitedFetch(url, init)
57
+ return wocLimitedFetch(url, {
58
+ ...requestInit,
59
+ ...init,
60
+ headers: mergeHeaders(requestInit.headers, init?.headers)
61
+ })
62
+ }
63
+
64
+ /** One page of rows from a history endpoint. `rows: undefined` with a
65
+ * `reason` is a failure; a 404 is a page with no rows. */
66
+ type Page = { rows: string[]; fullPage: boolean; token?: string } | { failed: MarkerUnknownReason }
67
+ const readPage = async (url: string, pageSize: number, suspectCaps: number[] = []): Promise<Page> => {
68
+ let response: Response
69
+ try {
70
+ response = await doFetch(url)
71
+ } catch {
72
+ return { failed: 'request-failed' }
73
+ }
74
+ if (response.status === 404) return { rows: [], fullPage: false }
75
+ if (response.status === 429) return { failed: 'rate-limited' }
76
+ if (!response.ok) return { failed: 'request-failed' }
77
+ let body: any
78
+ try {
79
+ body = await response.json()
80
+ } catch {
81
+ return { failed: 'malformed' }
82
+ }
83
+ // The plain /history endpoint answers a bare array; the paged endpoints
84
+ // answer {result: [...]}.
85
+ const list: unknown = Array.isArray(body)
86
+ ? body
87
+ : body !== null && typeof body === 'object'
88
+ ? body.result
89
+ : undefined
90
+ if (!Array.isArray(list)) return { failed: 'malformed' }
91
+ const rows: string[] = list.map((r: any) => r?.tx_hash).filter((h: unknown) => typeof h === 'string')
92
+ const token = Array.isArray(body) ? undefined : pageTokenFrom(body)
93
+ return {
94
+ rows,
95
+ // A page as long as the request, or exactly as long as a server-side cap
96
+ // we know of (the plain /history cap of 100), with no token after it is
97
+ // treated as cut off, never as complete.
98
+ fullPage: list.length >= pageSize || suspectCaps.includes(list.length),
99
+ token
100
+ }
101
+ }
102
+
103
+ return {
104
+ async transactionsForLockingScript(lockingScriptHex: string): Promise<string[]> {
105
+ // The marker is always a P2PKH output; derive its address from the
106
+ // script's hash160 rather than adding a second WoC endpoint shape.
107
+ //
108
+ // The VaultChainLookup contract (see this file's interface doc) treats
109
+ // an EMPTY result as a genuine "no marker at this index" miss — so a
110
+ // failure to even ask the question (an unrecognizable script), a
111
+ // non-2xx response (rate limiting, a transient 5xx, a maintenance
112
+ // window) or a thrown exception (DNS failure, timeout, offline) must
113
+ // never collapse into that same empty array: recoverVaultFromChain's
114
+ // OWN catch around this call (never a miss, and now bounded — see
115
+ // VAULT_RECOVERY_MAX_CONSECUTIVE_PROBLEMS) is what has to handle these,
116
+ // not the miss-counting branch.
117
+ const address = p2pkhAddressFromScript(lockingScriptHex, woc.network)
118
+ if (!address) {
119
+ throw new Error('wocChainLookup: marker script is not a recognizable P2PKH script')
120
+ }
121
+ const response = await doFetch(`${base}/address/${address}/history`)
122
+ // WhatsOnChain's answer for an address that has never been used: a
123
+ // genuine miss, not a failure.
124
+ if (response.status === 404) return []
125
+ if (!response.ok) {
126
+ throw new Error(`wocChainLookup: address history request failed (HTTP ${response.status})`)
127
+ }
128
+ const body = await response.json()
129
+ const rows = Array.isArray(body) ? body : Array.isArray(body?.result) ? body.result : []
130
+ const txids = rows.map((r: any) => r?.tx_hash).filter((h: unknown) => typeof h === 'string')
131
+ return [...new Set<string>(txids)]
132
+ },
133
+
134
+ markerAddress(lockingScriptHex: string): string | undefined {
135
+ return p2pkhAddressFromScript(lockingScriptHex, woc.network)
136
+ },
137
+
138
+ async markerHistory(lockingScriptHex: string): Promise<MarkerHistory> {
139
+ const address = p2pkhAddressFromScript(lockingScriptHex, woc.network)
140
+ if (!address) return { status: 'unknown', reason: 'malformed', txids: [] }
141
+
142
+ const seen = new Set<string>()
143
+ let problem: MarkerUnknownReason | undefined
144
+ const note = (reason: MarkerUnknownReason) => {
145
+ problem ??= reason
146
+ }
147
+
148
+ // Confirmed rows, oldest first, paged by token.
149
+ let token: string | undefined
150
+ for (let page = 1; page <= VAULT_HISTORY_MAX_PAGES; page++) {
151
+ const url =
152
+ `${base}/address/${address}/confirmed/history?order=asc&limit=${VAULT_HISTORY_PAGE}` +
153
+ (token === undefined ? '' : `&token=${encodeURIComponent(token)}`)
154
+ const result = await readPage(url, VAULT_HISTORY_PAGE, [VAULT_HISTORY_LEGACY_CAP])
155
+ if ('failed' in result) {
156
+ note(result.failed)
157
+ break
158
+ }
159
+ for (const txid of result.rows) seen.add(txid)
160
+ if (result.token === undefined) {
161
+ // A full page with nothing after it: the window is cut off.
162
+ if (result.fullPage) note('window-full')
163
+ break
164
+ }
165
+ if (page === VAULT_HISTORY_MAX_PAGES) {
166
+ note('window-full')
167
+ break
168
+ }
169
+ token = result.token
170
+ }
171
+
172
+ // Unconfirmed rows. Skipped after a failure that a second request would
173
+ // only make worse; still read when the confirmed window was just full.
174
+ if (problem === undefined || problem === 'window-full') {
175
+ const result = await readPage(`${base}/address/${address}/unconfirmed/history`, Number.POSITIVE_INFINITY)
176
+ if ('failed' in result) note(result.failed)
177
+ else for (const txid of result.rows) seen.add(txid)
178
+ }
179
+
180
+ // Legacy plain /history (newest first, capped at 100 rows): the endpoint
181
+ // the base code used, verified live on 2026-09-27. Its rows are unioned
182
+ // in so base behaviour is the floor if the paged endpoints differ from
183
+ // their documentation (a 404 there must not read as "no history"). Its
184
+ // cap is not a window problem: only a failure counts.
185
+ if (problem === undefined || problem === 'window-full') {
186
+ const result = await readPage(`${base}/address/${address}/history`, Number.POSITIVE_INFINITY)
187
+ if ('failed' in result) note(result.failed)
188
+ else for (const txid of result.rows) seen.add(txid)
189
+ }
190
+
191
+ const txids = [...seen]
192
+ if (problem !== undefined) return { status: 'unknown', reason: problem, txids }
193
+ return txids.length > 0 ? { status: 'found', txids } : { status: 'none' }
194
+ },
195
+
196
+ async transactionForTxid(txid: string): Promise<{ beef: number[]; confirmed: boolean } | null> {
197
+ try {
198
+ const [beefResp, txResp] = await Promise.all([
199
+ doFetch(`${base}/tx/${txid}/beef`),
200
+ doFetch(`${base}/tx/hash/${txid}`)
201
+ ])
202
+ const beef = parseWocBeefBodyText(beefResp.ok, await beefResp.text())
203
+ if (!beef) return null
204
+ let confirmed = false
205
+ if (txResp.ok) {
206
+ const info = await txResp.json()
207
+ confirmed = Number.isInteger(info?.confirmations) && info.confirmations > 0
208
+ }
209
+ return { beef, confirmed }
210
+ } catch {
211
+ return null
212
+ }
213
+ },
214
+
215
+ async outputStatus(outpoint: { txid: string; vout: number }): Promise<'unspent' | 'spent' | 'unknown'> {
216
+ // Fail-safe default is 'unknown' (never trusted as unspent — see this
217
+ // file's VaultChainLookup interface doc). The row must be about this
218
+ // exact outpoint. Unspent is a clean row with no `spentIn`; spent is a
219
+ // `spentIn` naming another transaction; an unknown output comes back as
220
+ // `spentIn.status: "Unknown UTXO"` echoing its own txid, which is
221
+ // neither.
222
+ try {
223
+ const response = await doFetch(`${base}/utxos/spent`, {
224
+ method: 'POST',
225
+ headers: { 'Content-Type': 'application/json' },
226
+ body: JSON.stringify({ utxos: [{ txid: outpoint.txid, vout: outpoint.vout }] })
227
+ })
228
+ if (!response.ok) return 'unknown'
229
+ const body = await response.json()
230
+ const row = Array.isArray(body) && body.length === 1 ? body[0] : undefined
231
+ if (row === null || typeof row !== 'object') return 'unknown'
232
+ if (row.utxo?.txid !== outpoint.txid || row.utxo?.vout !== outpoint.vout) return 'unknown'
233
+ if (row.error !== '') return 'unknown'
234
+ const spentIn = row.spentIn
235
+ if (spentIn === undefined) return 'unspent'
236
+ if (
237
+ spentIn !== null &&
238
+ typeof spentIn === 'object' &&
239
+ typeof spentIn.txid === 'string' &&
240
+ /^[0-9a-fA-F]{64}$/.test(spentIn.txid) &&
241
+ spentIn.txid.toLowerCase() !== outpoint.txid.toLowerCase() &&
242
+ spentIn.status !== 'Unknown UTXO'
243
+ ) {
244
+ return 'spent'
245
+ }
246
+ return 'unknown'
247
+ } catch {
248
+ return 'unknown'
249
+ }
250
+ }
251
+ }
252
+ }
253
+
254
+ /**
255
+ * Next-page token of a history response. The documented field name is not
256
+ * confirmed against the live API, so the known names come first and any other
257
+ * top-level string field that looks like a page token is accepted too. A
258
+ * missed token would read a truncated page as complete, which is the unsafe
259
+ * direction.
260
+ */
261
+ export function pageTokenFrom(body: Record<string, unknown>): string | undefined {
262
+ const known = body.nextPageToken ?? body['next-page']
263
+ if (typeof known === 'string' && known.length > 0) return known
264
+ for (const [key, value] of Object.entries(body)) {
265
+ if (key === 'address' || key === 'script' || key === 'error' || key === 'result') continue
266
+ if (typeof value === 'string' && value.length > 0 && /token|next|cursor|page/i.test(key)) return value
267
+ }
268
+ return undefined
269
+ }
270
+
271
+ /** Local copy of address.ts's parseWocBeefBody signature over (ok, text)
272
+ * rather than a Response, so this module does not need to import it just to
273
+ * reshape the call. */
274
+ function parseWocBeefBodyText(ok: boolean, text: string): number[] | undefined {
275
+ if (!ok) return undefined
276
+ const hex = text.trim()
277
+ if (hex.length === 0 || hex.length % 2 !== 0 || !/^[0-9a-fA-F]+$/.test(hex)) return undefined
278
+ try {
279
+ return Utils.toArray(hex, 'hex') as number[]
280
+ } catch {
281
+ return undefined
282
+ }
283
+ }
284
+
285
+ /** hash160 out of a standard P2PKH script, re-encoded as a base58check
286
+ * address for the WoC address-history endpoint, via @bsv/sdk's own public
287
+ * `Utils.toBase58Check` (already imported for toHex/toArray above) — the
288
+ * same primitive `PublicKey.prototype.toAddress()` uses internally elsewhere
289
+ * in this codebase (core/pay/rails/address.ts). Returns undefined for
290
+ * anything else (defensive — deriveVaultMarkerScript always builds P2PKH). */
291
+ export function p2pkhAddressFromScript(lockingScriptHex: string, network: 'mainnet' | 'testnet'): string | undefined {
292
+ let bytes: number[]
293
+ try {
294
+ bytes = Utils.toArray(lockingScriptHex, 'hex') as number[]
295
+ } catch {
296
+ return undefined
297
+ }
298
+ if (
299
+ bytes.length !== 25 ||
300
+ bytes[0] !== 0x76 ||
301
+ bytes[1] !== 0xa9 ||
302
+ bytes[2] !== 0x14 ||
303
+ bytes[23] !== 0x88 ||
304
+ bytes[24] !== 0xac
305
+ ) {
306
+ return undefined
307
+ }
308
+ const hash160 = bytes.slice(3, 23)
309
+ return Utils.toBase58Check(hash160, [network === 'mainnet' ? 0x00 : 0x6f])
310
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bsv/expo-wallet-toolbox",
3
- "version": "0.24.3",
3
+ "version": "0.25.1",
4
4
  "private": false,
5
5
  "description": "Wallet screens and P2P local-payment backend for Expo/React Native apps, extracted from BSV Wallet.",
6
6
  "license": "Apache-2.0",
@@ -23,10 +23,11 @@
23
23
  "main": "core/index.ts",
24
24
  "types": "core/index.ts",
25
25
  "scripts": {
26
- "prepack": "node -e \"const fs=require('fs');for(const f of ['NOTICE'])fs.copyFileSync('../../'+f,f)\""
26
+ "prepack": "node -e \"const fs=require('fs');for(const f of ['NOTICE','PATENTS'])fs.copyFileSync('../../'+f,f)\""
27
27
  },
28
28
  "files": [
29
29
  "LICENSE",
30
+ "PATENTS",
30
31
  "NOTICE",
31
32
  "core",
32
33
  "ui",
@@ -97,7 +97,7 @@ export async function generatePrintHTML(
97
97
  <p>${
98
98
  format === 'entropy'
99
99
  ? 'Any two of these pages rebuild your twelve-word recovery phrase, and therefore your entire wallet — everyday balance and vault alike. Treat two pages together as you would the phrase itself.'
100
- : 'These shares are an older format. They restore your everyday balance but cannot open a vault.'
100
+ : 'These shares are an older format. They restore your everyday balance. A vault can only be set up on a wallet made from a recovery phrase.'
101
101
  }</p>
102
102
  <p>To recover: In ${appName}, go to Import Existing Wallet &rarr; Scan Backup Shares.</p>
103
103
  </div>
@@ -93,7 +93,12 @@ const KEY: Record<VaultErrorCode, string> = {
93
93
  'key-cannot-cover': 'vault_err_key_cannot_cover',
94
94
  'too-small-to-relock': 'vault_err_too_small_to_relock',
95
95
  'bad-version': 'vault_err_bad_version',
96
- 'chain-scan-failed': 'vault_err_chain_scan_failed'
96
+ 'chain-scan-failed': 'vault_err_chain_scan_failed',
97
+ 'lookup-unknown': 'vault_err_lookup_unknown',
98
+ 'keys-unproven': 'vault_err_keys_unproven',
99
+ 'not-enough-proven-keys': 'vault_err_not_enough_proven_keys',
100
+ 'chain-check-required': 'vault_err_chain_check_required',
101
+ 'no-mnemonic': 'vault_err_no_mnemonic'
97
102
  }
98
103
 
99
104
  /**
@@ -103,7 +108,9 @@ const KEY: Record<VaultErrorCode, string> = {
103
108
  * the button renders but does nothing. 'key-removed-mid-op' is deliberately
104
109
  * excluded even though the signing loop can produce it, because it can ALSO
105
110
  * arrive from a moment the loop does not cover (waiting-for-key), where retry
106
- * would be a dead button.
111
+ * would be a dead button. 'lookup-unknown' is excluded too: the ceremony has
112
+ * no retry waiter for it, so a Retry button would do nothing. Callers that
113
+ * throw it outside a ceremony show their own retry.
107
114
  */
108
115
  export const RETRYABLE_VAULT_ERRORS: ReadonlySet<VaultErrorCode> = new Set<VaultErrorCode>([
109
116
  'touch-timeout',