Marketplace has launched, further enabling blockchain developers! Learn more

How to generate a new Bitcoin address in JavaScript

September 09, 2022

Overview

To do any type of transaction on the Bitcoin blockchain, you’ll need a public key or a Bitcoin address. In this guide, we’ll cover how to generate a new Bitcoin address in JavaScript using CyrptoCoinJS.

What is a Bitcoin address?

You can think of a Bitcoin address as an account number for your bank account. The main difference being is that It is used to direct bitcoin during a transaction rather than store it. A Bitcoin address is a string combining letters and digits representing a destination on the bitcoin network. Every time someone wants to receive Bitcoin, they will ideally generate a new unique single-use address for each transaction using a wallet app or code. There are three types of Bitcoin addresses: 

  1. Legacy (P2PKH): Legacy is the original bitcoin address; they all start with one. It is the most compatible and supported by wallets. Example:1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN2

  2. Nested SegWit (P2PSH): Nested SegWit is an improvement on Legacy; they have a 40% lesser transaction fee than Legacy addresses and have multi-signature. It starts with 3.
    Example: 3EktnHQD7RiAE6uzMj2ZifT9YgRrkSgzQX 

  3. Native SegWit (Bech32): SegWit, short for Segregated Witness, has smaller transaction sizes; they can save 80% of transaction fees compared to Legacy. They start with bc1.
    Example: bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4

How is a Bitcoin address generated?

  • A random string of private key consisting of 64 (hex) characters (256 bits / 32 bytes) is generated first, it can be any number between 0 and ≤ n-1, where n is a constant (n = 1.1578*1077).
    A string of 256-bit number which is less than n is fed to the SHA256 hashing algorithm which then generates a new 256-bit number. This is our private key.
    For example:
1184CD2CDD640CA42CFC3A091C51D549B2F016D454B2774019C2B2D2E08529FD

  •  A 128 (hex) character (64 bytes) public key is then derived from the generated private key using, It has ‘04’ as the prefix. The public key is generated from the private key using secp256k1, which is a curve of ECDSA (Elliptic Curve Digital Signature Algorithm). So a public key is generated using a formula P = p*G, where p is the private key and G is the generator point. The generator point G is a defined point on the secp256k1 curve.
    For example:

how is a bitcoin address generated

Copy
04d0988bfa799f7d7ef9ab3de97ef481cd0f75d2367ad456607647edde665d6f6fbdd594388756a7beaf73b4822bc22d36e9bda7db82df2b8b623673eefc0b7495

Image source: O’Reilly.
  • An address of 34 characters is generated by applying the SHA256 hashing algorithm on the pubic key, then computing the RIPEMD160 hash of the result. A = RIPEMD160(SHA256(P)), where P is the public key, and A is the Bitcoin address. Bitcoin addresses are always encoded as Base58Check which uses 58 characters (Base58 number system), and a checksum to avoid ambiguity, errors in address transcription, and to aid in human readability.
    For example: 

how is a bitcoin address generated

Copy
16UjcYNBG9GTK4uq2f7yYEbuifqCzoLMGS

Note: A private key can be generated to the public key, but the public cannot be converted back to the private key as the algorithm is a one-way function.

What is CryptoCoinJS?

CryptoCoinJS is a JavaScript library that helps you interface with different cryptocurrencies like Bitcoin, Litecoin, and Dogecoin.

Generating a Bitcoin address in JavaScript

First, we’ll need to install the CryptoCoinJs library. We’ll use npm (Node Package Manager) which comes with node.js, to install the library.

Let’s check if we have node.js install on our system by typing the following in our terminal/cmd:

generating a bitcoin address in javascript

Copy
node -v

This should return the installed version of node.js on your system. If it errors, download and install the LTS version of node.js from its official website.

Now, let’s create a new project directory, and make it our working directory

generating a bitcoin address in javascript

Copy
mkdir Bitcoin
cd Bitcoin

To install the library, type the following in your terminal/cmd:

generating a bitcoin address in javascript

Copy
npm i coinkey

The most common issue at this step is an internal failure with `node-gyp`. You can follow node-gyp installation instructions here.

Note: You will need to have your python version match one of the compatible versions listed in the instructions above if you encounter the node-gyp issue. 

Another common issue is a stale cache; clear your npm cache by simply typing the below into your terminal:

generating a bitcoin address in javascript

Copy
npm cache clean

If everything goes right, CryptoCoinJSwill be installed on your system.

Now open a text editor of your choice and create a new javascript file address.js, and copy-paste the following in it:

generating a bitcoin address in javascript

Copy
var CoinKey = require('coinkey'); 

var wallet = new CoinKey.createRandom();

console.log("SAVE BUT DO NOT SHARE THIS:", wallet.privateKey.toString('hex'));
console.log("Address:", wallet.publicAddress);

Explanation of the code above

Line 1: Importing the CryptoCoinJS library.

Line 2: Creating a random address with keys using Coinkey.createRandom method and storing it in the wallet variable.

Line3: Printing the private key to the console along with a warning.

Line4: Printing the address to the console along with a string.

Save the script file and run it using the following command.

generating a bitcoin address in javascript

Copy
node address

It will give an output that is similar to this.

Conclusion

Congratulations on creating your own Bitcoin address which you can use to receive funds! There are many algorithms and functions that are used in tandem to create the functionality in your favorite wallet's software. You now know one small piece of it, and have taken a look behind the curtain to see the inner workings yourself!

Subscribe to our newsletter for more articles and guides on Ethereum. If you have any feedback, feel free to reach out to us via Twitter. You can always chat with us on our Discord community server, featuring some of the coolest developers you’ll ever meet :)

Related articles 36

How to Access Bitcoin Mempool
Published: Aug 16, 2021
Updated: Sep 21, 2022

Bitcoin is the father of blockchain technology. With Bitcoin started a new era of blockchain and decentralization. Bitcoin enabled everyone to make the peer-to-peer transactions they enjoy...

Continue reading
How to access Ethereum Mempool
Published: Oct 15, 2020
Updated: Sep 15, 2022

On Ethereum, when a transaction is sent, before being added to a block, it resides in what is called a Mempool. To receive information about this transaction, the Mempool must be queried. This...

Continue reading
The Web3 Developer Stack
Published: Jul 3, 2021
Updated: Sep 15, 2022

A developer stack is a bag of technologies a developer possesses. For example, MEAN (MongoDB, Express.js, AngularJS/Angular, and Node.js) and MERN (MongoDB, Express.js, React, and Node.js) are...

Continue reading
Introduction to Scaffold-ETH 🏗
Published: Oct 7, 2021
Updated: Sep 9, 2022

Developing applications involves juggling several moving pieces like front-ends, back-ends, and databases. But developing a decentralized application on a blockchain adds a few more elements...

Continue reading
How to create your own DAO with Aragon
Published: Aug 8, 2021
Updated: Sep 9, 2022

Blockchain provides us with the power of decentralization. Decentralization means the transfer of power to users/members rather than having a single centralized authority governing everything;...

Continue reading
How to connect to Ethereum using PHP
Published: Jun 11, 2021
Updated: Sep 9, 2022

PHP is a very popular choice among developers and has a vast community due to its long presence in web development. In this guide, we’ll cover how to connect to Ethereum with PHP using the

Continue reading
How to use Subspace with QuickNode
Published: Sep 8, 2020
Updated: Sep 9, 2022

In this guide, we'll understand a bit about reactive development and how to use Subspace with QuickNode.JavaScript is the programming language behind most of the internet apps and...

Continue reading