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
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 bitcoin = require('bitcoinjs-lib')
const { alice, bob, carol, dave, eve, mallory } = require('./wallets.json')
const network = bitcoin.networks.regtest
const keyPairAlice1 = bitcoin.ECPair.fromWIF(alice[1].wif, network)
const psbt = new bitcoin.Psbt({network})
.addInput({
hash: 'TX_ID',
index: TX_OUT,
nonWitnessUtxo: Buffer.from('TX_HEX', 'hex')
}) (1)
.addOutput({
address: bob[1].p2pkh,
value: 2e7,
}) (2)
.addOutput({
address: carol[1].p2pkh,
value: 2e7,
})
.addOutput({
address: dave[1].p2pkh,
value: 2e7,
})
.addOutput({
address: eve[1].p2pkh,
value: 2e7,
})
.addOutput({
address: mallory[1].p2pkh,
value: 2e7,
})
1 | Input referencing the 1.001 BTC UTXO just created |
2 | Outputs distributing 0.2 BTC to each five addresses |
The miner fee is calculated by subtracting the outputs from the inputs. |
psbt.signInput(0, keyPairAlice1)
psbt.validateSignaturesOfInput(0)
psbt.finalizeAllInputs()
BitcoinJS will automatically place the signature into the scriptSig
field of the input 0.
console.log('Transaction hexadecimal:')
console.log(psbt.extractTransaction().toHex())
decoderawtransaction TX_HEX