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