Data Anchoring with OP_RETURN
To follow along this tutorial
|
Let’s store for eternity some data on the Bitcoin blockchain using the special OP_RETURN opcode. It will create a special nulldata
output type.
An output using an OP_RETURN is provably unspendable, so we don’t need to lock any BTC in this UTXO. However, we still need to pay the miner fees, so we will spend BTC from a previous P2WPKH UTXO, create one nulldata
UTXO and an other one for the change, leaving the difference as mining fees.
For more information about OP_RETURN check out:
Create a UTXO to spend from
Let’s create a P2WPKH UTXO to spend from.
const bitcoin = require('bitcoinjs-lib')
const { alice } = require('./wallets.json')
const network = bitcoin.networks.regtest
sendtoaddress bcrt1qlwyzpu67l7s9gwv4gzuv4psypkxa4fx4ggs05g 1
gettransaction TX_ID
Find the output index (or vout) under | .
Creating the transaction
Now let’s create our OP_RETURN P2PKH UTXO.
const keyPairAlice1 = bitcoin.ECPair.fromWIF(alice[1].wif, network)
const p2wpkhAlice1 = bitcoin.payments.p2wpkh({pubkey: keyPairAlice1.publicKey, network})
console.log('P2WPKH alice_1 address:')
console.log(p2wpkhAlice1.address)
const txb = new bitcoin.TransactionBuilder(network)
// txb.addInput(prevTx, prevOut, sequence, prevTxScript)
txb.addInput('TX_ID', TX_VOUT, null, p2wpkhAlice1.output)
Don’t forget the prevTxScript, necessary because we are spending a P2WPKH. |
embed
payment method.const data = Buffer.from('Programmable money FTW!', 'utf8')
const embed = bitcoin.payments.embed({data: [data]})
txb.addOutput(embed.output, 0)
An output using an OP_RETURN is provably unspendable, the script will always evaluate to false. For this reason, and because this is a Bitcoin Core policy rule, the value of an OP_RETURN output is set to 0. |
txb.addOutput(p2wpkhAlice1.address, 99900000)
Keep note of the bitcoin value of the UTXO we are spending, necessary because we are spending a P2WPKH.
// txb.sign(index, keyPair, redeemScript, sign.hashType, value, witnessScript)
txb.sign(0, keyPairAlice1, null, null, 1e8, null)
Since we are spending a Segwit UTXO, we need to sign its value, 1e8 btc. |
const tx = txb.build()
console.log('Transaction hexadecimal:')
console.log(tx.toHex())
decoderawtransaction TX_HEX