|
| 1 | +const bitcoin = require('bitcoinjs-lib'); |
| 2 | +const { ECPairFactory } = require('ecpair'); |
| 3 | +const secp256k1 = require('@bitcoinerlab/secp256k1'); |
| 4 | +const ECPair = ECPairFactory(secp256k1); |
| 5 | + |
| 6 | +// Initialize the elliptic curve library for Bitcoin operations |
| 7 | +bitcoin.initEccLib(secp256k1); |
| 8 | + |
| 9 | +// Set network to testnet for development purposes |
| 10 | +const network = bitcoin.networks.testnet; |
| 11 | + |
| 12 | +/** |
| 13 | + * Convert a public key to x-only format required for Taproot |
| 14 | + * @param {Buffer} pubKey - The full public key |
| 15 | + * @returns {Buffer} The x-only public key (32 bytes) |
| 16 | + */ |
| 17 | +function toXOnly(pubKey) { |
| 18 | + return Buffer.from(pubKey).slice(1, 33); |
| 19 | +} |
| 20 | + |
| 21 | +/** |
| 22 | + * SchnorrSigner class for handling Taproot signatures |
| 23 | + * Implements the Schnorr signature scheme required for Taproot |
| 24 | + */ |
| 25 | +class SchnorrSigner { |
| 26 | + constructor(keyPair) { |
| 27 | + this.keyPair = keyPair; |
| 28 | + // Convert to x-only public key format required for Taproot |
| 29 | + this.publicKey = toXOnly(keyPair.publicKey); |
| 30 | + } |
| 31 | + |
| 32 | + // Sign transaction with Schnorr signature |
| 33 | + sign(hash) { |
| 34 | + return this.keyPair.sign(hash, true); // Enable Schnorr signing |
| 35 | + } |
| 36 | + |
| 37 | + signSchnorr(hash) { |
| 38 | + return this.sign(hash); |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +/** |
| 43 | + * Creates a Taproot address and associated data |
| 44 | + * @returns {Object} Contains signer, address and output script |
| 45 | + */ |
| 46 | +function createTaprootAddress() { |
| 47 | + // Generate random keypair for Taproot |
| 48 | + const keyPair = ECPair.makeRandom({ network }); |
| 49 | + const schnorrSigner = new SchnorrSigner(keyPair); |
| 50 | + |
| 51 | + // Create P2TR (Pay-to-Taproot) payment object |
| 52 | + const { address, output } = bitcoin.payments.p2tr({ |
| 53 | + pubkey: schnorrSigner.publicKey, |
| 54 | + network, |
| 55 | + }); |
| 56 | + |
| 57 | + return { signer: schnorrSigner, address, output }; |
| 58 | +} |
| 59 | + |
| 60 | +/** |
| 61 | + * Adds OP_RETURN output to transaction |
| 62 | + * @param {Psbt} psbt - The Partially Signed Bitcoin Transaction |
| 63 | + * @param {string} message - Message to embed in OP_RETURN |
| 64 | + */ |
| 65 | +function addOpReturnOutput(psbt, message) { |
| 66 | + const data = Buffer.from(message, 'utf8'); |
| 67 | + const embed = bitcoin.payments.embed({ data: [data] }); |
| 68 | + psbt.addOutput({ script: embed.output, value: 0 }); |
| 69 | +} |
| 70 | + |
| 71 | +/** |
| 72 | + * Creates and signs a Taproot transaction |
| 73 | + * @param {Object} taprootData - Contains signer and output information |
| 74 | + * @param {string} recipient - Recipient's address |
| 75 | + * @param {number} satoshis - Amount to send |
| 76 | + * @param {string} message - Optional OP_RETURN message |
| 77 | + * @returns {string} Signed transaction in hex format |
| 78 | + */ |
| 79 | +async function createTaprootTransaction(taprootData, recipient, satoshis, message = "Created with Bitcoin Taproot Demo") { |
| 80 | + try { |
| 81 | + // Initialize PSBT (Partially Signed Bitcoin Transaction) |
| 82 | + const psbt = new bitcoin.Psbt({ network }); |
| 83 | + |
| 84 | + // Example transaction ID (replace with actual UTXO in production) |
| 85 | + const txid = Buffer.from('a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2', 'hex'); |
| 86 | + |
| 87 | + // Add input with Taproot specific fields |
| 88 | + psbt.addInput({ |
| 89 | + hash: txid, |
| 90 | + index: 0, |
| 91 | + witnessUtxo: { |
| 92 | + value: satoshis, |
| 93 | + script: taprootData.output, |
| 94 | + }, |
| 95 | + tapInternalKey: taprootData.signer.publicKey, |
| 96 | + }); |
| 97 | + |
| 98 | + // Add recipient output (with fee deduction) |
| 99 | + psbt.addOutput({ |
| 100 | + address: recipient, |
| 101 | + value: satoshis - 1000 // Deduct transaction fee |
| 102 | + }); |
| 103 | + |
| 104 | + // Add optional OP_RETURN message |
| 105 | + addOpReturnOutput(psbt, message); |
| 106 | + |
| 107 | + // Sign and finalize the transaction |
| 108 | + await psbt.signInput(0, taprootData.signer); |
| 109 | + psbt.finalizeAllInputs(); |
| 110 | + |
| 111 | + return psbt.extractTransaction().toHex(); |
| 112 | + } catch (error) { |
| 113 | + console.error('Error in createTaprootTransaction:', error); |
| 114 | + throw error; |
| 115 | + } |
| 116 | +} |
| 117 | + |
| 118 | +// Print debug information |
| 119 | +function printDebugInfo(data) { |
| 120 | + console.log('\nDebug Information:'); |
| 121 | + for (const [key, value] of Object.entries(data)) { |
| 122 | + if (Buffer.isBuffer(value)) { |
| 123 | + console.log(`${key}: ${value.toString('hex')} (Buffer)`); |
| 124 | + } else if (typeof value === 'object' && value !== null) { |
| 125 | + console.log(`${key}: [Object]`); |
| 126 | + } else { |
| 127 | + console.log(`${key}: ${value}`); |
| 128 | + } |
| 129 | + } |
| 130 | +} |
| 131 | + |
| 132 | +async function main() { |
| 133 | + try { |
| 134 | + // Create Taproot address |
| 135 | + const taprootData = createTaprootAddress(); |
| 136 | + |
| 137 | + console.log('Taproot Details:'); |
| 138 | + console.log('Taproot Address:', taprootData.address); |
| 139 | + console.log('Public Key:', taprootData.signer.publicKey.toString('hex')); |
| 140 | + console.log('Output Script:', taprootData.output.toString('hex')); |
| 141 | + |
| 142 | + // Output debug information |
| 143 | + printDebugInfo({ |
| 144 | + network: network.messagePrefix, |
| 145 | + publicKeyType: taprootData.signer.publicKey.constructor.name, |
| 146 | + publicKeyLength: taprootData.signer.publicKey.length, |
| 147 | + hasPrivateKey: !!taprootData.signer.keyPair.privateKey, |
| 148 | + outputType: taprootData.output.constructor.name, |
| 149 | + outputLength: taprootData.output.length |
| 150 | + }); |
| 151 | + |
| 152 | + // Create transaction |
| 153 | + const recipientAddress = 'tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx'; |
| 154 | + const tx = await createTaprootTransaction(taprootData, recipientAddress, 100000); |
| 155 | + |
| 156 | + // Parse and print transaction details |
| 157 | + const decodedTx = bitcoin.Transaction.fromHex(tx); |
| 158 | + console.log('\nTransaction Details:'); |
| 159 | + console.log('Version:', decodedTx.version); |
| 160 | + console.log('Inputs:', decodedTx.ins.length); |
| 161 | + console.log('Outputs:', decodedTx.outs.length); |
| 162 | + console.log('Transaction Hex:', tx); |
| 163 | + |
| 164 | + // Print signature information |
| 165 | + console.log('\nSignature Details:'); |
| 166 | + decodedTx.ins.forEach((input, index) => { |
| 167 | + console.log(`Input #${index} Witness:`, input.witness.map(w => w.toString('hex'))); |
| 168 | + }); |
| 169 | + } catch (error) { |
| 170 | + console.error('Main Error:', error); |
| 171 | + } |
| 172 | +} |
| 173 | + |
| 174 | +main().catch(console.error); |
0 commit comments