@exodus/bitcoin-api 5.1.1 → 5.1.2

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,15 @@
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.2](https://github.com/ExodusMovement/assets/compare/@exodus/bitcoin-api@5.1.1...@exodus/bitcoin-api@5.1.2) (2026-11-19)
7
+
8
+
9
+ ### Performance Improvements
10
+
11
+ * **bitcoin-api:** skip re-verifying known history signatures ([#9376](https://github.com/ExodusMovement/assets/issues/9376)) ([d1f4906](https://github.com/ExodusMovement/assets/commit/d1f4906d80621dfbea29c91367c521d2921f80c0))
12
+
13
+
14
+
6
15
  ## [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
16
 
8
17
 
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.2",
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": "9bf1912c78b942063d49b76a022f6f22f1287568"
64
64
  }
@@ -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
  }