Skip to content

Commit ab39d31

Browse files
refactor(abstract-utxo): move signTransaction to its own file
Issue: BTC-1450
1 parent 489aa32 commit ab39d31

File tree

5 files changed

+196
-145
lines changed

5 files changed

+196
-145
lines changed

modules/abstract-utxo/src/abstractUtxoCoin.ts

Lines changed: 5 additions & 143 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,7 @@ import assert from 'assert';
22
import { randomBytes } from 'crypto';
33
import _ from 'lodash';
44
import * as utxolib from '@bitgo/utxo-lib';
5-
import { bip32, BIP32Interface, bitgo, getMainnet, isMainnet, isTestnet } from '@bitgo/utxo-lib';
6-
import debugLib from 'debug';
5+
import { bip32, bitgo, getMainnet, isMainnet, isTestnet } from '@bitgo/utxo-lib';
76

87
import {
98
backupKeyRecovery,
@@ -59,7 +58,6 @@ import {
5958
Wallet,
6059
} from '@bitgo/sdk-core';
6160
import { isReplayProtectionUnspent } from './replayProtection';
62-
import { signAndVerifyPsbt, signAndVerifyWalletTransaction } from './sign';
6361
import { supportedCrossChainRecoveries } from './config';
6462
import {
6563
assertValidTransactionRecipient,
@@ -76,10 +74,9 @@ import { CustomChangeOptions } from './transaction/fixedScript';
7674
import { toBip32Triple, UtxoKeychain, UtxoNamedKeychains } from './keychains';
7775
import { verifyKeySignature, verifyUserPublicKey } from './verifyKey';
7876
import { getPolicyForEnv } from './descriptor/validatePolicy';
77+
import { signTransaction } from './transaction/signTransaction';
7978
import { UtxoWallet } from './wallet';
8079

81-
const debug = debugLib('bitgo:v2:utxo');
82-
8380
import ScriptType2Of3 = utxolib.bitgo.outputScripts.ScriptType2Of3;
8481

8582
type UtxoCustomSigningFunction<TNumber extends number | bigint> = {
@@ -111,11 +108,11 @@ const { getExternalChainCode, isChainCode, scriptTypeForChain, outputScripts } =
111108

112109
type Unspent<TNumber extends number | bigint = number> = bitgo.Unspent<TNumber>;
113110

114-
type DecodedTransaction<TNumber extends number | bigint> =
111+
export type DecodedTransaction<TNumber extends number | bigint> =
115112
| utxolib.bitgo.UtxoTransaction<TNumber>
116113
| utxolib.bitgo.UtxoPsbt;
117114

118-
type RootWalletKeys = bitgo.RootWalletKeys;
115+
export type RootWalletKeys = bitgo.RootWalletKeys;
119116

120117
export type UtxoCoinSpecific = AddressCoinSpecific | DescriptorAddressCoinSpecific;
121118

@@ -358,16 +355,6 @@ export abstract class AbstractUtxoCoin extends BaseCoin {
358355
this._network = network;
359356
}
360357

361-
/**
362-
* Key Value: Unsigned tx id => PSBT
363-
* It is used to cache PSBTs with taproot key path (MuSig2) inputs during external express signer is activated.
364-
* Reason: MuSig2 signer secure nonce is cached in the UtxoPsbt object. It will be required during the signing step.
365-
* For more info, check SignTransactionOptions.signingStep
366-
*
367-
* TODO BTC-276: This cache may need to be done with LRU like memory safe caching if memory issues comes up.
368-
*/
369-
private static readonly PSBT_CACHE = new Map<string, utxolib.bitgo.UtxoPsbt>();
370-
371358
get network() {
372359
return this._network;
373360
}
@@ -831,132 +818,7 @@ export abstract class AbstractUtxoCoin extends BaseCoin {
831818
async signTransaction<TNumber extends number | bigint = number>(
832819
params: SignTransactionOptions<TNumber>
833820
): Promise<SignedTransaction | HalfSignedUtxoTransaction> {
834-
const txPrebuild = params.txPrebuild;
835-
836-
if (_.isUndefined(txPrebuild) || !_.isObject(txPrebuild)) {
837-
if (!_.isUndefined(txPrebuild) && !_.isObject(txPrebuild)) {
838-
throw new Error(`txPrebuild must be an object, got type ${typeof txPrebuild}`);
839-
}
840-
throw new Error('missing txPrebuild parameter');
841-
}
842-
843-
let tx = this.decodeTransactionFromPrebuild(params.txPrebuild);
844-
845-
const isTxWithKeyPathSpendInput = tx instanceof bitgo.UtxoPsbt && bitgo.isTransactionWithKeyPathSpendInput(tx);
846-
847-
let isLastSignature = false;
848-
if (_.isBoolean(params.isLastSignature)) {
849-
// We can only be the first signature on a transaction with taproot key path spend inputs because
850-
// we require the secret nonce in the cache of the first signer, which is impossible to retrieve if
851-
// deserialized from a hex.
852-
if (params.isLastSignature && isTxWithKeyPathSpendInput) {
853-
throw new Error('Cannot be last signature on a transaction with key path spend inputs');
854-
}
855-
856-
// if build is called instead of buildIncomplete, no signature placeholders are left in the sig script
857-
isLastSignature = params.isLastSignature;
858-
}
859-
860-
const getSignerKeychain = (): utxolib.BIP32Interface => {
861-
const userPrv = params.prv;
862-
if (_.isUndefined(userPrv) || !_.isString(userPrv)) {
863-
if (!_.isUndefined(userPrv)) {
864-
throw new Error(`prv must be a string, got type ${typeof userPrv}`);
865-
}
866-
throw new Error('missing prv parameter to sign transaction');
867-
}
868-
const signerKeychain = bip32.fromBase58(userPrv, utxolib.networks.bitcoin);
869-
if (signerKeychain.isNeutered()) {
870-
throw new Error('expected user private key but received public key');
871-
}
872-
debug(`Here is the public key of the xprv you used to sign: ${signerKeychain.neutered().toBase58()}`);
873-
return signerKeychain;
874-
};
875-
876-
const setSignerMusigNonceWithOverride = (
877-
psbt: utxolib.bitgo.UtxoPsbt,
878-
signerKeychain: utxolib.BIP32Interface,
879-
nonSegwitOverride: boolean
880-
) => {
881-
utxolib.bitgo.withUnsafeNonSegwit(psbt, () => psbt.setAllInputsMusig2NonceHD(signerKeychain), nonSegwitOverride);
882-
};
883-
884-
let signerKeychain: utxolib.BIP32Interface | undefined;
885-
886-
if (tx instanceof bitgo.UtxoPsbt && isTxWithKeyPathSpendInput) {
887-
switch (params.signingStep) {
888-
case 'signerNonce':
889-
signerKeychain = getSignerKeychain();
890-
setSignerMusigNonceWithOverride(tx, signerKeychain, !!params.allowNonSegwitSigningWithoutPrevTx);
891-
AbstractUtxoCoin.PSBT_CACHE.set(tx.getUnsignedTx().getId(), tx);
892-
return { txHex: tx.toHex() };
893-
case 'cosignerNonce':
894-
assert(txPrebuild.walletId, 'walletId is required for MuSig2 bitgo nonce');
895-
return { txHex: (await this.signPsbt(tx.toHex(), txPrebuild.walletId)).psbt };
896-
case 'signerSignature':
897-
const txId = tx.getUnsignedTx().getId();
898-
const psbt = AbstractUtxoCoin.PSBT_CACHE.get(txId);
899-
assert(
900-
psbt,
901-
`Psbt is missing from txCache (cache size ${AbstractUtxoCoin.PSBT_CACHE.size}).
902-
This may be due to the request being routed to a different BitGo-Express instance that for signing step 'signerNonce'.`
903-
);
904-
AbstractUtxoCoin.PSBT_CACHE.delete(txId);
905-
tx = psbt.combine(tx);
906-
break;
907-
default:
908-
// this instance is not an external signer
909-
assert(txPrebuild.walletId, 'walletId is required for MuSig2 bitgo nonce');
910-
signerKeychain = getSignerKeychain();
911-
setSignerMusigNonceWithOverride(tx, signerKeychain, !!params.allowNonSegwitSigningWithoutPrevTx);
912-
const response = await this.signPsbt(tx.toHex(), txPrebuild.walletId);
913-
tx.combine(bitgo.createPsbtFromHex(response.psbt, this.network));
914-
break;
915-
}
916-
} else {
917-
switch (params.signingStep) {
918-
case 'signerNonce':
919-
case 'cosignerNonce':
920-
/**
921-
* In certain cases, the caller of this method may not know whether the txHex contains a psbt with taproot key path spend input(s).
922-
* Instead of throwing error, no-op and return the txHex. So that the caller can call this method in the same sequence.
923-
*/
924-
return { txHex: tx.toHex() };
925-
}
926-
}
927-
928-
if (signerKeychain === undefined) {
929-
signerKeychain = getSignerKeychain();
930-
}
931-
932-
let signedTransaction: bitgo.UtxoTransaction<bigint> | bitgo.UtxoPsbt;
933-
if (tx instanceof bitgo.UtxoPsbt) {
934-
signedTransaction = signAndVerifyPsbt(tx, signerKeychain, {
935-
isLastSignature,
936-
allowNonSegwitSigningWithoutPrevTx: params.allowNonSegwitSigningWithoutPrevTx,
937-
});
938-
} else {
939-
if (tx.ins.length !== txPrebuild.txInfo?.unspents?.length) {
940-
throw new Error('length of unspents array should equal to the number of transaction inputs');
941-
}
942-
943-
if (!params.pubs || !isTriple(params.pubs)) {
944-
throw new Error(`must provide xpub array`);
945-
}
946-
947-
const keychains = params.pubs.map((pub) => bip32.fromBase58(pub)) as Triple<BIP32Interface>;
948-
const cosignerPub = params.cosignerPub ?? params.pubs[2];
949-
const cosignerKeychain = bip32.fromBase58(cosignerPub);
950-
951-
const walletSigner = new bitgo.WalletUnspentSigner<RootWalletKeys>(keychains, signerKeychain, cosignerKeychain);
952-
signedTransaction = signAndVerifyWalletTransaction(tx, txPrebuild.txInfo.unspents, walletSigner, {
953-
isLastSignature,
954-
}) as bitgo.UtxoTransaction<bigint>;
955-
}
956-
957-
return {
958-
txHex: signedTransaction.toBuffer().toString('hex'),
959-
};
821+
return signTransaction<TNumber>(this, params);
960822
}
961823

962824
/**

modules/abstract-utxo/src/recovery/crossChainRecovery.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import * as utxolib from '@bitgo/utxo-lib';
33
import { bip32, BIP32Interface } from '@bitgo/utxo-lib';
44

55
const { unspentSum, scriptTypeForChain, outputScripts } = utxolib.bitgo;
6-
export type RootWalletKeys = utxolib.bitgo.RootWalletKeys;
6+
type RootWalletKeys = utxolib.bitgo.RootWalletKeys;
77
type Unspent<TNumber extends number | bigint = number> = utxolib.bitgo.Unspent<TNumber>;
88
type WalletUnspent<TNumber extends number | bigint = number> = utxolib.bitgo.WalletUnspent<TNumber>;
99
type WalletUnspentLegacy<TNumber extends number | bigint = number> = utxolib.bitgo.WalletUnspentLegacy<TNumber>;
Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
export { explainPsbt, explainLegacyTx, ChangeAddressInfo } from './explainTransaction';
22
export { parseTransaction } from './parseTransaction';
3-
export { verifyTransaction } from './verifyTransaction';
43
export { CustomChangeOptions } from './parseOutput';
4+
export { verifyTransaction } from './verifyTransaction';
5+
export { signTransaction } from './signTransaction';
Lines changed: 152 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
import assert from 'assert';
2+
import _ from 'lodash';
3+
import { bip32, BIP32Interface, bitgo } from '@bitgo/utxo-lib';
4+
import * as utxolib from '@bitgo/utxo-lib';
5+
import { isTriple, Triple } from '@bitgo/sdk-core';
6+
import buildDebug from 'debug';
7+
8+
import { signAndVerifyPsbt, signAndVerifyWalletTransaction } from '../../sign';
9+
import { AbstractUtxoCoin, DecodedTransaction, RootWalletKeys } from '../../abstractUtxoCoin';
10+
11+
const debug = buildDebug('bitgo:abstract-utxo:signTransaction');
12+
13+
/**
14+
* Key Value: Unsigned tx id => PSBT
15+
* It is used to cache PSBTs with taproot key path (MuSig2) inputs during external express signer is activated.
16+
* Reason: MuSig2 signer secure nonce is cached in the UtxoPsbt object. It will be required during the signing step.
17+
* For more info, check SignTransactionOptions.signingStep
18+
*
19+
* TODO BTC-276: This cache may need to be done with LRU like memory safe caching if memory issues comes up.
20+
*/
21+
const PSBT_CACHE = new Map<string, utxolib.bitgo.UtxoPsbt>();
22+
23+
export async function signTransaction<TNumber extends number | bigint>(
24+
coin: AbstractUtxoCoin,
25+
tx: DecodedTransaction<TNumber>,
26+
params: {
27+
walletId: string | undefined;
28+
txInfo: { unspents?: utxolib.bitgo.Unspent<TNumber>[] } | undefined;
29+
isLastSignature: boolean;
30+
prv: string | undefined;
31+
signingStep: 'signerNonce' | 'cosignerNonce' | 'signerSignature' | undefined;
32+
allowNonSegwitSigningWithoutPrevTx: boolean;
33+
pubs: string[] | undefined;
34+
cosignerPub: string | undefined;
35+
}
36+
): Promise<{ txHex: string }> {
37+
const isTxWithKeyPathSpendInput = tx instanceof bitgo.UtxoPsbt && bitgo.isTransactionWithKeyPathSpendInput(tx);
38+
39+
let isLastSignature = false;
40+
if (_.isBoolean(params.isLastSignature)) {
41+
// We can only be the first signature on a transaction with taproot key path spend inputs because
42+
// we require the secret nonce in the cache of the first signer, which is impossible to retrieve if
43+
// deserialized from a hex.
44+
if (params.isLastSignature && isTxWithKeyPathSpendInput) {
45+
throw new Error('Cannot be last signature on a transaction with key path spend inputs');
46+
}
47+
48+
// if build is called instead of buildIncomplete, no signature placeholders are left in the sig script
49+
isLastSignature = params.isLastSignature;
50+
}
51+
52+
const getSignerKeychain = (): utxolib.BIP32Interface => {
53+
const userPrv = params.prv;
54+
if (_.isUndefined(userPrv) || !_.isString(userPrv)) {
55+
if (!_.isUndefined(userPrv)) {
56+
throw new Error(`prv must be a string, got type ${typeof userPrv}`);
57+
}
58+
throw new Error('missing prv parameter to sign transaction');
59+
}
60+
const signerKeychain = bip32.fromBase58(userPrv, utxolib.networks.bitcoin);
61+
if (signerKeychain.isNeutered()) {
62+
throw new Error('expected user private key but received public key');
63+
}
64+
debug(`Here is the public key of the xprv you used to sign: ${signerKeychain.neutered().toBase58()}`);
65+
return signerKeychain;
66+
};
67+
68+
const setSignerMusigNonceWithOverride = (
69+
psbt: utxolib.bitgo.UtxoPsbt,
70+
signerKeychain: utxolib.BIP32Interface,
71+
nonSegwitOverride: boolean
72+
) => {
73+
utxolib.bitgo.withUnsafeNonSegwit(psbt, () => psbt.setAllInputsMusig2NonceHD(signerKeychain), nonSegwitOverride);
74+
};
75+
76+
let signerKeychain: utxolib.BIP32Interface | undefined;
77+
78+
if (tx instanceof bitgo.UtxoPsbt && isTxWithKeyPathSpendInput) {
79+
switch (params.signingStep) {
80+
case 'signerNonce':
81+
signerKeychain = getSignerKeychain();
82+
setSignerMusigNonceWithOverride(tx, signerKeychain, params.allowNonSegwitSigningWithoutPrevTx);
83+
PSBT_CACHE.set(tx.getUnsignedTx().getId(), tx);
84+
return { txHex: tx.toHex() };
85+
case 'cosignerNonce':
86+
assert(params.walletId, 'walletId is required for MuSig2 bitgo nonce');
87+
return { txHex: (await coin.signPsbt(tx.toHex(), params.walletId)).psbt };
88+
case 'signerSignature':
89+
const txId = tx.getUnsignedTx().getId();
90+
const psbt = PSBT_CACHE.get(txId);
91+
assert(
92+
psbt,
93+
`Psbt is missing from txCache (cache size ${PSBT_CACHE.size}).
94+
This may be due to the request being routed to a different BitGo-Express instance that for signing step 'signerNonce'.`
95+
);
96+
PSBT_CACHE.delete(txId);
97+
tx = psbt.combine(tx);
98+
break;
99+
default:
100+
// this instance is not an external signer
101+
assert(params.walletId, 'walletId is required for MuSig2 bitgo nonce');
102+
signerKeychain = getSignerKeychain();
103+
setSignerMusigNonceWithOverride(tx, signerKeychain, params.allowNonSegwitSigningWithoutPrevTx);
104+
const response = await coin.signPsbt(tx.toHex(), params.walletId);
105+
tx.combine(bitgo.createPsbtFromHex(response.psbt, coin.network));
106+
break;
107+
}
108+
} else {
109+
switch (params.signingStep) {
110+
case 'signerNonce':
111+
case 'cosignerNonce':
112+
/**
113+
* In certain cases, the caller of this method may not know whether the txHex contains a psbt with taproot key path spend input(s).
114+
* Instead of throwing error, no-op and return the txHex. So that the caller can call this method in the same sequence.
115+
*/
116+
return { txHex: tx.toHex() };
117+
}
118+
}
119+
120+
if (signerKeychain === undefined) {
121+
signerKeychain = getSignerKeychain();
122+
}
123+
124+
let signedTransaction: bitgo.UtxoTransaction<bigint> | bitgo.UtxoPsbt;
125+
if (tx instanceof bitgo.UtxoPsbt) {
126+
signedTransaction = signAndVerifyPsbt(tx, signerKeychain, {
127+
isLastSignature,
128+
allowNonSegwitSigningWithoutPrevTx: params.allowNonSegwitSigningWithoutPrevTx,
129+
});
130+
} else {
131+
if (tx.ins.length !== params.txInfo?.unspents?.length) {
132+
throw new Error('length of unspents array should equal to the number of transaction inputs');
133+
}
134+
135+
if (!params.pubs || !isTriple(params.pubs)) {
136+
throw new Error(`must provide xpub array`);
137+
}
138+
139+
const keychains = params.pubs.map((pub) => bip32.fromBase58(pub)) as Triple<BIP32Interface>;
140+
const cosignerPub = params.cosignerPub ?? params.pubs[2];
141+
const cosignerKeychain = bip32.fromBase58(cosignerPub);
142+
143+
const walletSigner = new bitgo.WalletUnspentSigner<RootWalletKeys>(keychains, signerKeychain, cosignerKeychain);
144+
signedTransaction = signAndVerifyWalletTransaction(tx, params.txInfo.unspents, walletSigner, {
145+
isLastSignature,
146+
}) as bitgo.UtxoTransaction<bigint>;
147+
}
148+
149+
return {
150+
txHex: signedTransaction.toBuffer().toString('hex'),
151+
};
152+
}

0 commit comments

Comments
 (0)