Multi-signature Native Segwit 2 of 4
To follow along this tutorial
|
Let’s create, fund and spend a 2 of 4 multi-signature with a native Segwit P2WSH transaction.
Creating and Funding a P2WSH Multi-Signature UTXO
const bitcoin = require('bitcoinjs-lib')
const {alice, bob, carol, dave} = require('./wallets.json')
const network = bitcoin.networks.regtest
p2ms
payment method.const p2ms = bitcoin.payments.p2ms({
m: 2, pubkeys: [
Buffer.from(alice[1].pubKey, 'hex'),
Buffer.from(bob[1].pubKey, 'hex'),
Buffer.from(carol[1].pubKey, 'hex'),
Buffer.from(dave[1].pubKey, 'hex'),
], network})
console.log('Witness script:')
console.log(p2ms.output.toString('hex'))
console.log()
console.log('Witness script SHA256:')
console.log(bitcoin.crypto.sha256(p2ms.output).toString('hex'))
console.log()
decodescript SCRIPT
The asm field should contain:
02 03745c9aceb84dcdeddf2c3cdc1edb0b0b5af2f9bf85612d73fa6394758eaee35d 027efbabf425077cdbceb73f6681c7ebe2ade74a65ea57ebcf0c42364d3822c590 023a11cfcedb993ff2e7523f92e359c4454072a66d42e8b74b4b27a8a1258abddd 02e9d617f38f8c3ab9a6bde36ce991bafb295d7adba457699f8620c8160ec9e87a 04 OP_CHECKMULTISIG
p2wsh
method with the BitcoinJS p2ms
object.const p2wsh = bitcoin.payments.p2wsh({redeem: p2ms, network})
console.log('P2WSH address')
console.log(p2wsh.address) (1)
1 | The p2wsh payment method generates an object that contains the P2WSH address. |
sendtoaddress bcrt1qtvraes6lc2efmwqtupv7f9wg3adhvzwpu0vg3s2zgpnc7qpp0v7sj6dkmu 1
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 and having two persons (private keys) to sign the transaction. In this tutorial, alice_1 and bob_1 will redeem the P2WSH multi-signature and send the funds to alice_2 P2WPKH address.
const psbt = new bitcoin.Psbt({network})
.addInput({
hash: 'TX_ID',
index: TX_VOUT,
witnessScript: p2wsh.redeem.output,
witnessUtxo: {
script: Buffer.from('0020' + bitcoin.crypto.sha256(p2ms.output).toString('hex'), 'hex'), (1)
value: 1e8,
}
})
.addOutput({
address: alice[2].p2wpkh,
value: 999e5,
}) (2)
1 | Locking script of the UTXO we are spending, which is a P2WSH witness program, <00> + PushByte 20 + SHA256(witness script) |
2 | Output locking the funds to alice_2 P2WPKH address, leaving 100 000 satoshis as mining fees |
const keyPairAlice1 = bitcoin.ECPair.fromWIF(alice[1].wif, network)
const keyPairBob1 = bitcoin.ECPair.fromWIF(bob[1].wif, network)
psbt
.signInput(0, keyPairAlice1)
.signInput(0, keyPairBob1)
psbt.validateSignaturesOfInput(0, Buffer.from(alice[1].pubKey, 'hex'))
psbt.validateSignaturesOfInput(0, Buffer.from(bob[1].pubKey, 'hex'))
psbt.finalizeAllInputs()
console.log('Transaction hexadecimal:')
console.log(psbt.extractTransaction().toHex())
decoderawtransaction TX_HEX