@exodus/bitcoin-api 5.0.12 → 5.0.14

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
@@ -3,6 +3,24 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
+ ## [5.0.14](https://github.com/ExodusMovement/assets/compare/@exodus/bitcoin-api@5.0.13...@exodus/bitcoin-api@5.0.14) (2026-11-10)
7
+
8
+
9
+ ### Bug Fixes
10
+
11
+ * **bitcoin:** prioritize broadcasts over queued mempool reads ([#9260](https://github.com/ExodusMovement/assets/issues/9260)) ([616b21b](https://github.com/ExodusMovement/assets/commit/616b21bbbd82afd138a569323ef82e7e9e48eab4))
12
+
13
+
14
+
15
+ ## [5.0.13](https://github.com/ExodusMovement/assets/compare/@exodus/bitcoin-api@5.0.12...@exodus/bitcoin-api@5.0.13) (2026-11-03)
16
+
17
+
18
+ ### Bug Fixes
19
+
20
+ * **bitcoin:** cache authenticated history inputs across scans ([#9174](https://github.com/ExodusMovement/assets/issues/9174)) ([b19d85b](https://github.com/ExodusMovement/assets/commit/b19d85b15f292bfccb023e5801320bc0f6e6f6cf))
21
+
22
+
23
+
6
24
  ## [5.0.12](https://github.com/ExodusMovement/assets/compare/@exodus/bitcoin-api@5.0.11...@exodus/bitcoin-api@5.0.12) (2026-11-03)
7
25
 
8
26
  **Note:** Version bump only for package @exodus/bitcoin-api
package/README.md CHANGED
@@ -16,14 +16,16 @@ Confirmation checks recheck their inputs if a WebSocket update, disconnect, or b
16
16
 
17
17
  ## Mempool Retry-After
18
18
 
19
- Every HTTP 429 starts a process-local cooldown shared across clients and endpoints on the same origin. Valid `Retry-After` seconds or HTTP dates take precedence, using the server's `Date` header for clock skew when available, and are capped at five minutes. Missing or invalid values use a ten-second fallback; failed recovery doubles it with 0–20% positive jitter, also capped at five minutes. Concurrent responses from the original burst do not multiply backoff, but longer server deadlines are preserved.
19
+ Every HTTP 429 starts a process-local cooldown shared across clients and endpoints on the same origin. Valid `Retry-After` seconds or HTTP dates take precedence, using the server's `Date` header for clock skew when available, and are capped at five minutes. Missing or invalid values use a ten-second fallback; failed recovery doubles it with 0–20% positive jitter, also capped at five minutes. Concurrent responses from the original burst do not multiply backoff, but longer server deadlines are preserved. A 429 from a broadcast dispatched during cooldown or recovery renews the read cooldown, including the fallback for missing or invalid `Retry-After`; an older recovery response cannot release that renewed cooldown. Broadcasts do not increase the fallback as failed recovery reads do.
20
20
 
21
21
  Reads receiving HTTP 429 rejoin the end of the queue instead of immediately failing the monitor scan. Each read permits at most two retries, sharing its original 30-second queue deadline; cancellation, overflow, or expiry still fail finally. Exhausted retries fail with code `429`, `finalError`, bounded `retryAt`/`retryAfterMs`, and hint `mempoolRateLimited`; generic retries stop. Queued reads wait until one recovery read can run, with a ten-second timeout including its body. Success or an ordinary 404 releases the cooldown; other HTTP, transport, or body failures renew it. No recovery request is generated when the queue is empty.
22
22
 
23
23
  ## Mempool request scheduling
24
24
 
25
- At most two REST requests run concurrently, including body consumption, with at least 200 ms between starts. Reads queue FIFO, bounded to 100 entries and a 30-second wait including cooldown. Abort signals remove queued reads; expired or cancelled entries never dispatch later. Normal requests have a 30-second dispatch-time timeout including the body, respecting shorter caller timeouts. History scans submit two address batches at a time while retaining full address coverage; Insight concurrency is unchanged.
25
+ At most two REST requests run concurrently, including body consumption, with at least 200 ms between starts. Reads queue FIFO, bounded to 100 entries and a 30-second wait including cooldown. Abort signals remove queued requests; expired or cancelled entries never dispatch later. Normal requests have a 30-second dispatch-time timeout including the body, respecting shorter caller timeouts. History scans submit two address batches at a time while retaining full address coverage; Insight concurrency is unchanged.
26
26
 
27
- Broadcasts wait only for a short pacing interval (at most one second) when capacity is available and no request is queued. Busy, cooling, or recovering origins reject sends rather than retaining them for later broadcast. Queue overflow/expiry use `MEMPOOL_REQUEST_BUSY`/`MEMPOOL_REQUEST_QUEUE_TIMEOUT` with `finalError`. Broadcasts are never recovery probes, and dispatched broadcasts receiving 429 are not automatically replayed.
27
+ Broadcasts jump ahead of queued reads only when request capacity is available. Active requests and broadcasts waiting for pacing reserve the two request slots; when both slots are occupied or reserved, a new broadcast fails immediately with `MEMPOOL_REQUEST_BUSY` and `finalError`, without automatic retry or later dispatch. The read queue limit does not consume broadcast capacity. Accepted broadcasts preserve FIFO order and 200 ms pacing, with the original one-second queue deadline; expired broadcasts fail finally with `MEMPOOL_REQUEST_QUEUE_TIMEOUT`. Active requests remain uninterrupted. New and queued broadcasts bypass local cooldown and recovery waits. Broadcasts never become recovery probes, and their success does not release read cooldown. Dispatched broadcasts receiving 429 still establish read cooldown and fail without automatic replay.
28
+
29
+ Queue and request deadlines apply per attempt. The send wrapper can retry one non-final broadcast failure after ten seconds, so pacing waits and network timeouts across both attempts can total about 72 seconds, excluding transaction preparation and post-failure checks. The broadcast client does not currently accept a caller cancellation signal; consumers should await the send result rather than assume an earlier UI timeout cancels it.
28
30
 
29
31
  Recovery resumes paced traffic rather than a burst. This client budget is not a vendor quota and cannot guarantee freedom from rate limits or bans. The five-minute cap may permit requests earlier than the server requested; queues and cooldowns are not persisted or coordinated across processes.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@exodus/bitcoin-api",
3
- "version": "5.0.12",
3
+ "version": "5.0.14",
4
4
  "description": "Bitcoin transaction and fee monitors, RPC with the blockchain node, other networking code.",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
@@ -41,6 +41,7 @@
41
41
  "eventemitter3": "^5.0.4",
42
42
  "events": "^3.3.0",
43
43
  "lodash": "^4.17.21",
44
+ "lru-cache": "^6.0.0",
44
45
  "minimalistic-assert": "^1.0.1",
45
46
  "ms": "^2.1.1",
46
47
  "socket.io-client": "^2.1.1",
@@ -59,5 +60,5 @@
59
60
  "type": "git",
60
61
  "url": "git+https://github.com/ExodusMovement/assets.git"
61
62
  },
62
- "gitHead": "cc266df454f96bb8efd03909701476c54985e3d7"
63
+ "gitHead": "d15eb6df1549d7381e8dc697e8ed1559a2495426"
63
64
  }
@@ -2,8 +2,9 @@ import { safeString } from '@exodus/safe-string'
2
2
 
3
3
  const MAX_ACTIVE_REQUESTS = 2
4
4
  const REQUEST_INTERVAL_MS = 200
5
- const MAX_QUEUED_REQUESTS = 100
5
+ const MAX_QUEUED_READS = 100
6
6
  const MAX_QUEUE_WAIT_MS = 30_000
7
+ const MAX_BROADCAST_QUEUE_WAIT_MS = 1000
7
8
  const MAX_READ_RETRIES = 2
8
9
  const schedulersByOrigin = new Map()
9
10
 
@@ -33,15 +34,17 @@ const drain = (origin) => {
33
34
  clearTimeout(scheduler.wakeTimer)
34
35
  scheduler.wakeTimer = null
35
36
  const cooldown = scheduler.getCooldown?.()
36
- if (scheduler.queue.length > 0 && cooldown?.retryAt > Date.now()) {
37
+ const broadcastIndex = scheduler.queue.findIndex((entry) => entry.isBroadcast)
38
+ if (broadcastIndex === -1 && scheduler.queue.length > 0 && cooldown?.retryAt > Date.now()) {
37
39
  scheduler.wakeTimer = setTimeout(() => drain(origin), cooldown.retryAt - Date.now())
38
40
  } else if (
39
41
  scheduler.active < MAX_ACTIVE_REQUESTS &&
40
42
  !scheduler.timer &&
41
- !cooldown?.recovering &&
43
+ (broadcastIndex !== -1 || !cooldown?.recovering) &&
42
44
  scheduler.queue.length > 0
43
45
  ) {
44
- const entry = scheduler.queue.shift()
46
+ // Give sends the next available slot without interrupting active requests.
47
+ const [entry] = scheduler.queue.splice(broadcastIndex === -1 ? 0 : broadcastIndex, 1)
45
48
  entry.cleanup()
46
49
  scheduler.active++
47
50
  scheduler.timer = setTimeout(() => {
@@ -68,7 +71,11 @@ const drain = (origin) => {
68
71
 
69
72
  export const resumeMempoolRequests = (origin) => drain(origin)
70
73
 
71
- function enqueueMempoolRequest(origin, execute, { signal, isBroadcast, getCooldown, expiresAt }) {
74
+ function enqueueMempoolRequest(
75
+ origin,
76
+ execute,
77
+ { signal, isBroadcast = false, getCooldown, expiresAt }
78
+ ) {
72
79
  if (signal?.aborted) return Promise.reject(createAbortError(signal))
73
80
  const maxWaitMs = expiresAt - Date.now()
74
81
  if (maxWaitMs <= 0) {
@@ -80,10 +87,10 @@ function enqueueMempoolRequest(origin, execute, { signal, isBroadcast, getCooldo
80
87
  schedulersByOrigin.set(origin, scheduler)
81
88
  }
82
89
 
83
- if (
84
- scheduler.queue.length >= MAX_QUEUED_REQUESTS ||
85
- (isBroadcast && (scheduler.active >= MAX_ACTIVE_REQUESTS || scheduler.queue.length > 0))
86
- ) {
90
+ const queuedCount = scheduler.queue.filter((entry) => entry.isBroadcast === isBroadcast).length
91
+ // Broadcasts can wait for pacing, but never for an occupied request slot.
92
+ const queueLimit = isBroadcast ? MAX_ACTIVE_REQUESTS - scheduler.active : MAX_QUEUED_READS
93
+ if (queuedCount >= queueLimit) {
87
94
  return Promise.reject(createQueueError('MEMPOOL_REQUEST_BUSY'))
88
95
  }
89
96
 
@@ -93,6 +100,7 @@ function enqueueMempoolRequest(origin, execute, { signal, isBroadcast, getCooldo
93
100
  resolve,
94
101
  reject,
95
102
  expiresAt,
103
+ isBroadcast,
96
104
  cleanup: () => {
97
105
  clearTimeout(timeout)
98
106
  signal?.removeEventListener('abort', onAbort)
@@ -121,7 +129,8 @@ function enqueueMempoolRequest(origin, execute, { signal, isBroadcast, getCooldo
121
129
  }
122
130
 
123
131
  export default async function scheduleMempoolRequest(origin, execute, options = {}) {
124
- const expiresAt = Date.now() + (options.isBroadcast ? 1000 : MAX_QUEUE_WAIT_MS)
132
+ const expiresAt =
133
+ Date.now() + (options.isBroadcast ? MAX_BROADCAST_QUEUE_WAIT_MS : MAX_QUEUE_WAIT_MS)
125
134
  for (let attempt = 0; ; attempt++) {
126
135
  try {
127
136
  return await enqueueMempoolRequest(origin, execute, { ...options, expiresAt })
@@ -41,9 +41,9 @@ const createRateLimitError = (retryAt, response) => {
41
41
  return error
42
42
  }
43
43
 
44
- const enterCooldown = (origin, recoveryState, retryAfterMs) => {
44
+ const enterCooldown = (origin, recoveryState, retryAfterMs, renewCooldown = false) => {
45
45
  let state = rateLimitsByOrigin.get(origin)
46
- if (!state || recoveryState || retryAfterMs !== undefined) {
46
+ if (!state || recoveryState || retryAfterMs !== undefined || renewCooldown) {
47
47
  const backoffMs = state
48
48
  ? Math.min(state.backoffMs * (recoveryState ? 2 : 1), MAX_RETRY_AFTER_MS)
49
49
  : INITIAL_BACKOFF_MS
@@ -60,17 +60,18 @@ const enterCooldown = (origin, recoveryState, retryAfterMs) => {
60
60
  return state
61
61
  }
62
62
 
63
- const checkCooldown = (origin, isBroadcast) => {
63
+ const checkCooldown = (origin) => {
64
64
  const state = rateLimitsByOrigin.get(origin)
65
- if (state && (Date.now() < state.retryAt || recoveringOrigins.has(origin) || isBroadcast)) {
65
+ if (state && (Date.now() < state.retryAt || recoveringOrigins.has(origin))) {
66
66
  throw createRateLimitError(state.retryAt)
67
67
  }
68
68
  }
69
69
 
70
70
  async function executeRequest(url, fetchOptions, consumeResponse, isBroadcast) {
71
71
  const origin = new URL(url).origin
72
- checkCooldown(origin, isBroadcast)
73
- const recoveryState = rateLimitsByOrigin.get(origin)
72
+ if (!isBroadcast) checkCooldown(origin)
73
+ const cooldownAtDispatch = rateLimitsByOrigin.get(origin)
74
+ const recoveryState = isBroadcast ? undefined : cooldownAtDispatch
74
75
  let recoveryResponseHandled = false
75
76
  if (recoveryState) {
76
77
  recoveringOrigins.add(origin)
@@ -87,7 +88,13 @@ async function executeRequest(url, fetchOptions, consumeResponse, isBroadcast) {
87
88
  return await fetchWithTimeout(url, fetchOptions, async (response) => {
88
89
  try {
89
90
  if (response.status === 429) {
90
- const state = enterCooldown(origin, recoveryState, getRetryAfterMs(response, Date.now()))
91
+ // A new send during cooldown must renew it; delayed pre-cooldown responses need not.
92
+ const state = enterCooldown(
93
+ origin,
94
+ recoveryState,
95
+ getRetryAfterMs(response, Date.now()),
96
+ isBroadcast && cooldownAtDispatch !== undefined
97
+ )
91
98
  recoveryResponseHandled = true
92
99
  throw createRateLimitError(state.retryAt, response)
93
100
  }
@@ -137,7 +144,6 @@ export default async function mempoolRequest(
137
144
  { isBroadcast = false } = {}
138
145
  ) {
139
146
  const origin = new URL(url).origin
140
- if (isBroadcast) checkCooldown(origin, true)
141
147
  return scheduleMempoolRequest(
142
148
  origin,
143
149
  () => executeRequest(url, fetchOptions, consumeResponse, isBroadcast),
@@ -42,6 +42,7 @@ export class BitcoinMonitorScanner {
42
42
  #gapLimit
43
43
  #refreshGapLimit
44
44
  #addressBatchConcurrency
45
+ #loadTransaction
45
46
  constructor({
46
47
  asset,
47
48
  assetClientInterface,
@@ -83,6 +84,7 @@ export class BitcoinMonitorScanner {
83
84
  this.#gapLimit = gapLimit
84
85
  this.#refreshGapLimit = refreshGapLimit
85
86
  this.#addressBatchConcurrency = addressBatchConcurrency
87
+ this.#loadTransaction = createTransactionLoader((id) => insightClient.fetchRawTx(id))
86
88
  }
87
89
 
88
90
  async #getGapLimit({ assetConfig, refresh }) {
@@ -94,7 +96,7 @@ export class BitcoinMonitorScanner {
94
96
  const asset = this.#asset
95
97
  const assetClientInterface = this.#assetClientInterface
96
98
  const insightClient = this.#insightClient
97
- const loadTransaction = createTransactionLoader((id) => insightClient.fetchRawTx(id))
99
+ const loadTransaction = this.#loadTransaction
98
100
  const txFetchLimit = this.#txFetchLimitResolver({ assetName: asset.name, refresh })
99
101
  const assetName = asset.name
100
102
  const accountState = await assetClientInterface.getAccountState({ assetName, walletAccount })
@@ -797,12 +799,20 @@ export class BitcoinMonitorScanner {
797
799
  ) {
798
800
  continue
799
801
  }
800
- const verified = await verifyTransactionSignatures({
801
- txId: item.txid,
802
- ownedScripts,
803
- transactionData: await loadTransactionWithPrevouts({ txId: item.txid, loadTransaction }),
804
- })
805
- assert(verified === true, `Cannot authenticate outgoing transaction ${item.txid}`)
802
+ try {
803
+ const verified = await verifyTransactionSignatures({
804
+ txId: item.txid,
805
+ ownedScripts,
806
+ transactionData: await loadTransactionWithPrevouts({
807
+ txId: item.txid,
808
+ loadTransaction,
809
+ }),
810
+ })
811
+ assert(verified === true, `Cannot authenticate outgoing transaction ${item.txid}`)
812
+ } catch (error) {
813
+ loadTransaction.delete(item.txid)
814
+ throw error
815
+ }
806
816
  verifiedIds.add(item.txid)
807
817
  }
808
818
  }
@@ -1,12 +1,14 @@
1
- import { memoize } from '@exodus/basic-utils'
1
+ import { restrictConcurrency } from '@exodus/basic-utils'
2
2
  import { crypto, opcodes, payments, script, scriptClassify, Transaction } from '@exodus/bitcoinjs'
3
3
  import { fromBigInt, toBigInt } from '@exodus/bytes/bigint.js'
4
4
  import { ecdsaVerifyHashSync } from '@exodus/crypto/secp256k1'
5
+ import LRU from 'lru-cache'
5
6
  import assert from 'minimalistic-assert'
6
7
 
7
8
  import { verifyTaprootInput } from './verify-taproot-input.js'
8
9
 
9
10
  const CURVE_ORDER = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141')
11
+ const TRANSACTION_FETCH_CONCURRENCY = 4
10
12
 
11
13
  const classifyOutput = scriptClassify.outputFactory()
12
14
  const { P2PKH, P2SH, P2WPKH, P2WSH, P2TR } = scriptClassify.types
@@ -105,32 +107,85 @@ function verifyInput(tx, index, prevouts, requireAllOutputs) {
105
107
  return false
106
108
  }
107
109
 
108
- export function createTransactionLoader(fetchRawTx) {
109
- return memoize(async (id) => {
110
- const raw = await fetchRawTx(id)
111
- assert(typeof raw === 'string' && /^(?:[\da-f]{2})+$/i.test(raw), 'Missing raw transaction')
112
- const tx = Transaction.fromHex(raw)
113
- assert(tx.getId() === id, 'Raw transaction hash mismatch')
114
- return tx
110
+ export function createTransactionLoader(fetchRawTx, { maxBytes = 16 * 1024 * 1024 } = {}) {
111
+ const cache = new LRU({
112
+ max: maxBytes,
113
+ // Allow for per-entry overhead as well as the retained raw bytes.
114
+ length: (bytes) => Math.max(1024, bytes.length),
115
115
  })
116
+ const pending = new Map()
117
+ const fetchTransaction = restrictConcurrency(
118
+ async (id) => {
119
+ const raw = await fetchRawTx(id)
120
+ assert(typeof raw === 'string' && /^(?:[\da-f]{2})+$/i.test(raw), 'Missing raw transaction')
121
+ const bytes = Buffer.from(raw, 'hex')
122
+ assert(Transaction.fromBuffer(bytes).getId() === id, 'Raw transaction hash mismatch')
123
+ return bytes
124
+ },
125
+ { concurrency: TRANSACTION_FETCH_CONCURRENCY }
126
+ )
127
+ const loadTransaction = async (id) => {
128
+ let bytes = cache.get(id)
129
+ if (!bytes) {
130
+ let promise = pending.get(id)
131
+ if (!promise) {
132
+ promise = fetchTransaction(id)
133
+ .then((bytes) => {
134
+ if (pending.get(id) === promise) cache.set(id, bytes)
135
+ return bytes
136
+ })
137
+ .finally(() => {
138
+ if (pending.get(id) === promise) pending.delete(id)
139
+ })
140
+ pending.set(id, promise)
141
+ }
142
+ bytes = await promise
143
+ }
144
+ // The parser creates Buffer views. Copy first so callers cannot mutate the cache
145
+ // or another account's transaction, including when they share an in-flight fetch.
146
+ return Transaction.fromBuffer(Buffer.from(bytes))
147
+ }
148
+ // A txid does not commit to witness data. Failed authentication must allow
149
+ // the next scan to fetch a different witness for the same transaction.
150
+ loadTransaction.delete = (id) => {
151
+ cache.del(id)
152
+ pending.delete(id)
153
+ }
154
+ return loadTransaction
116
155
  }
117
156
 
118
157
  export async function loadTransactionWithPrevouts({ txId, loadTransaction }) {
119
158
  const tx = await loadTransaction(txId)
159
+ if (tx.isCoinbase()) return { tx, prevouts: [] }
160
+ const outpoints = new Set()
161
+ const inputIds = tx.ins.map((input) => {
162
+ const id = Buffer.from(input.hash).reverse().toString('hex')
163
+ const outpoint = `${id}:${input.index}`
164
+ assert(!outpoints.has(outpoint), 'Duplicate transaction input')
165
+ outpoints.add(outpoint)
166
+ return id
167
+ })
120
168
  const prevouts = []
121
- if (!tx.isCoinbase()) {
122
- const outpoints = new Set()
123
- for (const input of tx.ins) {
124
- const id = Buffer.from(input.hash).reverse().toString('hex')
125
- const outpoint = `${id}:${input.index}`
126
- assert(!outpoints.has(outpoint), 'Duplicate transaction input')
127
- outpoints.add(outpoint)
128
- const previous = await loadTransaction(id)
129
- const output = previous.outs[input.index]
130
- assert(output, 'Missing previous output')
131
- prevouts.push(output)
169
+ let nextIndex = 0
170
+ let stopped = false
171
+ const loadPrevouts = async () => {
172
+ while (!stopped && nextIndex < inputIds.length) {
173
+ const index = nextIndex++
174
+ try {
175
+ const previous = await loadTransaction(inputIds[index])
176
+ const output = previous.outs[tx.ins[index].index]
177
+ assert(output, 'Missing previous output')
178
+ prevouts[index] = output
179
+ } catch (error) {
180
+ // Leave already-started reads alone: another account may be using them.
181
+ stopped = true
182
+ throw error
183
+ }
132
184
  }
133
185
  }
186
+ await Promise.all(
187
+ Array.from({ length: Math.min(TRANSACTION_FETCH_CONCURRENCY, inputIds.length) }, loadPrevouts)
188
+ )
134
189
  return { tx, prevouts }
135
190
  }
136
191