|
| 1 | +import { Psbt, Transaction } from '@bitgo/utxo-lib'; |
| 2 | + |
| 3 | +export type AddressDetails = { |
| 4 | + redeemScript?: Buffer; |
| 5 | + witnessScript?: Buffer; |
| 6 | +}; |
| 7 | + |
| 8 | +/** |
| 9 | + * Construct the toSign PSBT for a BIP322 verification. |
| 10 | + * Source implementation: |
| 11 | + * https://github.com/bitcoin/bips/blob/master/bip-0322.mediawiki#full |
| 12 | + * |
| 13 | + * @param {string} toSpendTxHex - The hex representation of the `toSpend` transaction. |
| 14 | + * @param {AddressDetails} addressDetails - The details of the address, including redeemScript and/or witnessScript. |
| 15 | + * @returns {string} - The hex representation of the constructed PSBT. |
| 16 | + */ |
| 17 | +export function buildToSignPsbt(toSpendTx: Transaction<bigint>, addressDetails: AddressDetails): Psbt { |
| 18 | + if (!addressDetails.redeemScript && !addressDetails.witnessScript) { |
| 19 | + throw new Error('redeemScript and/or witnessScript must be provided'); |
| 20 | + } |
| 21 | + |
| 22 | + // Create PSBT object for constructing the transaction |
| 23 | + const psbt = new Psbt(); |
| 24 | + // Set default value for nVersion and nLockTime |
| 25 | + psbt.setVersion(0); // nVersion = 0 |
| 26 | + psbt.setLocktime(0); // nLockTime = 0 |
| 27 | + // Set the input |
| 28 | + psbt.addInput({ |
| 29 | + hash: toSpendTx.getId(), // vin[0].prevout.hash = to_spend.txid |
| 30 | + index: 0, // vin[0].prevout.n = 0 |
| 31 | + sequence: 0, // vin[0].nSequence = 0 |
| 32 | + nonWitnessUtxo: toSpendTx.toBuffer(), // previous transaction for us to rebuild later to verify |
| 33 | + }); |
| 34 | + if (addressDetails.redeemScript) { |
| 35 | + psbt.updateInput(0, { redeemScript: addressDetails.redeemScript }); |
| 36 | + } |
| 37 | + if (addressDetails.witnessScript) { |
| 38 | + psbt.updateInput(0, { |
| 39 | + witnessUtxo: { value: BigInt(0), script: addressDetails.witnessScript }, |
| 40 | + }); |
| 41 | + } |
| 42 | + |
| 43 | + // Set the output |
| 44 | + psbt.addOutput({ |
| 45 | + value: BigInt(0), // vout[0].nValue = 0 |
| 46 | + script: Buffer.from([0x6a]), // vout[0].scriptPubKey = OP_RETURN |
| 47 | + }); |
| 48 | + return psbt; |
| 49 | +} |
0 commit comments