Skip to content

Instantly share code, notes, and snippets.

@pseudozach
Last active September 23, 2021 21:50
Show Gist options
  • Save pseudozach/90035da367a972f21e40260832c6e3c3 to your computer and use it in GitHub Desktop.
Save pseudozach/90035da367a972f21e40260832c6e3c3 to your computer and use it in GitHub Desktop.
create and broadcast op_return data to bitcoin blockchain by using polar and bitcoinjs.
var bitcoin = require('bitcoinjs-lib');
const Client = require('bitcoin-core');
const client = new Client({ network: 'regtest',port: 18443, username: 'polaruser', password: 'polarpass', version: '0.21.1' });
async function sendopreturn() {
try {
const unspentutxos = await client.command('listunspent');
// console.log("unspentutxos: ", unspentutxos);
// get a random UTXO
const randomutxo = unspentutxos[Math.floor(Math.random()*unspentutxos.length)];
console.log(`randomutxo: `, JSON.stringify(randomutxo));
// get privkey for the utxo
const wif = await client.command(`dumpprivkey`, randomutxo.address);
// console.log("privkey for the utxo: ", wif);
// use bitcoinjs-lib psbt to get raw op_return tx
const alice = bitcoin.ECPair.fromWIF(wif, bitcoin.networks.regtest);
const inputData1 = {
hash: randomutxo.txid,
index: randomutxo.vout,
witnessUtxo: {script: Buffer.from(randomutxo.scriptPubKey, 'hex'), value: parseInt(randomutxo.amount*100000000)}
};
// this is opreturn data - can be anything under 80 bytes
const data = Buffer.from('03729d8e7a3bfcffc65b4f97df0bdbb128339a7110a1c1b33d8462d1355fc7ba', 'hex');
const embed = bitcoin.payments.embed({ data: [data] });
const psbt = new bitcoin.Psbt({ network: bitcoin.networks.regtest })
.addInput(inputData1)
.addOutput({
script: embed.output,
value: 0,
})
.addOutput({
address: 'bcrt1q7xp6jcgmnuvvaqzr9sdg7yjdqfftswjdqz9897',
value: 500000,
})
.addOutput({
address: randomutxo.address,
value: parseInt(randomutxo.amount*100000000)-501000,
})
.signInput(0, alice);
psbt.finalizeAllInputs();
const txHex = psbt.extractTransaction().toHex();
console.log(`txHex ${txHex}`);
await client.command(`sendrawtransaction`, txHex);
console.log("raw tx sent: ", txHex);
} catch (error) {
console.log("error: ", error);
}
}
sendopreturn();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment