Hello!

© 2024 Kishan Kumar. All rights reserved.

What is Bitcoin?

Bitcoin is a distributed, peer-to-peer system; Bitcoins are created through a process called mining, which involves competing to find solutions to a mathematical problem while processing bitcoin transactions.

May 20, 2023

Hero

Bitcoin is a distributed, peer-to-peer system.

Bitcoins are created through a process called mining, which involves competing to find solutions to a mathematical problem while processing bitcoin transactions. What is that mathematical problem?

Participants or miners, who use the bitcoin stack to run the bitcoin network on their machine, use their computer’s processing power to verify and record transactions. Every 10 minutes, on average, a bitcoin miner is able to validate the transaction of the past 10 minutes and is rewarded with brand new bitcoin. How is this helpful? This mining thing decentralizes the currency-issuance and clearing functions of a central bank and replaces the need for any central bank (RBI). No single authority has the power to print money in any way they wish.

So, what would happen if we mined all the bitcoins? How will miners get incentivized to keep running their node? The miners will be incentivized with the fees alone. The process of mining bitcoins involves halving the block reward approximately every four years. Based on this information, it is estimated that the last bitcoin will be mined around the year 2140.

Bitcoin represents the culmination of decades of research in cryptography and distributed systems and includes four key innovations brought together in a unique and powerful combination. Bitcoin consists of:

  1. A decentralized Peer-to-peer network (the bitcoin protocol)
  2. A public transaction ledger (the blockchain)
  3. A set of rules for independent transaction validation and currency issuance (consensus rules)
  4. A mechanism for reaching global decentralized consensus on the valid blockchain (Proof-Of-Work algorithm)

The key innovation was to use a distributed computation system (called Proof-Of-Work) to conduct a global “election” every 10 minutes, allowing the decentralized network to arrive at consensus about the state of transactions.

Bitcoin Wallet

A bitcoin wallet is the most common user interface to the bitcoin system, just like a web browser is the most common user interface for the HTTP protocol.

  1. Full-node client: It stores the entire history of bitcoin transactions, manages user’s wallets, and can initiate transactions directly on the bitcoin network. (desktop full client)
  2. Lightweight client: also known as simple-payment-verification (SPV) client connects to bitcoin full nodes for access to the bitcoin transaction information, but stores the user wallet locally and independently creates, validates, and transmits transactions. (mobile lightweight wallet)
  3. Third-party API client: interacts with bitcoin network through a third-party APIs. (web third-party wallet)

Bitcoin addresses start with a 1 or 3. There is nothing sensitive, from a security perspective, about the bitcoin address. A wallet is simply a collection of addresses and the keys that unlock the funds within.Only once it has been associated with a transaction does it become part of the known addresses in the network.

Bitcoin transactions are irreversible
Now, you might ask yourself:
  • Who sets the bitcoin price?: The short answer is that the price is set by markets. The price of bitcoin in US dollars is calculated in each market based on the most recent trade of bitcoin and US dollars.
  • I am seeing Unconfirmed in my wallet, what does it mean?: Unconfirmed: the transaction has been propagated to the network but has not yet been recorded in the bitcoin transaction ledger, known as the blockchain. To be confirmed, a transaction must be included in a block and added to the blockchain, which happens every 10 minutes, on average. In traditional financial terms, this is known as clearing.
  • Where can I see my transactions? : In a blockchain explorer, is a web application that operates as a bitcoin search engine, in that it allows you to search for addresses, transactions, and blocks and see the relationships and flows between them.
Say, Alice received 0.15 bitcoin from Bob. That transaction created a bitcoin value locked by Alice’s key. When Alice decides to spend it, her key provides the signature that unlocks those previous transactions (that she received 0.15 BTC), thereby proving to the bitcoin network that she owns the funds.

Transactions move value from transaction input to transaction outputs. An input is a reference to a previous transaction’s output, showing where the value is coming from. A transaction output directs a specific value to a new owner’s bitcoin address and can include a change output, back to the original owner.

So, if Alice had 0.15 BTC and she wanted to send 0.05 BTC to Bob. The wallet will create one input transaction (from Alice, signed by Alice) and two output transactions.
  • Output0 To Bob (0.05 BTC).
  • Output1 To Herself (0.10 BTC - fees), change.

When Alice initiates a transaction to Bob, it contains a script that says something like, “This output is payable to whoever can present a signature from the key corresponding to Bob’s public address”. Because only Bob has the wallet with the keys corresponding to that address, only Bob’s wallet can present such a signature to redeem this output.

How does this transaction become a part of a new block and how the block is mined?
  • The transaction contains all the information necessary to process. The purpose of the bitcoin network is to propagate transactions and blocks to all participants.
  • Any bitcoin node that receives a valid transaction it has not seen before will immediately forward it to all other nodes to which it is connected, a propagation technique known as flooding.
  • If Bob’s wallet application is directly connected to Alice’s wallet application, Bob’s wallet application might be the first node to receive the transaction. However, even if Alice’s wallet sends the transaction through other nodes, it will reach Bob’s wallet within a few seconds.
  • Alice’s transaction is now propagated on the bitcoin network. It does not become part of the blockchain until it is verified and included in a block by a process called mining.
  • Transactions are bundled into blocks, which requires an enormous amount of computation to prove, but only a small amount to verify as proven.
A good way to describe mining is like a giant competitive game of sudoku that resets every time someone finds a solution and whose difficulty automatically adjusts so that it takes approximately 10 minutes to find a solution. If I show you a completed puzzle you can verify it quite quickly. However, if the puzzle has few squares filled and the rest are empty, it takes a lot of work to solve! The difficulty of the sudoku can be adjusted by changing its size (fewer rows and columns), but it can still be verified quite easily even if it is large.

The algorithm for Proof-Of-Work involves repeatedly hashing the header of the block and a random number with the SHA256 cryptographic algorithm until a solution matching a predetermined pattern emerges. The first miner to find a solution wins the round of competition and publishes that block into the blockchain.

  • New transactions flow into the network and are added to a temporary pool.
  • Miners construct new blocks by including these transactions and verifying their validity using the mining algorithm.
  • They start mining a new block as soon as they receive the previous one from the network, knowing they have lost the previous round.
  • Miners include a special transaction in their block that pays them the block reward and transaction fees

When Alice's transaction is validated by the mining software, it is included in a candidate block. Miners in the mining pool compute Proof-of-Work for the candidate block. If a miner finds the solution, they announce it to the network. Once the winning block is validated by other miners, they compete to generate the next block

By convention, any block with more than six confirmations is considered irrevocable, because it would require an immense amount of computation to invalidate and recalculate six blocks.

BIP stands for Bitcoin Improvement Proposal

1$ bitcoind -printtoconsole
2Bitcoin version v0.15.0
3InitParameterInteraction: parameter interaction: -
4whitelistforcerelay=1 -> setting -whitelistrelay=1
5Assuming ancestors of block
60000000000000000003b9ce759c2a087d52abc4266f8f4ebd6d768b89defa50a
7have valid signatures.
8Using the 'standard' SHA256 implementation
9Default data directory /home/ubuntu/.bitcoin
10Using data directory /lotsofspace/.bitcoin
11Using config file /home/ubuntu/.bitcoin/bitcoin.conf
12Using at most 125 automatic connections (1048576 file descriptors
13available)
14Using 16 MiB out of 32/2 requested for signature cache, able to
15store 524288 elements
16Using 16 MiB out of 32/2 requested for script execution cache,
17able to store 524288 elements
18Using 2 threads for script verification
19HTTP: creating work queue of depth 16
20No rpcpassword set - using random cookie authentication
21Generated RPC authentication cookie /lotsofspace/.bitcoin/.cookie
22HTTP: starting 4 worker threads
23init message: Verifying wallet(s)...
24Using BerkeleyDB version Berkeley DB 4.8.30: (April 9, 2010)
25Using wallet wallet.dat
26CDBEnv::Open: LogDir=/lotsofspace/.bitcoin/database
27ErrorFile=/lotsofspace/.bitcoin/db.log
28scheduler thread start
29Cache configuration:
30* Using 250.0MiB for block index database
31* Using 8.0MiB for chain state database
32* Using 1742.0MiB for in-memory UTXO set (plus up to 286.1MiB of
33unused mempool space)
34init message: Loading block index...
35Opening LevelDB in /lotsofspace/.bitcoin/blocks/index
36Opened LevelDB successfully
37[... more startup messages ...]
To run Bitcoin Core in the background as a process, start it with the daemon option, as
1bitcoind -daemon
To monitor the progress and runtime status of your bitcoin node, use the command
1bitcoin-cli getinfo.

A transaction ID is not authoritative until the transaction is confirmed. The absence of a transaction hash in the blockchain doesn't mean it wasn't processed. This is called transaction malleability, where transaction hashes can be modified before confirmation. Once confirmed, the txid becomes immutable and authoritative.

  • Bitcoin ownership is established through digital keys, addresses, and signatures.
  • Users create and store these keys in a wallet.
  • Transactions require valid signatures generated with secret keys, granting control to those with the key.
  • Keys are private-public pairs

Bitcoin uses elliptic curve multiplication as the basis for its cryptography. The public key is used to receive funds, and the private key is used to sign transactions to spend the funds. The private key (k), a random number, is used to generate a public key (K) through elliptic curve multiplication. The public key (K) is then transformed into a bitcoin address (A) using a cryptographic hash function.

Why use Asymmetric Cryptography (Public/Private Keys)?

It’s not used to encrypt the transactions. Rather, the useful property of asymmetric cryptography is the ability to generate digital signatures. private key + transaction fingerprint = digital signature. Anyone with access to the public key and the transaction fingerprint can use them to verify the signature.

How to generate a private key?

Most important step in generating keys is to find a secure source of entropy, or randomness. The private key can be any number between 1 and n - 1, where n is a constant (n = 1.158 * 1077, < 2256) defined as the order of the elliptic curve.

Avoid writing your own code or using a basic random number generator provided by a programming language. Instead, use a cryptographically secure pseudorandom number generator (CSPRNG) with a seed from a source of ample entropy

The size of bitcoin’s private key space, (2256) is an unfathomably large number. It is approximately 1077 in decimal. For comparison,the visible universe is estimated to contain 1080atoms.

11E99423A4ED27608A15A2616A2B0E9E52CED330AC530EDCC32C8FFC6A526AEDD

It is 256 bits, shown as 64 hexadecimal digits, each 4 bits.

How to generate a public key?

The public key (K) is obtained through irreversible elliptic curve multiplication: K = k * G. Here, k represents the private key, G is a constant generator point, and K is the resulting public key. The reverse operation, finding the private key (k) given the public key (K), known as "finding the discrete logarithm," is as challenging as a brute-force search through all possible values of k.

Elliptic Curve Cryptography

Bitcoin employs the
1secp256k1
elliptic curve defined by NIST, which is specified by a specific set of mathematical constants. This curve is utilized to generate an elliptic curve for cryptographic operations in Bitcoin.

y2 % p = (x3 + 7) % p

The % p (modulo prime number p) indicates that this curve is over a finite field of prime order p, also written as ኀp, where p = 2256 – 232 – 29 – 28 – 27 – 26 – 24 – 1, a very large prime number. The following is a point P with coordinates (x,y) that is a point on the secp256k1 curve:

1 P = (     55066263022277343669578718895168534326250603453777594175500187360389116729240,
2     32670510020758816978083085130507043184471273380659243275938904335757337482424
3 )

Implementing the elliptic curve multiplication, we take the private key k generated previously and multiply it with the generator point G to find the public key K:

K = 1E99423A4ED27608A15A2616A2B0E9E52CED330AC530EDCC32C8FFC6A526AEDD * G Public key K is defined as a point K = (x, y): K = (x, y), where x = F028892BAD7ED57D2FB57BF33081D5CFCF6F9ED3D3D7F159C2E2FFF579DC341A y = 07CF33DA18BD734C600B96A72BBC4749D5141C90EC8AC328AE52DDFE2E505BDB

Bitcoin Address

The bitcoin address is derived from the public key through the use of one-way cryptographic hashing. The algorithms used to make a bitcoin address from a public key are the Secure Hash Algorithm (SHA) and the RACE Integrity Primitives Evaluation Message Digest (RIPEMD), specifically SHA256 and RIPEMD160.
1 A = RIPEMD160(SHA256(K))

Where K is the public key and A is the resulting bitcoin address. Bitcoin addresses are almost always encoded as “Base58Check”, which uses 58 characters and a checksum to help human readability. Base59 is a text-based binary-encoding format developed for use in bitcoin and used in many other cryptocurrencies. Base58 is Base64 without 0 (zero), O (capital o), l (lower L), I (capital i), and the symbols +, and /.

1123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz

To convert data into a Base58Check format, we first add a prefix to the data, called the “version type”. For, e.g., in the case of bitcoin address the prefix is zero (0x00 in hex), whereas the prefix used when encoding a private key is 128 (0x80).

Now, we compute the “double-SHA” checksum.

checksum = SHA256(SHA256(prefix + data))

This gives us a 32-byte hash, we take only the first four bytes. These four bytes serve as the error-checking code, or checksum. The checksum is concatenated to the end. Thus, the result is composed of three items: a prefix, the data, and a checksum. Then it is encoded using the Base58 alphabet.

TypeVersion PrefixBase58 Result Prefix
Bitcoin Address0x001
Pay-to-Script-Hash Address0x053
Bitcoin Testnet Address0x6Fm or n
Private Key WIF0x805, K or L
BIP-32 Extended Public Key0x0488B21Expub
  • The WIF is used for import/export of keys between wallets and often used in QR code representation of private keys.
  • Compressed public keys were introduced in Bitcoin to minimize transaction size and conserve disk space on nodes storing the blockchain. Each public key, comprising (prefix, x, y-coordinate), occupies 520 bits. Considering the high volume of transactions per block or day, this significantly increases the blockchain's data burden.
  • Compressed public keys are gradually becoming the default across bitcoin clients.

BIP-38

BIP-38 proposes a common standard for encrypting private keys with a passphrase and encoding them with Base58Check so that they can be stored securely on backup media, transported securely between wallets, or kept in any other conditions where the key might be exposed. The standard for encryption uses the Advanced Encryption Standard (AES). The result of the BIP-38 encryption scheme is a Base58Check-encoded encrypted private key that begins with the prefix 6P.

Pay-to-Script Hash (P2SH) and Multisign Addresses

  • P2SH is like a special type of Bitcoin address that starts with the number "3" instead of "1". It's used when you want to send Bitcoin to a more complex script or set of conditions, rather than just a single public key or address. It helps make transactions more flexible and powerful by allowing you to use different conditions or rules for spending the Bitcoin.
  • Multisig addresses, on the other hand, involve multiple signatures to authorize a transaction. Instead of just one person having control over the Bitcoin in an address, you can set it up so that multiple people or entities need to provide their signatures to make a transaction valid. This adds an extra layer of security and can be useful for shared wallets or situations where you want to ensure multiple parties agree before funds are spent.

Wallet Technology

A common misconception about bitcoin is that bitcoin wallets contain bitcoin. In fact, the wallet contains only keys. The “Coins” are recorded in the blockchain on the bitcoin network. In a sense, a bitcoin wallet is a keychain.

The coins are stored on the blockchain in the form of transaction outputs (often noted as vout or txout)

There are two primary types of wallets, distinguished by whether the keys they contain are related to each other or not.

  • Nondeterministic wallet: each key is independently generated from a random number, also known as JBOK “Just a Bunch Of Keys”.
  • Deterministic wallet: keys are derived from a single master key, known as the seed. All the keys in this type of wallet are related to each other and can be generated again if one has the original seed. These wallets contain private keys that are all derived from a common seed, through the use of a one-way hash function.
  • HD Wallets (BIP-32/BIP-44): (seed) -> (master key) -> (child keys, k0, k1, k2...kn) -> (grandchild keys, k01, k02..., kn1,kn2...). It has a tree-like structure that can run to infinite depth.
  • Seeds and Mnemonic Codes (BIP-39): Use of mnemonics (army van defense carry etc) to export or recover the wallet. A user can export a mnemonic generated on one of these wallets and import it in another wallet, recovering all transactions, keys, and addresses.
Non-deterministic wallets are not recommended for anything beyond simple tests because they are difficult to back up and use. Instead, it is advised to use an industry-standard HD (hierarchical deterministic) wallet with a mnemonic seed for backup

How to generate the mnemonic words?

The wallet starts from a source of entropy, adds a checksum, and then maps the entropy to a word list:

  • Create a random sequence (entropy) of 128 or 256 bits.
  • Create a checksum of the random sequence by taking the first bits of its SHA246 hash.
  • Add the checksum to the end of the random sequence.
  • Divide the sequence into sections of 11 bits.
  • Map each 11-bit value to a word from the predefined dictionary of 2048 words.
  • The mnemonic code is the sequence of words.
BIP-39 English Word List (2048) Words
000 0000 0000abandon
........
000 0011 0000army
........
111 1111 1111zoo

Mnemonic words, typically 12 to 24 in length, represent entropy ranging from 128 to 256 bits. This entropy is utilized to generate a 512-bit seed using the key-stretching function PBKDF2. The resulting seed is then employed to construct a deterministic wallet and derive its keys.

The set of possible wallets is so large (2512) that there is no practical possibility of brute-forcing or accidentally guessing one that is in use.

What is an extended key and how to use it?

  • Extended keys in Bitcoin are hierarchical deterministic (HD) keys that allow for the generation of multiple child keys from a single root key, enabling convenient key management and organization.
  • One can use extended keys on a web store. HD wallet offers a much better solution through the ability to derive public child keys without knowing the private keys. One can load an extended public key (xpub) on their website which can be used to derive a unique address for every customer order.
-----> To Bitcoin Transactions
.   .   .

The 0xkishan Newsletter

Subscribe to the newsletter to learn more about the decentralized web, AI and technology.

Comments on this article

Please be respectful!

© 2024 Kishan Kumar. All rights reserved.