Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 30 additions & 1 deletion modules/sdk-api/src/v1/signPsbt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand All @@ -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'),
};
Expand Down
83 changes: 80 additions & 3 deletions modules/sdk-api/src/v1/transactionBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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, T];

Expand All @@ -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<string> {
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' }
Expand Down Expand Up @@ -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<string, Buffer>();

// 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<void> {
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 });
Expand All @@ -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<bigint> = {
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
Expand Down Expand Up @@ -899,6 +975,7 @@ exports.createTransaction = function (params) {
})
.then(collectInputs)
.then(collectOutputs)
.then(getPrevTxsForPsbt)
.then(serialize);
};

Expand Down
5 changes: 5 additions & 0 deletions modules/sdk-api/src/v1/wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down
79 changes: 63 additions & 16 deletions modules/sdk-api/test/unit/v1/signPsbt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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/);
});
});
Loading
Loading