import bitcoin from 'bitcoinjs-lib'; import { ECPairFactory } from 'ecpair'; import * as tinysecp from 'tiny-secp256k1';
bitcoin.initEccLib(tinysecp); const ECPair = ECPairFactory(tinysecp);
const NETWORK = bitcoin.networks.bitcoin;
const keyPair = ECPair.fromWIF("xxx", NETWORK);
const publicKey = keyPair.publicKey;
const xOnlyPubKey = toXOnly(publicKey);
const p2trAddress = bitcoin.payments.p2tr({ internalPubkey: xOnlyPubKey, network: NETWORK, }); console.log("生成的 Taproot 地址: ", p2trAddress.address);
const txid = Buffer.from('9af012261e23fb6f9efc051e1e31f7c6210c5683ca66eb071f6f416c57a52223', 'hex'); if (txid.length !== 32) { throw new Error("交易 ID 长度不正确,应为 32 字节"); } console.log(p2trAddress.output);
const psbt = new bitcoin.Psbt({ network: NETWORK }); psbt.addInput({ hash: txid, index: 0, witnessUtxo: { script: p2trAddress.output, value: 100000, }, tapInternalKey: xOnlyPubKey, });
psbt.addOutput({ address: 'bc1p2we2ujewmfzjcvlmh60dwyzp9qwaahuxa78rx7m08vxez9azlrlq9kxcg5', value: 90000, });
psbt.signInput(0, keyPair);
const validator = (pubkey, msghash, signature) => tinysecp.verifySchnorr(msghash, pubkey, signature); psbt.validateSignaturesOfInput(0, validator); psbt.finalizeAllInputs();
const txHex = psbt.extractTransaction().toHex(); console.log("已签名的交易 HEX: ", txHex);
请教一下大佬,为什么我的私钥生成的密钥对没办法去签名,Can not sign for input #0 with the key 03d2ad3efd7734cebc4d757ac12656504daedbcf5ec3ceb49611e1c790aebb2782,如果我把internalPubkey: xOnlyPubKey, 换成pubkey: xOnlyPubKey,可以进行签名,但是地址跟我私钥对应的地址不一样