diff --git a/modules/sdk-api/src/v1/signPsbt.ts b/modules/sdk-api/src/v1/signPsbt.ts index b047726d0be..3972bc6e0e5 100644 --- a/modules/sdk-api/src/v1/signPsbt.ts +++ b/modules/sdk-api/src/v1/signPsbt.ts @@ -4,6 +4,33 @@ import buildDebug from 'debug'; const debug = buildDebug('bitgo:v1:txb'); +/** + * The legacy sighash used by non-segwit inputs does not commit to the input value. Such an input can only be + * signed safely if it carries the full previous transaction (nonWitnessUtxo) and that transaction hashes to + * the txid the input spends. Throws if any non-segwit input does not meet this, so no input is signed. + */ +function assertNonSegwitInputsHavePrevTx(psbt: utxolib.bitgo.UtxoPsbt): void { + psbt.data.inputs.forEach((input, i) => { + const scriptType = utxolib.bitgo.getPsbtInputScriptType(input); + if (scriptType !== 'p2sh' && scriptType !== 'p2shP2pk') { + return; + } + if (!input.nonWitnessUtxo) { + throw new Error(`input ${i} is a non-segwit input without nonWitnessUtxo`); + } + const prevTx = utxolib.bitgo.createTransactionFromBuffer(input.nonWitnessUtxo, psbt.network, { + amountType: 'bigint', + }); + const txInput = psbt.txInputs[i]; + if (!prevTx.getHash().equals(txInput.hash)) { + throw new Error(`input ${i} nonWitnessUtxo does not match the txid the input spends`); + } + if (!prevTx.outs[txInput.index]) { + throw new Error(`input ${i} nonWitnessUtxo has no output ${txInput.index}`); + } + }); +} + /** * Co-sign a PSBT. * Simply a wrapper around `utxolib.bitgo.createPsbtFromBuffer` and `psbt.signAllInputsHD`. @@ -29,9 +56,11 @@ export function signPsbtRequest(params: { psbt: string; keychain: { xprv: string } const psbt = utxolib.bitgo.createPsbtDecode(params.psbt, utxolib.networks.bitcoin); + assertNonSegwitInputsHavePrevTx(psbt); const keypair = utxolib.bip32.fromBase58(params.keychain.xprv, utxolib.networks.bitcoin); debug('signing PSBT with keychain %s', keypair.neutered().toBase58()); - utxolib.bitgo.withUnsafeNonSegwit(psbt, () => psbt.signAllInputsHD(keypair)); + // Sign in safe mode: non-segwit inputs are hashed from nonWitnessUtxo, never from a claimed witnessUtxo value. + utxolib.bitgo.withUnsafeNonSegwit(psbt, () => psbt.signAllInputsHD(keypair), false); return { psbt: psbt.toBuffer().toString('hex'), }; diff --git a/modules/sdk-api/src/v1/transactionBuilder.ts b/modules/sdk-api/src/v1/transactionBuilder.ts index 1cbe97f65e3..8e7ebf0407c 100644 --- a/modules/sdk-api/src/v1/transactionBuilder.ts +++ b/modules/sdk-api/src/v1/transactionBuilder.ts @@ -20,6 +20,7 @@ const debug = debugLib('bitgo:v1:txb'); import { common, getAddressP2PKH, getNetwork, sanitizeLegacyPath } from '@bitgo/sdk-core'; import { verifyAddress } from './verifyAddress'; import { tryPromise } from '../util'; +const request = require('superagent'); type Triple = [T, T, T]; @@ -40,6 +41,31 @@ function parseChainPath(chainPath: string): { chain: number; index: number } { return { chain: parseInt(parts[0], 10), index: parseInt(parts[1], 10) }; } +/** + * A previous transaction does not match the unspent it should fund. The transaction must not be built in + * any format, so callers must not fall back to the legacy transaction format on this error. + */ +class PrevTxMismatchError extends Error { + constructor(message: string) { + super(message); + this.name = 'PrevTxMismatchError'; + } +} +exports.PrevTxMismatchError = PrevTxMismatchError; + +/** + * Fetch the hex of a previous transaction from the block explorer. The caller verifies the txid, + * so the explorer does not need to be trusted. + */ +async function getPrevTxHex(bitgo: { getEnv(): string }, txid: string): Promise { + const explorerBaseUrl = common.Environments[bitgo.getEnv()].btcExplorerBaseUrl; + const result = await request.get(`${explorerBaseUrl}/tx/${txid}/hex`); + if (typeof result.text !== 'string' || !/^([a-f0-9]{2})+$/.test(result.text.trim())) { + throw new Error(`could not fetch previous transaction ${txid}`); + } + return result.text.trim(); +} + /** * Create RootWalletKeys from v1 wallet keychains. * v1 keychains have a structure like { xpub, path: 'm', walletSubPath: '/0/0' } @@ -789,6 +815,55 @@ exports.createTransaction = function (params) { }); }; + // Previous transactions for non-segwit inputs, keyed by txid. The legacy sighash does not commit to the + // input value, so the signer needs the full previous transaction to verify the value it is spending. + const prevTxs = new Map(); + + // Fetch and verify the previous transaction of every non-segwit input. A previous transaction is only + // accepted if it hashes to the input's txid and the spent output has the unspent's script and value, + // so the value used for fee calculation is the value the signature commits to. + const getPrevTxsForPsbt = async function (): Promise { + if (params.usePsbt !== true) { + return; + } + for (const unspent of unspents) { + const { chain } = parseChainPath(unspent.chainPath) as { chain: utxolib.bitgo.ChainCode }; + if (utxolib.bitgo.isSegwit(chain) || prevTxs.has(unspent.tx_hash)) { + continue; + } + const prevTxHex = + typeof unspent.prevTx === 'string' ? unspent.prevTx : await getPrevTxHex(bitgo, unspent.tx_hash); + const prevTxBuffer = Buffer.from(prevTxHex, 'hex'); + const prevTx = utxolib.bitgo.createTransactionFromBuffer(prevTxBuffer, network, { amountType: 'bigint' }); + if (prevTx.getId() !== unspent.tx_hash) { + throw new PrevTxMismatchError(`previous transaction for input ${unspent.tx_hash} has txid ${prevTx.getId()}`); + } + prevTxs.set(unspent.tx_hash, prevTxBuffer); + } + for (const unspent of unspents) { + const prevTxBuffer = prevTxs.get(unspent.tx_hash); + if (!prevTxBuffer) { + continue; + } + const prevTx = utxolib.bitgo.createTransactionFromBuffer(prevTxBuffer, network, { amountType: 'bigint' }); + const output = prevTx.outs[unspent.tx_output_n]; + const id = `${unspent.tx_hash}:${unspent.tx_output_n}`; + if (!output) { + throw new PrevTxMismatchError(`previous transaction has no output for input ${id}`); + } + if (output.value !== BigInt(unspent.value)) { + throw new PrevTxMismatchError( + `value of input ${id} is ${output.value} in the previous transaction, expected ${unspent.value}` + ); + } + if (!output.script.equals(utxolib.address.toOutputScript(unspent.address, network))) { + throw new PrevTxMismatchError( + `script of input ${id} in the previous transaction does not match address ${unspent.address}` + ); + } + } + }; + // Build PSBT with all signing metadata embedded const buildPsbt = function (): utxolib.bitgo.UtxoPsbt { const psbt = utxolib.bitgo.createPsbtForNetwork({ network }); @@ -806,17 +881,18 @@ exports.createTransaction = function (params) { for (const unspent of unspents) { const { chain, index } = parseChainPath(unspent.chainPath) as { chain: utxolib.bitgo.ChainCode; index: number }; + const prevTx = prevTxs.get(unspent.tx_hash); const walletUnspent: utxolib.bitgo.WalletUnspent = { id: `${unspent.tx_hash}:${unspent.tx_output_n}`, address: unspent.address, chain, index, value: BigInt(unspent.value), + ...(prevTx ? { prevTx } : {}), }; - utxolib.bitgo.addWalletUnspentToPsbt(psbt, walletUnspent, rootWalletKeys, 'user', 'backup', { - skipNonWitnessUtxo: true, - }); + // Non-segwit inputs get nonWitnessUtxo (the verified previous transaction), segwit inputs get witnessUtxo. + utxolib.bitgo.addWalletUnspentToPsbt(psbt, walletUnspent, rootWalletKeys, 'user', 'backup'); } // Fee single key inputs are not supported with PSBT yet - throw to trigger fallback to legacy @@ -899,6 +975,7 @@ exports.createTransaction = function (params) { }) .then(collectInputs) .then(collectOutputs) + .then(getPrevTxsForPsbt) .then(serialize); }; diff --git a/modules/sdk-api/src/v1/wallet.ts b/modules/sdk-api/src/v1/wallet.ts index ca53eae85e4..8ca4f863be7 100644 --- a/modules/sdk-api/src/v1/wallet.ts +++ b/modules/sdk-api/src/v1/wallet.ts @@ -924,6 +924,11 @@ Wallet.prototype.createTransaction = function (params, callback) { return result; }) .catch((psbtError: Error) => { + // A previous transaction that contradicts the unspent data means the unspent data cannot be trusted, + // so the transaction must not be built in the legacy format either. + if (psbtError instanceof TransactionBuilder.PrevTxMismatchError) { + throw psbtError; + } // PSBT failed - fall back to legacy and capture error for backend reporting console.warn('PSBT transaction failed, falling back to legacy'); return TransactionBuilder.createTransaction({ ...params, usePsbt: false }).then((result: any) => { diff --git a/modules/sdk-api/test/unit/v1/signPsbt.ts b/modules/sdk-api/test/unit/v1/signPsbt.ts index fad70b361cf..de1c18ee169 100644 --- a/modules/sdk-api/test/unit/v1/signPsbt.ts +++ b/modules/sdk-api/test/unit/v1/signPsbt.ts @@ -3,25 +3,72 @@ import * as utxolib from '@bitgo/utxo-lib'; import { signPsbtRequest } from '../../../src/v1/signPsbt'; describe('signPsbt', function () { - it('signs psbt', function () { - const keys = utxolib.testutil.getDefaultWalletKeys(); - const psbt = utxolib.testutil.constructPsbt( - [{ scriptType: 'p2sh', value: BigInt(1e8) }], - [{ scriptType: 'p2sh', value: BigInt(1e8 - 1000) }], - utxolib.networks.bitcoin, + const keys = utxolib.testutil.getDefaultWalletKeys(); + const network = utxolib.networks.bitcoin; + + function constructUnsignedPsbt( + inputs: { scriptType: 'p2sh' | 'p2shP2wsh' | 'p2wsh'; value: bigint }[], + params?: { skipNonWitnessUtxo?: boolean } + ): utxolib.bitgo.UtxoPsbt { + const total = inputs.reduce((sum, input) => sum + input.value, BigInt(0)); + return utxolib.testutil.constructPsbt( + inputs, + [{ scriptType: 'p2sh', value: total - BigInt(1000) }], + network, keys, - 'unsigned' + 'unsigned', + params ); - const result = signPsbtRequest({ - psbt: psbt.toHex(), - keychain: { - xprv: keys.triple[0].toBase58(), - }, - }); - const halfSignedPsbt = utxolib.bitgo.createPsbtFromBuffer( - Buffer.from(result.psbt, 'hex'), - utxolib.networks.bitcoin + } + + function sign(psbt: utxolib.bitgo.UtxoPsbt): utxolib.bitgo.UtxoPsbt { + const result = signPsbtRequest({ psbt: psbt.toHex(), keychain: { xprv: keys.triple[0].toBase58() } }); + return utxolib.bitgo.createPsbtFromBuffer(Buffer.from(result.psbt, 'hex'), network); + } + + it('signs psbt', function () { + const halfSignedPsbt = sign(constructUnsignedPsbt([{ scriptType: 'p2sh', value: BigInt(1e8) }])); + assert.ok(halfSignedPsbt.validateSignaturesOfInputHD(0, keys.triple[0])); + }); + + it('signs segwit inputs that only carry witnessUtxo', function () { + const psbt = constructUnsignedPsbt( + [ + { scriptType: 'p2shP2wsh', value: BigInt(1e8) }, + { scriptType: 'p2wsh', value: BigInt(1e8) }, + ], + { skipNonWitnessUtxo: true } ); + assert.strictEqual(psbt.data.inputs[0].nonWitnessUtxo, undefined); + const halfSignedPsbt = sign(psbt); assert.ok(halfSignedPsbt.validateSignaturesOfInputHD(0, keys.triple[0])); + assert.ok(halfSignedPsbt.validateSignaturesOfInputHD(1, keys.triple[0])); + }); + + it('refuses a p2sh input without nonWitnessUtxo', function () { + const psbt = constructUnsignedPsbt([{ scriptType: 'p2sh', value: BigInt(1e8) }], { skipNonWitnessUtxo: true }); + assert.ok(psbt.data.inputs[0].witnessUtxo); + assert.strictEqual(psbt.data.inputs[0].nonWitnessUtxo, undefined); + assert.throws(() => sign(psbt), /input 0 is a non-segwit input without nonWitnessUtxo/); + }); + + it('refuses the whole psbt if one p2sh input has no nonWitnessUtxo', function () { + const full = constructUnsignedPsbt([ + { scriptType: 'p2wsh', value: BigInt(1e8) }, + { scriptType: 'p2sh', value: BigInt(1e8) }, + ]); + const lite = utxolib.bitgo.clonePsbtWithoutNonWitnessUtxo(full); + assert.strictEqual(lite.data.inputs[1].nonWitnessUtxo, undefined); + assert.throws(() => sign(lite), /input 1 is a non-segwit input without nonWitnessUtxo/); + }); + + it('refuses a p2sh input whose nonWitnessUtxo is not the transaction it spends', function () { + const psbt = constructUnsignedPsbt([ + { scriptType: 'p2sh', value: BigInt(1e8) }, + { scriptType: 'p2sh', value: BigInt(2e8) }, + ]); + // Swap in the previous transaction of the other input + psbt.data.inputs[0].nonWitnessUtxo = psbt.data.inputs[1].nonWitnessUtxo; + assert.throws(() => sign(psbt), /input 0 nonWitnessUtxo does not match the txid the input spends/); }); }); diff --git a/modules/sdk-api/test/unit/v1/wallet.ts b/modules/sdk-api/test/unit/v1/wallet.ts index e46ba747aa4..d126dc919e1 100644 --- a/modules/sdk-api/test/unit/v1/wallet.ts +++ b/modules/sdk-api/test/unit/v1/wallet.ts @@ -22,6 +22,21 @@ nock.disableNetConnect(); const TestBitGo = { TEST_WALLET1_PASSCODE: 'iVWeATjqLS1jJShrPpETti0b', }; + +/** + * Give a test unspent a real previous transaction: one that pays `value` to the unspent's script at + * output `tx_output_n`. The unspent's txid is set to that transaction's txid and the hex is attached as `prevTx`. + */ +function attachPrevTx(unspent: any, value: number = unspent.value): void { + const prevTx = new utxolib.Transaction(); + prevTx.addInput(Buffer.alloc(32, 1), 0); + for (let i = 0; i < unspent.tx_output_n; i++) { + prevTx.addOutput(Buffer.from('6a', 'hex'), 0); + } + prevTx.addOutput(Buffer.from(unspent.script, 'hex'), value); + unspent.txid = unspent.tx_hash = prevTx.getId(); + unspent.prevTx = prevTx.toHex(); +} describe('Wallet Prototype Methods', function () { const fixtures = getFixtures(); @@ -315,6 +330,7 @@ describe('Wallet Prototype Methods', function () { unspent.tx_hash = unspent.txid; unspent.tx_output_n = unspent.n; unspent.script = unspent.outputScript; + attachPrevTx(unspent); const txParams = { changeAddress: p2shAddress.address, @@ -433,6 +449,7 @@ describe('Wallet Prototype Methods', function () { unspent.tx_hash = unspent.txid; unspent.tx_output_n = unspent.n; unspent.script = unspent.outputScript; + attachPrevTx(unspent); nock(bgUrl).post('/api/v1/billing/address').reply(200, { address: '2MswQjkvN6oWYdE7L2brJ5cAAMjPmG59oco' }); @@ -461,9 +478,11 @@ describe('Wallet Prototype Methods', function () { psbt.data.inputs.length.should.equal(1); psbt.data.outputs.length.should.equal(2); // OP_RETURN + change - // Verify input has required PSBT metadata + // Verify input has required PSBT metadata. A p2sh input carries the full previous transaction, + // because the legacy sighash does not commit to the input value. const input = psbt.data.inputs[0]; - should.exist(input.witnessUtxo); + should.exist(input.nonWitnessUtxo); + should.not.exist(input.witnessUtxo); should.exist(input.redeemScript); should.exist(input.bip32Derivation); input.bip32Derivation!.length.should.equal(3); // user, backup, bitgo @@ -485,6 +504,104 @@ describe('Wallet Prototype Methods', function () { should.ok(signedPsbt.validateSignaturesOfInputHD(0, utxolib.bip32.fromBase58(userKeypair.xpub))); }); + describe('p2sh PSBT previous transactions', function () { + const explorerUrl = 'https://blockstream.info'; + + function p2shUnspent(): any { + const p2shAddress = fakeProdWallet.generateAddress({ path: '/0/13', segwit: false }); + const unspent: any = { value: 504422, tx_output_n: 1, confirmations: 9 }; + _.extend(unspent, p2shAddress); + unspent.script = unspent.outputScript; + return unspent; + } + + async function createPsbtTransaction(unspent: any): Promise { + nock(bgUrl).post('/api/v1/billing/address').reply(200, { address: '2MswQjkvN6oWYdE7L2brJ5cAAMjPmG59oco' }); + return fakeProdWallet.createTransaction({ + changeAddress: unspent.address, + unspents: [unspent], + recipients: {}, + noSplitChange: true, + forceChangeAtEnd: true, + feeRate: 10000, + bitgoFee: { amount: 0, address: '' }, + opReturns: { 'BitGo p2sh test': 1000 }, + usePsbt: true, + }); + } + + afterEach(function () { + nock.cleanAll(); + }); + + it('fetches the previous transaction from the explorer when it is not provided', async function () { + const unspent = p2shUnspent(); + attachPrevTx(unspent); + const prevTxHex = unspent.prevTx; + delete unspent.prevTx; + const explorer = nock(explorerUrl).get(`/api/tx/${unspent.tx_hash}/hex`).reply(200, prevTxHex); + + const transaction = await createPsbtTransaction(unspent); + + explorer.done(); + transaction.psbtAttempt.success.should.be.true(); + const psbt = utxolib.bitgo.createPsbtFromHex(transaction.transactionHex, utxolib.networks.bitcoin); + psbt.data.inputs[0].nonWitnessUtxo!.toString('hex').should.equal(prevTxHex); + }); + + it('falls back to the legacy format when the previous transaction cannot be fetched', async function () { + const unspent = p2shUnspent(); + attachPrevTx(unspent); + delete unspent.prevTx; + nock(explorerUrl).get(`/api/tx/${unspent.tx_hash}/hex`).reply(500); + + const transaction = await createPsbtTransaction(unspent); + + transaction.psbtAttempt.success.should.be.false(); + utxolib.bitgo.isPsbt(transaction.transactionHex).should.be.false(); + }); + + it('refuses to build any transaction when the claimed input value differs from the previous transaction', async function () { + const unspent = p2shUnspent(); + // The previous transaction holds 10 BTC, but the unspent claims 0.00504422 BTC + attachPrevTx(unspent, 1e9); + + await createPsbtTransaction(unspent).should.be.rejectedWith({ + name: 'PrevTxMismatchError', + message: /value of input .* is 1000000000 in the previous transaction, expected 504422/, + }); + }); + + it('refuses to build any transaction when the explorer returns a different transaction', async function () { + const unspent = p2shUnspent(); + attachPrevTx(unspent); + const otherUnspent = p2shUnspent(); + attachPrevTx(otherUnspent, 1e9); + delete unspent.prevTx; + nock(explorerUrl).get(`/api/tx/${unspent.tx_hash}/hex`).reply(200, otherUnspent.prevTx); + + await createPsbtTransaction(unspent).should.be.rejectedWith({ + name: 'PrevTxMismatchError', + message: /previous transaction for input .* has txid/, + }); + }); + + it('refuses to build any transaction when the previous transaction pays a different script', async function () { + const unspent = p2shUnspent(); + const segwitAddress = fakeProdWallet.generateAddress({ path: '/10/13', segwit: true }); + // Same value, but the output pays another address + const forged = { ...unspent, script: segwitAddress.outputScript }; + attachPrevTx(forged); + unspent.tx_hash = unspent.txid = forged.tx_hash; + unspent.prevTx = forged.prevTx; + + await createPsbtTransaction(unspent).should.be.rejectedWith({ + name: 'PrevTxMismatchError', + message: /script of input .* does not match address/, + }); + }); + }); + it('segwit with PSBT format', async function () { const segwitAddress = fakeProdWallet.generateAddress({ path: '/10/13', segwit: true }); const unspent: any = {