@exodus/bitcoin-api 5.1.1 → 5.1.3

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.1.3](https://github.com/ExodusMovement/assets/compare/@exodus/bitcoin-api@5.1.2...@exodus/bitcoin-api@5.1.3) (2026-11-20)
7
+
8
+
9
+ ### Bug Fixes
10
+
11
+ * **bitcoin:** bypass request queue for mempool broadcasts ([#9398](https://github.com/ExodusMovement/assets/issues/9398)) ([42bb75d](https://github.com/ExodusMovement/assets/commit/42bb75d6705186eade6c1fc1a0cc4fff694880fc))
12
+
13
+
14
+
15
+ ## [5.1.2](https://github.com/ExodusMovement/assets/compare/@exodus/bitcoin-api@5.1.1...@exodus/bitcoin-api@5.1.2) (2026-11-19)
16
+
17
+
18
+ ### Performance Improvements
19
+
20
+ * **bitcoin-api:** skip re-verifying known history signatures ([#9376](https://github.com/ExodusMovement/assets/issues/9376)) ([d1f4906](https://github.com/ExodusMovement/assets/commit/d1f4906d80621dfbea29c91367c521d2921f80c0))
21
+
22
+
23
+
6
24
  ## [5.1.1](https://github.com/ExodusMovement/assets/compare/@exodus/bitcoin-api@5.1.0...@exodus/bitcoin-api@5.1.1) (2026-11-19)
7
25
 
8
26
 
package/README.md CHANGED
@@ -22,10 +22,10 @@ Reads receiving HTTP 429 rejoin the end of the queue instead of immediately fail
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 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.
25
+ At most two REST reads 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 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.
27
+ Broadcasts dispatch directly without entering the read queue, waiting for pacing, or consuming read request slots. They bypass local cooldown and recovery waits even when both read slots are occupied or the read queue is full. They have no queue deadline or local concurrency limit. Broadcasts never become recovery probes, and their success does not release read cooldown. Broadcasts receiving HTTP 429 still establish read cooldown and fail without automatic replay.
28
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.
29
+ Request timeouts apply per attempt. The send wrapper can retry one non-final broadcast failure after ten seconds, so network timeouts across both attempts can total about 70 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.
30
30
 
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.
31
+ Recovery resumes paced reads rather than a burst. This read 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.1.1",
3
+ "version": "5.1.3",
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",
@@ -60,5 +60,5 @@
60
60
  "type": "git",
61
61
  "url": "git+https://github.com/ExodusMovement/assets.git"
62
62
  },
63
- "gitHead": "d0511126ddc16785880aabd6882c4a08edafef79"
63
+ "gitHead": "542f0821665b4771aeecab4ce2a2e9614a2515c1"
64
64
  }
@@ -4,7 +4,6 @@ const MAX_ACTIVE_REQUESTS = 2
4
4
  const REQUEST_INTERVAL_MS = 200
5
5
  const MAX_QUEUED_READS = 100
6
6
  const MAX_QUEUE_WAIT_MS = 30_000
7
- const MAX_BROADCAST_QUEUE_WAIT_MS = 1000
8
7
  const MAX_READ_RETRIES = 2
9
8
  const schedulersByOrigin = new Map()
10
9
 
@@ -34,17 +33,15 @@ const drain = (origin) => {
34
33
  clearTimeout(scheduler.wakeTimer)
35
34
  scheduler.wakeTimer = null
36
35
  const cooldown = scheduler.getCooldown?.()
37
- const broadcastIndex = scheduler.queue.findIndex((entry) => entry.isBroadcast)
38
- if (broadcastIndex === -1 && scheduler.queue.length > 0 && cooldown?.retryAt > Date.now()) {
36
+ if (scheduler.queue.length > 0 && cooldown?.retryAt > Date.now()) {
39
37
  scheduler.wakeTimer = setTimeout(() => drain(origin), cooldown.retryAt - Date.now())
40
38
  } else if (
41
39
  scheduler.active < MAX_ACTIVE_REQUESTS &&
42
40
  !scheduler.timer &&
43
- (broadcastIndex !== -1 || !cooldown?.recovering) &&
41
+ !cooldown?.recovering &&
44
42
  scheduler.queue.length > 0
45
43
  ) {
46
- // Give sends the next available slot without interrupting active requests.
47
- const [entry] = scheduler.queue.splice(broadcastIndex === -1 ? 0 : broadcastIndex, 1)
44
+ const entry = scheduler.queue.shift()
48
45
  entry.cleanup()
49
46
  scheduler.active++
50
47
  scheduler.timer = setTimeout(() => {
@@ -71,11 +68,7 @@ const drain = (origin) => {
71
68
 
72
69
  export const resumeMempoolRequests = (origin) => drain(origin)
73
70
 
74
- function enqueueMempoolRequest(
75
- origin,
76
- execute,
77
- { signal, isBroadcast = false, getCooldown, expiresAt }
78
- ) {
71
+ function enqueueMempoolRequest(origin, execute, { signal, getCooldown, expiresAt }) {
79
72
  if (signal?.aborted) return Promise.reject(createAbortError(signal))
80
73
  const maxWaitMs = expiresAt - Date.now()
81
74
  if (maxWaitMs <= 0) {
@@ -87,10 +80,7 @@ function enqueueMempoolRequest(
87
80
  schedulersByOrigin.set(origin, scheduler)
88
81
  }
89
82
 
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) {
83
+ if (scheduler.queue.length >= MAX_QUEUED_READS) {
94
84
  return Promise.reject(createQueueError('MEMPOOL_REQUEST_BUSY'))
95
85
  }
96
86
 
@@ -100,7 +90,6 @@ function enqueueMempoolRequest(
100
90
  resolve,
101
91
  reject,
102
92
  expiresAt,
103
- isBroadcast,
104
93
  cleanup: () => {
105
94
  clearTimeout(timeout)
106
95
  signal?.removeEventListener('abort', onAbort)
@@ -129,13 +118,18 @@ function enqueueMempoolRequest(
129
118
  }
130
119
 
131
120
  export default async function scheduleMempoolRequest(origin, execute, options = {}) {
132
- const expiresAt =
133
- Date.now() + (options.isBroadcast ? MAX_BROADCAST_QUEUE_WAIT_MS : MAX_QUEUE_WAIT_MS)
121
+ if (options.isBroadcast) {
122
+ if (options.signal?.aborted) throw createAbortError(options.signal)
123
+ // Broadcast immediately, independently of read capacity, pacing, and recovery.
124
+ return execute()
125
+ }
126
+
127
+ const expiresAt = Date.now() + MAX_QUEUE_WAIT_MS
134
128
  for (let attempt = 0; ; attempt++) {
135
129
  try {
136
130
  return await enqueueMempoolRequest(origin, execute, { ...options, expiresAt })
137
131
  } catch (error) {
138
- if (options.isBroadcast || error?.code !== '429' || attempt >= MAX_READ_RETRIES) throw error
132
+ if (error?.code !== '429' || attempt >= MAX_READ_RETRIES) throw error
139
133
  }
140
134
  }
141
135
  }
@@ -1,7 +1,7 @@
1
1
  import { RBF_SEQUENCE } from '@exodus/bitcoin-lib'
2
2
  import assert from 'minimalistic-assert'
3
3
 
4
- import { loadTransactionWithPrevouts } from './verify-transaction-signatures.js'
4
+ import { getWitnessTxId, loadTransactionWithPrevouts } from './verify-transaction-signatures.js'
5
5
 
6
6
  // Only status and time come from the indexer. Spend attribution, amounts,
7
7
  // scripts and destinations must all describe the transaction whose hash we checked.
@@ -23,6 +23,7 @@ export async function readAuthenticatedHistory({ item, asset, loadTransaction })
23
23
  assert(tx.isCoinbase() || inputValue >= outputValue, 'Transaction spends more than its inputs')
24
24
  return {
25
25
  txid: tx.getId(),
26
+ wtxid: getWitnessTxId(tx),
26
27
  time: item.time,
27
28
  confirmations: item.confirmations,
28
29
  fees: value(tx.isCoinbase() ? BigInt(0) : inputValue - outputValue),
@@ -1,5 +1,6 @@
1
1
  import { UtxoCollection } from '@exodus/models'
2
2
  import lodash from 'lodash'
3
+ import LRU from 'lru-cache'
3
4
  import assert from 'minimalistic-assert'
4
5
  import ms from 'ms'
5
6
 
@@ -15,8 +16,10 @@ import { getUtxos } from '../utxos-utils.js'
15
16
  import { readAuthenticatedHistory } from './authenticated-history.js'
16
17
  import {
17
18
  createTransactionLoader,
19
+ getOwnedInputIndexes,
20
+ getWitnessTxId,
18
21
  loadTransactionWithPrevouts,
19
- verifyTransactionSignatures,
22
+ verifyTransactionInput,
20
23
  } from './verify-transaction-signatures.js'
21
24
 
22
25
  const { compact, isEqual, uniq } = lodash
@@ -30,6 +33,12 @@ const COINBASE_MATURITY_HEIGHT = 100
30
33
  // scan (synchronous secp256k1 work) doesn't starve the event loop (timers, RPC).
31
34
  const ADDRESS_DERIVATION_BATCH_SIZE = 10
32
35
 
36
+ // Signature checks are synchronous too; yield between batches for the same reason.
37
+ const SIGNATURE_VERIFICATION_BATCH_SIZE = 4
38
+ const MAX_VERIFIED_INPUTS = 4096
39
+
40
+ const yieldToEventLoop = () => new Promise((resolve) => setTimeout(resolve, 0))
41
+
33
42
  export class BitcoinMonitorScanner {
34
43
  #verifyNewSentTransactions
35
44
  #asset
@@ -43,6 +52,9 @@ export class BitcoinMonitorScanner {
43
52
  #refreshGapLimit
44
53
  #addressBatchConcurrency
45
54
  #loadTransaction
55
+ // `${wtxid}:${inputIndex}` whose signature passed. A different witness for the
56
+ // same txid changes the wtxid, so its signatures and vsize are checked again.
57
+ #verifiedInputs = new LRU({ max: MAX_VERIFIED_INPUTS })
46
58
  constructor({
47
59
  asset,
48
60
  assetClientInterface,
@@ -254,7 +266,7 @@ export class BitcoinMonitorScanner {
254
266
  })
255
267
  // Yield so pending timers / RPC can run instead of being starved for the whole scan.
256
268
  if (i + ADDRESS_DERIVATION_BATCH_SIZE < tasks.length) {
257
- await new Promise((resolve) => setTimeout(resolve, 0))
269
+ await yieldToEventLoop()
258
270
  }
259
271
  }
260
272
 
@@ -804,10 +816,18 @@ export class BitcoinMonitorScanner {
804
816
  )
805
817
  const storedOutpoints = new Set(stored.map((utxo) => `${utxo.txId}:${utxo.vout}`))
806
818
  const verifiedIds = new Set()
819
+ let checksInBatch = 0
820
+ const beforeSignatureCheck = () => {
821
+ checksInBatch++
822
+ if (checksInBatch > SIGNATURE_VERIFICATION_BATCH_SIZE) {
823
+ checksInBatch = 1
824
+ return yieldToEventLoop()
825
+ }
826
+ }
807
827
  // The extra refresh results can remove stored UTXOs outside today's gap
808
828
  // range. Match those outpoints even when their addresses are absent from addrMap.
809
829
  for (const item of [...allTxs, ...storedUtxoAddressTxs]) {
810
- if (verifiedIds.has(item.txid)) continue
830
+ if (verifiedIds.has(item.wtxid)) continue
811
831
  if (
812
832
  !item.vin.some(
813
833
  (input) => addrMap[input.addr] || storedOutpoints.has(`${input.txid}:${input.vout}`)
@@ -815,21 +835,36 @@ export class BitcoinMonitorScanner {
815
835
  ) {
816
836
  continue
817
837
  }
838
+ const passedInputs = []
818
839
  try {
819
- const verified = await verifyTransactionSignatures({
840
+ const { tx, prevouts } = await loadTransactionWithPrevouts({
820
841
  txId: item.txid,
821
- ownedScripts,
822
- transactionData: await loadTransactionWithPrevouts({
823
- txId: item.txid,
824
- loadTransaction,
825
- }),
842
+ loadTransaction,
826
843
  })
827
- assert(verified === true, `Cannot authenticate outgoing transaction ${item.txid}`)
844
+ assert(tx.getId() === item.txid, 'Raw transaction hash mismatch')
845
+ // History fields such as vsize must come from the bytes verified here.
846
+ const wtxid = getWitnessTxId(tx)
847
+ assert(wtxid === item.wtxid, `Raw transaction ${item.txid} changed during the scan`)
848
+ const owned = getOwnedInputIndexes({ prevouts, ownedScripts })
849
+ assert(owned.length > 0, `Cannot authenticate outgoing transaction ${item.txid}`)
850
+ for (const index of owned) {
851
+ const key = `${wtxid}:${index}`
852
+ if (this.#verifiedInputs.get(key)) continue
853
+ const verified = await verifyTransactionInput({
854
+ tx,
855
+ index,
856
+ prevouts,
857
+ beforeSignatureCheck,
858
+ })
859
+ assert(verified === true, `Cannot authenticate outgoing transaction ${item.txid}`)
860
+ passedInputs.push(key)
861
+ }
828
862
  } catch (error) {
829
863
  loadTransaction.delete(item.txid)
830
864
  throw error
831
865
  }
832
- verifiedIds.add(item.txid)
866
+ for (const key of passedInputs) this.#verifiedInputs.set(key, true)
867
+ verifiedIds.add(item.wtxid)
833
868
  }
834
869
  }
835
870
 
@@ -3,13 +3,19 @@ import { schnorrVerifySync } from '@exodus/crypto/secp256k1'
3
3
  import assert from 'minimalistic-assert'
4
4
  import varuint from 'varuint-bitcoin'
5
5
 
6
- export function verifyTaprootInput({ tx, index, prevouts, requireAllOutputs }) {
6
+ export async function verifyTaprootInput({
7
+ tx,
8
+ index,
9
+ prevouts,
10
+ requireAllOutputs,
11
+ beforeSignatureCheck,
12
+ }) {
7
13
  const input = tx.ins[index]
8
14
  const output = prevouts[index].script
9
15
  assert(input.script.length === 0, 'Unexpected scriptSig for Taproot')
10
16
  const stack = [...input.witness]
11
17
  const annex = stack.length >= 2 && stack.at(-1)[0] === 0x50 ? stack.pop() : undefined
12
- const verify = (signature, xOnly, leafHash) => {
18
+ const verify = async (signature, xOnly, leafHash) => {
13
19
  assert(signature.length === 64 || signature.length === 65, 'Invalid Taproot signature length')
14
20
  const hashType = signature.length === 64 ? 0 : signature[64]
15
21
  assert(
@@ -20,6 +26,8 @@ export function verifyTaprootInput({ tx, index, prevouts, requireAllOutputs }) {
20
26
  !requireAllOutputs || hashType === 0 || (hashType & 0x1f) === 1,
21
27
  'Signature does not authorize all outputs'
22
28
  )
29
+ const pause = beforeSignatureCheck?.()
30
+ if (pause) await pause
23
31
  const data = tx.hashForWitnessV1(
24
32
  index,
25
33
  prevouts.map((out) => out.script),
@@ -77,7 +85,7 @@ export function verifyTaprootInput({ tx, index, prevouts, requireAllOutputs }) {
77
85
  )
78
86
  const signature = stack[count - 1 - i]
79
87
  if (signature.length === 0) continue
80
- if (!verify(signature, publicKey, leafHash)) return false
88
+ if (!(await verify(signature, publicKey, leafHash))) return false
81
89
  valid++
82
90
  }
83
91
  return valid === threshold
@@ -13,7 +13,13 @@ const TRANSACTION_FETCH_CONCURRENCY = 4
13
13
  const classifyOutput = scriptClassify.outputFactory()
14
14
  const { P2PKH, P2SH, P2WPKH, P2WSH, P2TR } = scriptClassify.types
15
15
 
16
- function verifyInput(tx, index, prevouts, requireAllOutputs) {
16
+ export async function verifyTransactionInput({
17
+ tx,
18
+ index,
19
+ prevouts,
20
+ requireAllOutputs = false,
21
+ beforeSignatureCheck,
22
+ }) {
17
23
  const input = tx.ins[index]
18
24
  const prevout = prevouts[index]
19
25
  let output = prevout.script
@@ -53,12 +59,12 @@ function verifyInput(tx, index, prevouts, requireAllOutputs) {
53
59
  }
54
60
  outputType = classifyOutput(output)
55
61
  } else if (outputType === P2TR) {
56
- return verifyTaprootInput({ tx, index, prevouts, requireAllOutputs })
62
+ return verifyTaprootInput({ tx, index, prevouts, requireAllOutputs, beforeSignatureCheck })
57
63
  } else {
58
64
  assert(input.witness.length === 0, 'Unexpected witness')
59
65
  }
60
66
 
61
- const verify = (encodedSignature, publicKey) => {
67
+ const verify = async (encodedSignature, publicKey) => {
62
68
  const { signature, hashType } = script.signature.decode(encodedSignature)
63
69
  assert(
64
70
  (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE || index < tx.outs.length,
@@ -68,6 +74,8 @@ function verifyInput(tx, index, prevouts, requireAllOutputs) {
68
74
  !requireAllOutputs || (hashType & 0x1f) === Transaction.SIGHASH_ALL,
69
75
  'Signature does not authorize all outputs'
70
76
  )
77
+ const pause = beforeSignatureCheck?.()
78
+ if (pause) await pause
71
79
  const hash = witness
72
80
  ? tx.hashForWitnessV0(index, output, prevout.value, hashType)
73
81
  : tx.hashForSignature(index, output, hashType)
@@ -101,7 +109,7 @@ function verifyInput(tx, index, prevouts, requireAllOutputs) {
101
109
  if (stack.length !== required + 1 || stack[0].length > 0) return false
102
110
  let signatureIndex = 1
103
111
  for (const publicKey of publicKeys) {
104
- if (verify(stack[signatureIndex], publicKey)) signatureIndex++
112
+ if (await verify(stack[signatureIndex], publicKey)) signatureIndex++
105
113
  if (signatureIndex === stack.length) return true
106
114
  }
107
115
  return false
@@ -189,6 +197,15 @@ export async function loadTransactionWithPrevouts({ txId, loadTransaction }) {
189
197
  return { tx, prevouts }
190
198
  }
191
199
 
200
+ // Unlike the txid, the wtxid commits to the witness, which sets vsize and the signatures.
201
+ export const getWitnessTxId = (tx) => Buffer.from(tx.getHash(true)).reverse().toString('hex')
202
+
203
+ export function getOwnedInputIndexes({ prevouts, ownedScripts }) {
204
+ return prevouts.flatMap((out, index) =>
205
+ ownedScripts.has(out.script.toString('hex')) ? [index] : []
206
+ )
207
+ }
208
+
192
209
  export async function verifyTransactionSignatures({
193
210
  txId,
194
211
  fetchRawTx,
@@ -203,10 +220,9 @@ export async function verifyTransactionSignatures({
203
220
  loadTransaction: createTransactionLoader(fetchRawTx),
204
221
  }))
205
222
  assert(tx.getId() === txId, 'Raw transaction hash mismatch')
206
- const owned = prevouts.flatMap((out, index) =>
207
- ownedScripts.has(out.script.toString('hex')) ? [index] : []
208
- )
209
- return (
210
- owned.length > 0 && owned.every((index) => verifyInput(tx, index, prevouts, requireAllOutputs))
211
- )
223
+ const owned = getOwnedInputIndexes({ prevouts, ownedScripts })
224
+ for (const index of owned) {
225
+ if (!(await verifyTransactionInput({ tx, index, prevouts, requireAllOutputs }))) return false
226
+ }
227
+ return owned.length > 0
212
228
  }