@exodus/bitcoin-api 5.0.2 → 5.0.4

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,30 @@
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.0.4](https://github.com/ExodusMovement/assets/compare/@exodus/bitcoin-api@5.0.3...@exodus/bitcoin-api@5.0.4) (2026-09-28)
7
+
8
+
9
+ ### Bug Fixes
10
+
11
+ * **bitcoin-api:** gracefully handle hardware wallets with incomplete xpubs ([#8429](https://github.com/ExodusMovement/assets/issues/8429)) ([6b7901e](https://github.com/ExodusMovement/assets/commit/6b7901ee09cf224442a64b94ecb973c1d1cca5ea))
12
+ * **bitcoin-api:** honor mempool Retry-After on HTTP 429 ([#8749](https://github.com/ExodusMovement/assets/issues/8749)) ([eedf948](https://github.com/ExodusMovement/assets/commit/eedf94874e688ffff72303a67233820a16384f0d))
13
+ * disable @exodus/hydra/no-param-reassign-prop-only warnings ([#8531](https://github.com/ExodusMovement/assets/issues/8531)) ([ddae556](https://github.com/ExodusMovement/assets/commit/ddae556361285919fe82cd10a81cfeae79ccc6b5))
14
+ * **lint:** convert console.log/info to console.debug and enforce no-console ([#8529](https://github.com/ExodusMovement/assets/issues/8529)) ([81cf5e9](https://github.com/ExodusMovement/assets/commit/81cf5e90b8157b084cf4cb311c02803c29e622e4))
15
+ * **lint:** migrate lodash to @exodus/basic-utils ([#8514](https://github.com/ExodusMovement/assets/issues/8514)) ([12c574f](https://github.com/ExodusMovement/assets/commit/12c574f1ac8ab0592700df574b2643141237090a))
16
+
17
+
18
+
19
+ ## [5.0.3](https://github.com/ExodusMovement/assets/compare/@exodus/bitcoin-api@5.0.0...@exodus/bitcoin-api@5.0.3) (2026-08-10)
20
+
21
+
22
+ ### Bug Fixes
23
+
24
+ * extract broadcast rejection reason from error body message field ([#8396](https://github.com/ExodusMovement/assets/issues/8396)) ([a916a55](https://github.com/ExodusMovement/assets/commit/a916a55af921da5125405a0be8ca43321a3654fd))
25
+ * refuse SIGHASH_SINGLE signatures that commit to no output (3927405) ([#8479](https://github.com/ExodusMovement/assets/issues/8479)) ([cde191b](https://github.com/ExodusMovement/assets/commit/cde191b91a32be1bc5de4bb838b97d0e6a843527))
26
+ * **send-validation:** improve displayed amount format in validation messages ([#8366](https://github.com/ExodusMovement/assets/issues/8366)) ([940dcd4](https://github.com/ExodusMovement/assets/commit/940dcd4cbe75f4ab48e067bd033afd249caae9a4))
27
+
28
+
29
+
6
30
  ## [5.0.2](https://github.com/ExodusMovement/assets/compare/@exodus/bitcoin-api@5.0.0...@exodus/bitcoin-api@5.0.2) (2026-07-16)
7
31
 
8
32
 
package/README.md CHANGED
@@ -1,3 +1,11 @@
1
1
  # @exodus/bitcoin-api
2
2
 
3
3
  Transaction monitors, fee monitors, RPC with the blockchain node, and other networking code for Bitcoin and Bitcoin-like assets (e.g. dogecoin, litecoin, zcash). See [Asset Packages](../../docs/asset-packages.md) for more detail on this package's role.
4
+
5
+ ## Mempool Retry-After
6
+
7
+ When a mempool REST request receives HTTP 429 with a valid future `Retry-After`, subsequent requests to the same origin fail locally until the cooldown expires. Each response's cooldown is capped at five minutes so a single excessive server value cannot lock out reads and sends indefinitely. Shorter delays are honored as supplied. The cooldown is shared across client instances within the application process and accepts both delay-seconds and HTTP-date headers, using the server's `Date` header when available to account for clock skew. Already-running requests are not cancelled, and cooldowns do not persist across application restarts.
8
+
9
+ These errors retain code `429` and expose the bounded `retryAt`, `retryAfterMs`, and the safe hint `mempoolRateLimited`. They stop the generic retry loop; reads resume on the next normal request after the deadline. A new 429 with a valid future `Retry-After` starts another bounded cooldown. The cap can allow requests earlier than the server requested and does not guarantee that the server will accept them. Broadcasts also fail immediately during the cooldown rather than being queued or retried later.
10
+
11
+ Missing, malformed, zero, or expired `Retry-After` values keep the existing HTTP-error and retry behavior. This change does not add a fallback cooldown, concurrency limits, or backoff changes for other responses.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@exodus/bitcoin-api",
3
- "version": "5.0.2",
3
+ "version": "5.0.4",
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",
@@ -16,9 +16,7 @@
16
16
  "provenance": false
17
17
  },
18
18
  "scripts": {
19
- "test": "run -T exodus-test --jest",
20
- "lint": "run -T eslintc .",
21
- "lint:fix": "yarn lint --fix"
19
+ "test": "exodus-test --jest"
22
20
  },
23
21
  "dependencies": {
24
22
  "@exodus/asset-lib": "^5.0.0",
@@ -28,18 +26,17 @@
28
26
  "@exodus/bip44-constants": "^195.0.0",
29
27
  "@exodus/bitcoin-lib": "^2.4.3",
30
28
  "@exodus/bitcoinjs": "^2.0.0",
29
+ "@exodus/bytes": "^1.16.0",
31
30
  "@exodus/crypto": "^1.0.0-rc.13",
32
31
  "@exodus/currency": "^6.0.1",
33
32
  "@exodus/i18n-dummy": "^1.0.0",
34
- "@exodus/key-identifier": "^1.3.0",
33
+ "@exodus/key-identifier": "^1.5.0",
35
34
  "@exodus/models": "^13.0.0",
36
35
  "@exodus/safe-string": "^1.4.0",
37
36
  "@exodus/send-validation-model": "^1.0.0",
38
37
  "@exodus/simple-retry": "^0.0.6",
39
38
  "@exodus/traceparent": "^3.0.1",
40
- "bech32": "^1.1.3",
41
39
  "bip32-path": "^0.4.2",
42
- "bs58check": "^3.0.1",
43
40
  "delay": "^4.0.1",
44
41
  "eventemitter3": "^5.0.4",
45
42
  "events": "^3.3.0",
@@ -48,8 +45,7 @@
48
45
  "ms": "^2.1.1",
49
46
  "socket.io-client": "^2.1.1",
50
47
  "url-join": "^4.0.0",
51
- "varuint-bitcoin": "^1.1.0",
52
- "wif": "^4.0.0"
48
+ "varuint-bitcoin": "^1.1.0"
53
49
  },
54
50
  "devDependencies": {
55
51
  "@exodus/bitcoin-meta": "^2.0.0",
@@ -63,5 +59,5 @@
63
59
  "type": "git",
64
60
  "url": "git+https://github.com/ExodusMovement/assets.git"
65
61
  },
66
- "gitHead": "a701d1d9a7fbefc15d3f5b528cd3b2ebba90ee83"
62
+ "gitHead": "c24c69f957a347f7b0439d0a83814707aa840fd2"
67
63
  }
@@ -17,3 +17,64 @@ function parsePath(address) {
17
17
  const p1 = path ? path.replace('m/', '').split('/') : ['0', '0']
18
18
  return p1.map((i) => parseInt(i, 10))
19
19
  }
20
+
21
+ // The address provider's public-key-provider throws PublicKeyNotFoundError when the
22
+ // wallet account has no xpub in storage for the requested derivation path. The error
23
+ // carries no `code` and the class is not importable from this package (and instanceof
24
+ // would break across duplicated copies), so match on `name` — an own instance property
25
+ // that survives minification — with a message fallback for older provider versions.
26
+ export function isMissingXpubError(error) {
27
+ return (
28
+ error?.name === 'PublicKeyNotFoundError' || /no public key found/i.test(error?.message ?? '')
29
+ )
30
+ }
31
+
32
+ export async function getAvailablePurposes({
33
+ assetClientInterface,
34
+ assetName,
35
+ walletAccount,
36
+ multisigDataLength,
37
+ }) {
38
+ const supportedPurposes = await assetClientInterface.getSupportedPurposes({
39
+ assetName,
40
+ walletAccount,
41
+ })
42
+
43
+ // getSupportedPurposes reflects derivation capability, not which xpubs the wallet
44
+ // account actually has in storage — hardware wallets (e.g. old Trezor models) may
45
+ // only provide some of them. Probe the first address of each purpose and skip the
46
+ // purposes that cannot derive.
47
+ const probes = await Promise.all(
48
+ supportedPurposes.map(async (purpose) => {
49
+ try {
50
+ await assetClientInterface.getAddress({
51
+ assetName,
52
+ walletAccount,
53
+ purpose,
54
+ chainIndex: 0,
55
+ addressIndex: 0,
56
+ ...(multisigDataLength ? { multisigDataIndex: 0 } : Object.create(null)),
57
+ })
58
+ return { purpose }
59
+ } catch (error) {
60
+ // Degrade only on the condition this helper is about — a missing xpub. Any
61
+ // other failure (locked seed, storage error, timeout) is transient or a real
62
+ // bug: silently dropping the purpose would corrupt tx classification, while a
63
+ // thrown scan is recoverable on the next attempt.
64
+ if (!isMissingXpubError(error)) throw error
65
+
66
+ console.warn(
67
+ `${assetName}: no xpub for purpose ${purpose} in wallet account ${walletAccount}, skipping it. ${error.message}`
68
+ )
69
+ return { purpose, error }
70
+ }
71
+ })
72
+ )
73
+
74
+ const availablePurposes = probes.filter((probe) => !probe.error).map((probe) => probe.purpose)
75
+ if (supportedPurposes.length > 0 && availablePurposes.length === 0) {
76
+ throw probes[0].error
77
+ }
78
+
79
+ return availablePurposes
80
+ }
@@ -1,10 +1,11 @@
1
+ /* oxlint-disable @exodus/oxlint-plugin-restricted-imports/prefer-basic-utils -- identity not in basic-utils */
1
2
  import * as bitcoinjsOriginal from '@exodus/bitcoinjs'
2
- import * as bech32 from 'bech32'
3
- import bs58check from 'bs58check'
3
+ import { pickBy } from '@exodus/basic-utils'
4
+ import { fromBase58checkSync } from '@exodus/bytes/base58check.js'
4
5
  import lodash from 'lodash'
5
6
  import assert from 'minimalistic-assert'
6
7
 
7
- const { identity, pickBy } = lodash
8
+ const { identity } = lodash
8
9
 
9
10
  export const createBtcLikeAddress = ({
10
11
  versions,
@@ -21,8 +22,12 @@ export const createBtcLikeAddress = ({
21
22
  version === undefined
22
23
  ? undefined
23
24
  : (string) => {
24
- const payload = bs58check.decodeUnsafe(string)
25
- return !!payload && payload.length === 21 && payload[0] === version
25
+ try {
26
+ const payload = fromBase58checkSync(string)
27
+ return payload.length === 21 && payload[0] === version
28
+ } catch {
29
+ return false
30
+ }
26
31
  }
27
32
 
28
33
  const bech32ValidateFactory = (version, length) =>
@@ -30,13 +35,10 @@ export const createBtcLikeAddress = ({
30
35
  ? undefined
31
36
  : (string) => {
32
37
  try {
33
- const decoded = bech32.decode(string)
34
- // bech32 lib normalizes prefixes, so not worrying about uppercase
35
- if (decoded.prefix !== versions.bech32) return false
38
+ // fromBech32 normalizes prefixes, so not worrying about uppercase
39
+ const { prefix, version, data } = bitcoinjsOriginal.address.fromBech32(string)
36
40
  // NOTE: We only support version zero witness programs
37
- if (decoded.words[0] !== 0) return false
38
- // Ensure correct length
39
- return bech32.fromWords(decoded.words.slice(1)).length === length
41
+ return prefix === versions.bech32 && version === 0 && data.length === length
40
42
  } catch {
41
43
  return false
42
44
  }
@@ -1,18 +1,19 @@
1
+ /* oxlint-disable @exodus/oxlint-plugin-restricted-imports/prefer-basic-utils -- identity not in basic-utils */
1
2
  import * as defaultBitcoinjsLib from '@exodus/bitcoinjs'
3
+ import { pickBy } from '@exodus/basic-utils'
4
+ import { toBase58checkSync } from '@exodus/bytes/base58check.js'
5
+ import { fromWifStringSync, toWifStringSync } from '@exodus/bytes/wif.js'
2
6
  import * as secp256k1 from '@exodus/crypto/secp256k1'
3
- import * as bech32 from 'bech32'
4
- import bs58check from 'bs58check'
5
7
  import lodash from 'lodash'
6
8
  import assert from 'minimalistic-assert'
7
- import wif from 'wif'
8
9
 
9
10
  import { hash160 } from './hash-utils.js'
10
11
 
11
- const { identity, pickBy } = lodash
12
+ const { identity } = lodash
12
13
 
13
14
  export const publicKeyToHashFactory = (p2pkh) => (publicKey) => {
14
15
  const payload = Buffer.concat([Buffer.from([p2pkh]), hash160(publicKey)])
15
- return bs58check.encode(payload)
16
+ return toBase58checkSync(payload)
16
17
  }
17
18
 
18
19
  export const createBtcLikeKeys = ({
@@ -37,13 +38,13 @@ export const createBtcLikeKeys = ({
37
38
  const encodePrivate =
38
39
  encodePrivateCustom ||
39
40
  ((privateKey, compressed = true) => {
40
- return wif.encode(coinInfo.versions.private, privateKey, compressed)
41
+ return toWifStringSync({ version: coinInfo.versions.private, privateKey, compressed })
41
42
  })
42
43
  const encodePublicPurpose44 = encodePublicCustom || publicKeyToHashFactory(versions.p2pkh)
43
44
  const encodePublicFromWIF =
44
45
  encodePublicFromWIFCustom ||
45
46
  ((privateKeyWIF) => {
46
- const { privateKey, compressed } = wif.decode(privateKeyWIF, coinInfo.versions.private)
47
+ const { privateKey, compressed } = fromWifStringSync(privateKeyWIF, coinInfo.versions.private)
47
48
  const publicKey = secp256k1.privateKeyToPublicKey({ privateKey, compressed })
48
49
  return encodePublicPurpose44(publicKey)
49
50
  })
@@ -52,13 +53,12 @@ export const createBtcLikeKeys = ({
52
53
  (versions.bech32 === undefined
53
54
  ? undefined
54
55
  : (publicKey) => {
55
- const pubKeyHash = hash160(publicKey)
56
- const witnessVersion = Buffer.from([0])
57
- const witnessProgram = Buffer.concat([
56
+ const witnessVersion = 0
57
+ return defaultBitcoinjsLib.address.toBech32(
58
+ hash160(publicKey),
58
59
  witnessVersion,
59
- Buffer.from(bech32.toWords(pubKeyHash)),
60
- ])
61
- return bech32.encode(versions.bech32, witnessProgram)
60
+ versions.bech32
61
+ )
62
62
  })
63
63
  const encodePublicBech32FromWIF =
64
64
  encodePublicBech32FromWIFCustom ||
@@ -66,7 +66,7 @@ export const createBtcLikeKeys = ({
66
66
  ? (privateKeyWIF) => {
67
67
  // NOTE: No password support here
68
68
  const { versions } = coinInfo
69
- const { privateKey, compressed } = wif.decode(privateKeyWIF, versions.private)
69
+ const { privateKey, compressed } = fromWifStringSync(privateKeyWIF, versions.private)
70
70
  const publicKey = secp256k1.privateKeyToPublicKey({ privateKey, compressed })
71
71
  return encodePublicBech32(publicKey)
72
72
  }
@@ -1,4 +1,3 @@
1
- // eslint-disable-next-line @exodus/import/no-deprecated
2
1
  import { isNumberUnit, UnitType } from '@exodus/currency'
3
2
  import { UtxoCollection } from '@exodus/models'
4
3
  import assert from 'minimalistic-assert'
@@ -33,6 +32,23 @@ export function getExtraFee({ asset, inputs, feePerKB, unconfirmedTxAncestor })
33
32
  return extraFee
34
33
  }
35
34
 
35
+ export function parseCurrency(val, currency) {
36
+ assert(currency instanceof UnitType, 'Currency must be supples as a UnitType')
37
+
38
+ if (isNumberUnit(val)) return val // TODO: consider checking if the unitType.equals(currency) (if currency is object)
39
+
40
+ if (typeof val === 'string') return currency.parse(val)
41
+ return currency.parse(val.value + ' ' + val.unit)
42
+ }
43
+
44
+ export function serializeCurrency(val, currency) {
45
+ if (val === undefined) {
46
+ return val
47
+ }
48
+
49
+ return parseCurrency(val, currency).toDefaultString({ unit: true })
50
+ }
51
+
36
52
  export default function createDefaultFeeEstimator(getSize) {
37
53
  return (asset, feePerKB, options = {}) => {
38
54
  return ({
@@ -50,21 +66,3 @@ export default function createDefaultFeeEstimator(getSize) {
50
66
  }
51
67
  }
52
68
  }
53
-
54
- export function parseCurrency(val, currency) {
55
- assert(currency instanceof UnitType, 'Currency must be supples as a UnitType')
56
-
57
- // eslint-disable-next-line @exodus/import/no-deprecated
58
- if (isNumberUnit(val)) return val // TODO: consider checking if the unitType.equals(currency) (if currency is object)
59
-
60
- if (typeof val === 'string') return currency.parse(val)
61
- return currency.parse(val.value + ' ' + val.unit)
62
- }
63
-
64
- export function serializeCurrency(val, currency) {
65
- if (val === undefined) {
66
- return val
67
- }
68
-
69
- return parseCurrency(val, currency).toDefaultString({ unit: true })
70
- }
@@ -1,6 +1,5 @@
1
1
  import { memoizeLruCache } from '@exodus/asset-lib'
2
2
  import { scriptClassify } from '@exodus/bitcoinjs'
3
- // eslint-disable-next-line @exodus/import/no-deprecated
4
3
  import { hashSync } from '@exodus/crypto/hash'
5
4
  import assert from 'minimalistic-assert'
6
5
 
@@ -9,7 +8,6 @@ const { P2PKH, P2SH, P2WPKH, P2WSH, P2TR } = scriptClassify.types
9
8
  const cacheSize = 1000
10
9
  const maxSize = 30
11
10
  const hashStringIfTooBig = (str) =>
12
- // eslint-disable-next-line @exodus/import/no-deprecated
13
11
  str.length > maxSize ? hashSync('sha256', str, 'hex').slice(0, maxSize) : str
14
12
 
15
13
  export const scriptClassifierFactory = ({ addressApi }) => {
package/src/hash-utils.js CHANGED
@@ -1,12 +1,9 @@
1
- // eslint-disable-next-line @exodus/import/no-deprecated
2
1
  import { hashSync } from '@exodus/crypto/hash'
3
2
 
4
3
  export function hash160(buffer) {
5
- // eslint-disable-next-line @exodus/import/no-deprecated
6
4
  return hashSync('hash160', buffer)
7
5
  }
8
6
 
9
7
  export function sha256(buffer) {
10
- // eslint-disable-next-line @exodus/import/no-deprecated
11
8
  return hashSync('sha256', buffer)
12
9
  }
@@ -221,7 +221,7 @@ export default class InsightAPIClient {
221
221
 
222
222
  async broadcastTx(rawTx) {
223
223
  const _rawTx = rawTx instanceof Uint8Array ? Buffer.from(rawTx).toString('hex') : rawTx
224
- console.log('gonna broadcastTx')
224
+ console.debug('gonna broadcastTx')
225
225
  const url = urlJoin(this.#baseURL, '/tx/send')
226
226
  const fetchOptions = {
227
227
  method: 'post',
@@ -0,0 +1,57 @@
1
+ import { safeString } from '@exodus/safe-string'
2
+ import { TraceId } from '@exodus/traceparent'
3
+
4
+ import fetchWithTimeout from './fetch-with-timeout.js'
5
+
6
+ const MAX_RETRY_AFTER_MS = 5 * 60_000
7
+ const retryAtByOrigin = new Map()
8
+
9
+ const getRetryAfterMs = (response, now) => {
10
+ const header = response.headers?.get?.('retry-after')?.trim()
11
+ if (!header) return
12
+
13
+ if (/^\d+$/.test(header)) {
14
+ const duration = Math.min(Number(header) * 1000, MAX_RETRY_AFTER_MS)
15
+ return Number.isSafeInteger(now + duration) && duration > 0 ? duration : undefined
16
+ }
17
+
18
+ const retryAt = Date.parse(header)
19
+ const serverDate = Date.parse(response.headers?.get?.('date'))
20
+ const duration = Math.min(
21
+ retryAt - (Number.isFinite(serverDate) ? serverDate : now),
22
+ MAX_RETRY_AFTER_MS
23
+ )
24
+ return Number.isSafeInteger(now + duration) && duration > 0 ? duration : undefined
25
+ }
26
+
27
+ const createRateLimitError = (retryAt, response) => {
28
+ const error = new Error('mempool-api-rate-limited')
29
+ error.hint = safeString`mempoolRateLimited`
30
+ error.code = '429'
31
+ error.finalError = true
32
+ error.retryAt = retryAt
33
+ error.retryAfterMs = Math.max(0, retryAt - Date.now())
34
+ const traceId = response && TraceId.fromResponse?.(response)
35
+ if (traceId) error.traceId = traceId
36
+ return error
37
+ }
38
+
39
+ export default async function mempoolRequest(url, fetchOptions) {
40
+ const origin = new URL(url).origin
41
+ const blockedUntil = retryAtByOrigin.get(origin)
42
+ if (Date.now() < blockedUntil) throw createRateLimitError(blockedUntil)
43
+ retryAtByOrigin.delete(origin)
44
+
45
+ const response = await fetchWithTimeout(url, fetchOptions)
46
+ if (response.status === 429) {
47
+ const now = Date.now()
48
+ const retryAfterMs = getRetryAfterMs(response, now)
49
+ if (retryAfterMs !== undefined) {
50
+ const retryAt = Math.max(retryAtByOrigin.get(origin) ?? 0, now + retryAfterMs)
51
+ retryAtByOrigin.set(origin, retryAt)
52
+ throw createRateLimitError(retryAt, response)
53
+ }
54
+ }
55
+
56
+ return response
57
+ }
@@ -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
@@ -122,7 +122,7 @@ async function withRetry(fn, args = [], { waitTimes = RETRY_WAIT_TIMES } = {}) {
122
122
  }
123
123
 
124
124
  async function fetchJson(url, fetchOptions, { nullWhen404 = false, httpErrorMessage } = {}) {
125
- const response = await fetchWithTimeout(url, fetchOptions)
125
+ const response = await mempoolRequest(url, fetchOptions)
126
126
  if (nullWhen404 && response.status === 404) {
127
127
  return null
128
128
  }
@@ -145,7 +145,7 @@ async function fetchJson(url, fetchOptions, { nullWhen404 = false, httpErrorMess
145
145
  }
146
146
 
147
147
  async function fetchText(url, fetchOptions, { nullWhen404 = false, httpErrorMessage } = {}) {
148
- const response = await fetchWithTimeout(url, fetchOptions)
148
+ const response = await mempoolRequest(url, fetchOptions)
149
149
  if (nullWhen404 && response.status === 404) {
150
150
  return null
151
151
  }
@@ -238,7 +238,7 @@ export default class MempoolRestClient {
238
238
  return urlJoin(this._mempoolBaseURL, version === 'v1' ? '/api/v1' : '/api', path)
239
239
  }
240
240
 
241
- async _fetchTipHeight() {
241
+ _fetchTipHeight() {
242
242
  const now = Date.now()
243
243
  if (this._tipHeightCache && now - this._tipHeightCache.startedAt < TIP_HEIGHT_CACHE_TTL_MS) {
244
244
  return this._tipHeightCache.promise
@@ -658,7 +658,7 @@ export default class MempoolRestClient {
658
658
  // classification (broadcast-tx.js) pattern-matches it.
659
659
  async broadcastTx(rawTx) {
660
660
  const payload = rawTx instanceof Uint8Array ? Buffer.from(rawTx).toString('hex') : rawTx
661
- const response = await fetch(this._mempoolApiUrl('/tx'), {
661
+ const response = await mempoolRequest(this._mempoolApiUrl('/tx'), {
662
662
  method: 'post',
663
663
  headers: {
664
664
  Accept: 'text/plain',
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
  }
package/src/psbt-utils.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import BIP32 from '@exodus/bip32'
2
+ import { Transaction } from '@exodus/bitcoinjs'
2
3
  import BipPath from 'bip32-path'
3
4
  import lodash from 'lodash'
4
5
  import assert from 'minimalistic-assert'
@@ -167,3 +168,31 @@ export function normalizeWitnessUtxoValue(value) {
167
168
  export function setPsbtVersionIfNotBitcoin(psbt, assetName) {
168
169
  if (!['bitcoin', 'bitcoinregtest', 'bitcointestnet'].includes(assetName)) psbt.setVersion(1)
169
170
  }
171
+
172
+ // A SIGHASH_SINGLE signature commits only to the output at the same index as the input it
173
+ // signs. When that index is at or past the last output there is no such output, and under
174
+ // both the legacy and the BIP143 digest the outputs commitment becomes a constant. The
175
+ // signature then authorises the inputs while binding none of the recipients, so whoever
176
+ // holds the signed PSBT can replace every output and still broadcast a valid transaction.
177
+ //
178
+ // Bitcoin Core rejects that case when verifying legacy inputs, but a wallet that produces
179
+ // the signature has already lost: the caller keeps it. So refuse before signing.
180
+ //
181
+ // The mask is used rather than a value list because the ANYONECANPAY variant, 0x83, has to
182
+ // be caught as well, and Transaction.SIGHASH_OUTPUT_MASK is the base type mask.
183
+ export const assertOutputCommitment = ({ psbt, index }) => {
184
+ const { sighashType } = psbt.data.inputs[index] ?? {}
185
+
186
+ if (sighashType === undefined) return // SIGHASH_DEFAULT, taproot's implicit sign-all.
187
+
188
+ const isSighashSingle =
189
+ (sighashType & Transaction.SIGHASH_OUTPUT_MASK) === Transaction.SIGHASH_SINGLE
190
+
191
+ if (isSighashSingle && index >= psbt.txOutputs.length) {
192
+ throw new Error(
193
+ `Refusing to sign input ${index} with SIGHASH_SINGLE: the transaction has ` +
194
+ `${psbt.txOutputs.length} output(s), so there is no output at index ${index} for the ` +
195
+ `signature to commit to. Every recipient could be replaced after signing.`
196
+ )
197
+ }
198
+ }
@@ -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.')
@@ -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
 
@@ -69,7 +74,6 @@ export class BitcoinMonitorScanner {
69
74
  const insightClient = this.#insightClient
70
75
  const txFetchLimit = this.#txFetchLimitResolver({ assetName: asset.name, refresh })
71
76
  const assetName = asset.name
72
- const purposes = await assetClientInterface.getSupportedPurposes({ assetName, walletAccount })
73
77
  const accountState = await assetClientInterface.getAccountState({ assetName, walletAccount })
74
78
  const currency = asset.currency
75
79
  const currentTxs = await assetClientInterface.getTxLog({ assetName, walletAccount })
@@ -80,6 +84,13 @@ export class BitcoinMonitorScanner {
80
84
 
81
85
  const multisigDataLength = assetConfig.multisigDataLength
82
86
 
87
+ const purposes = await getAvailablePurposes({
88
+ assetClientInterface,
89
+ assetName,
90
+ walletAccount,
91
+ multisigDataLength,
92
+ })
93
+
83
94
  // multiAddressMode may be null, in which case it is enabled.
84
95
  const multiAddressMode = assetConfig.multiAddressMode ?? true
85
96
 
@@ -313,12 +324,25 @@ export class BitcoinMonitorScanner {
313
324
 
314
325
  if (fetchCount === 0) {
315
326
  // 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())) {
327
+ let receiveAddress
328
+ try {
329
+ receiveAddress = await this.#assetClientInterface.getReceiveAddressObject({
330
+ assetName,
331
+ walletAccount,
332
+ useCache: true,
333
+ })
334
+ } catch (error) {
335
+ // The default purpose may be one of the ones without an xpub (e.g. old
336
+ // Trezor accounts missing purpose 84); the scan can still proceed on the
337
+ // available purposes.
338
+ if (!isMissingXpubError(error)) throw error
339
+
340
+ console.warn(
341
+ `${assetName}: no xpub for the default receive address in wallet account ${walletAccount}, skipping it. ${error.message}`
342
+ )
343
+ }
344
+
345
+ if (receiveAddress && !addresses.includes(receiveAddress.toString())) {
322
346
  addresses.push(receiveAddress.toString())
323
347
  scannedAddressSet.add(receiveAddress.toString())
324
348
  addrMap[receiveAddress.toString()] = receiveAddress
@@ -360,14 +384,14 @@ export class BitcoinMonitorScanner {
360
384
  (newChain) => newChain.purpose === purposeToUpdate
361
385
  )
362
386
  if (!chainToUpgrade) {
363
- console.log(
387
+ console.debug(
364
388
  `${assetName}: There is no chain info for purpose ${purposeToUpdate} and address ${addressString}`
365
389
  )
366
390
  return
367
391
  }
368
392
 
369
393
  if (chainToUpgrade.chain[metaChainIndex] === undefined) {
370
- console.log(
394
+ console.debug(
371
395
  `${assetName}: There is no chain info for purpose ${purposeToUpdate}, address ${addressString} and chain index ${metaChainIndex}`
372
396
  )
373
397
  return
@@ -382,9 +406,9 @@ export class BitcoinMonitorScanner {
382
406
  }
383
407
 
384
408
  gapSearchParameters.forEach((indexData) => {
385
- // eslint-disable-next-line @exodus/mutable/no-param-reassign-prop-only
409
+ // eslint-disable-next-line @exodus/hydra/no-param-reassign-prop-only
386
410
  indexData.startAddressIndexes = [...indexData.endAddressIndexes]
387
- // eslint-disable-next-line @exodus/mutable/no-param-reassign-prop-only
411
+ // eslint-disable-next-line @exodus/hydra/no-param-reassign-prop-only
388
412
  indexData.endAddressIndexes = indexData.chain.map((addressIndex) => {
389
413
  return addressIndex + resolvedGapLimit
390
414
  })
@@ -649,7 +673,7 @@ export class BitcoinMonitorScanner {
649
673
  const txStatus = await insightClient.fetchTx(tx.txId)
650
674
  return { tx, shouldDrop: !txStatus }
651
675
  } catch (err) {
652
- console.log(
676
+ console.debug(
653
677
  `${assetName}: failed to verify pending tx ${tx.txId} before drop check: ${
654
678
  err?.message || 'unknown'
655
679
  }`
@@ -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
 
@@ -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' })
@@ -1,7 +1,7 @@
1
1
  import { bip371, payments, Transaction } from '@exodus/bitcoinjs'
2
2
  import { publicKeyToX } from '@exodus/crypto/secp256k1'
3
3
 
4
- import { withUnsafeNonSegwit } from '../psbt-utils.js'
4
+ import { assertOutputCommitment, withUnsafeNonSegwit } from '../psbt-utils.js'
5
5
  import { createGetKeyWithMetadata } from './create-get-key-and-purpose.js'
6
6
  import { toAsyncBufferSigner, toAsyncSigner } from './taproot.js'
7
7
 
@@ -38,6 +38,12 @@ export function createSignWithWallet({
38
38
  if (!inputInfo) continue
39
39
 
40
40
  const input = psbt.data.inputs[index]
41
+
42
+ // Refuse a sighash whose signature would commit to no outputs at all. Checked on
43
+ // the PSBT input rather than on inputsToSign, because the value in the PSBT is the
44
+ // one the digest is built from.
45
+ assertOutputCommitment({ psbt, index })
46
+
41
47
  const { address, sigHash, derivationPath } = inputInfo
42
48
  // The sighash value from the PSBT input itself will be used.
43
49
  // This list just represents possible sighash values the inputs can have.
@@ -1,5 +1,6 @@
1
1
  import assert from 'minimalistic-assert'
2
2
 
3
+ import { assertOutputCommitment } from '../psbt-utils.js'
3
4
  import { extractTransaction, shouldSkipFinalize } from './common.js'
4
5
  import { createPrepareForSigning } from './default-prepare-for-signing.js'
5
6
 
@@ -59,6 +60,14 @@ function createSignWithHardwareWallet({ assetName, resolvePurpose }) {
59
60
  addressPathsMap,
60
61
  accountIndex,
61
62
  })
63
+ // Same refusal as the software path in create-sign-with-wallet.js. A hardware device is
64
+ // handed the serialised PSBT and signs what it is given, so the check has to happen here
65
+ // too or the guard only covers software wallets.
66
+ for (let index = 0; index < psbt.inputCount; index++) {
67
+ if (!inputsToSign[index]) continue
68
+ assertOutputCommitment({ psbt, index })
69
+ }
70
+
62
71
  const signatures = await hardwareDevice.signTransaction({
63
72
  assetName,
64
73
  signableTransaction: psbt.toBuffer(),
@@ -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