Batching Transaction (1 input, 5 outputs) - Legacy P2PKH
To follow along this tutorial
|
Let’s create a batching transaction, also called distributing transaction.
It is a transaction that distributes one input to multiple outputs representing multiple recipients. This type of transaction is sometimes used by commercial entities to distribute funds, such as when processing payroll payments to multiple employees.
For this example we will spend a legacy P2PKH UTXO and distribute it to five different P2PKH addresses.
Create a UTXO to spend from
const bitcoin = require('bitcoinjs-lib')
const { alice, bob, carol, dave, eve, mallory } = require('./wallets.json')
const network = bitcoin.networks.regtest
First we need to create a previous transaction in order to have an UTXO at our disposal.
sendtoaddress n4SvybJicv79X1Uc4o3fYXWGwXadA53FSq 1.001 (1)
1 | Check out your wallets.json file in the code directory. Replace the address if necessary. |
We have now a UTXO locked with alice_1 public key hash. In order to spend it, we refer to it with the transaction id (txid) and the output index (vout), also called outpoint.
gettransaction TX_ID
Find the output index (or vout) under | .
Creating the batching transaction
Now let’s spend the UTXO with BitcoinJS.
const keyPairAlice1 = bitcoin.ECPair.fromWIF(alice[1].wif, network)
const keyPairBob1 = bitcoin.ECPair.fromWIF(bob[1].wif, network)
const p2pkhBob1 = bitcoin.payments.p2pkh({pubkey: keyPairBob1.publicKey, network})
const keyPairCarol1 = bitcoin.ECPair.fromWIF(carol[1].wif, network)
const p2pkhCarol1 = bitcoin.payments.p2pkh({pubkey: keyPairCarol1.publicKey, network})
const keyPairDave1 = bitcoin.ECPair.fromWIF(dave[1].wif, network)
const p2pkhDave1 = bitcoin.payments.p2pkh({pubkey: keyPairDave1.publicKey, network})
const keyPairEve1 = bitcoin.ECPair.fromWIF(eve[1].wif, network)
const p2pkhEve1 = bitcoin.payments.p2pkh({pubkey: keyPairEve1.publicKey, network})
const keyPairMallory1 = bitcoin.ECPair.fromWIF(mallory[1].wif, network)
const p2pkhMallory1 = bitcoin.payments.p2pkh({pubkey: keyPairMallory1.publicKey, network})
const txb = new bitcoin.TransactionBuilder(network)
txb.addInput('TX_ID', TX_VOUT)
txb.addOutput(p2pkhBob1.address, 2e7)
txb.addOutput(p2pkhCarol1.address, 2e7)
txb.addOutput(p2pkhDave1.address, 2e7)
txb.addOutput(p2pkhEve1.address, 2e7)
txb.addOutput(p2pkhMallory1.address, 2e7)
The miner fee is calculated by subtracting the outputs from the inputs. |
txb.sign(0, keyPairAlice1)
BitcoinJS will automatically place the signature into the scriptSig
field of the input 0.
const tx = txb.build()
console.log('Transaction hexadecimal:')
console.log(tx.toHex())
decoderawtransaction TX_HEX