@bsv/expo-wallet-toolbox 0.25.0 → 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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,18 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 0.25.1
6
+
7
+ WhatsOnChain rate limit. No native change: hosts do not rebuild.
8
+
9
+ ### Fixed
10
+
11
+ - **WhatsOnChain requests no longer exceed the anonymous rate limit.** WhatsOnChain answers more than 3 requests per second with no API key with HTTP 429. The Vault chain scan sent 3 history requests per index back to back, so an empty gap of 20 indexes was 60 requests in one burst, and indexes failed as `rate-limited`. All WhatsOnChain calls now go through one shared limiter: the Vault lookup, address sweeps, BEEF repair, proof refresh, the merkle-path service, the spendability check, broadcast and the exchange rate. It sends at most 2.5 requests per second per API origin, pauses a lane for 1.5 s after a 429, and sends a GET or HEAD once more after a 429. Requests with a `woc-api-key` header use a lane of their own with the same spacing. An empty Vault scan of 20 indexes now takes about 25 s.
12
+
13
+ ### Added
14
+
15
+ - **`configureWocLimiter`, `resetWocLimiter` and `wocLimitedFetch`.** A host with a paid WhatsOnChain key can lower `keyedIntervalMs`.
16
+
5
17
  ## 0.25.0
6
18
 
7
19
  Vault hardening: a planted key, a stale scan or a reset on a new phone can no longer cost funds or add a key. No native change: hosts do not rebuild.
@@ -305,6 +305,7 @@ import { prewarmOwnRoots } from '../headers/prewarm'
305
305
  import { syncHeaders } from '../headers/syncHeaders'
306
306
  import type { HeaderSource } from '../headers/syncHeaders'
307
307
  import { startHeaderSyncTriggers } from '../headers/headerSyncTriggers'
308
+ import { wocLimitedFetch } from '../net/wocLimiter'
308
309
 
309
310
  // Auto-approve accounting (misc-p2-04). Previously a single global cooldown
310
311
  // timer let multiple paired origins accidentally throttle each other while
@@ -1681,7 +1682,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1681
1682
  try {
1682
1683
  const headers: Record<string, string> = {}
1683
1684
  if (wocApiKey) headers['woc-api-key'] = wocApiKey
1684
- const res = await fetch(`${wocBumpBase}/tx/${txid}/proof/bump`, { headers })
1685
+ const res = await wocLimitedFetch(`${wocBumpBase}/tx/${txid}/proof/bump`, { headers })
1685
1686
  if (res.status === 404) {
1686
1687
  r.notes.push({ what: 'getMerklePathNoData', when: new Date().toISOString() })
1687
1688
  return r
@@ -4248,7 +4249,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
4248
4249
  const woc = NETWORKS[selectedNetwork].woc
4249
4250
  if (!woc) return 'pending'
4250
4251
 
4251
- const res = await fetch(`${woc.apiBase}/v1/bsv/${woc.segment}/tx/${txid}/proof/bump`)
4252
+ const res = await wocLimitedFetch(`${woc.apiBase}/v1/bsv/${woc.segment}/tx/${txid}/proof/bump`)
4252
4253
 
4253
4254
  if (res.ok) {
4254
4255
  // XR-059 remainder: a compromised/misbehaving configured indexer must
@@ -4288,7 +4289,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
4288
4289
  txid,
4289
4290
  proof,
4290
4291
  fetchRawTx: async () => {
4291
- const r = await fetch(`${woc.apiBase}/v1/bsv/${woc.segment}/tx/${txid}/hex`)
4292
+ const r = await wocLimitedFetch(`${woc.apiBase}/v1/bsv/${woc.segment}/tx/${txid}/hex`)
4292
4293
  if (!r.ok) throw new Error(`raw tx fetch failed: ${r.status}`)
4293
4294
  // XR-059 remainder: same unbounded-hex-decode gap as the BUMP
4294
4295
  // fetch above, on the raw-tx body this time. Throwing here (like
@@ -4308,7 +4309,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
4308
4309
  // unconfirmed but perfectly healthy tx also has no proof.
4309
4310
  let onChain = false
4310
4311
  try {
4311
- const head = await fetch(`${woc.apiBase}/v1/bsv/${woc.segment}/tx/hash/${txid}`)
4312
+ const head = await wocLimitedFetch(`${woc.apiBase}/v1/bsv/${woc.segment}/tx/hash/${txid}`)
4312
4313
  onChain = head.ok
4313
4314
  // XR-030: any other non-OK (429/500/401/403/...) is a service
4314
4315
  // problem, not proof of absence — only a 404 is authoritative.
@@ -4448,16 +4449,9 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
4448
4449
  if (!woc) return releasedNote + 'Spendability check needs WhatsOnChain, which this network does not have.'
4449
4450
  const wocBase = `${woc.apiBase}/v1/bsv/${woc.segment}`
4450
4451
 
4451
- // Rate limit: max 3 requests/sec (WoC limit ~1 per 0.34s)
4452
- const WOC_INTERVAL = 340
4453
- let lastRequest = 0
4454
- const throttledFetch = async (url: string, init?: RequestInit): Promise<Response> => {
4455
- const now = Date.now()
4456
- const wait = WOC_INTERVAL - (now - lastRequest)
4457
- if (wait > 0) await new Promise(r => setTimeout(r, wait))
4458
- lastRequest = Date.now()
4459
- return fetch(url, init)
4460
- }
4452
+ // The shared WhatsOnChain limiter paces these, together with every other
4453
+ // WhatsOnChain request the app sends at the same time.
4454
+ const throttledFetch = wocLimitedFetch
4461
4455
 
4462
4456
  try {
4463
4457
  const outputs = await storage.findOutputs({
package/core/index.ts CHANGED
@@ -37,6 +37,14 @@ export { TaskCreditInbox } from './monitor/TaskCreditInbox'
37
37
  export { TaskDrainOutbox, drainUnsentEntries } from './monitor/TaskDrainOutbox'
38
38
  export { getOnline, subscribeOnline, probeOnline } from './net/online'
39
39
  export { validateArcUrl } from './net/validateArcUrl'
40
+ export {
41
+ configureWocLimiter,
42
+ resetWocLimiter,
43
+ wocLimitedFetch,
44
+ WOC_ANON_INTERVAL_MS,
45
+ WOC_RATE_LIMIT_PAUSE_MS,
46
+ type WocLimiterOptions
47
+ } from './net/wocLimiter'
40
48
  export * from './logging'
41
49
  export * from './diskSpace'
42
50
  export type { AppChain, WalletChain } from './config'
@@ -0,0 +1,133 @@
1
+ /**
2
+ * One request pacer for every WhatsOnChain call in the app.
3
+ *
4
+ * WhatsOnChain answers more than 3 requests per second from one client with no
5
+ * API key with HTTP 429. Before this module, each feature paced itself or not at
6
+ * all: the Vault chain scan sent 3 history requests per index back to back, so
7
+ * an empty gap of 20 indices was 60 requests with no pause, and a sweep,
8
+ * a proof refresh or a broadcast at the same time added to the same quota.
9
+ *
10
+ * Every WhatsOnChain request now takes a slot from a lane before it is sent. A
11
+ * lane is one API origin, for requests with no key. The slot is reserved
12
+ * synchronously, before any await, so callers that start at the same moment
13
+ * queue behind each other instead of passing together. The first request on an
14
+ * idle lane goes at once.
15
+ *
16
+ * A request that carries a `woc-api-key` header uses a lane of its own: it
17
+ * counts against the key's quota, not the anonymous one. That lane has the same
18
+ * spacing by default, because the tier of a key is not known here; a host with
19
+ * a paid key can lower `keyedIntervalMs`. A 429 on any lane pushes that lane's
20
+ * next slot out by `pauseMs`.
21
+ */
22
+
23
+ /** Spacing of requests with no key: 2.5 per second, under the limit of 3 with room for network jitter. */
24
+ export const WOC_ANON_INTERVAL_MS = 400
25
+ /** Extra pause on a lane after WhatsOnChain answers 429. */
26
+ export const WOC_RATE_LIMIT_PAUSE_MS = 1500
27
+ /** The header WhatsOnChain reads an API key from. */
28
+ export const WOC_KEY_HEADER = 'woc-api-key'
29
+
30
+ export interface WocLimiterOptions {
31
+ /** Spacing of requests with no key. */
32
+ intervalMs: number
33
+ /** Spacing of requests with a key. */
34
+ keyedIntervalMs: number
35
+ /** Extra pause after a 429. */
36
+ pauseMs: number
37
+ now: () => number
38
+ sleep: (ms: number) => Promise<void>
39
+ }
40
+
41
+ const defaults = (): WocLimiterOptions => ({
42
+ intervalMs: WOC_ANON_INTERVAL_MS,
43
+ keyedIntervalMs: WOC_ANON_INTERVAL_MS,
44
+ pauseMs: WOC_RATE_LIMIT_PAUSE_MS,
45
+ now: () => Date.now(),
46
+ sleep: ms => new Promise(resolve => setTimeout(resolve, ms))
47
+ })
48
+
49
+ let options: WocLimiterOptions = defaults()
50
+ /** Lane name to the earliest time its next request may go. */
51
+ const nextSlot = new Map<string, number>()
52
+
53
+ /** Change the limiter's spacing or clock (tests, or a host with a paid key). Clears every lane. */
54
+ export function configureWocLimiter(over: Partial<WocLimiterOptions>): void {
55
+ options = { ...options, ...over }
56
+ nextSlot.clear()
57
+ }
58
+
59
+ /** Back to the default spacing and clock, with every lane idle. */
60
+ export function resetWocLimiter(): void {
61
+ options = defaults()
62
+ nextSlot.clear()
63
+ }
64
+
65
+ function originOf(url: string): string {
66
+ const match = /^[a-z][a-z0-9+.-]*:\/\/[^/?#]+/i.exec(url)
67
+ return match ? match[0].toLowerCase() : url
68
+ }
69
+
70
+ function hasKey(headers: HeadersInit | undefined): boolean {
71
+ if (!headers) return false
72
+ if (Array.isArray(headers)) return headers.some(([name, value]) => name.toLowerCase() === WOC_KEY_HEADER && !!value)
73
+ if (typeof (headers as Headers).get === 'function') return !!(headers as Headers).get(WOC_KEY_HEADER)
74
+ return Object.entries(headers as Record<string, string>).some(
75
+ ([name, value]) => name.toLowerCase() === WOC_KEY_HEADER && !!value
76
+ )
77
+ }
78
+
79
+ function laneFor(url: string, keyed: boolean): string {
80
+ return `${originOf(url)}|${keyed ? 'key' : 'anon'}`
81
+ }
82
+
83
+ /**
84
+ * Reserve this request's slot and return how long to wait for it (0 on an
85
+ * idle lane). The reservation is synchronous, so the order of calls is the
86
+ * order of requests.
87
+ */
88
+ export function reserveWocSlot(url: string, keyed = false): number {
89
+ const lane = laneFor(url, keyed)
90
+ const now = options.now()
91
+ const at = Math.max(now, nextSlot.get(lane) ?? 0)
92
+ nextSlot.set(lane, at + (keyed ? options.keyedIntervalMs : options.intervalMs))
93
+ return at - now
94
+ }
95
+
96
+ /** Wait the time that `reserveWocSlot` returned. Resolves at once for 0. */
97
+ export function waitWocSlot(ms: number): Promise<void> {
98
+ return ms > 0 ? options.sleep(ms) : Promise.resolve()
99
+ }
100
+
101
+ /** Reserve this request's slot and wait for it. */
102
+ export function wocSlot(url: string, keyed = false): Promise<void> {
103
+ return waitWocSlot(reserveWocSlot(url, keyed))
104
+ }
105
+
106
+ /** Record a 429 on a lane: its next slot moves out by `pauseMs`. */
107
+ export function wocRateLimited(url: string, keyed = false): void {
108
+ const lane = laneFor(url, keyed)
109
+ const until = options.now() + options.pauseMs
110
+ nextSlot.set(lane, Math.max(nextSlot.get(lane) ?? 0, until))
111
+ }
112
+
113
+ type FetchLike = (url: string, init?: RequestInit) => Promise<Response>
114
+
115
+ /**
116
+ * `fetch` for WhatsOnChain, paced by the shared limiter. A GET or HEAD that
117
+ * gets 429 is sent once more, after the lane's pause; the second answer is
118
+ * returned as it is, so a caller still sees a 429 that lasts.
119
+ */
120
+ export async function wocLimitedFetch(url: string, init?: RequestInit, fetchImpl?: FetchLike): Promise<Response> {
121
+ const doFetch: FetchLike = fetchImpl ?? ((u, i) => (i ? fetch(u, i) : fetch(u)))
122
+ const keyed = hasKey(init?.headers)
123
+ const method = (init?.method ?? 'GET').toUpperCase()
124
+ const retryable = method === 'GET' || method === 'HEAD'
125
+ for (let attempt = 0; ; attempt++) {
126
+ const wait = reserveWocSlot(url, keyed)
127
+ if (wait > 0) await waitWocSlot(wait)
128
+ const response = await doFetch(url, init)
129
+ if (response.status !== 429) return response
130
+ wocRateLimited(url, keyed)
131
+ if (!retryable || attempt >= 1) return response
132
+ }
133
+ }
@@ -24,6 +24,7 @@
24
24
  */
25
25
  import { Beef, Utils } from '@bsv/sdk'
26
26
  import { MAX_HEX_RESPONSE_CHARS, wocRequestInit, type WocConfig } from './rails/address'
27
+ import { wocLimitedFetch } from '../net/wocLimiter'
27
28
 
28
29
  /** Injectable for tests; production uses global fetch. */
29
30
  export type FetchLike = (
@@ -45,7 +46,8 @@ export async function refetchAtomicBeef(args: {
45
46
  fetchImpl?: FetchLike
46
47
  }): Promise<number[] | undefined> {
47
48
  const { woc, txid } = args
48
- const doFetch = args.fetchImpl ?? (globalThis.fetch as unknown as FetchLike)
49
+ // An injected fetch is used as it is; the default goes through the shared WhatsOnChain limiter.
50
+ const doFetch = args.fetchImpl ?? (wocLimitedFetch as unknown as FetchLike)
49
51
 
50
52
  let bytes: number[]
51
53
  try {
@@ -26,6 +26,7 @@ import { abbreviateKey, addressLabel, FROM_ADDRESS_LABEL_PREFIX, TO_ADDRESS_LABE
26
26
  import { addressNetwork, isValidBsvAddress } from './index'
27
27
 
28
28
  import { BRC29_PROTOCOL_ID } from '../../peerpay/brc29'
29
+ import { wocLimitedFetch } from '../../net/wocLimiter'
29
30
  export { BRC29_PROTOCOL_ID } from '../../peerpay/brc29'
30
31
 
31
32
  /** Whether the address rail can carry a particular payment, and why not when it cannot. */
@@ -183,8 +184,7 @@ export function wocRequestInit(woc: WocConfig): { headers: Record<string, string
183
184
 
184
185
  /** A WhatsOnChain GET that turns a 429 into WocRateLimited. Shared with pay/rails/sweep.ts. */
185
186
  export async function wocFetch(woc: WocConfig, url: string): Promise<Response> {
186
- const init = wocRequestInit(woc)
187
- const response = init ? await fetch(url, init) : await fetch(url)
187
+ const response = await wocLimitedFetch(url, wocRequestInit(woc))
188
188
  if (response.status === 429) throw new WocRateLimited()
189
189
  return response
190
190
  }
@@ -1,6 +1,7 @@
1
1
  import { Beef, Transaction } from '@bsv/sdk'
2
2
  import type { NetworkProfile, WocEndpoints } from '../networks'
3
3
  import { trimTrailingSlashes } from '../net/trimTrailingSlashes'
4
+ import { reserveWocSlot, waitWocSlot, wocRateLimited } from '../net/wocLimiter'
4
5
  import type { PostBeefResult, PostTxResultForTxid } from '../toolboxTypes'
5
6
 
6
7
  const BROADCAST_TIMEOUT_MS = 30_000
@@ -483,6 +484,10 @@ export function createWocBroadcastService(woc: WocEndpoints, apiKey?: string) {
483
484
  Accept: 'text/plain'
484
485
  }
485
486
  if (apiKey) headers['woc-api-key'] = apiKey
487
+ // The limiter wait comes before the deadline starts, so time in the
488
+ // queue never counts against this request's timeout.
489
+ const wait = reserveWocSlot(baseUrl, !!apiKey)
490
+ if (wait > 0) await waitWocSlot(wait)
486
491
  const response = await fetchWithBodyDeadline(
487
492
  `${baseUrl}/tx/raw`,
488
493
  {
@@ -492,6 +497,7 @@ export function createWocBroadcastService(woc: WocEndpoints, apiKey?: string) {
492
497
  },
493
498
  timeoutMs
494
499
  )
500
+ if (response.status === 429) wocRateLimited(baseUrl, !!apiKey)
495
501
  const body = await response.text()
496
502
  console.log(`[${name}] POST /tx/raw ${response.status}`, loggableSnippet(body))
497
503
  const txResult: PostTxResultForTxid = {
@@ -1,5 +1,6 @@
1
1
  import AsyncStorage from '@react-native-async-storage/async-storage'
2
2
  import type { BsvExchangeRate } from '../toolboxTypes'
3
+ import { reserveWocSlot, waitWocSlot, wocRateLimited } from '../net/wocLimiter'
3
4
 
4
5
  // Shared with context/ExchangeRateContext.tsx so a single cache serves both the
5
6
  // fiat-display UI and the wallet-build seed. Same key + same { usdPerBsv } shape.
@@ -8,6 +9,7 @@ import type { BsvExchangeRate } from '../toolboxTypes'
8
9
  export const CACHE_KEY = 'cached_exchange_rate'
9
10
  export const FALLBACK_RATE = 16.75
10
11
  const REFRESH_TIMEOUT_MS = 4000
12
+ const EXCHANGE_RATE_URL = 'https://api.whatsonchain.com/v1/bsv/main/exchangerate'
11
13
 
12
14
  /**
13
15
  * `getExchangeRate()`'s own return, plus a handle on the SAME background
@@ -31,12 +33,17 @@ export interface ExchangeRateSeed extends BsvExchangeRate {
31
33
  */
32
34
  function refreshExchangeRateCache(): Promise<number | undefined> {
33
35
  return (async () => {
36
+ // The limiter wait comes before the timeout starts, so time in the queue
37
+ // never counts against the request.
38
+ const wait = reserveWocSlot(EXCHANGE_RATE_URL)
39
+ if (wait > 0) await waitWocSlot(wait)
34
40
  const controller = new AbortController()
35
41
  const timeout = setTimeout(() => controller.abort(), REFRESH_TIMEOUT_MS)
36
42
  try {
37
- const res = await fetch('https://api.whatsonchain.com/v1/bsv/main/exchangerate', {
43
+ const res = await fetch(EXCHANGE_RATE_URL, {
38
44
  signal: controller.signal
39
45
  })
46
+ if (res.status === 429) wocRateLimited(EXCHANGE_RATE_URL)
40
47
  const data = await res.json()
41
48
  const usdPerBsv = Number(data?.rate)
42
49
  if (Number.isFinite(usdPerBsv) && usdPerBsv > 0) {
@@ -4,6 +4,7 @@
4
4
  */
5
5
  import { Utils } from '@bsv/sdk'
6
6
  import { wocConfigFor, type WocConfig } from '../../pay/rails/address'
7
+ import { wocLimitedFetch } from '../../net/wocLimiter'
7
8
  import type { AppChain } from '../../config'
8
9
  import type { MarkerHistory, MarkerUnknownReason, VaultChainLookup } from './markerLookup'
9
10
 
@@ -49,9 +50,11 @@ export function wocChainLookup(chain: AppChain, requestInit?: RequestInit): Vaul
49
50
 
50
51
  // `requestInit` (for example the app's WhatsOnChain key header) is merged
51
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.
52
55
  const doFetch = (url: string, init?: RequestInit): Promise<Response> => {
53
- if (!requestInit) return init ? fetch(url, init) : fetch(url)
54
- return fetch(url, {
56
+ if (!requestInit) return wocLimitedFetch(url, init)
57
+ return wocLimitedFetch(url, {
55
58
  ...requestInit,
56
59
  ...init,
57
60
  headers: mergeHeaders(requestInit.headers, init?.headers)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bsv/expo-wallet-toolbox",
3
- "version": "0.25.0",
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",