Skip to content

Instantly share code, notes, and snippets.

@mahdiidarabi
Last active December 4, 2020 13:55
Show Gist options
  • Save mahdiidarabi/47c56dee1d9e1535253eaa450503c2dc to your computer and use it in GitHub Desktop.
Save mahdiidarabi/47c56dee1d9e1535253eaa450503c2dc to your computer and use it in GitHub Desktop.
build a multi sig P2SH address in go
package main
import (
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcutil"
)
func BuildMultiSigP2SHAddr() (string, error) {
// you can use your wif
wifStr1 := "cQpHXfs91s5eR9PWXui6qo2xjoJb2X3VdUspwKXe4A8Dybvut2rL"
wif1, err := btcutil.DecodeWIF(wifStr1)
if err != nil {
return "", err
}
// public key extracted from wif.PrivKey
pk1 := wif1.PrivKey.PubKey().SerializeCompressed()
wifStr2 := "cVgxEkRBtnfvd41ssd4PCsiemahAHidFrLWYoDBMNojUeME8dojZ"
wif2, err := btcutil.DecodeWIF(wifStr2)
if err != nil {
return "", err
}
pk2 := wif2.PrivKey.PubKey().SerializeCompressed()
wifStr3 := "cPXZBMz5pKytwCyUNAdq94R9VafU8L2QmAW8uw3gKrzjuCWCd3TM"
wif3, err := btcutil.DecodeWIF(wifStr3)
if err != nil {
return "", nil
}
pk3 := wif3.PrivKey.PubKey().SerializeCompressed()
// create redeem script for 2 of 3 multi-sig
builder := txscript.NewScriptBuilder()
// add the minimum number of needed signatures
builder.AddOp(txscript.OP_2)
// add the 3 public key
builder.AddData(pk1).AddData(pk2).AddData(pk3)
// add the total number of public keys in the multi-sig screipt
builder.AddOp(txscript.OP_3)
// add the check-multi-sig op-code
builder.AddOp(txscript.OP_CHECKMULTISIG)
// redeem script is the script program in the format of []byte
redeemScript, err := builder.Script()
if err != nil {
return "", err
}
// calculate the hash160 of the redeem script
redeemHash := btcutil.Hash160(redeemScript)
// if using Bitcoin main net then pass &chaincfg.MainNetParams as second argument
addr, err := btcutil.NewAddressScriptHashFromHash(redeemHash, &chaincfg.TestNet3Params)
if err != nil {
return "", err
}
return addr.EncodeAddress(), nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment