@exodus/bitcoin-api 5.1.0 → 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,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.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
+
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)
16
+
17
+
18
+ ### Bug Fixes
19
+
20
+ * **bitcoin-api:** exclude pending send inputs from stale history ([#9380](https://github.com/ExodusMovement/assets/issues/9380)) ([3aa8738](https://github.com/ExodusMovement/assets/commit/3aa873848245e40573b24d08a77d45a0f8235d0b))
21
+
22
+
23
+
6
24
  ## [5.1.0](https://github.com/ExodusMovement/assets/compare/@exodus/bitcoin-api@5.0.14...@exodus/bitcoin-api@5.1.0) (2026-11-16)
7
25
 
8
26
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@exodus/bitcoin-api",
3
- "version": "5.1.0",
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": "2189bb5f649f746ce303d0453daf7c82ede80c8f"
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
 
@@ -697,17 +709,7 @@ export class BitcoinMonitorScanner {
697
709
 
698
710
  const txIdsToCheck = new Set(Object.keys(unconfirmedTxsToCheck))
699
711
  if (refresh) {
700
- const refreshedTxIds = new Set(newTxs.map((tx) => tx.txId))
701
712
  const scannedTxIds = new Set([...allTxs, ...storedUtxoAddressTxs].map((tx) => tx.txid))
702
- // Refresh overwrites the tx log. Keep unindexed recent sends, including their
703
- // original date and inputs, so another refresh preserves the same grace period.
704
- // The extra stored-UTXO-address scan does not emit entries to the refreshed log.
705
- for (const tx of currentTxs) {
706
- if (tx.pending && isRecentSentTx(tx) && !refreshedTxIds.has(tx.txId)) {
707
- existingTxs.push({ ...tx })
708
- }
709
- }
710
-
711
713
  // A previous refresh may have removed a funding tx from the log while retaining
712
714
  // its UTXOs. Verify retained outputs independently of pending tx-log entries.
713
715
  for (const { txId } of utxoCol.toArray()) {
@@ -733,9 +735,11 @@ export class BitcoinMonitorScanner {
733
735
  })
734
736
  )
735
737
 
738
+ const droppedTxIds = new Set()
736
739
  for (const { txId, shouldDrop } of verificationResults) {
737
740
  if (!shouldDrop) continue
738
741
 
742
+ droppedTxIds.add(txId)
739
743
  utxoCol = utxoCol.difference(utxoCol.getTxIdUtxos(txId))
740
744
  const tx = unconfirmedTxsToCheck[txId]
741
745
  if (!tx) continue
@@ -768,6 +772,30 @@ export class BitcoinMonitorScanner {
768
772
  utxoCol = utxoCol.union(UtxoCollection.fromArray(utxosToAdd, { currency }))
769
773
  }
770
774
 
775
+ const pendingSpentOutpoints = new Set()
776
+ const refreshedTxIds = refresh ? new Set(newTxs.map((tx) => tx.txId)) : null
777
+ for (const tx of currentTxs) {
778
+ if (!tx.pending || !tx.sent || droppedTxIds.has(tx.txId)) continue
779
+
780
+ if (tx.data.inputs) {
781
+ const inputs = UtxoCollection.fromJSON(tx.data.inputs, { currency })
782
+ for (const input of inputs.toArray()) {
783
+ pendingSpentOutpoints.add(`${input.txId}-${input.vout}`)
784
+ }
785
+ }
786
+
787
+ // Refresh overwrites the log. Preserve unindexed sends and their original
788
+ // date/inputs until explicitly dropped, including when a status lookup fails.
789
+ if (refreshedTxIds && !refreshedTxIds.has(tx.txId)) {
790
+ existingTxs.push({ ...tx })
791
+ }
792
+ }
793
+ // Stale history can still list a local send's inputs as unspent. Exclude them
794
+ // after drop recovery too: another pending send may spend a restored input.
795
+ if (pendingSpentOutpoints.size > 0) {
796
+ utxoCol = utxoCol.filter((utxo) => !pendingSpentOutpoints.has(`${utxo.txId}-${utxo.vout}`))
797
+ }
798
+
771
799
  // no changes, ignore
772
800
  if (utxoCol.equals(storedUtxos)) {
773
801
  utxoCol = null
@@ -788,10 +816,18 @@ export class BitcoinMonitorScanner {
788
816
  )
789
817
  const storedOutpoints = new Set(stored.map((utxo) => `${utxo.txId}:${utxo.vout}`))
790
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
+ }
791
827
  // The extra refresh results can remove stored UTXOs outside today's gap
792
828
  // range. Match those outpoints even when their addresses are absent from addrMap.
793
829
  for (const item of [...allTxs, ...storedUtxoAddressTxs]) {
794
- if (verifiedIds.has(item.txid)) continue
830
+ if (verifiedIds.has(item.wtxid)) continue
795
831
  if (
796
832
  !item.vin.some(
797
833
  (input) => addrMap[input.addr] || storedOutpoints.has(`${input.txid}:${input.vout}`)
@@ -799,21 +835,36 @@ export class BitcoinMonitorScanner {
799
835
  ) {
800
836
  continue
801
837
  }
838
+ const passedInputs = []
802
839
  try {
803
- const verified = await verifyTransactionSignatures({
840
+ const { tx, prevouts } = await loadTransactionWithPrevouts({
804
841
  txId: item.txid,
805
- ownedScripts,
806
- transactionData: await loadTransactionWithPrevouts({
807
- txId: item.txid,
808
- loadTransaction,
809
- }),
842
+ loadTransaction,
810
843
  })
811
- 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
+ }
812
862
  } catch (error) {
813
863
  loadTransaction.delete(item.txid)
814
864
  throw error
815
865
  }
816
- verifiedIds.add(item.txid)
866
+ for (const key of passedInputs) this.#verifiedInputs.set(key, true)
867
+ verifiedIds.add(item.wtxid)
817
868
  }
818
869
  }
819
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
  }