how to generate bech32/segwit address from pubkey in golang

1

I am trying to generate bech32/segwit address in golang with the following code:

var pubkey *btcec.PubKey
address, err := btcutil.NewAddressPubKey(pubkey.SerializeCompressed(), chainParams)
if err != nil {
    log.Fatal(err)
}
address.SetFormat(btcutil.PKFCompressed)
bech32Bytes, err := bech32.ConvertBits(address.ScriptAddress(), 8, 5, true)
if err != nil {
    log.Fatal(err)
}
segwitaddr, err := bech32.Encode("tb", bech32Bytes)
if err != nil {
    log.Fatal(err)
}

and also more simply

var e *hdkeychain.ExtendedKey
address, err := e.Address(chainParams)
bech32Bytes, err := bech32.ConvertBits(address.ScriptAddress(), 8, 5, true)
if err != nil {
    log.Fatal(err)
}
segwitaddr, err := bech32.Encode("tb", bech32Bytes)
if err != nil {
    log.Fatal(err)
}

But neither segwitaddr generated match the bip84 address I got from https://iancoleman.io/bip39/. What is wrong with the code above or how to properly get a bech32 address from a pub key?

I have looked into another post on the same question, but could not figure out how to prepare the data needed in golang. More specifically, I am confused in preparing the input []byte to call bech32.Encode() and using bech32.ConvertBits().

tbraden

Posted 2020-08-20T10:15:19.767

Reputation: 169

Answers

0

I have found the answer thanks to modood/btckeygen.

Here is the relevant code extracted from the repo.

witnessProg := btcutil.Hash160(pubkey.SerializeCompressed())
addressWitnessPubKeyHash, err := btcutil.NewAddressWitnessPubKeyHash(witnessProg, chainParams)
if err != nil {
    panic(err)
}
address := addressWitnessPubKeyHash.EncodeAddress()

tbraden

Posted 2020-08-20T10:15:19.767

Reputation: 169