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()
.