@exodus/bitcoin-api 5.0.9 → 5.0.10

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.0.10](https://github.com/ExodusMovement/assets/compare/@exodus/bitcoin-api@5.0.9...@exodus/bitcoin-api@5.0.10) (2026-10-27)
7
+
8
+
9
+ ### Bug Fixes
10
+
11
+ * **bitcoin:** authenticate monitor history and fee replacements ([#9100](https://github.com/ExodusMovement/assets/issues/9100)) ([686bdc7](https://github.com/ExodusMovement/assets/commit/686bdc7dcae8e947a77f372109802fa790405f40))
12
+
13
+
14
+
6
15
  ## [5.0.9](https://github.com/ExodusMovement/assets/compare/@exodus/bitcoin-api@5.0.8...@exodus/bitcoin-api@5.0.9) (2026-10-19)
7
16
 
8
17
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@exodus/bitcoin-api",
3
- "version": "5.0.9",
3
+ "version": "5.0.10",
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",
@@ -59,5 +59,5 @@
59
59
  "type": "git",
60
60
  "url": "git+https://github.com/ExodusMovement/assets.git"
61
61
  },
62
- "gitHead": "2344cc95f78ce9e6f7f5b4367614b5fb09940a2f"
62
+ "gitHead": "fdbcba5fb13ebd05e32c5415fc4bfdbda669322c"
63
63
  }
@@ -1,3 +1,4 @@
1
+ import { Address } from '@exodus/models'
1
2
  import assert from 'minimalistic-assert'
2
3
 
3
4
  export function isReceiveAddress(address) {
@@ -78,3 +79,64 @@ export async function getAvailablePurposes({
78
79
 
79
80
  return availablePurposes
80
81
  }
82
+
83
+ export const normalizeAddressObject = (asset, value) => {
84
+ const address =
85
+ value instanceof Address
86
+ ? value
87
+ : Address.create(value.address ?? value, value.meta ?? Object.create(null))
88
+
89
+ return asset.address.toLegacyAddress
90
+ ? Address.create(asset.address.toLegacyAddress(String(address)), address.meta)
91
+ : address
92
+ }
93
+
94
+ export const getWalletAddressObjects = async ({
95
+ asset,
96
+ assetClientInterface,
97
+ assetName,
98
+ walletAccount,
99
+ chainIndex,
100
+ multisigDataLength,
101
+ purposes,
102
+ }) => {
103
+ const unusedAddressIndexes = await assetClientInterface.getUnusedAddressIndexes({
104
+ assetName,
105
+ walletAccount,
106
+ highestUnusedIndexes: true,
107
+ })
108
+
109
+ const addresses = []
110
+ const addressSet = new Set()
111
+
112
+ for (const purpose of purposes) {
113
+ const chainIndexes = unusedAddressIndexes.find((entry) => entry.purpose === purpose)?.chain || [
114
+ 0, 0,
115
+ ]
116
+ // users can switch between multi address mode and single address mode, so we need to use the highest unused address index irrespective of current mode
117
+ const endAddressIndex = chainIndexes[chainIndex] ?? 0
118
+ const dataLength = multisigDataLength ?? 1
119
+
120
+ for (let addressIndex = 0; addressIndex <= endAddressIndex; addressIndex++) {
121
+ for (let multisigDataIndex = 0; multisigDataIndex < dataLength; multisigDataIndex++) {
122
+ const address = await assetClientInterface.getAddress({
123
+ assetName,
124
+ walletAccount,
125
+ purpose,
126
+ chainIndex,
127
+ addressIndex,
128
+ ...(multisigDataLength ? { multisigDataIndex } : Object.create(null)),
129
+ })
130
+
131
+ const addressObject = normalizeAddressObject(asset, address)
132
+ const addressKey = String(addressObject)
133
+ if (addressSet.has(addressKey)) continue
134
+
135
+ addressSet.add(addressKey)
136
+ addresses.push(addressObject)
137
+ }
138
+ }
139
+ }
140
+
141
+ return addresses
142
+ }
@@ -0,0 +1,109 @@
1
+ import { UtxoCollection } from '@exodus/models'
2
+ import assert from 'minimalistic-assert'
3
+
4
+ import { getAvailablePurposes, getWalletAddressObjects } from '../address-utils.js'
5
+ import { parseCurrency } from '../fee/fee-utils.js'
6
+ import {
7
+ createTransactionLoader,
8
+ loadTransactionWithPrevouts,
9
+ verifyTransactionSignatures,
10
+ } from '../tx-log/verify-transaction-signatures.js'
11
+
12
+ export async function authenticateReplacement({ tx, asset, assetClientInterface, walletAccount }) {
13
+ const assetName = asset.name
14
+ const { multisigDataLength } = await assetClientInterface.getAssetConfig({
15
+ assetName,
16
+ walletAccount,
17
+ })
18
+ const purposes = await getAvailablePurposes({
19
+ assetClientInterface,
20
+ assetName,
21
+ walletAccount,
22
+ multisigDataLength,
23
+ })
24
+ // Use the same derivation range as send accounting, including historical
25
+ // change addresses after the wallet switches back to single-address mode.
26
+ const addressChains = await Promise.all(
27
+ [0, 1].map((chainIndex) =>
28
+ getWalletAddressObjects({
29
+ asset,
30
+ assetClientInterface,
31
+ assetName,
32
+ walletAccount,
33
+ chainIndex,
34
+ multisigDataLength,
35
+ purposes,
36
+ })
37
+ )
38
+ )
39
+ const addresses = addressChains.flat()
40
+ const scriptForAddress = (address) =>
41
+ asset.address.toScriptPubKey(String(address)).toString('hex')
42
+ const ownedScripts = new Set(addresses.map(scriptForAddress))
43
+ const transactionData = await loadTransactionWithPrevouts({
44
+ txId: tx.txId,
45
+ loadTransaction: createTransactionLoader((id) => asset.baseAsset.insightClient.fetchRawTx(id)),
46
+ })
47
+ const { tx: signed, prevouts } = transactionData
48
+ // Our replacement builder only reconstructs our own inputs. A collaborative
49
+ // transaction's outputs cannot safely be paid again with those inputs alone.
50
+ assert(
51
+ prevouts.length > 0 && prevouts.every((out) => ownedScripts.has(out.script.toString('hex'))),
52
+ 'Cannot replace a transaction with foreign inputs'
53
+ )
54
+ assert(
55
+ await verifyTransactionSignatures({
56
+ txId: tx.txId,
57
+ transactionData,
58
+ ownedScripts,
59
+ requireAllOutputs: true,
60
+ }),
61
+ 'Cannot authenticate replacement transaction'
62
+ )
63
+
64
+ const inputs = UtxoCollection.fromJSON(tx.data.inputs, { currency: asset.currency }).toArray()
65
+ assert(inputs.length === signed.ins.length, 'Replacement inputs do not match signed transaction')
66
+ signed.ins.forEach((input, index) => {
67
+ const txId = Buffer.from(input.hash).reverse().toString('hex')
68
+ const stored = inputs.find((entry) => entry.txId === txId && entry.vout === input.index)
69
+ const prevout = prevouts[index]
70
+ assert(
71
+ stored &&
72
+ stored.script === prevout.script.toString('hex') &&
73
+ scriptForAddress(stored.address) === stored.script &&
74
+ stored.value.toBaseString() === String(prevout.value),
75
+ 'Replacement input does not match signed previous output'
76
+ )
77
+ })
78
+ const external = signed.outs.filter((out) => !ownedScripts.has(out.script.toString('hex')))
79
+ const outputKey = (script, value) => `${script}:${value}`
80
+ const signedOutputs = external
81
+ .map((out) => outputKey(out.script.toString('hex'), out.value))
82
+ .sort()
83
+ const storedOutputs = tx.data.sent
84
+ .map(({ address, amount }) =>
85
+ outputKey(scriptForAddress(address), parseCurrency(amount, asset.currency).toBaseString())
86
+ )
87
+ .sort()
88
+ assert(
89
+ signedOutputs.length === storedOutputs.length &&
90
+ signedOutputs.every((output, index) => output === storedOutputs[index]),
91
+ 'Replacement recipients do not match signed transaction'
92
+ )
93
+ if (tx.data.changeAddress) {
94
+ assert(
95
+ ownedScripts.has(scriptForAddress(tx.data.changeAddress)),
96
+ 'Replacement change is not ours'
97
+ )
98
+ }
99
+ const sum = (outputs) => outputs.reduce((total, out) => total + BigInt(out.value), BigInt(0))
100
+ const fee = sum(prevouts) - sum(signed.outs)
101
+ assert(fee >= BigInt(0), 'Transaction spends more than its inputs')
102
+ return tx.update({
103
+ feeAmount: asset.currency.baseUnit(fee),
104
+ data: {
105
+ ...tx.data,
106
+ feePerKB: (Number(fee) * 1000) / signed.virtualSize(),
107
+ },
108
+ })
109
+ }
@@ -10,6 +10,7 @@ import { createPsbtWithMetadata } from '../psbt-builder.js'
10
10
  import { findUnconfirmedSentRbfTxs } from '../tx-utils.js'
11
11
  import { getUnconfirmedTxAncestorMap } from '../unconfirmed-ancestor-data.js'
12
12
  import { getUsableUtxos, getUtxos } from '../utxos-utils.js'
13
+ import { authenticateReplacement } from './authenticate-replacement.js'
13
14
  import { createInputs, createOutput, getBlockHeight, getNonWitnessTxs } from './tx-create-utils.js'
14
15
 
15
16
  // Helper to shuffle arrays for randomized input/output ordering
@@ -374,6 +375,7 @@ const transferHandler = {
374
375
  allowedPurposes,
375
376
  Psbt,
376
377
  Transaction,
378
+ authenticateReplacementTransactions,
377
379
  }) => {
378
380
  const assetName = asset.name
379
381
  const insightClient = asset.baseAsset.insightClient
@@ -399,6 +401,21 @@ const transferHandler = {
399
401
  // Get replaceable transactions
400
402
  let replaceableTxs = findUnconfirmedSentRbfTxs(context.txSet)
401
403
 
404
+ if (authenticateReplacementTransactions) {
405
+ const authenticated = []
406
+ for (const tx of replaceableTxs) {
407
+ try {
408
+ authenticated.push(
409
+ await authenticateReplacement({ tx, asset, assetClientInterface, walletAccount })
410
+ )
411
+ } catch {
412
+ // Never use an unverified candidate for RBF. Independent inputs or
413
+ // CPFP can still fund a send without reconstructing that transaction.
414
+ }
415
+ }
416
+ replaceableTxs = authenticated
417
+ }
418
+
402
419
  // Determine bumping strategy (RBF or CPFP)
403
420
  const {
404
421
  replaceableTxs: updatedReplaceableTxs,
@@ -545,6 +562,7 @@ export const createTxFactory =
545
562
  assetClientInterface,
546
563
  changeAddressType,
547
564
  allowedPurposes,
565
+ authenticateReplacementTransactions = false,
548
566
  Psbt = DefaultPsbt,
549
567
  Transaction = DefaultTransaction,
550
568
  }) =>
@@ -596,5 +614,6 @@ export const createTxFactory =
596
614
  allowedPurposes,
597
615
  Psbt,
598
616
  Transaction,
617
+ authenticateReplacementTransactions,
599
618
  })
600
619
  }
@@ -0,0 +1,50 @@
1
+ import { RBF_SEQUENCE } from '@exodus/bitcoin-lib'
2
+ import assert from 'minimalistic-assert'
3
+
4
+ import { loadTransactionWithPrevouts } from './verify-transaction-signatures.js'
5
+
6
+ // Only status and time come from the indexer. Spend attribution, amounts,
7
+ // scripts and destinations must all describe the transaction whose hash we checked.
8
+ export async function readAuthenticatedHistory({ item, asset, loadTransaction }) {
9
+ const { tx, prevouts } = await loadTransactionWithPrevouts({
10
+ txId: item.txid,
11
+ loadTransaction,
12
+ })
13
+ const addressForScript = (script) => {
14
+ try {
15
+ return asset.address.fromScriptPubKey(script)
16
+ } catch {
17
+ // e.g. OP_RETURN, which has no payment address
18
+ }
19
+ }
20
+ const value = (amount) => asset.currency.baseUnit(amount).toDefaultString()
21
+ const inputValue = prevouts.reduce((sum, out) => sum + BigInt(out.value), BigInt(0))
22
+ const outputValue = tx.outs.reduce((sum, out) => sum + BigInt(out.value), BigInt(0))
23
+ assert(tx.isCoinbase() || inputValue >= outputValue, 'Transaction spends more than its inputs')
24
+ return {
25
+ txid: tx.getId(),
26
+ time: item.time,
27
+ confirmations: item.confirmations,
28
+ fees: value(tx.isCoinbase() ? BigInt(0) : inputValue - outputValue),
29
+ vsize: tx.virtualSize(),
30
+ rbf: tx.ins.some((input) => input.sequence <= RBF_SEQUENCE),
31
+ vin: prevouts.map((out, index) => ({
32
+ txid: Buffer.from(tx.ins[index].hash).reverse().toString('hex'),
33
+ vout: tx.ins[index].index,
34
+ addr: addressForScript(out.script),
35
+ value: value(out.value),
36
+ })),
37
+ vout: tx.outs.map((out, n) => {
38
+ const address = addressForScript(out.script)
39
+ return {
40
+ n,
41
+ value: value(out.value),
42
+ scriptPubKey: {
43
+ hex: out.script.toString('hex'),
44
+ addresses: address ? [address] : [],
45
+ },
46
+ spentTxId: item.vout?.find((output) => output.n === n)?.spentTxId,
47
+ }
48
+ }),
49
+ }
50
+ }
@@ -1,4 +1,4 @@
1
- import { Address, UtxoCollection } from '@exodus/models'
1
+ import { UtxoCollection } from '@exodus/models'
2
2
  import lodash from 'lodash'
3
3
  import assert from 'minimalistic-assert'
4
4
  import ms from 'ms'
@@ -8,9 +8,16 @@ import {
8
8
  isChangeAddress,
9
9
  isMissingXpubError,
10
10
  isReceiveAddress,
11
+ normalizeAddressObject,
11
12
  } from '../address-utils.js'
12
13
  import { orderTxs } from '../insight-api-client/util.js'
13
14
  import { getUtxos } from '../utxos-utils.js'
15
+ import { readAuthenticatedHistory } from './authenticated-history.js'
16
+ import {
17
+ createTransactionLoader,
18
+ loadTransactionWithPrevouts,
19
+ verifyTransactionSignatures,
20
+ } from './verify-transaction-signatures.js'
14
21
 
15
22
  const { compact, isEqual, uniq } = lodash
16
23
 
@@ -24,6 +31,7 @@ const COINBASE_MATURITY_HEIGHT = 100
24
31
  const ADDRESS_DERIVATION_BATCH_SIZE = 10
25
32
 
26
33
  export class BitcoinMonitorScanner {
34
+ #verifyNewSentTransactions
27
35
  #asset
28
36
  #insightClient
29
37
  #assetClientInterface
@@ -45,7 +53,13 @@ export class BitcoinMonitorScanner {
45
53
  gapLimit = 10,
46
54
  refreshGapLimit = 10,
47
55
  addressBatchConcurrency = Infinity,
56
+ verifyNewSentTransactions = false,
48
57
  }) {
58
+ assert(
59
+ typeof verifyNewSentTransactions === 'boolean',
60
+ 'verifyNewSentTransactions must be a boolean'
61
+ )
62
+ this.#verifyNewSentTransactions = verifyNewSentTransactions
49
63
  assert(asset, 'asset is required!')
50
64
  assert(assetClientInterface, 'assetClientInterface is required!')
51
65
  assert(insightClient, 'insightClient is required')
@@ -80,6 +94,7 @@ export class BitcoinMonitorScanner {
80
94
  const asset = this.#asset
81
95
  const assetClientInterface = this.#assetClientInterface
82
96
  const insightClient = this.#insightClient
97
+ const loadTransaction = createTransactionLoader((id) => insightClient.fetchRawTx(id))
83
98
  const txFetchLimit = this.#txFetchLimitResolver({ assetName: asset.name, refresh })
84
99
  const assetName = asset.name
85
100
  const accountState = await assetClientInterface.getAccountState({ assetName, walletAccount })
@@ -206,12 +221,7 @@ export class BitcoinMonitorScanner {
206
221
  ...(multisigDataLength ? { multisigDataIndex: i } : Object.create(null)),
207
222
  })
208
223
  .then((address) => {
209
- const addressObject = this.#asset.address.toLegacyAddress
210
- ? Address.create(
211
- this.#asset.address.toLegacyAddress(String(address)),
212
- address.meta
213
- )
214
- : address
224
+ const addressObject = normalizeAddressObject(asset, address)
215
225
 
216
226
  const addressString = String(addressObject)
217
227
 
@@ -271,7 +281,13 @@ export class BitcoinMonitorScanner {
271
281
  )
272
282
  listOfTxs.push(...transactions)
273
283
  }
274
- return listOfTxs.flat()
284
+ const items = listOfTxs.flat()
285
+ if (!this.#verifyNewSentTransactions) return items
286
+ const authenticated = []
287
+ for (const item of items) {
288
+ authenticated.push(await readAuthenticatedHistory({ item, asset, loadTransaction }))
289
+ }
290
+ return authenticated
275
291
  }
276
292
 
277
293
  const gapSearchParameters = newChains.map(({ purpose, chain }) => {
@@ -761,6 +777,36 @@ export class BitcoinMonitorScanner {
761
777
  return !isEqual(chain, originalChain.chain)
762
778
  })
763
779
 
780
+ if (this.#verifyNewSentTransactions) {
781
+ const stored = storedUtxos.toArray()
782
+ const ownedScripts = new Set(
783
+ [...Object.keys(addrMap), ...stored.map((utxo) => String(utxo.address))].map((address) =>
784
+ asset.address.toScriptPubKey(address).toString('hex')
785
+ )
786
+ )
787
+ const storedOutpoints = new Set(stored.map((utxo) => `${utxo.txId}:${utxo.vout}`))
788
+ const verifiedIds = new Set()
789
+ // The extra refresh results can remove stored UTXOs outside today's gap
790
+ // range. Match those outpoints even when their addresses are absent from addrMap.
791
+ for (const item of [...allTxs, ...storedUtxoAddressTxs]) {
792
+ if (verifiedIds.has(item.txid)) continue
793
+ if (
794
+ !item.vin.some(
795
+ (input) => addrMap[input.addr] || storedOutpoints.has(`${input.txid}:${input.vout}`)
796
+ )
797
+ ) {
798
+ continue
799
+ }
800
+ const verified = await verifyTransactionSignatures({
801
+ txId: item.txid,
802
+ ownedScripts,
803
+ transactionData: await loadTransactionWithPrevouts({ txId: item.txid, loadTransaction }),
804
+ })
805
+ assert(verified === true, `Cannot authenticate outgoing transaction ${item.txid}`)
806
+ verifiedIds.add(item.txid)
807
+ }
808
+ }
809
+
764
810
  return {
765
811
  txsToUpdate: existingTxs,
766
812
  txsToAdd: newTxs,
@@ -0,0 +1,84 @@
1
+ import { crypto, opcodes, payments, script } from '@exodus/bitcoinjs'
2
+ import { schnorrVerifySync } from '@exodus/crypto/secp256k1'
3
+ import assert from 'minimalistic-assert'
4
+ import varuint from 'varuint-bitcoin'
5
+
6
+ export function verifyTaprootInput({ tx, index, prevouts, requireAllOutputs }) {
7
+ const input = tx.ins[index]
8
+ const output = prevouts[index].script
9
+ assert(input.script.length === 0, 'Unexpected scriptSig for Taproot')
10
+ const stack = [...input.witness]
11
+ const annex = stack.length >= 2 && stack.at(-1)[0] === 0x50 ? stack.pop() : undefined
12
+ const verify = (signature, xOnly, leafHash) => {
13
+ assert(signature.length === 64 || signature.length === 65, 'Invalid Taproot signature length')
14
+ const hashType = signature.length === 64 ? 0 : signature[64]
15
+ assert(
16
+ signature.length === 64 || [1, 2, 3, 0x81, 0x82, 0x83].includes(hashType),
17
+ 'Invalid Taproot sighash type'
18
+ )
19
+ assert(
20
+ !requireAllOutputs || hashType === 0 || (hashType & 0x1f) === 1,
21
+ 'Signature does not authorize all outputs'
22
+ )
23
+ const data = tx.hashForWitnessV1(
24
+ index,
25
+ prevouts.map((out) => out.script),
26
+ prevouts.map((out) => out.value),
27
+ hashType,
28
+ leafHash,
29
+ annex
30
+ )
31
+ return schnorrVerifySync({ signature: signature.subarray(0, 64), data, xOnly })
32
+ }
33
+ if (stack.length === 1) return verify(stack[0], output.subarray(2))
34
+
35
+ // bitcoinjs verifies the control block, Merkle path, tweaked key and parity
36
+ // against the actual previous output, not a script supplied by the indexer.
37
+ payments.p2tr({ output, witness: stack })
38
+ const control = stack.pop()
39
+ const leaf = stack.pop()
40
+ assert((control[0] & 0xfe) === 0xc0, 'Unsupported Taproot leaf version')
41
+ const leafHash = crypto.taggedHash(
42
+ 'TapLeaf',
43
+ Buffer.concat([Buffer.from([0xc0]), varuint.encode(leaf.length), leaf])
44
+ )
45
+ const chunks = script.decompile(leaf)
46
+ assert(chunks, 'Invalid Taproot script')
47
+
48
+ // Support CHECKSIG and the CHECKSIGADD threshold template generated by
49
+ // encodeMultisigContract. Arbitrary scripts need an execution verifier.
50
+ const single = chunks.length === 2 && chunks[1] === opcodes.OP_CHECKSIG
51
+ let threshold = 1
52
+ let keyChunks = chunks
53
+ if (!single) {
54
+ assert(
55
+ chunks.length >= 4 && chunks.at(-1) === opcodes.OP_NUMEQUAL,
56
+ 'Unsupported Taproot script'
57
+ )
58
+ const encoded = chunks.at(-2)
59
+ threshold = Buffer.isBuffer(encoded)
60
+ ? script.number.decode(encoded, 4)
61
+ : encoded - opcodes.OP_1 + 1
62
+ keyChunks = chunks.slice(0, -2)
63
+ }
64
+ const count = keyChunks.length / 2
65
+ assert(
66
+ Number.isInteger(count) && count >= 1 && count <= 16 && threshold >= 1 && threshold <= count,
67
+ 'Invalid Taproot threshold'
68
+ )
69
+ assert(stack.length === count, 'Unexpected Taproot witness stack')
70
+ let valid = 0
71
+ for (let i = 0; i < count; i++) {
72
+ const publicKey = keyChunks[i * 2]
73
+ assert(Buffer.isBuffer(publicKey) && publicKey.length === 32, 'Invalid Taproot public key')
74
+ assert(
75
+ keyChunks[i * 2 + 1] === (i === 0 ? opcodes.OP_CHECKSIG : opcodes.OP_CHECKSIGADD),
76
+ 'Unsupported Taproot script'
77
+ )
78
+ const signature = stack[count - 1 - i]
79
+ if (signature.length === 0) continue
80
+ if (!verify(signature, publicKey, leafHash)) return false
81
+ valid++
82
+ }
83
+ return valid === threshold
84
+ }
@@ -0,0 +1,157 @@
1
+ import { memoize } from '@exodus/basic-utils'
2
+ import { crypto, opcodes, payments, script, scriptClassify, Transaction } from '@exodus/bitcoinjs'
3
+ import { fromBigInt, toBigInt } from '@exodus/bytes/bigint.js'
4
+ import { ecdsaVerifyHashSync } from '@exodus/crypto/secp256k1'
5
+ import assert from 'minimalistic-assert'
6
+
7
+ import { verifyTaprootInput } from './verify-taproot-input.js'
8
+
9
+ const CURVE_ORDER = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141')
10
+
11
+ const classifyOutput = scriptClassify.outputFactory()
12
+ const { P2PKH, P2SH, P2WPKH, P2WSH, P2TR } = scriptClassify.types
13
+
14
+ function verifyInput(tx, index, prevouts, requireAllOutputs) {
15
+ const input = tx.ins[index]
16
+ const prevout = prevouts[index]
17
+ let output = prevout.script
18
+ let outputType = classifyOutput(output)
19
+ let stack = script.decompile(input.script)
20
+ assert(stack, 'Invalid input script')
21
+ stack = stack.map((chunk) => (chunk === opcodes.OP_0 ? Buffer.alloc(0) : chunk))
22
+ assert(stack.every(Buffer.isBuffer), 'Input script must be push-only')
23
+ let witness = false
24
+
25
+ if (outputType === P2SH) {
26
+ const redeem = stack.pop()
27
+ assert(
28
+ redeem && crypto.hash160(redeem).equals(output.subarray(2, 22)),
29
+ 'Redeem script mismatch'
30
+ )
31
+ outputType = classifyOutput(redeem)
32
+ if (outputType === P2WPKH || outputType === P2WSH) {
33
+ assert(input.script.equals(script.compile([redeem])), 'Non-canonical witness scriptSig')
34
+ }
35
+ output = redeem
36
+ }
37
+
38
+ if (outputType === P2WPKH || outputType === P2WSH) {
39
+ assert(stack.length === 0, 'Unexpected scriptSig for witness input')
40
+ witness = true
41
+ stack = [...input.witness]
42
+ if (outputType === P2WPKH) {
43
+ output = payments.p2pkh({ hash: output.subarray(2) }).output
44
+ } else {
45
+ const witnessScript = stack.pop()
46
+ assert(
47
+ witnessScript && crypto.sha256(witnessScript).equals(output.subarray(2)),
48
+ 'Witness script mismatch'
49
+ )
50
+ output = witnessScript
51
+ }
52
+ outputType = classifyOutput(output)
53
+ } else if (outputType === P2TR) {
54
+ return verifyTaprootInput({ tx, index, prevouts, requireAllOutputs })
55
+ } else {
56
+ assert(input.witness.length === 0, 'Unexpected witness')
57
+ }
58
+
59
+ const verify = (encodedSignature, publicKey) => {
60
+ const { signature, hashType } = script.signature.decode(encodedSignature)
61
+ assert(
62
+ (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE || index < tx.outs.length,
63
+ 'Signature does not commit to an output'
64
+ )
65
+ assert(
66
+ !requireAllOutputs || (hashType & 0x1f) === Transaction.SIGHASH_ALL,
67
+ 'Signature does not authorize all outputs'
68
+ )
69
+ const hash = witness
70
+ ? tx.hashForWitnessV0(index, output, prevout.value, hashType)
71
+ : tx.hashForSignature(index, output, hashType)
72
+ // Historical legacy transactions can contain high-S signatures. Normalize
73
+ // the mathematically equivalent S value for the crypto helper's low-S check.
74
+ const s = toBigInt(signature.subarray(32))
75
+ let normalized = signature
76
+ if (s > CURVE_ORDER / BigInt(2) && s < CURVE_ORDER) {
77
+ normalized = Buffer.concat([
78
+ signature.subarray(0, 32),
79
+ fromBigInt(CURVE_ORDER - s, { length: 32, format: 'buffer' }),
80
+ ])
81
+ }
82
+ return ecdsaVerifyHashSync({ signature: normalized, hash, publicKey })
83
+ }
84
+
85
+ if (outputType === P2PKH) {
86
+ if (stack.length !== 2 || !crypto.hash160(stack[1]).equals(output.subarray(3, 23))) return false
87
+ return verify(stack[0], stack[1])
88
+ }
89
+ const chunks = script.decompile(output)
90
+ assert(chunks && chunks.at(-1) === opcodes.OP_CHECKMULTISIG, 'Unsupported spend script')
91
+ const required = chunks[0] - opcodes.OP_1 + 1
92
+ const count = chunks.at(-2) - opcodes.OP_1 + 1
93
+ const publicKeys = chunks.slice(1, -2)
94
+ assert(
95
+ required >= 1 && required <= count && count <= 16 && count === publicKeys.length,
96
+ 'Invalid multisig script'
97
+ )
98
+ assert(publicKeys.every(Buffer.isBuffer), 'Invalid multisig keys')
99
+ if (stack.length !== required + 1 || stack[0].length > 0) return false
100
+ let signatureIndex = 1
101
+ for (const publicKey of publicKeys) {
102
+ if (verify(stack[signatureIndex], publicKey)) signatureIndex++
103
+ if (signatureIndex === stack.length) return true
104
+ }
105
+ return false
106
+ }
107
+
108
+ export function createTransactionLoader(fetchRawTx) {
109
+ return memoize(async (id) => {
110
+ const raw = await fetchRawTx(id)
111
+ assert(typeof raw === 'string' && /^(?:[\da-f]{2})+$/i.test(raw), 'Missing raw transaction')
112
+ const tx = Transaction.fromHex(raw)
113
+ assert(tx.getId() === id, 'Raw transaction hash mismatch')
114
+ return tx
115
+ })
116
+ }
117
+
118
+ export async function loadTransactionWithPrevouts({ txId, loadTransaction }) {
119
+ const tx = await loadTransaction(txId)
120
+ const prevouts = []
121
+ if (!tx.isCoinbase()) {
122
+ const outpoints = new Set()
123
+ for (const input of tx.ins) {
124
+ const id = Buffer.from(input.hash).reverse().toString('hex')
125
+ const outpoint = `${id}:${input.index}`
126
+ assert(!outpoints.has(outpoint), 'Duplicate transaction input')
127
+ outpoints.add(outpoint)
128
+ const previous = await loadTransaction(id)
129
+ const output = previous.outs[input.index]
130
+ assert(output, 'Missing previous output')
131
+ prevouts.push(output)
132
+ }
133
+ }
134
+ return { tx, prevouts }
135
+ }
136
+
137
+ export async function verifyTransactionSignatures({
138
+ txId,
139
+ fetchRawTx,
140
+ ownedScripts,
141
+ transactionData,
142
+ requireAllOutputs = false,
143
+ }) {
144
+ const { tx, prevouts } =
145
+ transactionData ||
146
+ (await loadTransactionWithPrevouts({
147
+ txId,
148
+ loadTransaction: createTransactionLoader(fetchRawTx),
149
+ }))
150
+ assert(tx.getId() === txId, 'Raw transaction hash mismatch')
151
+ const owned = prevouts.flatMap((out, index) =>
152
+ ownedScripts.has(out.script.toString('hex')) ? [index] : []
153
+ )
154
+ return (
155
+ owned.length > 0 && owned.every((index) => verifyInput(tx, index, prevouts, requireAllOutputs))
156
+ )
157
+ }
@@ -1,19 +1,12 @@
1
1
  import { Address } from '@exodus/models'
2
2
 
3
- import { getAvailablePurposes } from '../address-utils.js'
3
+ import {
4
+ getAvailablePurposes,
5
+ getWalletAddressObjects,
6
+ normalizeAddressObject,
7
+ } from '../address-utils.js'
4
8
  import { serializeCurrency } from '../fee/fee-utils.js'
5
9
 
6
- const normalizeAddressObject = (asset, value) => {
7
- const address =
8
- value instanceof Address
9
- ? value
10
- : Address.create(value.address ?? value, value.meta ?? Object.create(null))
11
-
12
- return asset.address.toLegacyAddress
13
- ? Address.create(asset.address.toLegacyAddress(String(address)), address.meta)
14
- : address
15
- }
16
-
17
10
  // internalOutputs are deterministically derivable while scanning while change address is not
18
11
  // internalOutput.address is an Address object, so platform can re-derive complete Address object from the tx log
19
12
  const buildInternalOutputs = ({
@@ -52,56 +45,6 @@ const buildInternalOutputs = ({
52
45
  return internalOutputs
53
46
  }
54
47
 
55
- const getWalletAddressObjects = async ({
56
- asset,
57
- assetClientInterface,
58
- assetName,
59
- walletAccount,
60
- chainIndex,
61
- multisigDataLength,
62
- purposes,
63
- }) => {
64
- const unusedAddressIndexes = await assetClientInterface.getUnusedAddressIndexes({
65
- assetName,
66
- walletAccount,
67
- highestUnusedIndexes: true,
68
- })
69
-
70
- const addresses = []
71
- const addressSet = new Set()
72
-
73
- for (const purpose of purposes) {
74
- const chainIndexes = unusedAddressIndexes.find((entry) => entry.purpose === purpose)?.chain || [
75
- 0, 0,
76
- ]
77
- // users can switch between multi address mode and single address mode, so we need to use the highest unused address index irrespective of current mode
78
- const endAddressIndex = chainIndexes[chainIndex] ?? 0
79
- const dataLength = multisigDataLength ?? 1
80
-
81
- for (let addressIndex = 0; addressIndex <= endAddressIndex; addressIndex++) {
82
- for (let multisigDataIndex = 0; multisigDataIndex < dataLength; multisigDataIndex++) {
83
- const address = await assetClientInterface.getAddress({
84
- assetName,
85
- walletAccount,
86
- purpose,
87
- chainIndex,
88
- addressIndex,
89
- ...(multisigDataLength ? { multisigDataIndex } : Object.create(null)),
90
- })
91
-
92
- const addressObject = normalizeAddressObject(asset, address)
93
- const addressKey = String(addressObject)
94
- if (addressSet.has(addressKey)) continue
95
-
96
- addressSet.add(addressKey)
97
- addresses.push(addressObject)
98
- }
99
- }
100
- }
101
-
102
- return addresses
103
- }
104
-
105
48
  export function updateAccountStateBatch({
106
49
  batch,
107
50
  assetClientInterface,