@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.
@@ -0,0 +1,154 @@
1
+ import { safeString } from '@exodus/safe-string'
2
+ import { TraceId } from '@exodus/traceparent'
3
+
4
+ import fetchWithTimeout from './fetch-with-timeout.js'
5
+ import scheduleMempoolRequest, { resumeMempoolRequests } from './mempool-request-scheduler.js'
6
+
7
+ const MAX_RETRY_AFTER_MS = 5 * 60_000
8
+ const INITIAL_BACKOFF_MS = 10_000
9
+ const RECOVERY_TIMEOUT_MS = 10_000
10
+ const REQUEST_TIMEOUT_MS = 30_000
11
+ const rateLimitsByOrigin = new Map()
12
+ const recoveringOrigins = new Set()
13
+
14
+ const getRetryAfterMs = (response, now) => {
15
+ const header = response.headers?.get?.('retry-after')?.trim()
16
+ if (!header) return
17
+
18
+ if (/^\d+$/.test(header)) {
19
+ const duration = Math.min(Number(header) * 1000, MAX_RETRY_AFTER_MS)
20
+ return Number.isSafeInteger(now + duration) && duration > 0 ? duration : undefined
21
+ }
22
+
23
+ const retryAt = Date.parse(header)
24
+ const serverDate = Date.parse(response.headers?.get?.('date'))
25
+ const duration = Math.min(
26
+ retryAt - (Number.isFinite(serverDate) ? serverDate : now),
27
+ MAX_RETRY_AFTER_MS
28
+ )
29
+ return Number.isSafeInteger(now + duration) && duration > 0 ? duration : undefined
30
+ }
31
+
32
+ const createRateLimitError = (retryAt, response) => {
33
+ const error = new Error('mempool-api-rate-limited')
34
+ error.hint = safeString`mempoolRateLimited`
35
+ error.code = '429'
36
+ error.finalError = true
37
+ error.retryAt = retryAt
38
+ error.retryAfterMs = Math.max(0, retryAt - Date.now())
39
+ const traceId = response && TraceId.fromResponse?.(response)
40
+ if (traceId) error.traceId = traceId
41
+ return error
42
+ }
43
+
44
+ const enterCooldown = (origin, recoveryState, retryAfterMs) => {
45
+ let state = rateLimitsByOrigin.get(origin)
46
+ if (!state || recoveryState || retryAfterMs !== undefined) {
47
+ const backoffMs = state
48
+ ? Math.min(state.backoffMs * (recoveryState ? 2 : 1), MAX_RETRY_AFTER_MS)
49
+ : INITIAL_BACKOFF_MS
50
+ const duration =
51
+ retryAfterMs ??
52
+ Math.min(Math.round(backoffMs * (1 + Math.random() * 0.2)), MAX_RETRY_AFTER_MS)
53
+ state = {
54
+ retryAt: Math.max(state?.retryAt ?? 0, Date.now() + duration),
55
+ backoffMs,
56
+ }
57
+ rateLimitsByOrigin.set(origin, state)
58
+ }
59
+ resumeMempoolRequests(origin)
60
+ return state
61
+ }
62
+
63
+ const checkCooldown = (origin, isBroadcast) => {
64
+ const state = rateLimitsByOrigin.get(origin)
65
+ if (state && (Date.now() < state.retryAt || recoveringOrigins.has(origin) || isBroadcast)) {
66
+ throw createRateLimitError(state.retryAt)
67
+ }
68
+ }
69
+
70
+ async function executeRequest(url, fetchOptions, consumeResponse, isBroadcast) {
71
+ const origin = new URL(url).origin
72
+ checkCooldown(origin, isBroadcast)
73
+ const recoveryState = rateLimitsByOrigin.get(origin)
74
+ let recoveryResponseHandled = false
75
+ if (recoveryState) {
76
+ recoveringOrigins.add(origin)
77
+ }
78
+ const timeout = fetchOptions?.timeout
79
+ const maximumTimeout = recoveryState ? RECOVERY_TIMEOUT_MS : REQUEST_TIMEOUT_MS
80
+ fetchOptions = {
81
+ ...fetchOptions,
82
+ timeout:
83
+ Number.isFinite(timeout) && timeout > 0 ? Math.min(timeout, maximumTimeout) : maximumTimeout,
84
+ }
85
+
86
+ try {
87
+ return await fetchWithTimeout(url, fetchOptions, async (response) => {
88
+ try {
89
+ if (response.status === 429) {
90
+ const state = enterCooldown(origin, recoveryState, getRetryAfterMs(response, Date.now()))
91
+ recoveryResponseHandled = true
92
+ throw createRateLimitError(state.retryAt, response)
93
+ }
94
+
95
+ if (recoveryState && !response.ok) {
96
+ if (response.status === 404) {
97
+ if (rateLimitsByOrigin.get(origin) === recoveryState) rateLimitsByOrigin.delete(origin)
98
+ } else {
99
+ enterCooldown(origin, recoveryState)
100
+ }
101
+ recoveryResponseHandled = true
102
+ }
103
+
104
+ const result = await consumeResponse(response)
105
+ if (recoveryState && rateLimitsByOrigin.get(origin) === recoveryState && response.ok) {
106
+ rateLimitsByOrigin.delete(origin)
107
+ }
108
+ return result
109
+ } finally {
110
+ try {
111
+ await response.body?.cancel?.()
112
+ } catch {}
113
+ }
114
+ })
115
+ } catch (error) {
116
+ if (recoveryState) {
117
+ const state = recoveryResponseHandled
118
+ ? rateLimitsByOrigin.get(origin)
119
+ : enterCooldown(origin, recoveryState)
120
+ error.finalError = true
121
+ if (state) {
122
+ error.retryAt = state.retryAt
123
+ error.retryAfterMs = Math.max(0, state.retryAt - Date.now())
124
+ }
125
+ }
126
+
127
+ throw error
128
+ } finally {
129
+ if (recoveryState) recoveringOrigins.delete(origin)
130
+ }
131
+ }
132
+
133
+ export default async function mempoolRequest(
134
+ url,
135
+ fetchOptions,
136
+ consumeResponse,
137
+ { isBroadcast = false } = {}
138
+ ) {
139
+ const origin = new URL(url).origin
140
+ if (isBroadcast) checkCooldown(origin, true)
141
+ return scheduleMempoolRequest(
142
+ origin,
143
+ () => executeRequest(url, fetchOptions, consumeResponse, isBroadcast),
144
+ {
145
+ signal: fetchOptions?.signal,
146
+ isBroadcast,
147
+ getCooldown: () => {
148
+ const state = rateLimitsByOrigin.get(origin)
149
+ const recovering = recoveringOrigins.has(origin)
150
+ return state || recovering ? { ...state, recovering } : undefined
151
+ },
152
+ }
153
+ )
154
+ }
@@ -4,7 +4,7 @@ import { TraceId } from '@exodus/traceparent'
4
4
  import delay from 'delay'
5
5
  import urlJoin from 'url-join'
6
6
 
7
- import fetchWithTimeout from './fetch-with-timeout.js'
7
+ import mempoolRequest from './mempool-request.js'
8
8
 
9
9
  const API_PAGE_SIZE = 25
10
10
  const DEFAULT_PAGE_SIZE = 10
@@ -14,6 +14,8 @@ const RETRY_WAIT_TIMES = ['5s', '10s', '20s', '30s']
14
14
  // Serving them from a short-lived cache keeps one request per tick without letting
15
15
  // confirmation counts go meaningfully stale.
16
16
  const TIP_HEIGHT_CACHE_TTL_MS = 10_000
17
+ const WS_STATUS_CACHE_TTL_MS = 10_000
18
+ const MAX_WS_CACHED_STATUSES = 1000
17
19
 
18
20
  const MEMPOOL_HTTP_ERROR_MESSAGE = safeString`mempool-api-http-error`
19
21
  const MEMPOOL_MISSING_TXID_MESSAGE = safeString`mempool-api-missing-txid`
@@ -32,6 +34,7 @@ const MEMPOOL_HTTP_ERROR_FEES_MESSAGE = safeString`mempool-api-http-error:fees`
32
34
  const MEMPOOL_HTTP_ERROR_CPFP_MESSAGE = safeString`mempool-api-http-error:cpfp`
33
35
  const MEMPOOL_FEES_PAYLOAD_ERROR_MESSAGE = safeString`mempool-api-invalid-fees-payload`
34
36
  const MEMPOOL_INVALID_VALUE_ERROR_MESSAGE = safeString`mempool-api-invalid-value`
37
+ const MEMPOOL_STALE_CONFIRMATIONS_MESSAGE = safeString`mempool-api-stale-confirmations`
35
38
 
36
39
  // A txid is a double-SHA256 hash: always exactly 32 bytes / 64 hex chars.
37
40
  const TXID_HEX_PATTERN = /^[\da-f]{64}$/i
@@ -54,6 +57,7 @@ const parseBroadcastErrorReason = (data) => {
54
57
  }
55
58
 
56
59
  const isFiniteNumber = (value) => typeof value === 'number' && Number.isFinite(value)
60
+ const isBlockHeight = (height) => Number.isSafeInteger(height) && height >= 0
57
61
 
58
62
  const toBTCStringFromSatsString = (satsString) => {
59
63
  let value = String(satsString)
@@ -122,49 +126,51 @@ async function withRetry(fn, args = [], { waitTimes = RETRY_WAIT_TIMES } = {}) {
122
126
  }
123
127
 
124
128
  async function fetchJson(url, fetchOptions, { nullWhen404 = false, httpErrorMessage } = {}) {
125
- const response = await fetchWithTimeout(url, fetchOptions)
126
- if (nullWhen404 && response.status === 404) {
127
- return null
128
- }
129
-
130
- if (!response.ok) {
131
- throw createHttpError(response, httpErrorMessage || MEMPOOL_HTTP_ERROR_MESSAGE)
132
- }
129
+ return mempoolRequest(url, fetchOptions, async (response) => {
130
+ if (nullWhen404 && response.status === 404) {
131
+ return null
132
+ }
133
133
 
134
- try {
135
- return await response.json()
136
- } catch (err) {
137
- const error = new Error(MEMPOOL_JSON_ERROR_MESSAGE, { cause: err })
138
- const traceId = TraceId.fromResponse && TraceId.fromResponse(response)
139
- if (traceId) {
140
- error.traceId = traceId
134
+ if (!response.ok) {
135
+ throw createHttpError(response, httpErrorMessage || MEMPOOL_HTTP_ERROR_MESSAGE)
141
136
  }
142
137
 
143
- throw error
144
- }
138
+ try {
139
+ return await response.json()
140
+ } catch (err) {
141
+ const error = new Error(MEMPOOL_JSON_ERROR_MESSAGE, { cause: err })
142
+ const traceId = TraceId.fromResponse && TraceId.fromResponse(response)
143
+ if (traceId) {
144
+ error.traceId = traceId
145
+ }
146
+
147
+ throw error
148
+ }
149
+ })
145
150
  }
146
151
 
147
152
  async function fetchText(url, fetchOptions, { nullWhen404 = false, httpErrorMessage } = {}) {
148
- const response = await fetchWithTimeout(url, fetchOptions)
149
- if (nullWhen404 && response.status === 404) {
150
- return null
151
- }
152
-
153
- if (!response.ok) {
154
- throw createHttpError(response, httpErrorMessage || MEMPOOL_HTTP_ERROR_MESSAGE)
155
- }
153
+ return mempoolRequest(url, fetchOptions, async (response) => {
154
+ if (nullWhen404 && response.status === 404) {
155
+ return null
156
+ }
156
157
 
157
- try {
158
- return await response.text()
159
- } catch (err) {
160
- const error = new Error(MEMPOOL_TEXT_ERROR_MESSAGE, { cause: err })
161
- const traceId = TraceId.fromResponse && TraceId.fromResponse(response)
162
- if (traceId) {
163
- error.traceId = traceId
158
+ if (!response.ok) {
159
+ throw createHttpError(response, httpErrorMessage || MEMPOOL_HTTP_ERROR_MESSAGE)
164
160
  }
165
161
 
166
- throw error
167
- }
162
+ try {
163
+ return await response.text()
164
+ } catch (err) {
165
+ const error = new Error(MEMPOOL_TEXT_ERROR_MESSAGE, { cause: err })
166
+ const traceId = TraceId.fromResponse && TraceId.fromResponse(response)
167
+ if (traceId) {
168
+ error.traceId = traceId
169
+ }
170
+
171
+ throw error
172
+ }
173
+ })
168
174
  }
169
175
 
170
176
  const normalizeVin = (vin) => {
@@ -224,21 +230,74 @@ export default class MempoolRestClient {
224
230
  this._retryWaitTimes = retryWaitTimes
225
231
  this._configMinFeeRate = configMinFeeRate
226
232
  this._tipHeightCache = null
233
+ this._webSocketTxStatuses = new Map()
234
+ this._webSocketCacheRevision = 0
227
235
  }
228
236
 
229
237
  setMempoolBaseUrl(mempoolBaseURL) {
230
238
  if (mempoolBaseURL !== this._mempoolBaseURL) {
231
- this._tipHeightCache = null
239
+ this.clearWebSocketCache()
232
240
  }
233
241
 
234
242
  this._mempoolBaseURL = mempoolBaseURL
235
243
  }
236
244
 
245
+ clearWebSocketCache() {
246
+ this._webSocketCacheRevision++
247
+ this._tipHeightCache = null
248
+ this._webSocketTxStatuses.clear()
249
+ }
250
+
251
+ updateFromWebSocket(payload) {
252
+ const now = Date.now()
253
+ const blockHeight = payload?.block?.height
254
+ if (payload?.block) {
255
+ this.clearWebSocketCache()
256
+ if (isBlockHeight(blockHeight)) {
257
+ this._tipHeightCache = { promise: Promise.resolve(blockHeight), startedAt: now }
258
+ }
259
+ }
260
+
261
+ const addresses = payload?.['multi-address-transactions']
262
+ if (!addresses || typeof addresses !== 'object' || Array.isArray(addresses)) return
263
+
264
+ for (const transactions of Object.values(addresses)) {
265
+ for (const kind of ['mempool', 'confirmed', 'removed']) {
266
+ if (!Array.isArray(transactions?.[kind])) continue
267
+ for (const transaction of transactions[kind]) {
268
+ const txid = transaction?.txid
269
+ if (typeof txid !== 'string' || !TXID_HEX_PATTERN.test(txid)) continue
270
+ this._webSocketCacheRevision++
271
+ this._webSocketTxStatuses.delete(txid)
272
+ if (kind === 'removed') continue
273
+
274
+ const height = isBlockHeight(blockHeight)
275
+ ? blockHeight
276
+ : transaction.status?.confirmed === true
277
+ ? transaction.status.block_height
278
+ : undefined
279
+ if (kind === 'confirmed' && !isBlockHeight(height)) continue
280
+
281
+ if (kind === 'confirmed' && !isBlockHeight(blockHeight)) {
282
+ this._tipHeightCache = null
283
+ }
284
+
285
+ const status =
286
+ kind === 'confirmed' ? { confirmed: true, block_height: height } : { confirmed: false }
287
+ this._webSocketTxStatuses.set(txid, { status, receivedAt: now })
288
+ if (this._webSocketTxStatuses.size > MAX_WS_CACHED_STATUSES) {
289
+ this._webSocketTxStatuses.delete(this._webSocketTxStatuses.keys().next().value)
290
+ }
291
+ }
292
+ }
293
+ }
294
+ }
295
+
237
296
  _mempoolApiUrl(path, { version } = {}) {
238
297
  return urlJoin(this._mempoolBaseURL, version === 'v1' ? '/api/v1' : '/api', path)
239
298
  }
240
299
 
241
- async _fetchTipHeight() {
300
+ _fetchTipHeight() {
242
301
  const now = Date.now()
243
302
  if (this._tipHeightCache && now - this._tipHeightCache.startedAt < TIP_HEIGHT_CACHE_TTL_MS) {
244
303
  return this._tipHeightCache.promise
@@ -395,6 +454,32 @@ export default class MempoolRestClient {
395
454
  return this._fetchTipHeight()
396
455
  }
397
456
 
457
+ async fetchTxConfirmations(txid) {
458
+ for (let attempt = 0; attempt < 2; attempt++) {
459
+ const revision = this._webSocketCacheRevision
460
+ const cached = this._webSocketTxStatuses.get(txid)
461
+ const fresh = cached && Date.now() - cached.receivedAt < WS_STATUS_CACHE_TTL_MS
462
+ if (!fresh) this._webSocketTxStatuses.delete(txid)
463
+ const status = fresh
464
+ ? cached.status
465
+ : await fetchJson(
466
+ this._mempoolApiUrl(`/tx/${encodeURIComponent(txid)}/status`),
467
+ undefined,
468
+ {
469
+ nullWhen404: true,
470
+ httpErrorMessage: MEMPOOL_HTTP_ERROR_STATUS_MESSAGE,
471
+ }
472
+ )
473
+ if (revision !== this._webSocketCacheRevision) continue
474
+ if (!status?.confirmed) return 0
475
+ const tipHeight = await this._fetchTipHeight()
476
+ if (revision === this._webSocketCacheRevision) {
477
+ return normalizeTxConfirmations(status, tipHeight)
478
+ }
479
+ }
480
+ throw new Error(MEMPOOL_STALE_CONFIRMATIONS_MESSAGE)
481
+ }
482
+
398
483
  async fetchTx(txid) {
399
484
  const tipHeightPromise = this._fetchTipHeight()
400
485
  const encodedTxid = encodeURIComponent(txid)
@@ -658,38 +743,43 @@ export default class MempoolRestClient {
658
743
  // classification (broadcast-tx.js) pattern-matches it.
659
744
  async broadcastTx(rawTx) {
660
745
  const payload = rawTx instanceof Uint8Array ? Buffer.from(rawTx).toString('hex') : rawTx
661
- const response = await fetch(this._mempoolApiUrl('/tx'), {
662
- method: 'post',
663
- headers: {
664
- Accept: 'text/plain',
665
- 'Content-Type': 'text/plain',
746
+ return mempoolRequest(
747
+ this._mempoolApiUrl('/tx'),
748
+ {
749
+ method: 'post',
750
+ headers: {
751
+ Accept: 'text/plain',
752
+ 'Content-Type': 'text/plain',
753
+ },
754
+ body: payload,
666
755
  },
667
- body: payload,
668
- })
669
-
670
- const data = await response.text()
671
-
672
- if (!response.ok) {
673
- console.warn(`Mempool Client's Broadcast HTTP Error:`)
674
- console.warn(response.statusText)
675
- console.warn(data)
676
- const error = createHttpError(response, MEMPOOL_HTTP_ERROR_BROADCAST_MESSAGE)
677
- error.reason = parseBroadcastErrorReason(data)
678
- throw error
679
- }
756
+ async (response) => {
757
+ const data = await response.text()
758
+
759
+ if (!response.ok) {
760
+ console.warn(`Mempool Client's Broadcast HTTP Error:`)
761
+ console.warn(response.statusText)
762
+ console.warn(data)
763
+ const error = createHttpError(response, MEMPOOL_HTTP_ERROR_BROADCAST_MESSAGE)
764
+ error.reason = parseBroadcastErrorReason(data)
765
+ throw error
766
+ }
680
767
 
681
- const txid = String(data).trim()
682
- if (!TXID_HEX_PATTERN.test(txid)) {
683
- console.warn(`Mempool Client's Broadcast Unexpected Payload:`, data)
684
- const error = new Error(MEMPOOL_MISSING_TXID_MESSAGE)
685
- const traceId = TraceId.fromResponse && TraceId.fromResponse(response)
686
- if (traceId) {
687
- error.traceId = traceId
688
- }
768
+ const txid = String(data).trim()
769
+ if (!TXID_HEX_PATTERN.test(txid)) {
770
+ console.warn(`Mempool Client's Broadcast Unexpected Payload:`, data)
771
+ const error = new Error(MEMPOOL_MISSING_TXID_MESSAGE)
772
+ const traceId = TraceId.fromResponse && TraceId.fromResponse(response)
773
+ if (traceId) {
774
+ error.traceId = traceId
775
+ }
689
776
 
690
- throw error
691
- }
777
+ throw error
778
+ }
692
779
 
693
- return { txid }
780
+ return { txid }
781
+ },
782
+ { isBroadcast: true }
783
+ )
694
784
  }
695
785
  }
@@ -257,6 +257,10 @@ export default class MempoolWSClient extends EventEmitter {
257
257
  this.#clearPongTimeout()
258
258
  }
259
259
 
260
+ if (payload.block || payload['multi-address-transactions']) {
261
+ this.emit('update', payload)
262
+ }
263
+
260
264
  if (payload.block) {
261
265
  this.emit('block', payload.block)
262
266
  }
package/src/move-funds.js CHANGED
@@ -1,13 +1,13 @@
1
+ import { fromWifStringSync } from '@exodus/bytes/wif.js'
1
2
  import { privateKeyToPublicKey, publicKeyConvert } from '@exodus/crypto/secp256k1'
2
3
  import { Address, UtxoCollection } from '@exodus/models'
3
4
  import assert from 'minimalistic-assert'
4
- import wif from 'wif'
5
5
 
6
6
  import { createInputs, createOutput, getNonWitnessTxs } from './tx-create/tx-create-utils.js'
7
7
 
8
8
  const isValidPrivateKey = (privateKey) => {
9
9
  try {
10
- wif.decode(privateKey)
10
+ fromWifStringSync(privateKey)
11
11
  return true
12
12
  } catch {
13
13
  return false
@@ -19,7 +19,7 @@ const wifToPublicKey = ({ coinInfo, privateKeyWIF }) => {
19
19
  assert(privateKeyWIF, 'privateKeyWIF is required')
20
20
  const { versions } = coinInfo
21
21
 
22
- const { privateKey, compressed } = wif.decode(privateKeyWIF, versions.private)
22
+ const { privateKey, compressed } = fromWifStringSync(privateKeyWIF, versions.private)
23
23
  const publicKey = privateKeyToPublicKey({ privateKey, compressed, format: 'buffer' })
24
24
  return { compressed, publicKey }
25
25
  }
@@ -425,7 +425,11 @@ const transferHandler = {
425
425
  isSendAll,
426
426
  })
427
427
 
428
- let { selectedUtxos, fee, replaceTx } = selectUtxos({
428
+ const {
429
+ selectedUtxos: initialSelectedUtxos,
430
+ fee,
431
+ replaceTx,
432
+ } = selectUtxos({
429
433
  asset,
430
434
  usableUtxos: context.usableUtxos,
431
435
  replaceableTxs,
@@ -444,6 +448,7 @@ const transferHandler = {
444
448
  taprootInputWitnessSize,
445
449
  changeAddressType,
446
450
  })
451
+ let selectedUtxos = initialSelectedUtxos
447
452
 
448
453
  if (!selectedUtxos?.size && !replaceTx) {
449
454
  throw new Error('Not enough funds.')