Algebra Puzzle - Legacy P2SH
|
To follow along this tutorial
|
Let’s create a simple maths puzzle with a legacy P2SH transaction.
Creating and Funding the P2SH
const bitcoin = require('bitcoinjs-lib')
const { alice } = require('./wallets.json')
const network = bitcoin.networks.regtest
const redeemScript = bitcoin.script.compile([
bitcoin.opcodes.OP_ADD,
bitcoin.opcodes.OP_5,
bitcoin.opcodes.OP_EQUAL])
console.log('Redeem script:')
console.log(redeemScript.toString('hex'))
decodescript 935587
The p2sh method will generate an object that contains the P2SH address.
const p2sh = bitcoin.payments.p2sh({redeem: {output: redeemScript, network}, network})
console.log('P2SH address:')
console.log(p2sh.address)
sendtoaddress 2N7WfHK1ftrTdhWej8rnFNR7guhvhfGWwFR 1
| We can note that anyone can create this script and generate the corresponding address, it will always result in the same address. |
gettransaction TX_ID
| Find the output index (or vout) under . |
Preparing the spending transaction
Now let’s prepare the spending transaction by setting input and output.
Alice_1 wants to send the funds to her P2WPKH address.
const keyPairAlice1 = bitcoin.ECPair.fromWIF(alice[1].wif, network)
const p2wpkhAlice1 = bitcoin.payments.p2wpkh({pubkey: keyPairAlice1.publicKey, network})
console.log('P2WPKH address')
console.log(p2wpkhAlice1.address)
const txb = new bitcoin.TransactionBuilder(network)
txb.addInput('TX_ID', TX_VOUT)
txb.addOutput(p2wpkhAlice1.address, 999e5)
const tx = txb.buildIncomplete()
Creating the unlocking script
Now we can update the transaction with the unlocking script, providing a solution to the maths problem.
We provide 02 and 03 as an answer, plus the redeem script.
const InputScriptP2SH = bitcoin.script.compile([bitcoin.opcodes.OP_2, bitcoin.opcodes.OP_3, p2sh.redeem.output])
tx.setInputScript(0, InputScriptP2SH)
We don’t need to sign this transaction since the redeem script doesn’t ask for a signature.
No build step here as we have already called buildIncomplete
console.log('Transaction hexadecimal:')
console.log(tx.toHex())
decoderawtransaction TX_HEX
Broadcasting the transaction
sendrawtransaction TX_HEX
getrawtransaction TX_ID true
Observations
We can decrypt the unlocking script in Bitcoin Core CLI with decodescript. You will notice that it is the concatenation of the corresponding hex value of the specified opcodes, OP_2, OP_3 and the redeem script OP_ADD OP_5 OP_EQUAL.
decodescript 5253935587
| Be aware that the hex script is the serialized version, which includes a before the redeem script. In order to decode the script we need to remove this pushbyte. |