Money, Blockchain and Bitcoin

neerajneeraj
32 min read

What is money?

Money serves three fundamental functions:

  • medium of exchange - to trade goods and services efficiently

  • store of value - preserve purchasing power over time

  • unit of account - provide a standard measure for pricing and calculation

At its core, money is a social construct, built on collective trust and consensus. When we talk about money, we think about the paper form of currency (fiat currency - more on that later) we use today, but even the non-fiat currencies like gold derive their value from societal belief. We consider gold valuable primarily because it is scarce.

Various forms of money

Over centuries, different societies have used various forms of money, adapting to their needs and available resources.

Non-metal money

One of the earliest forms of money was commodity money, where objects with intrinsic value were used for trade.

  • Salt bars in Ethiopia - Salt was an essential resource, and since it was mined and limited in supply, it became a form of money.

  • Cowrie shells in West Africa - Europeans discovered that cowrie shells were widely accepted as currency in Africa. They later exploited this by introducing large quantities, debasing the currency, and using economic manipulation to facilitate the transatlantic slave trade, a practice that played a role in the triangle slave trade.

Metal money

As civilizations advanced, metals started gaining prominence as a form of money due to their durability and scarcity.

  • Bronze in Rome

  • Bronze Spades in China

  • Copper Plate in Sweden

Minted money

Around 2,500 years ago, societies moved toward minted money, where official sector (governments and rulers) began stamping and placing official emblems on scarce resource (metals) to standardize their use.

  • Lydian Coins (one of the earliest known coins)

  • Bronze Yuan in China

  • Silver Dekadrachm in Greece

  • Gold Aureus in Rome

Paper money

While metal coins were effective, they were heavy and inconvenient to carry in large quantities. This led to the introduction of paper money.

  • Promissory Notes in China: In ancient China, around 700 years ago, merchants and governments used warehouse receipts, which represented stored commodities like grain or gold. These receipts could be exchanged instead of carrying the actual goods.

  • Five-Pound Notes in England: The goldsmiths of London, acting as early bankers in the late 17th and early 18th centuries, began accepting gold deposits and issuing paper receipts in return. These receipts evolved into banknotes.

Before centralized banking, private banks in the US, Canada, Australia, England issued their own currency, leading to a decentralized yet fragmented financial system.

Ledgers

A ledger is a way to record economic activity and financial relationships. It is one of the most fundamental tools for a society to keep track of various economic transactions, both amongst individuals and between entities.

Research suggests that some of the very first methods of writing were not developed for communication or storytelling, but rather for recording numbers and maintaining ledgers.

Early Forms of Ledgers

  • Tally Sticks in England - Wooden sticks used to record debts and transactions.

  • Rai Stones in Yap Island, Micronesia: Massive limestone discs were used as a ledger rather than a medium of exchange because they were too heavy to be moved easily.

    • They were quarried from an island 200 km away, making them scarce and valuable.

    • In the late 19th century, a European sailor discovered this system and debased the currency by quarrying new stones from other island and within a few years, the entire economic system collapsed.

Types of Ledgers

Ledgers can be categorized based on how they store and structure financial information.

  • Transaction vs. Balance Ledgers:

    • Transaction ledger - records individual transactions as they occur.

    • Balance ledger - keeps track of overall balances without listing each individual transaction.

  • General vs. Sub-Ledgers:

    • General and sub-ledgers are hierarchical and form the heart of banking and financial systems.

    • Example: Central banks maintain the general ledger, which records the overall financial state and the commercial banks manage sub-ledgers, which track customer-level transactions.

  • Single-Entry vs. Double-Entry Accounting:

    • Single-entry accounting - lists transactions one below the other (but in reality, credits and debits often happen at different times).

    • Double-entry accounting - records transactions in two places - when money is added on one side, it is deducted from another. This ensures balance between assets and liabilities.

      • This system is linked to the Renaissance and played a role in Europe emerging from the Dark Ages and to the birth of capitalism.

      • A classic riddle in accounting :
        Three men go into a hotel. The man behind the desk says a room costs $30, so each man pays $10 and they go to their room.

        Later, the hotel clerk realizes the room was only $25, so he sends the bellboy with $5 to return to the men. On the way, the bellboy realizes he can’t evenly split $5 between three people, so he gives each man $1 back and keeps $2 for himself.

        Now, each man effectively paid $9 for the room, for a total of $27. The bellboy kept $2, which adds up to $29. Where is the missing dollar?

Payment systems

A payment system is nothing but a method to amend and record changes in ledgers of money.

For example, when you buy a cup of coffee:

  • The cafe’s ledger goes up because they receive money.

  • Your ledger goes down because you spend money.

Fiat currency

Fiat currency is different from traditional paper notes that were once backed by gold or other assets.

Off the Gold Standard

  • 1930s (Great Depression) – Governments restricted the ability to redeem paper money for gold.

  • 1970s – The world fully moved off the gold standard, meaning money was no longer directly tied to a scarce resource.

Despite this, fiat currency still holds value due to social and economic consensus, just like gold or any other non-fiat currency and you may wonder why..

Key Characteristics of Fiat Money

  • Legal Tender:

    • It must be accepted for all debts, both public and private.

    • Example: If you establish a debt at a cafe (when they have produced something for you and you have to pay them), they are legally required to accept fiat money as payment (but they can reject it before establishing the debt).

  • Liability of a Central Bank:

    • When you transfer money, the central bank is liable to move/update its ledgers accordingly.

    • The central bank also has a social responsibility to ensure the stability of money itself.

  • Accepted for Taxes:

    • Governments (which are separate from central banks) accept fiat currency as payment for taxes.
  • Relies on a System of Ledgers:

    • Various financial institutions integrate and maintain these ledgers.

Evolution of money

Good money

For a currency to function effectively, it should meet several criteria:

  • Durable – not degrade or wear out easily

  • Portable – easy to carry and transfer

  • Divisible – possible to divide into smaller units

  • Acceptable – widely accepted as a medium of exchange

  • Stable – value should not fluctuate drastically

  • Fungible – each unit should be interchangeable with another of the same value.

    • Example: Crawfurd vs. Royal Bank of Scotland (1748) – A case involving bearer instruments (documents that entitle the holder to money).

You can compare Bitcoin against these properties later.

Good ledger

A strong financial ledger should have the following properties:

  • Timestamped – transactions should be recorded with an accurate time reference

  • Ownership – should clearly track who owns what

  • Accuracy – recorded information must be correct

  • Immutable – once recorded, data should not be alterable or erasable

Problems with Traditional Financial Systems

  • Centralized Trust

    • Traditional financial systems rely heavily on centralized intermediaries like banks and governments to facilitate and verify transactions.

    • This means that individuals must trust these institutions to manage money and transactions fairly.

  • Closed Ledgers

    • Financial institutions operate on closed ledgers, meaning their transaction records are not transparent to the public.

    • This lack of transparency allows banks and governments to bail out failing entities or manipulate financial systems without broader accountability.

  • 2008 Financial Crisis

    • The 2008 crisis was a result of reckless financial practices. Banks had given out loans to people who couldn’t afford them and then sold these risky loans to investors and other banks, promising high returns.

    • When the system collapsed, governments bailed out these institutions, while the public bore the consequences.


Blockchain & Bitcoin

Solution - Decentralization

  • Moving Value Without an Intermediary

    • Blockchain enables transactions to occur without needing a central authority.

    • Instead of relying on banks, it uses an open, immutable, and distributed ledger where every transaction is publicly recorded.

      • Open - anyone can see the transactions

      • Immutable - no one can alter the transactions later

      • Distributed - not controlled by a central authority

  • Decentralized Trust

    • Transactions are verified and recorded on a distributed ledger maintained by a network of independent participants.

    • This removes the need to trust a single entity.

  • Consensus Mechanism

    • Instead of trusting banks or governments, blockchain operates on consensus - meaning the majority of network participants must agree on the validity of transactions.

    • The trust is moved to the network participants to maintain the correct ledger and not to approve fraudulent transactions.

Early solutions and failures

The idea of digital money and using cryptography to move value without intermediaries existed long before Bitcoin.

  • eCash - David Chaum (1983)

    • Aimed to enable anonymous and secure transactions. It relied on blind signatures to maintain privacy, preventing banks from tracking transactions.

    • Why it failed - depended on a central authority to issue the currency.

  • Hashcash - Adam Back (1997)

    • Designed to combat email spam and denial-of-service (DoS) attacks by attaching a computational cost/effort (proof-of-work) to sending an email because legitimate senders could afford the cost, but spammers could not.

    • Why it failed - lacked a built-in incentive system to encourage participation.

  • b-money - Wei Dai (1998)

    • Outlined a protocol for a distributed and anonymous digital currency. It introduced concepts like proof-of-work (PoW) and a distributed ledger to track balances.

    • Why it failed - remained a theoretical concept with no practical implementation or further development.

  • Bit Gold - Nick Szabo (1998)

    • Attempted to create a decentralized digital currency that used proof-of-work (PoW) to generate cryptographic puzzle solutions that were linked together to form a chain of blocks, each containing a hash of the previous block.

    • Why it failed - struggled with the double-spending problem and lacked a reliable way to achieve consensus without a central authority.

Summary of the failed attempts:

  • Lack of merchant adoption

  • Reliance on centralization

  • Double-spending problem

  • Consensus mechanism

Novelty of Satoshi’s work and Characteristics of Bitcoin

Satoshi’s breakthrough wasn’t exactly in inventing entirely new concepts, but in combining existing ideas from finance, cryptography, and blockchain to create a practical working system with incentives to participate in the network.

  • Decentralized consensus through Proof-of-Work (PoW)

    • While proof-of-work was used in Hashcash, Satoshi combined it with a distributed ledger to create a decentralized system.

    • This solved the double-spending problem by making it computationally expensive and difficult to alter past transactions.

  • Chain of blocks with transactions

    • Bitcoin’s blockchain is a linked series of transaction blocks, each secured by cryptographic hashes.

    • While the term “blockchain” wasn’t explicitly used in the Bitcoin whitepaper, the concept of a chronologically ordered, tamper-resistant ledger is at its core. Satoshi referred to it as a "timestamp server" that records transactions.

  • Decentralized Trust

    • Multiple network participants verify and agree on transactions (consensus).

    • Ensuring transactions are valid without a central intermediary using cryptographic proofs

    • Anyone can inspect the ledger to verify transactions (transparency).

  • Incentive mechanism through Bitcoin mining

    • Bitcoin introduced an economic system where miners are rewarded with newly minted bitcoins and transaction fees for validating, adding blocks to the chain and securing the network.

    • This ensures participation and decentralization.

  • Fixed Supply – A Scarce Digital Asset

    • Bitcoin has a hard cap of 21 million coins, making it deflationary like gold. This is in stark contrast to fiat currencies, where central banks can print more money, leading to inflation.

    • Example: During COVID-19, governments introduced massive amounts of new money through quantitative easing (QE), increasing the money supply by nearly 40%. This widened the wealth inequality gap as asset prices surged while wages lagged behind. Inflation itself isn’t always bad, but where do we draw the line?

  • Pseudonymity

    • Bitcoin transactions are tied to cryptographic addresses rather than real-world identities.

    • This provides a level of privacy while still allowing transaction histories to be publicly visible and traceable.

  • Open-Source and Permissionless Nature

    • The Bitcoin code is publicly available, allowing anyone to audit, contribute, or propose improvements (Bitcoin Improvement Proposals – BIPs).

    • Anyone can participate in the network, whether as a user, miner, or developer. No central authority controls access or decision-making.


Implementation details of Bitcoin

Wallets

A Bitcoin wallet is responsible for creating and storing key pairs. Unlike traditional bank accounts, a Bitcoin wallet does not store a balance or an account linked to an identity. Instead, it stores cryptographic key pairs, which determine what funds can be spent.

  • Key pairs

    • Each wallet generates key pairs using the Elliptic Curve Digital Signature Algorithm (ECDSA) with the secp256k1 curve.

    • The public key is used to receive funds, while the private key is required to sign transactions and prove ownership.

  • What does it mean when you own 1 BTC?

    • It means you have a private key that can authorize spending the Bitcoin sent to its corresponding public key.

    • Without the private key, ownership is meaningless since Bitcoin is just an entry in a distributed ledger that can only be updated through cryptographic signatures.

  • JBOK (Just a Bunch Of Keys) wallets

    • Early Bitcoin wallets used a simple structure called JBOK. In these wallets, each Bitcoin address was generated independently and stored without any structured relationship.

    • The downside was that if a user lost their wallet file, there was no way to regenerate the lost keys.

  • Seed Phrases and HD Wallets

    • To solve the issue of key management, Hierarchical Deterministic (HD) wallets were introduced. Highly Deterministic means you get the same output for the same input.

    • Instead of storing a random collection of keys, an HD wallet generates all its key pairs from a single seed phrase - a sequence of 12 or 24 words.

    • Example seed phrase:"accept now gone garment here backward donkey bridge affair money delay squirrel."

HD Wallet Structure

  • HD wallets generate keys in a tree-like hierarchy, where each private key can derive multiple child keys.

  • This allows users to back up their entire wallet by saving just the seed phrase. If the wallet is lost or damaged, all addresses and funds can be restored from the seed.

  • Each key in an HD wallet follows a derivation path, typically written in the format: m/44'/0'/0'/0/*

    • m → Master node (the root of the wallet)

    • 44' → BIP-44 standard (used for multi-account hierarchy)

    • 0' → Coin type (0 for Bitcoin)

    • 0' → Account number

    • 0/* → Change or receiving addresses

  • This structure makes it easy to move to a new wallet. As long as the user has their seed phrase, they can restore their wallet in any compatible Bitcoin wallet software.

Bitcoin Address

A Bitcoin address is not the same as a public key. When receiving Bitcoin, you don’t share the raw public key directly. Instead, a Bitcoin address is derived from the public key through cryptographic hashing.

  • Why Hash the Public Key?

    • It is computationally infeasible to derive a private key from a public key using today’s technology (it is mathematically possible though).

    • Quantum computers could use Shor’s algorithm to break Bitcoin’s elliptic curve cryptography (ECC) and recover private keys from public keys. However, it is harder to crack a hash. Quantum computers could use Grover’s algorithm, but that would only reduce the time taken to half, which is still large.

    • The public key is never revealed until a transaction is made. This means that, in a post-quantum world, Bitcoin remains safe until you want to spend the coins.

  • Address collision

    • Bitcoin addresses are 160-bit hashes, meaning there are 2¹⁶⁰ possible addresses. Theoretical probability of an address collision (two people generating the same address), according to birthday paradox theory, becomes significant after roughly 2⁸⁰ addresses.

    • Right now, there are fewer than 1.4 billion Bitcoin addresses in existence, which is an astronomically small fraction of the total space.

  • P2PKH (Pay-to-PubKey-Hash)

    • This is the original Bitcoin address format. The recipient's hashed public key is stored in the transaction.

    • To spend the Bitcoin, the recipient must provide the original public key and a valid signature proving ownership of the private key.

  • Checksum

    • To detect errors when typing or copying an address. This helps prevent accidental loss of funds due to mistyped addresses.

    • last byte of the hash…

  • Base58 encoding

    • It is a modified version of Base64 that removes visually similar characters: 0 (zero), O (uppercase o), l (lowercase L), I (uppercase i), +, and /.

Transactions

A Bitcoin transaction consists of inputs and outputs. Each input references a previous output, and each transaction creates a new output.

  • When Receiving:

    • The receiver provides their Bitcoin address. The sender then creates an output that includes the amount being sent and a locking script.

    • This script contains instructions that allow anyone to spend the output if they can prove they control the private key corresponding to the receiver’s hashed public key.

    • Legacy script: Pay-to-PubKey-Hash (P2PKH) script

  • When Sending:

    • To send Bitcoin, a new input is created that references a previous transaction output and a signature script (unlocking script) is included.

    • This script contains a signature and the public key, which satisfy the conditions set by the previous output’s public key script.

    • A new output is created in the same way as before, specifying the recipient’s address and amount. If there is extra Bitcoin left after the transaction, the change is sent back to the sender as a new output.

    • Signing scripts can be customized to support various spending conditions, such as multi-signature transactions or time-locked transactions.

UTXO set

As we saw earlier, Bitcoin does not use accounts and balances like traditional banking systems. Instead, it operates using Unspent Transaction Outputs (UTXOs).

  • This transaction ledger is the state of the blockchain. When a transaction is created, inputs are referenced from the ledger and removed once they are spent. New outputs are then added to the ledger as unspent outputs.

  • While it may seem like Bitcoin moves from wallet to wallet, what actually happens is that Bitcoin moves from one transaction to another.

  • Zero-sum transactions

    • When outputs are added to the ledger, the inputs that transaction referenced are removed.

    • This prevents double spending (same Bitcoin being used in multiple transactions).

  • Transaction fees

    • The total output of a transaction cannot be greater than the total input.

    • However, if the inputs are greater than the outputs, the difference is taken as a transaction fee and given to miners as an incentive.

  • Key-value pairs

    • Outputs are stored as key-value pairs in RAM of the miner’s computer/ASIC for quick access.

    • The key consists of the transaction ID and output index, while the value contains the amount and the locking script (public key script).

    • Databases like LevelDB or RocksDB are used for storage.

  • Bitcoin amounts are measured in satoshis, the smallest unit of Bitcoin. 1 BTC = 100,000,000 satoshis.

  • Wallets maintain a local UTXO set that keeps track of spendable outputs for the addresses they control.

Creating a new transaction

  • A transaction can have multiple inputs, each coming from previous unspent outputs.

  • If the inputs add up to more than the amount being sent, the remaining Bitcoin is returned to the sender as change.

  • Each input spends a previous output, effectively removing it from the UTXO set.

  • The signature script (unlocking script) provides the signature and the full public key (does not contain any logic) to satisfy the conditions set in the locking script of the inputs being referenced in the transaction.

  • A new P2PKH output script (locking script) is generated, with the public key hash of the receiver, ensuring that only the person who controls the corresponding private key can spend the Bitcoin in the future.

Example of a P2PKH transaction:

Validating a transaction

Bitcoin uses a stack-based scripting language to validate transactions.

  • It is stateless, meaning that once a transaction is added to the blockchain, it cannot be undone or modified.

  • It is also Turing-incomplete, meaning it lacks features like loops or jumps (e.g., goto statements). This limitation prevents complex operations but ensures security and predictability.

P2PKH script validation:

  • Equal Verify: Ensures that the provided public key hash matches the one in the script, but this alone is not enough because anyone can provide the correct public key.

  • Check Sig: Uses Elliptic Curve Digital Signature Algorithm (ECDSA) to verify that the provided signature was created using the correct private key, ensuring that only the rightful owner can spend the Bitcoin.

Creating a block

Mempool

The mempool (memory pool) is a temporary storage area where unconfirmed transactions wait before being included in a block.

  • It acts as a waiting area for transactions that have been broadcast but are not yet confirmed. Transactions in the mempool are stored in RAM, making access fast for miners and nodes.

  • Before a node adds a transaction to its mempool, it first checks whether:

    • The transaction inputs are valid and unspent.

    • The signatures are correct.

    • The transaction does not attempt double spending.

  • If a transaction is valid, the node adds it to its mempool and relays it to other connected nodes.

  • Sometimes, different miners may pick conflicting transactions, meaning two transactions try to spend the same input. If one of these transactions is successfully included in a block and added to the blockchain, the other transaction is automatically removed from the mempool of the other node (blocks added to the chain are relayed to other nodes).

  • When the mempool becomes too large (filled with too many transactions), miners can choose to prioritize transactions with higher fees.

Candidate block

A candidate block is a block that a miner is attempting to mine. It is not yet part of the blockchain but is being worked on. In the process of creating a block, the miners does the following things:

  1. Pick transactions from the mempool, usually prioritizing those with the highest transaction fees to maximize their rewards.

  2. Create a coinbase transaction which pays the miner a reward for successfully mining the block.

  3. Generate the block header, which includes essential information about the block.

Always remember that when you send a transaction, it does not go to just one miner. Instead, many miners across the network receive it and are independently competing to include it in a block.

This means that multiple miners are working on different candidate blocks, but only one will eventually win and have their block added to the blockchain.

Blocks

Once a miner successfully mines a candidate block, it becomes a valid block and is added to the blockchain.

A block has a block header, number of transactions and the transactions.

  • Block header - Version, Previous block hash, Merkle root, Target/bits, Nonce, Time

  • Transactions - Coinbase transaction, Regular transactions

Block header

Version

  • The version field was originally used to indicate changes to the block structure. It is now primarily used by miners as a way to vote for software upgrades on the Bitcoin network.

Previous block hash

  • Every block references the hash of the previous block in the chain. This is a double-SHA256 hash of the previous block's header and acts as the "tip" of the blockchain at that point in time.

  • The chain of hashes forms an immutable blockchain, making it extremely difficult for anyone to modify past transactions. If someone tried to change an earlier block, all subsequent block hashes would also change, breaking the chain.

  • Miners always aim to build on the longest chain otherwise their mining effort would be wasted if their mined block becomes part of a stale chain.

  • The genesis block (the first block in Bitcoin) has all zeros in this field since there was no previous block.

Merkle root

  • The Merkle root is a hash that represents all transactions in a block.

  • It is created by hashing transactions together in pairs, forming a tree-like structure, until a single hash remains. If there is an odd number of transactions, the last one is hashed with itself.

  • The Merkle root is stored in the block header, effectively “committing” all transactions in the block to that header.

  • This ensures tamper resistance. If even a single transaction in a block is modified, the Merkle root changes, which in turn changes the block header hash and since each block references the hash of the previous one, any change to an earlier block would break the chain.

Target/bits

  • The target is the threshold below which a block's hash must fall for it to be considered valid.

  • Miners attempt to find a valid block hash by adjusting a value called the nonce—this process is known as Proof of Work.

  • Demo: https://andersbrownworth.com/blockchain/tokens

  • A smaller target (more leading zeros in the hash) makes mining harder. Larger target makes mining easier.

  • Mining difficulty adjustment and its purpose:

    • If blocks are being mined too quickly, the difficulty increases by making the target lower. If blocks are being mined too slowly, the difficulty decreases by raising the target.

    • The Bitcoin network aims to produce one block every ~10 minutes. This adjustment occurs every 2016 blocks (approx. every two weeks).

    • This ensures that blocks propagate across the network before a new block is found. if blocks are being mined faster than they can be broadcast across the network, it will result in miners regularly working on top of "old" blocks in the blockchain (because they haven't had a chance to receive the latest blocks yet).

    • Adapts to changing miner participation - if more miners join the network, difficulty increases (lowering target) to maintain the 10-minute block time.

    • This also maintains a predictable supply of new bitcoins.

  • Target synchronization

    • Since each node on the network operates independently, there is no central authority to determine the current target value.

    • However, because nodes always adopt the longest chain of blocks as their blockchain and have the same copy as others, they will each calculate the same target.

    • When a new node joins the network, it performs IBD (Initial Block Download), reconstructing and verifying the blockchain from the genesis block. By receiving and verifying the same blocks as others, it will arrive at the same current difficulty target as the rest of the network when it reaches the tip of the blockchain.

Nonce

  • The nonce (number used once) is a random value that miners modify in an attempt to find a valid block hash.

  • Since hash functions are unpredictable, there is no skill involved. Miners must brute-force different nonce values until they find a hash below the target before other miners.

  • The nonce is only 4 bytes (32 bits), meaning it can take a maximum of 4.3 billion attempts before it is exhausted and this happens quickly.

  • Once the nonce space is exhausted, miners reconstruct the block slightly by doing any of the below and the cycle continues until a valid hash is found.

    • Adding more transactions

    • Modifying the timestamp or version number

    • Tweaking the scriptSig in the coinbase transaction, which changes that transaction’s hash and that alters the Merkle root and allows another 4.3 billion attempts.

Time

  • The timestamp in the block header represents the approximate time the block was created and does not indicate block order.

  • The network allows timestamps to drift by -1 to +2 hours relative to the network-adjusted time.

  • The timestamp is important for:

    • Target recalculation – Used to adjust difficulty every 2016 blocks based on whether blocks are being mined too fast or too slow.

    • Transaction lock time – Some transactions specify a future time before which they cannot be included in a block.

Block transactions

In Bitcoin, transactions within a block are stored in raw bytes inside files like blkxxxxx.dat, located in the blocks directory of a full node.

Coinbase transaction

  • This is a special type of transaction that is always the first transaction in every block and has no inputs, unlike regular transactions, because it is newly created money.

  • This transaction allows the miner to claim the block reward.

  • Structure

    • Since there are no previous outputs to spend, the input field is blank and since there is no input to unlock, miners can use the signature script (scriptSig) to include random data, messages, or an extra nonce.

    • Example: In Bitcoin's genesis block, Satoshi embedded a message in the coinbase transaction about the instability of the traditional financial system:

      "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks"

  • Transaction maturity

    • The block reward from the coinbase transaction cannot be spent until the block becomes 100 blocks deep (roughly 16-17 hours)

    • This rule prevents miners from quickly mining blocks and collecting rewards before other nodes confirm and accept the block in their own copy of the blockchain.

Regular transactions

  • Regular transactions in a block are selected from the mempool and are typically prioritized by high transaction fees.

  • A transaction cannot be added unless all its inputs have already been included. In other words, ancestors in the mempool should be included before adding its children.

  • A block can just have the coinbase transaction and not have any regular transaction.

  • The total size of all transactions cannot exceed the block size limit.

  • The first regular transaction in the Bitcoin blockchain occurred at block 170.

Block reward

  • The block reward is the incentive for miners to add new blocks to the Bitcoin blockchain.

  • Without this reward, there would be no reason for miners to dedicate their resources to securing the network and validating transactions.

  • Block reward contains the block subsidy (newly minted Bitcoin) + the transaction fees (from all included transactions in the block).

  • Circulation

    • Unlike traditional currencies, which are issued by central banks, Bitcoin has no central authority controlling its supply.

    • This reward is the only way new bitcoins are introduced into circulation.

  • 51% attacks

    • This reward also plays a role in discouraging 51% attacks (if a miner or group of miners controlled more than 50% of the network’s computing power, they could potentially reverse transactions).

    • However, the system is designed so that it is more profitable for miners to continue mining honestly and collecting block rewards rather than attempting an attack.

  • Empty blocks

    • it takes time to calculate the optimal combination of transactions that maximize transaction fees.

    • Instead of sitting idle while determining which transactions to include, miners start mining an empty block immediately. Occasionally, they get lucky and find a valid block before including any transactions.

  • Unclaimed rewards

    • In block 501726, the miner was lucky enough to mine the block before including any transactions but forgot to send the block reward of 12.5 BTC to themselves in the coinbase transaction and now they are lost forever.
  • Transaction fees

    • The first block to include transaction fees as part of the block reward was 2817. While it was unnecessary for transactions in that block to pay fees, it was the first recorded instance of a miner collecting fees in addition to the block subsidy.

    • Block 788695 was the first block where the transaction fees was greater than the block subsidy, highlighting decreasing block subsidies and increasing number of transactions.

Halving

  • Bitcoin started with a block subsidy of 50 BTC per block. Every 210,000 blocks (roughly every four years) the reward is halved. Currently, it stands at 3.125 BTC per block.

  • This halving mechanism ensures Bitcoin has a fixed supply, making it a deflationary currency.

  • At this rate, the block subsidy will continue halving until the year 2140, after which no new bitcoins will be issued which will bring the total Bitcoin in circulation to a maximum of 21 million Bitcoins.

  • At that point, the only incentive for miners will come from transaction fees rather than newly created bitcoins. However, after 2044, the subsidy becomes so small that it is largely insignificant.

  • Although the maximum supply is often stated as 21 million BTC, the actual number is slightly (2.31 million sats) lower because of how Bitcoin handles decimal precision when halving (check 9th-10th, 29th-30th halving cycles) and even lower if we consider the unclaimed subsidies and lost bitcoins.

P2P network

The Bitcoin network operates as a peer-to-peer (P2P) system where nodes communicate and validate transactions without relying on a central authority.

  • The Bitcoin node runs on TCP port 8333 by default.

  • A new node used the hardcoded DNS seeds (DNS servers run by trusted Bitcoin developers) to find peers and initiate connection. Once connected, the peers share the IPs and port numbers of other reliable peers on the network.

Operating modes

  • Full node (Bitcoin Core)

    • Maintains a full copy of the blockchain and validates the entire chain.

    • After the initial handshake with peers, it validates and relays new transactions and blocks.

    • Enforces all consensus rules and verifies all transactions and blocks.

    • Keeps a record of known peers in a database to connect directly to those peers on subsequent startups.

  • Lightweight Node (SPV - Simplified Payment Verification Wallets)

    • Stores only block headers (80 bytes per block), not full transactions.

    • Cannot independently validate transactions or enforce rules.

    • Can verify if a transaction exists with the help of full nodes.

  • Archival Node

    • Stores the full history of the blockchain.
  • Pruned Node

    • Deletes old data and keeps only recent blocks to save disk space

Miners vs Nodes

  • They need not be the same.

  • Miner - works to add transactions to the blockchain by Proof-of-Work.

  • Node - validates transactions and enforces rules.

  • However, it is easier for miners to run full nodes than to connect to full nodes to get the blockchain data.

Merkle Proofs

Lightweight (SPV) wallets are able to verify a transaction without the overhead of having to download and store the entire the blockchain because of Merkle proofs.

  • To verify if a transaction is valid, the SPV wallet needs to know if the hash of that transaction along with all the other transactions in that block make it up to the combined hash in the header.

  • The protocol could have just hashed all the TXIDs (Transactions ID - hash of the transaction) together. But later when the SPV wallet wants to check if a transaction is part of a block, it would need all the TXIDs that formed the combined hash to verify it.

  • Instead of hashing all TXIDs together at once, Bitcoin organizes them into a Merkle tree and adds the Merkle root hash in the block header. Because of this, the SPV wallets only need to know few branches along the path of the tree to check if a TXID was used to create the root hash and this is why light clients need not download the entire chain.

  • A node that the SPV wallet is connected to, could be malicious and could construct a valid block header with fraudulent transaction(s) and send to the wallet.

  • But it would take a lot of effort in mining for a full node to lie to an SPV wallet because wallets usually connect to several random full nodes.

  • This is the reason, it is recommended to at least wait for an hour (around 5-6 blocks deep) to consider a transaction final.

Consensus

Bitcoin achieves consensus in a decentralized way where nodes independently validate transactions and agree on a single version of the blockchain.

Chainwork

  • The chain with the most accumulated computational energy (chainwork), not necessarily the one with the most blocks, is considered the valid chain.

  • Chainwork is measured as the expected number of hashes required to produce the current chain.

$$\text{Expected Hashes for a block} = \frac{2^{256}}{\text{Target}} + 1$$

  • Example: Imagine a lottery with 100 tickets and 20 winning tickets. The probability of picking a winning ticket randomly = 20/100=0.2. On average, we need 1/0.2=5 tickets to pick before getting a winning ticket. In Bitcoin mining, instead of 100 possible numbers, there are 2^(256), and instead of 20 winning tickets, there are target number of valid hashes. We add 1 because we always perform at least one attempt, even in the best-case scenario.

Chain reorganizations

  • Temporary disagreements may arise when two miners mine a block at the same time or in a very short span. Some nodes will receive one block first, while others receive the competing block first due to the propagation speed of the network.

  • This results in a temporary fork, but as soon as a new block is added to one of the forks, the longer chain becomes the main chain. See the below image where 2 blocks might appear at the same depth but eventually the chain in black color became the main chain.

  • Transactions in the discarded block (stale block) go back into the mempool, if they were not in the competing block, and will be mined later in a future block.

  • If you try to spend the outputs from a transaction inside a stale block, nodes would reject your transaction because you are trying to spend bitcoins that do not exist in the valid chain. This is the reason to wait for a few blocks before considering the transaction valid.

Why miners always build on the longest chain?

  • If a miner builds on a shorter chain, they risk their mined block being orphaned and wasted. This ensures that all miners are economically incentivized to follow the main chain.

  • A miner can reject an incoming relay of block info from the network, mine new blocks, creating a fork and live in their own world because that fork would be rejected by the network, since it won’t have the most chainwork.

  • Nodes can be in disagreement at any given time, but adopting the longest available chain means that nodes will always eventually agree on the same view of the blockchain.

Hard fork vs Soft fork

  • Hard fork occurs when incompatible rule change creates a permanent split in the blockchain. Nodes running the old rules will reject blocks from nodes following the new rules. Example: Bitcoin Cash (BCH) forked from Bitcoin (BTC) in 2017.

  • Soft fork occurs when upgrades are backward-compatible, where old nodes still recognize new blocks as valid. Example: SegWit (Segregated Witness) in Bitcoin.

51% attack

  • A miner or group of miners controlling more than 50% of the network’s hash power/computational power could attempt to:

    • Build a new longest chain, excluding transactions or double-spending.

    • Reverse transactions, allowing them to spend the same Bitcoin twice.

  • If an attacker has more than 50% of the total hash power, they can mine blocks faster than the rest of the network combined and when their chain becomes longer, the honest nodes in the network will then switch to that chain, making it the new valid chain because it had highest chainwork.

  • If the malicious miner/group does not control more than 50% and tries to build a new long fork of the chain, they might get lucky to get their block mined and a couple of their blocks might make it to the chain and become the longest chain, but can’t keep up with the rest of the combined hash power, which only builds upon blocks with valid transactions.

  • The deeper a transaction is in the blockchain, the harder it becomes to rewrite history. There is an exponential decay in the probability of replacing a transaction, the deeper it makes it into the blockchain.

Is Bitcoin truly decentralized?

  • The below image shows the top mining pools and the number of blocks mined in the last 3 years.

  • While pools consist of many individual miners, pool operators ultimately decide which transactions get included in blocks.

  • If a few pools dominate (top 3 mining pools control nearly 60% of blocks mined), they could censor transactions or collude to attack the network.

  • The below image shows the probability of replacing the top blocks at different mining power levels.


DISCLAIMER:

I do not own the images in this post. They were taken from various sources, including learnmeabitcoin.com, hiro.so, Bitcoin developer docs, etc. This post was made with the intent to put out my notes that I created while studying about Blockchain and Bitcoin. Please reach out to me if you find inaccuracies.


0
Subscribe to my newsletter

Read articles from neeraj directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

neeraj
neeraj