1- import { Psbt , Transaction , bitgo } from '@bitgo/utxo-lib' ;
1+ import { Psbt , bitgo } from '@bitgo/utxo-lib' ;
22
3- import { isTaprootChain } from './utils' ;
3+ import { addBip322ProofMessage , isTaprootChain } from './utils' ;
4+ import { BIP322_TAG , buildToSpendTransaction } from './toSpend' ;
45
56export type AddressDetails = {
67 redeemScript ?: Buffer ;
@@ -13,11 +14,14 @@ export type AddressDetails = {
1314 * Source implementation:
1415 * https://github.com/bitcoin/bips/blob/master/bip-0322.mediawiki#full
1516 *
16- * @param {string } toSpendTxHex - The hex representation of the `toSpend ` transaction.
17+ * @param {string } message - The message that is hashed into the `to_spend ` transaction.
1718 * @param {AddressDetails } addressDetails - The details of the address, including redeemScript and/or witnessScript.
18- * @returns {string } - The hex representation of the constructed PSBT.
19+ * @param {string } [tag=BIP322_TAG] - The tag to use for hashing, defaults to BIP322_TAG.
20+ * @returns {Psbt } - The hex representation of the constructed PSBT.
1921 */
20- export function buildToSignPsbt ( toSpendTx : Transaction < bigint > , addressDetails : AddressDetails ) : Psbt {
22+ export function buildToSignPsbt ( message : string , addressDetails : AddressDetails , tag = BIP322_TAG ) : Psbt {
23+ const toSpendTx = buildToSpendTransaction ( addressDetails . scriptPubKey , message , tag ) ;
24+
2125 // Create PSBT object for constructing the transaction
2226 const psbt = new Psbt ( ) ;
2327 // Set default value for nVersion and nLockTime
@@ -41,6 +45,9 @@ export function buildToSignPsbt(toSpendTx: Transaction<bigint>, addressDetails:
4145 psbt . updateInput ( 0 , { witnessScript : addressDetails . witnessScript } ) ;
4246 }
4347
48+ // Add the message as a proprietary key value to the PSBT so we can verify it later
49+ addBip322ProofMessage ( psbt as bitgo . UtxoPsbt , 0 , Buffer . from ( message ) ) ;
50+
4451 // Set the output
4552 psbt . addOutput ( {
4653 value : BigInt ( 0 ) , // vout[0].nValue = 0
@@ -50,7 +57,7 @@ export function buildToSignPsbt(toSpendTx: Transaction<bigint>, addressDetails:
5057}
5158
5259export function buildToSignPsbtForChainAndIndex (
53- toSpendTx : Transaction < bigint > ,
60+ message : string ,
5461 rootWalletKeys : bitgo . RootWalletKeys ,
5562 chain : bitgo . ChainCode ,
5663 index : number
@@ -63,12 +70,7 @@ export function buildToSignPsbtForChainAndIndex(
6370 bitgo . scriptTypeForChain ( chain )
6471 ) ;
6572
66- const toSpendScriptPubKey = toSpendTx . outs [ 0 ] . script ;
67- if ( ! toSpendScriptPubKey . equals ( output . scriptPubKey ) ) {
68- throw new Error ( 'Output scriptPubKey does not match the expected output script for the chain and index.' ) ;
69- }
70-
71- return buildToSignPsbt ( toSpendTx , {
73+ return buildToSignPsbt ( message , {
7274 scriptPubKey : output . scriptPubKey ,
7375 redeemScript : output . redeemScript ,
7476 witnessScript : output . witnessScript ,
0 commit comments