- Creating Bitcoin Wallets in JS
- Wallets Are Not Online
- 2²⁵⁶, but not quite
- Generating Public Keys
- Making Nuggets
- Generating Private Key WIF
- Checking our Work
- Conclusion
- How to Generate a Bitcoin Address — Step by Step
- Introduction
- Dependencies
- Cryptography Primer
- Public Key Cryptography
- Creating a Bitcoin Address
- Private Key Generation
- Public Key Generation
- Compressed Public Key
- Address Generation
- Pay-to-Script Hash
Creating Bitcoin Wallets in JS
In this series, we will implement the core protocols of Bitcoin in JavaScript. By the end of series, we will be able to run a connected network of nodes and send transactions across the network — just like Bitcoin!
To start, we’ll create a wallet. Bitcoin wallets are not stored in the blockchain. Rather, they are managed by each individual user and referenced in individual transactions. A wallet consists of the following parts, which are generated in the same order:
- Private key
- Public key
- Public key hash (PKH)
- Public address
- Private key WIF (wallet import format)
Wallets Are Not Online
An important concept to understand is that you do not need to be online to generate a Bitcoin wallet address. Because the methods to generate an address rely on math, there is no need to connect to a separate server, website or other service.
Let’s look at the code to generate a private key:
That’s it! You generated a Bitcoin private key! 🎉
Now, what is it? Well, you might have been able to tell that it is a 32-byte array in binary. Since there are 8 bits in a byte, that makes 256 bits.
If you want to know the probability of someone else generating the same private key as you, then it is 2²⁵⁶, which is an astronomically² large number.
2²⁵⁶, but not quite
Okay, there’s one catch that I didn’t explain. Not every private key like this is valid. Only private keys that are less than the following value (in hexadecimal) work with Bitcoin: 0xFFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFE BAAE DCE6 AF48 A03B BFD2 5E8C D036 4140 .
This is because Bitcoin uses elliptic curve cryptography (ECC) and can only accept private keys below that number. In case that wasn’t enough, the version of elliptic curve cryptography that Bitcoin uses is called secp256k1 , because, well, you know…
Our revised code now looks like this:
We use a while loop to keep generating private keys until we find one that is below that max amount. That shouldn’t be hard, since max is fairly close to 2²⁵⁶.
Generating Public Keys
Once we have a valid private key, we can use the elliptic library to create a public key for us. Elliptic curve cryptography is amazing — I can use my private key to create a signature and a random person can verify it, without knowing my private key. Pretty amazing!
Elliptic curve cryptography gets heavy in the math department, so I won’t delve too deep here. If you’re interested in learning more about how it works, I would recommend the following resources. Hint: it involves complex spatial geometry and absurdly large prime numbers.
Here’s how the author of “Mastering Bitcoin” sums up ECC:
Elliptic curve cryptography is a type of asymmetric or public key cryptography based on the discrete logarithm problem as expressed by addition and multiplication on the points of an elliptic curve.¹
Now we’ll make use of the elliptic JavaScript library to generate our public key:
Making Nuggets
John Oliver recently aired a clip of a man making an analogy for Bitcoin — that it is like trying to make a live chicken from a chicken nugget. While the analogy sounds ridiculous, it is correct — hashing is a one-way process that you cannot reverse.
While our current private and public key are enough to create digital signatures, Bitcoin takes security even further. Rather than sending money to someone’s public key and exposing that key, Bitcoin users send money to a hashed version of the public key. This can either be as a public key hash or a public address, both of which are acceptable. Let’s go over how to do both:
- To create a public key hash, we run the public key through both the SHA-256 hashing algorithm and the RIPEMD-160 hashing algorithm. It looks like this:
- To create a public address, there are more steps involved. We first add the prefix “00” to our publicKeyHash . Then we derive the SHA-256 hash of the extended public key hash. Then we derive the SHA-256 hash of that and store the first byte as a “checksum.” We add the checksum to the extended public key hash and encode it with base 58. Whew! I promise it will look more understandable in the code:
Generating Private Key WIF
WIF stands for “wallet import format.” It was a standard introduced to make it easier and more secure for users to migrate wallets from different services.
The process of generating a private key WIF is not very different from generating a public address. Here are the steps:
- We add a prefix to the private key. In this case it is “80” (in hexadecimal)
- We derive the SHA-256 hash of the extended private key.
- We derive the SHA-256 hash of that, and then save the first byte as the checksum.
- We add the checksum to the extended private key and encode it to base 58.
Checking our Work
Now we have our own Bitcoin wallet that we can use to make transactions. We can check our address in blockchain.info to see our balance. Notice how it is able to infer our public key hash (“Hash 160″) from our address.
There are some other tools to verify our work. At this site we can verify that we are generating the public address properly. At another we can verify that the private key WIF is being generated correctly.
It’s important to verify that your wallet code works correctly, because there are a number mistakes that can be made. One common one is to hash the ascii private key or public key, instead of the actual number, as seen in this Stack Overflow thread. This is why we use Buffer s to hash.
Conclusion
That’s all for creating Bitcoin wallets. There are other improvements not covered here that have been made over time, such as HD wallets, compressed keys, and passphrase-protected private keys.
Here are a few more links to learn more about Bitcoin wallet creation:
Happy coding! If you liked the article, please clap 👏.
¹ Antonopoulos, Andreas M.. Mastering Bitcoin: Programming the Open Blockchain (p. 60). O’Reilly Media. Kindle Edition.
² Literally. There are an estimated 2⁸⁰ atoms in the known universe — much smaller than the number of potential Bitcoin private keys.
Источник
How to Generate a Bitcoin Address — Step by Step
Here is a bash script that does what is outlined below: https://bit.ly/2MIgeOD
Introduction
This is a hands-on, technical guide about the generation of Bitcoin addresses including private and public keys, and the cryptography involved.
Learn more and join people in 22 countries around the world in my course on how to Become a Bitcoin + Blockchain Programmer.
This guide will walk you through all the steps to generate a Bitcoin address using the command line on a Mac. Similar steps should be possible on other operating systems using similar cryptographic tools. Lines starting with $ denote terminal commands, which you can type and run (without the $ of course).
Dependencies
- brew — Installation: https://brew.sh/
- pip — Installation: sudo easy_install pip
- libressl — Installation: brew install libressl
- base58 — Installation: pip install base58
Note: To do the contained openssl cli commands, I installed libressl in order for some of the elliptic curve commands to work as the current version of openssl cli on mac has a bug.
Cryptography Primer
Public Key Cryptography
Or asymmetric cryptography, is a type of cryptography that uses key pairs, each of which is unique. The pair of keys includes a public key and a private key. This is the type of cryptography that Bitcoin uses to control funds. A public key can be generated from a private key, but not vice-versa (computationally too difficult). Also, something encrypted with a private key can be decrypted with the public key, and vice-versa, hence they are asymmetric.
- Encryption: When a user has a public key, a message can be encrypted using a public key, which can only be read by the person with the private key. This also works in reverse.
- Digital Signatures: A user can, with their private key and a hash of some data, use a digital signature algorithm such as ECDSA, to calculate a digital signature. Then, another user can use the algorithm to verify that signature using the public key and the hash of the same data. If it passes, this proves a user did in fact submit a specific message, which has not been tampered with.
- Digital Fingerprint: Is a way to represent an arbitrarily large data set by computing the hash of it to generate a fingerprint of a standard size. This fingerprint would be so difficult to replicate without the same exact data, which can be assumed to have not been tampered with.
Private keys are what prove you can send Bitcoin that has been sent to you. It is like the password to your bank account. If you lose it or someone else gets a hold of it, you’re toast.
Public keys help people know how to send you Bitcoin.
Creating a Bitcoin Address
Private Key Generation
Private keys can be any 256 bit (32 byte) value from 0x1 to 0xFFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF BAAE DCE6 AF48 A03B BFD2 5E8C D036 4140 .¹
The total possible number of private keys is therefore 2²⁵⁶ or 1.16 x 10⁷⁷. Imagine the total number of atoms in your body, then imagine that each of those atoms is an earth. The total number of atoms on all of those earths is about 7 x 10⁷⁷.² There is virtually no chance that your random private key will ever be generated randomly or found by someone else.
A common (but not the most secure) way of creating a private key is to start with a seed, such as a group of words or passphrases picked at random. This seed is then passed through the SHA256 algorithm, which will always conveniently generate a 256 bit value. This is possible because every computer character is represented by an integer value (see ASCII and Unicode).
Note: SHA256 is a one-way, deterministic function meaning that it is easy to compute in one direction, but you cannot reverse it. In order to find a specific output, you have to try all the possible inputs until you get the desired output (brute forcing) and it will always produce the same output given the same input, respectively.
The seed can be used to generate the same private key if the same hashing algorithm is used in the future, so it is only necessary to save the seed.
This private key is in hexadecimal or base 16. Every 2 digits represents 8 bits or 1 byte. So, with 64 characters, there are 256 bits total.
Public Key Generation
Public keys are generated from the private keys in Bitcoin using elliptic curve ( secp256k1 ) multiplication using the formula K = k * G , where K is the public key, k is the private key, and G is a constant called the Generator Point⁴, which for secp256k1 is equal to:
It doesn’t seem to be known how this point was chosen by they designers of the curve. Also, this algorithm is a one-way algorithm, or a “trap door” function so that a private key cannot be derived from the public key. It is important to note that elliptic curve multiplication is not the same as scalar multiplication, though it does share similar properties.
To do this in the terminal from our private key earlier,
This public key contains a prefix 0x04 and the x and y coordinates on the elliptic curve secp256k1 , respectively.
Compressed Public Key
Most wallets and nodes implement compressed public key as a default format because it is half as big as an uncompressed key, saving blockchain space. To convert from an uncompressed public key to a compressed public key, you can omit the y value because the y value can be solved for using the equation of the elliptic curve: y² = x³ + 7. Since the equation solves for y², the right side of the equation could be either positive or negative. So, 0x02 is prepended for positive y values, and 0x03 is prepended for negative ones. If the last binary digit of the y coordinate is 0, then the number is even, which corresponds to positive. If it is 1, then it is negative. The compressed version of the public key becomes:
The prefix is 0x02 because the y coordinate ends in 0xa4 , which is even, therefore positive.
Address Generation
There are multiple Bitcoin address types, currently P2SH or pay-to-script hash is the default for most wallets. P2PKH was the predecessor and stands for Pay to Public Key Hash. Scripts give you more functionality, which is one reason why they are more popular. We’ll first generate a P2PKH original format address, followed by the now standard P2SH .
The public key from the previous output is hashed first using sha256 and then hashed using ripemd160 . This shortens the number of output bytes and ensures that in case there is some unforeseen relationship between elliptic curve and sha256, another unrelated hash function would significantly increase the difficulty of reversing the operation:
Note that since the input is a string, the xxd -r -p will convert the hex string into binary and then output it in hexdump style (ascii), which is what the openssl hashing functions expect as input.
Now that we have hashed the public key, we now perform base58check encoding. Base58check allows the hash to be displayed in a more compact way (using more letters of the alphabet) while avoiding characters that could be confused with each other such as 0 and O where a typo could result in your losing your funds. A checksum is applied to make sure the address was transmitted correctly without any data corruption such as mistyping the address.
Bitcoin P2PKH addresses begin with the version byte value 0x00 denoting the address type and end with a 4 byte checksum. First we prepend the version byte (prefix) to our public key hash and calculate and append the checksum before we encode it using base58 :
Note: -c denotes a checksum is to be applied. The checksum is calculated as checksum = SHA256(SHA256(prefix+data)) and only the first 4 bytes of the hash are appended to the end of the data.
The resulting value is a P2PKH address that can be used to receive Bitcoin: 16JrGhLx5bcBSA34kew9V6Mufa4aXhFe9X
Pay-to-Script Hash
The new default address type is a pay-to-script-hash, where instead of paying to a pubKey hash, it is a script hash. Bitcoin has a scripting language, you can read more about it here. Basically it allows for things like multiple signature requirements to send Bitcoin or a time delay before you are allowed to send funds, etc. A commonly used script is a P2WPKH (Pay to Witness Public Key Hash): OP_0 0x14
where the PubKey Hash is the RIPEMD160 of the SHA256 of the public key, as before, and 0x14 is the number of bytes in the PubKey Hash. So, to turn this script into an address, you simply apply BASE58CHECK to the RIPEMD160 of the SHA256 of the script OP_0 0x14
except you prepend 0x05 to the script hash instead of 0x00 to denote the address type is a P2SH address.
If you like the article, check out my course on how to Become a Bitcoin + Blockchain Programmer.
Источник