This is the code I've been working on
import * as bitcoin from 'bitcoinjs-lib'
const NETWORK = bitcoin.networks.regtest;
const psbt = new bitcoin.Psbt({ network: NETWORK });
function p2shAddress(node: bitcoin.ECPairInterface): string {
const ecpair = bitcoin.ECPair.fromPublicKey(node.publicKey, { network: NETWORK });
const p2wpkh = bitcoin.payments.p2wpkh({ pubkey: ecpair.publicKey, network: NETWORK });
const p2sh = bitcoin.payments.p2sh({ redeem: p2wpkh });
return p2sh.address as string;
}
const tx = '02000000000105e11d8c7970aff25a8a431c49397316ce80af25dca6ac395f172e2d7326d42e570100000017160014cccb96f2ec1b5a2b7081f96b78077488769e3d8efeffffff77bcf72d69888cc739341107028e1e8a302d507fe9ffb94c5359fb1e82f08f370100000017160014527aef9caa6e0a12ecea8ce255cb36427a2f451afeffffff3cad9140403d6ec68bc0cf0b261daa4a41d92f04bddad98fc05a305127c7145c00000000171600143ea2fa276d3de26e4e220a1e6d343a235edbaff6feffffff250152b93632b8e275aba954c894dcbc2c0124a5c1db10de3ed...
// this is the raw-tx I sent to 2NFJUYmdpAPRoo6qqUZem7rmBq2QSSPKBPu.
// did I understand it wrong, and this is not the supposed to be nonWitnessUtxo?
psbt.addInput({
hash: '25ba0c45cadf92ded94432101d286975dcdb865df44b68da597910ea783cff74',
index: 0,
nonWitnessUtxo: Buffer.from(tx, 'hex'),
});
psbt.addOutput({
address: '2MuhtGHkdxiL4BjFAAaYjq8Q2mwnCoYSebt',
value: 4000,
});
const signer = bitcoin.ECPair.fromPrivateKey(Buffer.from('64e897b5fac936a30a7a73e1c2892697c91b0705a8d061ea28e59f41d2876e0d', 'hex'), { network: NETWORK });
console.log({ address: p2shAddress(signer) });
// { address: '2NFJUYmdpAPRoo6qqUZem7rmBq2QSSPKBPu' }
psbt.signInput(0, signer);
psbt.validateSignaturesOfInput(0, signer.publicKey);
An error keeps popping up stating:
The key 02c4ac... cannot sign for this input
I have double-checked by decoding the transaction using
bitcoin-cli decoderawtransaction $TX
and confirmed that the address in the first vout (index 0) matches the one generated by p2shAddress(signer), which is 2NFJUYmdpAPRoo6qqUZem7rmBq2QSSPKBPu
.
Can anyone help me identify where the mistake might be?