How to Generate a New Bitcoin Address in JavaScript | QuickNode | The Blockchain Development Platform – Guides
Mục lục bài viết
How to Generate a New Bitcoin Address in JavaScript
4 min read
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.
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:
- Legacy (P2PKH): Legacy is the original bitcoin address; they all start with one. It is the most compatible and supported by wallets. Example:1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN2
- 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
- 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
- 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.
- 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:
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:
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.
CryptoCoinJS is a JavaScript library that helps you interface with different cryptocurrencies like Bitcoin, Litecoin, and Dogecoin.
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:
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
mkdir Bitcoin
cd Bitcoin
To install the library, type the following in your terminal/cmd:
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:
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:
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.
node address
It will give an output that is similar to this.
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 🙂