1

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.

Shubham Chadokar
  • 2,520
  • 1
  • 24
  • 45

3 Answers3

4

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

Shubham Chadokar
  • 2,520
  • 1
  • 24
  • 45
1

It's filed as BIP 0173. You can find documentation about it in the Bitcoin Wiki. Wiki BIP0173

Det
  • 11
  • 2
0

Or you can just use bitcoin.payments.p2wpkh({pubkey:yourpubkey,network });

Chisom Maxwell
  • 149
  • 2
  • 7