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

1 Answer 1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.