@exodus/bitcoin-api 5.0.3 → 5.0.5

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.
@@ -3,7 +3,12 @@ import lodash from 'lodash'
3
3
  import assert from 'minimalistic-assert'
4
4
  import ms from 'ms'
5
5
 
6
- import { isChangeAddress, isReceiveAddress } from '../address-utils.js'
6
+ import {
7
+ getAvailablePurposes,
8
+ isChangeAddress,
9
+ isMissingXpubError,
10
+ isReceiveAddress,
11
+ } from '../address-utils.js'
7
12
  import { orderTxs } from '../insight-api-client/util.js'
8
13
  import { getUtxos } from '../utxos-utils.js'
9
14
 
@@ -28,6 +33,7 @@ export class BitcoinMonitorScanner {
28
33
  #extraChainIndex
29
34
  #gapLimit
30
35
  #refreshGapLimit
36
+ #addressBatchConcurrency
31
37
  constructor({
32
38
  asset,
33
39
  assetClientInterface,
@@ -38,6 +44,7 @@ export class BitcoinMonitorScanner {
38
44
  extraChainIndex,
39
45
  gapLimit = 10,
40
46
  refreshGapLimit = 10,
47
+ addressBatchConcurrency = Infinity,
41
48
  }) {
42
49
  assert(asset, 'asset is required!')
43
50
  assert(assetClientInterface, 'assetClientInterface is required!')
@@ -46,6 +53,11 @@ export class BitcoinMonitorScanner {
46
53
  assert(typeof shouldExcludeVoutUtxo === 'function', 'shouldExcludeVoutUtxo must be a function')
47
54
  assert(typeof gapLimit === 'number', 'gapLimit must be a number')
48
55
  assert(typeof refreshGapLimit === 'number', 'refreshGapLimit must be a number')
56
+ assert(
57
+ addressBatchConcurrency === Infinity ||
58
+ (Number.isSafeInteger(addressBatchConcurrency) && addressBatchConcurrency > 0),
59
+ 'addressBatchConcurrency must be positive'
60
+ )
49
61
 
50
62
  this.#asset = asset
51
63
  this.#insightClient = insightClient
@@ -56,6 +68,7 @@ export class BitcoinMonitorScanner {
56
68
  this.#extraChainIndex = extraChainIndex
57
69
  this.#gapLimit = gapLimit
58
70
  this.#refreshGapLimit = refreshGapLimit
71
+ this.#addressBatchConcurrency = addressBatchConcurrency
59
72
  }
60
73
 
61
74
  async #getGapLimit({ assetConfig, refresh }) {
@@ -69,7 +82,6 @@ export class BitcoinMonitorScanner {
69
82
  const insightClient = this.#insightClient
70
83
  const txFetchLimit = this.#txFetchLimitResolver({ assetName: asset.name, refresh })
71
84
  const assetName = asset.name
72
- const purposes = await assetClientInterface.getSupportedPurposes({ assetName, walletAccount })
73
85
  const accountState = await assetClientInterface.getAccountState({ assetName, walletAccount })
74
86
  const currency = asset.currency
75
87
  const currentTxs = await assetClientInterface.getTxLog({ assetName, walletAccount })
@@ -80,6 +92,13 @@ export class BitcoinMonitorScanner {
80
92
 
81
93
  const multisigDataLength = assetConfig.multisigDataLength
82
94
 
95
+ const purposes = await getAvailablePurposes({
96
+ assetClientInterface,
97
+ assetName,
98
+ walletAccount,
99
+ multisigDataLength,
100
+ })
101
+
83
102
  // multiAddressMode may be null, in which case it is enabled.
84
103
  const multiAddressMode = assetConfig.multiAddressMode ?? true
85
104
 
@@ -233,22 +252,25 @@ export class BitcoinMonitorScanner {
233
252
  const fetchAllTxs = async (addresses) => {
234
253
  if (addresses.length === 0) return []
235
254
 
236
- const promises = []
255
+ const batches = []
237
256
  const fetchTimeout = 250
238
257
 
239
258
  const fetchAddressesSize = 25
240
- for (let i = 0; i < addresses.length; i += fetchAddressesSize) {
241
- const fetchAddresses = addresses.slice(i, i + fetchAddressesSize)
242
- const promise = insightClient.fetchAllTxData(
243
- fetchAddresses,
244
- txFetchLimit,
245
- fetchTimeout,
246
- shouldStop
247
- )
248
- promises.push(promise)
259
+ for (let start = 0; start < addresses.length; start += fetchAddressesSize) {
260
+ batches.push(addresses.slice(start, start + fetchAddressesSize))
249
261
  }
250
262
 
251
- const listOfTxs = await Promise.all(promises)
263
+ const listOfTxs = []
264
+ for (let start = 0; start < batches.length; start += this.#addressBatchConcurrency) {
265
+ const transactions = await Promise.all(
266
+ batches
267
+ .slice(start, start + this.#addressBatchConcurrency)
268
+ .map((fetchAddresses) =>
269
+ insightClient.fetchAllTxData(fetchAddresses, txFetchLimit, fetchTimeout, shouldStop)
270
+ )
271
+ )
272
+ listOfTxs.push(...transactions)
273
+ }
252
274
  return listOfTxs.flat()
253
275
  }
254
276
 
@@ -313,12 +335,25 @@ export class BitcoinMonitorScanner {
313
335
 
314
336
  if (fetchCount === 0) {
315
337
  // in compatibility mode, the receive address could be different
316
- const receiveAddress = await this.#assetClientInterface.getReceiveAddressObject({
317
- assetName,
318
- walletAccount,
319
- useCache: true,
320
- })
321
- if (!addresses.includes(receiveAddress.toString())) {
338
+ let receiveAddress
339
+ try {
340
+ receiveAddress = await this.#assetClientInterface.getReceiveAddressObject({
341
+ assetName,
342
+ walletAccount,
343
+ useCache: true,
344
+ })
345
+ } catch (error) {
346
+ // The default purpose may be one of the ones without an xpub (e.g. old
347
+ // Trezor accounts missing purpose 84); the scan can still proceed on the
348
+ // available purposes.
349
+ if (!isMissingXpubError(error)) throw error
350
+
351
+ console.warn(
352
+ `${assetName}: no xpub for the default receive address in wallet account ${walletAccount}, skipping it. ${error.message}`
353
+ )
354
+ }
355
+
356
+ if (receiveAddress && !addresses.includes(receiveAddress.toString())) {
322
357
  addresses.push(receiveAddress.toString())
323
358
  scannedAddressSet.add(receiveAddress.toString())
324
359
  addrMap[receiveAddress.toString()] = receiveAddress
@@ -360,14 +395,14 @@ export class BitcoinMonitorScanner {
360
395
  (newChain) => newChain.purpose === purposeToUpdate
361
396
  )
362
397
  if (!chainToUpgrade) {
363
- console.log(
398
+ console.debug(
364
399
  `${assetName}: There is no chain info for purpose ${purposeToUpdate} and address ${addressString}`
365
400
  )
366
401
  return
367
402
  }
368
403
 
369
404
  if (chainToUpgrade.chain[metaChainIndex] === undefined) {
370
- console.log(
405
+ console.debug(
371
406
  `${assetName}: There is no chain info for purpose ${purposeToUpdate}, address ${addressString} and chain index ${metaChainIndex}`
372
407
  )
373
408
  return
@@ -382,9 +417,9 @@ export class BitcoinMonitorScanner {
382
417
  }
383
418
 
384
419
  gapSearchParameters.forEach((indexData) => {
385
- // eslint-disable-next-line @exodus/mutable/no-param-reassign-prop-only
420
+ // eslint-disable-next-line @exodus/hydra/no-param-reassign-prop-only
386
421
  indexData.startAddressIndexes = [...indexData.endAddressIndexes]
387
- // eslint-disable-next-line @exodus/mutable/no-param-reassign-prop-only
422
+ // eslint-disable-next-line @exodus/hydra/no-param-reassign-prop-only
388
423
  indexData.endAddressIndexes = indexData.chain.map((addressIndex) => {
389
424
  return addressIndex + resolvedGapLimit
390
425
  })
@@ -649,7 +684,7 @@ export class BitcoinMonitorScanner {
649
684
  const txStatus = await insightClient.fetchTx(tx.txId)
650
685
  return { tx, shouldDrop: !txStatus }
651
686
  } catch (err) {
652
- console.log(
687
+ console.debug(
653
688
  `${assetName}: failed to verify pending tx ${tx.txId} before drop check: ${
654
689
  err?.message || 'unknown'
655
690
  }`
@@ -742,12 +777,18 @@ export class BitcoinMonitorScanner {
742
777
 
743
778
  const maybeConfirmationList = await Promise.all(
744
779
  unconfirmedTxIds.map(async (txId) => {
745
- const txStatus = await this.#insightClient.fetchTx(txId)
746
- if (!txStatus?.confirmations) {
780
+ let confirmations
781
+ if (this.#insightClient.fetchTxConfirmations) {
782
+ confirmations = await this.#insightClient.fetchTxConfirmations(txId)
783
+ } else {
784
+ const transaction = await this.#insightClient.fetchTx(txId)
785
+ confirmations = transaction?.confirmations
786
+ }
787
+ if (!confirmations) {
747
788
  return
748
789
  }
749
790
 
750
- return { txId, confirmations: txStatus.confirmations }
791
+ return { txId, confirmations }
751
792
  })
752
793
  )
753
794
  const confirmationsList = maybeConfirmationList.filter(Boolean)
@@ -76,6 +76,7 @@ export class Monitor extends BaseMonitor {
76
76
  assetClientInterface,
77
77
  insightClient,
78
78
  ...extraScannerParams,
79
+ addressBatchConcurrency: monitorType === 'mempool' ? 2 : Infinity,
79
80
  })
80
81
 
81
82
  this.addHook('after-tick-multiple-wallet-accounts', () => this.#subscribeToNewAddresses())
@@ -84,6 +85,7 @@ export class Monitor extends BaseMonitor {
84
85
  this.#ws.close()
85
86
  this.#ws = null
86
87
  }
88
+ if (this.#monitorType === 'mempool') this.#insightClient.clearWebSocketCache?.()
87
89
  })
88
90
  this.addHook('after-stop', async () =>
89
91
  Promise.all(Object.keys(this.#runningByWalletAccount).map(this.#waitForWalletToFinish))
@@ -172,6 +174,9 @@ export class Monitor extends BaseMonitor {
172
174
  }
173
175
 
174
176
  this.#ws.connect(addressesArr)
177
+ if (this.#monitorType === 'mempool') {
178
+ this.#ws.on('update', (payload) => this.#insightClient.updateFromWebSocket?.(payload))
179
+ }
175
180
  this.#ws.on('connect', () => {
176
181
  this.#logWsStatus('connect to addresses', addressesArr)
177
182
  this.timer.setNewInterval(this.#wsInterval)
@@ -184,6 +189,7 @@ export class Monitor extends BaseMonitor {
184
189
  })
185
190
  this.#ws.on('block', () => this.onNewBlock())
186
191
  this.#ws.on('disconnect', () => {
192
+ if (this.#monitorType === 'mempool') this.#insightClient.clearWebSocketCache?.()
187
193
  this.#logWsStatus('disconnect')
188
194
  this.timer.setNewInterval(this.interval)
189
195
  })
@@ -29,7 +29,7 @@ export const indexOutputs = ({ tx, currency }) => {
29
29
  outputOffset = outputOffset.add(value)
30
30
  }
31
31
 
32
- // eslint-disable-next-line @exodus/mutable/no-param-reassign-prop-only
32
+ // eslint-disable-next-line @exodus/hydra/no-param-reassign-prop-only
33
33
  tx.inscriptionsMemoryIndexed = true // avoids btc being spent even when the mempool index was done in memory
34
34
  return tx
35
35
  }
@@ -52,7 +52,7 @@ export const cachedIndexOrdinalUnconfirmedTx = memoizeLruCache(
52
52
  throw new Error(`Cannot index ${tx.txid}. Input tx ${outputTx.txid} is not indexed. `)
53
53
  }
54
54
 
55
- // eslint-disable-next-line @exodus/mutable/no-param-reassign-prop-only
55
+ // eslint-disable-next-line @exodus/hydra/no-param-reassign-prop-only
56
56
  vin.inscriptions = outputTx.vout[vin.vout].inscriptions
57
57
  })
58
58
  )
@@ -88,13 +88,14 @@ export const getCreateBatchTransaction = ({
88
88
  let multisigDataIndex = assetConfig.multisigDataLength
89
89
  ? assetConfig.multisigDataLength - 1
90
90
  : 0
91
- let [address, xpub] = await Promise.all([
91
+ const [initialAddress, xpub] = await Promise.all([
92
92
  assetClientInterface.getAddress({
93
93
  ...addressOpts,
94
94
  multisigDataIndex,
95
95
  }),
96
96
  assetClientInterface.getExtendedPublicKey(addressOpts),
97
97
  ])
98
+ let address = initialAddress
98
99
  while (String(address) !== String(utxo.address)) {
99
100
  if (multisigDataIndex === 0) {
100
101
  throw new Error(`Address does not match ${String(address)} - ${String(utxo.address)}`)
@@ -42,7 +42,7 @@ export async function broadcastTransaction({ asset, rawTx }) {
42
42
  } catch (err) {
43
43
  if (getErrorText(err).includes('txn-already-in-mempool')) {
44
44
  // Not an error, transaction is already broadcast
45
- console.log('Transaction is already in the mempool.')
45
+ console.debug('Transaction is already in the mempool.')
46
46
  return
47
47
  }
48
48
 
@@ -211,6 +211,9 @@ export const sendTxFactory = ({
211
211
  try {
212
212
  await broadcastTransaction({ asset, rawTx })
213
213
  } catch (err) {
214
+ if (['MEMPOOL_REQUEST_BUSY', 'MEMPOOL_REQUEST_QUEUE_TIMEOUT'].includes(err.code)) {
215
+ throw err
216
+ }
214
217
  const txExists = await checkTxExists({ asset, txId })
215
218
  if (txExists) {
216
219
  console.warn(`tx-send: ${assetName} tx already broadcast`, txId)
@@ -1,5 +1,6 @@
1
1
  import { Address } from '@exodus/models'
2
2
 
3
+ import { getAvailablePurposes } from '../address-utils.js'
3
4
  import { serializeCurrency } from '../fee/fee-utils.js'
4
5
 
5
6
  const normalizeAddressObject = (asset, value) => {
@@ -58,12 +59,8 @@ const getWalletAddressObjects = async ({
58
59
  walletAccount,
59
60
  chainIndex,
60
61
  multisigDataLength,
62
+ purposes,
61
63
  }) => {
62
- const purposes = await assetClientInterface.getSupportedPurposes({
63
- assetName,
64
- walletAccount,
65
- })
66
-
67
64
  const unusedAddressIndexes = await assetClientInterface.getUnusedAddressIndexes({
68
65
  assetName,
69
66
  walletAccount,
@@ -186,6 +183,13 @@ export async function updateTransactionLog({
186
183
 
187
184
  const multisigDataLength = config?.multisigDataLength
188
185
 
186
+ const purposes = await getAvailablePurposes({
187
+ assetClientInterface,
188
+ assetName,
189
+ walletAccount,
190
+ multisigDataLength,
191
+ })
192
+
189
193
  const walletReceiveAddressObjects = await getWalletAddressObjects({
190
194
  asset,
191
195
  assetClientInterface,
@@ -193,6 +197,7 @@ export async function updateTransactionLog({
193
197
  walletAccount,
194
198
  chainIndex: 0,
195
199
  multisigDataLength,
200
+ purposes,
196
201
  })
197
202
  const walletChangeAddressObjects = await getWalletAddressObjects({
198
203
  asset,
@@ -201,6 +206,7 @@ export async function updateTransactionLog({
201
206
  walletAccount,
202
207
  chainIndex: 1,
203
208
  multisigDataLength,
209
+ purposes,
204
210
  })
205
211
 
206
212
  const walletAddressObjects = [...walletReceiveAddressObjects, ...walletChangeAddressObjects]
@@ -1,9 +1,9 @@
1
1
  import { getOwnProperty, memoize } from '@exodus/basic-utils'
2
+ import { fromWifStringSync } from '@exodus/bytes/wif.js'
2
3
  import { privateKeyToPublicKey } from '@exodus/crypto/secp256k1'
3
4
  import KeyIdentifier from '@exodus/key-identifier'
4
5
  import BipPath from 'bip32-path'
5
6
  import assert from 'minimalistic-assert'
6
- import WIF from 'wif'
7
7
 
8
8
  export const createGetKeyWithMetadata = ({
9
9
  signer,
@@ -43,7 +43,7 @@ function standardGetPrivateKeyFromMap(privateKeysAddressMap, networkInfo, purpos
43
43
 
44
44
  // networkInfo is coininfo('{something}').toBitcoinJS()
45
45
  const useNet = networkInfo || { wif: 0x80 } // default to bitcoin
46
- const { privateKey, compressed, version } = WIF.decode(privateWif)
46
+ const { privateKey, compressed, version } = fromWifStringSync(privateWif)
47
47
  if (version !== useNet.wif) throw new Error('Invalid network version')
48
48
 
49
49
  const publicKey = privateKeyToPublicKey({ privateKey, compressed, format: 'buffer' })
@@ -119,7 +119,7 @@ function isOrdinalUtxo({
119
119
  // if this condition is true, that means this is taproot
120
120
  // so we always return true to ensure we accidentally don't spend an ordinal as btc
121
121
  if (!hasOrdinals) {
122
- console.log('Excluding utxo from btc spending:', utxo.address.toString(), utxo)
122
+ console.debug('Excluding utxo from btc spending:', utxo.address.toString(), utxo)
123
123
  }
124
124
 
125
125
  return true // assume is ordinal just in case
@@ -150,7 +150,7 @@ export function mergeAdditionalInscriptions({ allUtxos, additionalInscriptions }
150
150
  offset: additionalInscription.offset || 0,
151
151
  }))
152
152
  if (inscriptions.length > 0) {
153
- // eslint-disable-next-line @exodus/mutable/no-param-reassign-prop-only
153
+ // eslint-disable-next-line @exodus/hydra/no-param-reassign-prop-only
154
154
  utxo.inscriptions = [...(utxo.inscriptions || []), ...inscriptions]
155
155
  }
156
156