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 psbt = new bitcoin.Psbt({network})
psbt
.addInput({
hash: 'TX_ID',
index: TX_VOUT,
witnessUtxo: {
script: Buffer.from('0014' + alice[1].pubKeyHash, 'hex'),
value: 1e8,
},
})
embed
payment method.const data = Buffer.from('Programmable money FTW', 'utf8')
const embed = bitcoin.payments.embed({data: [data]})
psbt
.addOutput({
script: embed.output,
value: 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. |
psbt
.addOutput({
address: alice[1].p2wpkh,
value: 999e5,
})
Keep note of the bitcoin value of the UTXO we are spending, necessary because we are spending a P2WPKH.
psbt.signInput(0, keyPairAlice1)
psbt.validateSignaturesOfInput(0)
psbt.finalizeAllInputs()
console.log('Transaction hexadecimal:')
console.log(psbt.extractTransaction().toHex())
decoderawtransaction TX_HEX