node.jsbitcoincryptocurrencybitcoinlib

How to generate bech32 address from the public key? Bitcoin


I am using bitcoinjs-lib for bitcoin key pair generation.

I got enough examples to generate legacy address and segwit address from the public key, but for bech32 address I could not found anything.

P2PKH which begin with the number 1,
eg: 1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN2.

P2SH type starting with the number 3,
eg: 3J98t1WpEZ73CNmQviecrnyiWrnqRhWNLy.

Bech32 type starting with bc1,
eg: bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq.

Thank you for the help.


Solution

  • There are many steps involved in it.

    hash160(publickey) which is ripemd160(sha256(publickey)).

    After that add 0 Uint8 to the output of bech32 words.

    Then using bech32 encode it with the prefix bc for bitcoin.
    It will work for litecoin also, change the bc to ltc.

    For Cosmos Atom also, it will work except skip the adding 0 to the ouput of bech32.

    const crypto = require("crypto");
    const bech32 = require("bech32");
    
    const sha256Digest = crypto
      .createHash("sha256")
      .update(data, "hex")
      .digest("hex");
    
    const ripemd160Digest = crypto
      .createHash("ripemd160")
      .update(sha256Digest, "hex")
      .digest("hex");
    
    const bech32Words = bech32.toWords(Buffer.from(ripemd160Digest, "hex"));
    const words = new Uint8Array([0, ...bech32Words]);
    address = bech32.encode("bc", words);
    console.log(address);