DEV Community

Oniya Adesubomi Daniel
Oniya Adesubomi Daniel

Posted on

How to Generate bech32 Bitcoin Address

Bitcoin addresses are used to receive and send transactions on the Bitcoin network, that’s not news.

To generate an address, you need to have a private key. This private key is converted using cryptographic magic to a public key, and the public key is hashed to produce the address. You can learn more about the relevance of these cryptographic processes from Abubakar.

But then, a little backstory;

Initially, Bitcoin addresses were based on a "Pay-to-Pubkey-Hash" (P2PKH) format, which used a public key hash as the address. These addresses began with the number "1."

Later, a new address format called "Pay-to-Script-Hash" (P2SH) was introduced, which allowed for more complex scripts to be used in transactions. P2SH addresses begin with the number "3." This format was created to enable the use of multi-signature and other advanced features.

Then, SegWit (short for Segregated Witness) was introduced, which modified the format of P2SH addresses. SegWit addresses, which begin with the number "3" as well, use a different hash and allow for more efficient use of block space, increased transaction capacity, and malleability fix.

Finally, the Bech32 format was introduced, it's a new format of segwit address which has the prefix "bc1" and is more efficient in terms of space and offers error-checking capabilities.

These address formats are all still in use today, but Bech32 is considered the most recommended format, as it offers the most benefits.

In this article, we will demonstrate how to generate a SegWit address in the "Bech32" format using the bitcoinjs-lib and some other libraries that would help us achieve our goal. We are mostly writing TypeScript.

The first step is to install the library by running the following command:

npm i bitcoinjs-lib bip32 bip39
Enter fullscreen mode Exit fullscreen mode

Next...

Generate a seed phrase

A seed phrase is just some a set of words that can be rearranged randomly. These words have a range of allowed lengths (i.e. you can only use a seed phrase of a combination of 3, 6, 9, 12, 15, 18, 21 or 24 words). If these words are truly randomly generated, it is statistically impossible to generate 2 identical sets of seed phrase.

This seed phrase should be kept save because whoever has the seed phrase would have access to any address generated from that seed phrase.

Generate a seed phrase with this piece of code:

// required imports
const bip39 = require("bip39");

// code
const mnemonic bip39.generateMnemonic().toString();
Enter fullscreen mode Exit fullscreen mode

Top comments (0)