TeachMeBitcoin - The Free Interactive Bitcoin Encyclopedia
TeachMeBitcoin
The Free, Developer-Grade Bitcoin Encyclopedia
Master Bitcoin from first principles. Explore 106 highly detailed, cryptographic, and network-grade educational modules complete with step-by-step stack visualizations, code emulation, and LaTeX math typesetting.
How Bitcoin Works
Learn how Bitcoin works in this simple, beginner-friendly guide. Understand the blockchain, digital scarcity, and the fundamentals of decentralized money.
Getting Started: Wallets
What is a Bitcoin wallet and how does it work? Learn how wallets manage cryptographic public and private keys to let you send and receive bitcoin.
Explore Module Lessons
Getting Started: Exchanges
A beginner-friendly guide explaining what a cryptocurrency exchange is, how order books work, and how to safely buy your very first bitcoin.
Explore Module Lessons
- What is a Cryptocurrency Exchange? The Anchor Guide to On-Ramping
- Centralized vs Decentralized Exchanges (CEX vs DEX) Explained
- Understanding Crypto Trading Fees: Maker vs Taker and Spreads
- What is KYC and AML on Crypto Exchanges and Why is it Required?
- How to Safely Withdraw Your Bitcoin from an Exchange to Your Wallet
Sending Transactions
A step-by-step beginner's guide on how to safely send a Bitcoin transaction, scan QR codes, double-check addresses, and verify on-chain status.
Explore Module Lessons
Protecting Your Keys
Discover why a dedicated hardware wallet is your absolute best defense against online malware, keyloggers, and digital hacking attempts.
Explore Module Lessons
- Why a Hardware Wallet is Essential: The Anchor Guide to Cold Storage
- The BIP 39 Passphrase Guide: Creating a Hidden Duress Wallet
- Metal Backup Guide: How to Stamp Your Seed Phrase on Steel
- The Golden Rules of Bitcoin Security: Keep it Simple & Stay Quiet
- Is 12 Words Enough? The Math Behind Seed Phrase Security
The Bitcoin Network
Deep dive into the peer-to-peer network layer. Understand node propagation, network latency, orphan blocks, and defense against Sybil attacks.
What is a Node?
Learn the critical role of transaction and block validation. Discover how to run a node, storage options (pruned vs. full), and why nodes don't receive payments.
Bitcoin Mining
A technical look at Proof of Work. Explore SHA-256 hashing, mining pool mechanics, mining rig hardware (ASICs vs. GPUs), and the block subsidy halving schedule.
The Blockchain
Understand the blockchain ledger structure. Learn how blocks are cryptographically chained and how Nakamoto Consensus (Longest Chain Rule) establishes trust.
Blocks
Break down block structures. Discover block size limits, block weight calculations, Merkle Trees, Coinbase transactions, and the blockspace bidding market.
Difficulty
Master the difficulty feedback loop. Learn how the two-week retarget rule regulates block speeds, protects hashrate, and debunks miner death spirals.
Transactions
The mathematical anatomy of transactions. Master serialized schemas, transaction inputs, Outputs, fees, and relative/absolute timelock consensus.
Outputs
Deep dive into the UTXO model. Understand how wallets track unspent outputs, change derivation paths, dust limit policies, and UTXO consolidation strategies.
Locks
Explore the smart-contracting capabilities of Bitcoin Script. Master scriptPubKey locking, scriptSig unlocking, stacktraces, and multisig OP_CHECKMULTISIG execution.
Keys & Addresses
An introduction to Bitcoin keys and addresses. Master private and public keys, secp256k1 math, compressed coordinates, and address derivation formats.
Private Keys
Explore the secrets of raw private key numbers. Learn about entropy generation (coin-flipping, dice-rolling, and CSPRNGs), WIF formats, storage setups, and BIP 39 HD mnemonic seeds.
Public Keys
Dive into the mathematical geometry of public key coordinates. Master point addition and doubling arithmetic, coordinate compression algebra, pure Python derivation, Hash160, and 32-byte Schnorr public keys (BIP 340).
Digital Signatures
Understand the authorization layers of Bitcoin. Explore the mathematical mechanics of ECDSA, DER signature serialization, strict BIP 66 parsing, fatal nonce-reuse and bias lattice-attacks (HNP), and the evolution of linear Schnorr signatures.
SegWit
Master Bitcoin's most critical scaling upgrade. Explore witness segregation mechanics, Block Weight Units (WU), the 4:1 witness discount, Nested vs. Native Bech32 layouts, malleability fixes, and P2WPKH/P2WSH script bytecode.
Technical: Networking
Deep dive into Bitcoin peer-to-peer connection protocols. Master TCP port bindings, 24-byte packet header layouts, and the bi-directional handshake exchange.
Explore Module Lessons
- Bitcoin P2P Networking: The Anchor Guide to Node Connections
- P2P Message Header: Serialization of the 24-Byte Wire Protocol
- The P2P Version Message: Byte Layout and Payload Specifications
- The P2P Handshake State Machine: Validation Rules and Timeout Boundaries
- Building a Custom Python P2P Handshake Client from First Principles
- Magic Bytes: Message Delimiters Across Bitcoin Networks
- The Mathematics of Magic Bytes: Entropy, UTF-8 Violations, and Integer Bounds
- P2P Stream Demultiplexing: Parsing TCP Byte Streams over Sockets
- Disk Serialization of Blocks: Raw blk*.dat File Delimiters
- Building a Real-Time TCP Packet Stream Parser in Pure Python
Technical: Mining & Mempool
Master the design architectures of the Bitcoin mempool. Explore time/size limit dynamic thresholds, ancestral dependency DAG structures, and package evaluation (CPFP) miners' math.
Explore Module Lessons
- The Mempool: The Anchor Guide to Bitcoin's Staging Area
- Understanding Mempool Ancestors & Descendants: Consensus Limits and DAG Structures
- How Child Pays For Parent (CPFP) Works: Mathematical Fee-Bumping and Miner Scoring
- Replace-By-Fee (RBF) & BIP 125 Opt-In: Mechanics, Security, and Double-Spend Protection
- Bitcoin Node Mempool Configuration: Mastering maxmempool, Expiry, and RPC Diagnostics
- Candidate Blocks: How Miners Assemble Transactions in Memory
- GetBlockTemplate (GBT) Protocol: The Industry Standard for Block Construction
- Enforcing Weight and SigOps Limits in Candidate Block Construction
- Constructing the Merkle Tree: Mathematical Proofs and Transaction Root Generation
- Building a Candidate Block Builder in Pure Python
- The Mining Target: The Anchor Guide to Bitcoin's Security Boundary
- Target vs. Difficulty: Mathematical Relations and Scaling Formulas
- The 'Bits' Field: Unpacking Compact Target Serialization in Block Headers
- Hash Verification: Mathematically Proving a Valid Proof of Work
- Building a Target and Bits Converter in Pure Python
- The Coinbase Transaction: The Anchor Guide to Bitcoin's Genesis Output
- The Coinbase Input: Demystifying the Null Input and Coinbase Script
- BIP 34: Enforcing Block Height in the Coinbase Script
- SegWit Witness Commitments: Binding Witness Data to the Coinbase Output
- Building a Coinbase Transaction Serializer in Pure Python
- Block Reward Subsidy Decay: The Anchor Guide to 21 Million
- Consensus Enforcement of the Block Subsidy Halving Schedule
- The Economics of Transaction Fee Collection in Mining
- The Underpaying Miner: Consensus Rules on Block Reward Underclaiming
- Building a Block Subsidy and Halving Simulator in Pure Python
Technical: Consensus & Blockchain
Master the chronological coordinate of the ledger. Learn about the Genesis Block (height 0), its unspendable outputs, and block height relative clocks.
Explore Module Lessons
- Understanding Block Height: The Anchor Guide to Bitcoin's Chronology
- Height vs. Chain Work: The Anchor Guide to Nakamoto Consensus
- Blockchain Reorganizations (Reorgs): The Anchor Guide to Chain Swaps
- BIP 34 (Coinbase Height): The Anchor Guide to TXID Uniqueness
- Building a Blockchain Height and Reorg Simulator in Pure Python
- Nakamoto Consensus: The Anchor Guide to the "Most Work" Rule
- The Byzantine Generals' Problem: The Anchor Guide to Decentralized Truth
- Game Theory & Miner Incentives: The Anchor Guide to Honest Consensus
- Probabilistic Finality: The Anchor Guide to Transaction Settlement
- Building a Nakamoto Consensus Simulator in Pure Python
- Natural Forks: The Anchor Guide to Latency and Stale Blocks
- The Block Tree: The Anchor Guide to Competing Chain Realities
- UTXO Rollback Mechanics: The Anchor Guide to Database Reversals
- Reorg Economics & Attack Cost: The Anchor Guide to the Work Barrier
- Building a UTXO & Mempool Reorg Simulator in Python
- The 51% Attack: The Anchor Guide to Majority Hashrate Control
- Double Spend & Shadow Mining: The Anchor Guide to Reorg Strikes
- Censorship & Minority Suppression: The Anchor Guide to Soft Power
- Hardware & Energy Attack Costs: The Anchor Guide to the ASIC Wall
- Building an Attacker Lead-Time Simulator in Python
- Hard Forks: The Anchor Guide to Incompatible Upgrades
- The Chain Split Phenomenon: The Anchor Guide to Ledger Divergence
- Replay Protection: The Anchor Guide to BIP 143 & SIGHASH_FORKID
- Historical Hard Forks: BTC vs. BCH vs. BSV
- Custom Python Fork Validator
Technical: Soft Forks
Master the mechanics of backward-compatible upgrades. Learn how rule tightening and forward compatibility allow Bitcoin to upgrade without splitting.
Technical: Block Structure
Master the six fields of the Bitcoin block header. Learn about little-endian serialization and the efficiency of the 80-byte header design.
Explore Module Lessons
- The 80-Byte Block Header: The Anchor Guide to Bitcoin's DNA
- Version Field Evolution: From v1 to BIP 9
- ASICBoost & Version Rolling
- Validation of Version Fields
- Custom Python Header Serializer
- The Hash Chain Connection
- Double-SHA256 Linkage
- Immutability Mechanics: The Domino Effect
- Genesis Block Linkage: The Null Anchor
- Custom Python Chain Linker
- Merkle Tree Fundamentals
- The Merkle Path: Efficient Verification
- Handling Odd Transaction Counts
- Merkle Malleability (CVE-2012-2459)
- Custom Python Merkle Tree Builder
- The Unix Timestamp Field
- Median Time Past (MTP)
- The 2-Hour Rule: Network Time Drift
- Timestamp Manipulation & Timejacking
- Custom Python Timestamp Auditor
- The Bits Field Overview
- The Exponent-Mantissa Logic
- Conversion: Bits to Target
- Precision Loss & Consensus Limits
- Custom Python Bits Decompressor
- The Nonce Field Overview
- The 4-Billion Value Limit
- Nonce Overflow & Extra Nonce
- Nonce Distribution Analysis
- Custom Python Nonce Brute-Forcer
- The Block Hash Definition
- Calculating the Hash: The Endianness Challenge
- The Leading Zeroes Requirement
- Block ID vs. Block Hash
- Custom Python Block Hash Verifier
Technical: Disk Storage
Understand how Bitcoin Core persists the blockchain to silicon. Learn about the 128MB blk.dat file structure and the role of flat binary storage.
Technical: Transaction Inputs
Deconstruct the structure of a Bitcoin input. Learn how inputs reference previous outputs to unlock and redistribute satoshis across the network.
Technical: VOUT Indexing
Understand the zero-based indexing of Bitcoin outputs. Learn why a TXID alone is insufficient to identify specific coins and how VOUT slots solve the ambiguity.
Technical: Unlocking Scripts
Analyze the 'Key' of the Bitcoin protocol. Learn how the ScriptSig field provides the cryptographic credentials required to satisfy the conditions of previous outputs.
Technical: Sequence & Timelocks
Deconstruct the 4-byte nSequence field. Learn its original purpose for high-frequency trades and its modern role in enabling RBF and relative timelocks.
Technical: Locking Scripts
Examine the foundation of Bitcoin's programmable ownership. Learn how ScriptPubKey defines the mathematical conditions required for any future spending of an output.
Technical: The Witness (SegWit)
Analyze the segregated proof area of Bitcoin. Learn how the Witness field stores signatures outside the main transaction structure to fix malleability and increase capacity.
Technical: Transaction Locktime
Examine the temporal bounds of the Bitcoin protocol. Learn how the 4-byte nLockTime field prevents transactions from being mined until a specific block height or date.
Technical: Transaction Fees
Understand the implicit accounting of the Bitcoin network. Learn how fees are derived from the difference between input and output values without a dedicated fee field.
Technical: Transaction Size & Weight
Master the physics of blockspace. Learn the difference between raw bytes and weight units, and how SegWit fundamentally changed how Bitcoin measures transaction size.
Technical: The UTXO Model
Explore the stateless architecture of Bitcoin. Learn why the Unspent Transaction Output (UTXO) model was chosen over accounts for massive parallelism and cryptographic security.
Technical: wTXID (Witness Transaction ID)
Explore the dual identity of SegWit transactions. Learn how the Witness Transaction Identifier (wTXID) protects the network from signature malleability while maintaining backward compatibility.
Technical: PSBT (BIP 174)
Introduction to Partially Signed Bitcoin Transactions. Learn how BIP 174 standardized the communication between multisig coordinators and offline signing devices.
Technical: P2PK (Pay-to-Public-Key)
Explore the original script type used by Satoshi Nakamoto. Learn how P2PK locks coins directly to raw public key bytes and why it was the foundation of the network.
Technical: P2PKH (Pay-to-Public-Key-Hash)
Explore the standard legacy address format. Learn how P2PKH improved space efficiency and security by locking coins to a 20-byte RIPEMD160 hash instead of raw keys.
Technical: P2MS (Pay-to-Multisig)
Introduction to collaborative ownership. Learn how the M-of-N multisig model works in its rawest form and why it was the first way joint accounts were created on Bitcoin.
Technical: P2SH (Pay-to-Script-Hash)
Introduction to the '3' address format. Learn how P2SH shifted the burden of complex script execution from the sender to the receiver using cryptographic hashes.
Technical: P2SH-P2WPKH (Nested SegWit)
Explore the bridge between legacy and modern Bitcoin. Learn how Nested SegWit allowed users to access the benefits of the 2017 upgrade while maintaining compatibility with old '3' addresses.
Technical: P2SH-P2WSH (Nested SegWit Multisig)
Introduction to multi-layered collaborative custody. Learn how P2SH-P2WSH enabled institutional multisig wallets to utilize SegWit benefits while remaining backward compatible.
Technical: P2WPKH (Native SegWit)
Explore the native SegWit standard. Learn how P2WPKH removed the legacy P2SH wrapper entirely, resulting in 'bc1q' addresses and the maximum possible fee efficiency for single keys.
Technical: P2WSH (Native SegWit Multisig)
Introduction to native SegWit multisig. Learn how P2WSH provides the maximum possible fee discount and utilizes 32-byte SHA256 security for complex collaborative custody scripts.
Technical: P2TR (Pay-to-Taproot)
Introduction to the 2021 Taproot upgrade. Learn how P2TR unified single keys and complex scripts into a single identity, maximizing privacy and introducing bc1p addresses.
Technical: OP_RETURN (Data Embeds)
Introduction to arbitrary data storage. Learn how OP_RETURN allows for embedding metadata into the blockchain without creating unspendable UTXOs.
Technical: Private Key (Mathematical Generation)
Deep dive into the 256-bit integer that powers Bitcoin. Understand the 'Secret Scalar' and the absolute responsibility of owning the key that controls your wealth.
Technical: Public Keys (Uncompressed vs. Compressed)
Explore the geometry of your Bitcoin identity. Learn how the private key scalar is transformed into a specific (x, y) coordinate on the secp256k1 elliptic curve.
Technical: Public Key Hash (HASH160)
Introduction to the 160-bit fingerprint. Learn how hashing the public key provides compact identifiers, uniform address sizes, and a layer of privacy for Bitcoin users.
Technical: Bitcoin Addresses (Encoding Standards)
Introduction to the payment identifier. Learn how addresses are essentially postal codes for your funds, derived from public key hashes and encoded for human use.
Technical: WIF Format (Encoding Secrets)
Introduction to the Wallet Import Format. Learn how WIF converts raw 256-bit scalars into human-readable secrets that are safer to copy and transport.
Technical: ECDSA Signatures (R and S components)
Introduction to digital signatures. Learn how a private key creates a unique 'Seal' over a transaction hash without ever revealing the underlying secret.
Technical: Checksums (Error Detection Mathematics)
Introduction to error detection. Learn why Bitcoin identifiers use mathematical checksums to prevent the unrecoverable loss of funds due to simple transcription typos.
Technical: Base58 Encoding (The Human-Friendly Hex)
Introduction to the legacy encoding standard. Discover why Satoshi chose a custom 58-character alphabet to replace raw hex and protect users from ambiguous characters.
Technical: Bech32 Encoding (The SegWit Standard)
Introduction to the modern SegWit encoding. Learn why Bitcoin transitioned to Bech32 for Native SegWit addresses and how it improves efficiency for humans and QR codes.
Technical: Mnemonic Phrases (BIP39 Standard)
Introduction to the human-readable backup. Discover how BIP39 replaced complex hex strings with 12 simple words, enabling universal wallet recovery.
Technical: Extended Keys (BIP32 xpub/xprv)
Introduction to Hierarchical Deterministic (HD) parent keys. Learn how a single extended key can generate an infinite tree of child keys using a master secret and chain code.
Technical: Derivation Paths (The BIP Hierarchy)
Introduction to HD instructions. Learn how derivation paths act as the 'map' that tells your wallet where to find specific keys within the infinite tree of your seed phrase.
Cryptography: Hash Functions (SHA256 & RIPEMD160)
Introduction to cryptographic hashing. Discover the 3 pillars of hash functions-Determinism, One-wayness, and Collision Resistance-and how they anchor the blockchain.
Cryptography: Elliptic Curve Math (secp256k1)
Introduction to ECC geometry. Learn why Bitcoin uses curves over finite fields and how modular arithmetic transforms smooth lines into a secure scattering of points.
Cryptography: Schnorr Signatures (The Taproot Standard)
Introduction to BIP340. Learn why Schnorr signatures are superior to ECDSA in terms of linearity, security proofs, and computational efficiency.
Upgrades: Segregated Witness (BIP141 details)
Introduction to BIP141. Learn how Segregated Witness separated signatures from base data to fix malleability and increase network capacity.
Upgrades: Taproot (BIP341/342 Details)
Introduction to BIP341. Learn how Taproot combines Schnorr signatures and Merkle trees to make complex smart contracts look identical to simple payments.
Technical: Hexadecimal & Byte Mapping
Introduction to Base16. Learn why Bitcoin uses hexadecimal to represent massive binary numbers like private keys and transaction hashes in a readable format.
Technical: Bytes (Raw Data Units)
Introduction to the fundamental unit of the blockchain. Learn why the 8-bit byte is the baseline for measuring block size, transaction fees, and cryptographic strength.
Technical: Little Endian (Byte Ordering)
Introduction to the counter-intuitive world of byte ordering. Learn the difference between Big and Little Endian and why Bitcoin chose the 'backward' way to store numbers.
Technical: Byte Order (Big vs. Little Endian Contexts)
Overview of the multi-endian stack. Learn how data changes byte order as it moves from hardware memory to disk storage and finally to the human-readable display layer.
Technical: Compact Size (VarInt)
Introduction to variable-length integers. Learn how Bitcoin saves massive amounts of blockchain space by using dynamic byte-counts for inputs, outputs, and scripts.
Script Fundamentals
Master the core concepts of Bitcoin Script. Understand Turing-incompleteness, the stack execution model, serialized bytecodes, standard vs non-standard scripts, and consensus limits.
Explore Module Lessons
- What is Bitcoin Script?
- Why Bitcoin Script is Not Turing Complete
- The Stack-Based Execution Model
- How Scripts Are Evaluated Step by Step
- What is a Locking Script (scriptPubKey)?
- What is an Unlocking Script (scriptSig)?
- How scriptSig and scriptPubKey Combine at Validation
- What is the Script Interpreter?
- How Bitcoin Nodes Execute Scripts
- What is Script Serialization?
- Script Version and Upgrade Mechanisms
- What is a Standard vs Non-Standard Script?
- IsStandard() Rules in Bitcoin Core
- What is a Bare Script?
- Script Size Limits and Consensus Rules
Data Push Opcodes
`OP_0`, also known as `OP_FALSE`, is one of the most foundational and frequently used opcodes in Bitcoin Script. It occupies opcode byte `0x00` and its sole ...
Explore Module Lessons
- OP_0 (OP_FALSE) - Pushing Zero
- OP_1 through OP_16 - Pushing Small Integers
- OP_1NEGATE - Pushing Negative One
- OP_PUSHDATA1 - Pushing Up to 255 Bytes
- OP_PUSHDATA2 - Pushing Up to 65535 Bytes
- OP_PUSHDATA4 - Pushing Up to 4GB (Theoretical)
- Minimal Push Rules (BIP 62)
- Direct Byte Push (Opcodes 0x01\u20130x4b)
- What is a Script Atom?
- How Data Items Sit on the Stack
- Python pseudocode for script atom parser
- The Difference Between OP_0 and OP_FALSE
- OP_RESERVED - The Undefined Opcode
- OP_NOP - The Do-Nothing Opcode Family
- OP_NOP1 through OP_NOP10 - Upgrade Reserved Slots
- How NOP Opcodes Enable Soft Forks
- OP_VER - The Disabled Version Opcode
- OP_VERIF and OP_VERNOTIF - Always-Invalid Opcodes
- OP_RETURN - Provably Unspendable Outputs
- The 80-Byte OP_RETURN Limit Explained
Flow Control Opcodes
`OP_IF` is one of the most powerful and foundational opcodes in Bitcoin Script. It introduces the concept of **conditional execution** - the ability for a sc...
Explore Module Lessons
- OP_IF - Conditional Execution Basics
- OP_NOTIF - The Inverted Conditional
- OP_ELSE - The Alternative Branch
- OP_ENDIF - Closing a Conditional Block
- Nested OP_IF Structures
- How Conditionals Work on the Stack
- OP_IF vs OP_NOTIF - When to Use Which
- Real World OP_IF Usage in HTLC Scripts
- OP_VERIFY - Fail-If-False Execution
- How OP_VERIFY Terminates Scripts
- OP_RETURN vs OP_VERIFY - Key Differences
- OP_TOALTSTACK - Moving Items to Alt Stack
- OP_FROMALTSTACK - Retrieving from Alt Stack
- What is the Alt Stack and Why It Exists
- Flow Control Script Attack Vectors
Stack Manipulation Opcodes
`OP_DROP` is one of the most fundamental stack manipulation opcodes in Bitcoin Script. Its sole purpose is to remove - or "drop\"- the topmost item from the stack, discarding it entirely.
Explore Module Lessons
- OP_DROP - Removing Top Stack Item
- OP_2DROP - Removing Two Stack Items
- OP_DUP - Duplicating the Top Item
- OP_2DUP - Duplicating Top Two Items
- OP_3DUP - Duplicating Top Three Items
- OP_SWAP - Swapping Top Two Items
- OP_2SWAP - Swapping Top Two Pairs
- OP_OVER - Copying Second Item to Top
- OP_2OVER - Copying Second Pair to Top
- OP_ROT - Rotating Top Three Items
- OP_2ROT - Rotating Top Three Pairs
- OP_IFDUP - Conditional Duplication
- OP_DEPTH - Counting Stack Items
- OP_NIP - Removing Second Stack Item
- OP_TUCK - Copying Top Item Below Second
- OP_PICK - Copying Nth Item to Top
- OP_ROLL - Moving Nth Item to Top
- OP_PICK vs OP_ROLL - Key Difference
- Stack Overflow and Depth Limits
- Visualizing Stack State Through Script Execution
Arithmetic Opcodes
OP_ADD is one of the most fundamental arithmetic opcodes in Bitcoin Script. It pops the top two elements from the stack and adds them together.
Explore Module Lessons
- OP_ADD - Adding Two Numbers
- OP_SUB - Subtracting Two Numbers
- OP_NEGATE - Flipping Sign
- OP_ABS - Absolute Value
- OP_NOT - Boolean Inversion
- OP_0NOTEQUAL - Testing for Non-Zero
- OP_BOOLAND - Logical AND
- OP_BOOLOR - Logical OR
- OP_NUMEQUAL - Numeric Equality Test
- OP_NUMEQUALVERIFY - Equality Test with Fail
- OP_NUMNOTEQUAL - Numeric Inequality Test
- OP_LESSTHAN - Less Than Comparison
- OP_GREATERTHAN - Greater Than Comparison
- OP_LESSTHANOREQUAL - Less Than or Equal
- OP_GREATERTHANOREQUAL - Greater Than or Equal
- OP_MIN - Returning the Smaller Value
- OP_MAX - Returning the Larger Value
- OP_WITHIN - Range Check Operation
- Script Number Encoding (CScriptNum)
- Why MUL, DIV, and MOD Are Disabled in Bitcoin
Bitwise & String Opcodes
OP_EQUAL performs a precise, byte-for-byte comparison of the top two items on the stack and returns a boolean result.
Explore Module Lessons
- OP_EQUAL - Byte-for-Byte Equality
- OP_EQUALVERIFY - Equality with Termination
- OP_EQUAL vs OP_NUMEQUAL - Critical Difference
- OP_CAT - Disabled String Concatenation
- OP_SUBSTR - Disabled Substring Extraction
- OP_LEFT and OP_RIGHT - Disabled Slice Opcodes
- OP_SIZE - Measuring Stack Item Byte Length
- OP_INVERT, OP_AND, OP_OR, OP_XOR - Disabled Bitwise Ops
- Why String Opcodes Were Disabled in 2010
- The Future of Disabled Opcodes - OP_CAT Revival Debate
Cryptographic Opcodes
OP_SHA1 applies the SHA-1 hash function to the top stack element. It is considered legacy and cryptographically broken.
Explore Module Lessons
- Collision example (conceptual):
- Script that verifies a SHA256 preimage
- Example
- Single SHA256 vulnerable to length extension:
- OP_RIPEMD160 - RIPEMD160 Hashing Directly
- At lock time: commit to H = HASH(secret)
- Canonical hash puzzle
- P2PK (Pay-to-Public-Key) — simplest form
- Fields in the sighash preimage (SIGHASH_ALL example)
- Conceptual model:
- Raw DER signature with SIGHASH_ALL appended
- Proof of key ownership without spending
- Two-party CoinJoin with SIGHASH_SINGLE:
- SIGHASH_ANYONECANPAY - Open Contribution Flag
- Combining Sighash Flags
- These two scripts are functionally identical:
- Locking script
- Expected behavior (conceptual):
- Pattern: 2-of-3 multisig PLUS a timelock condition
- Tapscript 2-of-3 using OP_CHECKSIGADD
- Key aggregation (off-chain computation)
- Schnorr signature format (BIP 340):
- Both of these verify correctly for the same message and public key:
- Crowdfunding Protocol Overview
- Approximate costs (relative):
Timelock Opcodes
Deep dive into BIP 65 and absolute timelocks, which allow locking funds until a specific block height or Unix timestamp.
Explore Module Lessons
- OP_CHECKLOCKTIMEVERIFY (CLTV) - BIP 65 Explained
- Pseudocode for CLTV validation logic
- Lock funds until block 850,000
- Examples:
- Pseudocode for BIP 68 validation
- Allow spending only after 144 blocks (≈1 day) from UTXO confirmation
- CLTV vs CSV - Absolute vs Relative Time
- Block height examples
- Inheritance script: Alice's heirs get access after block 950,000
- Escrow Script:
- Vault design:
- To-Local Output (in Alice's commitment transaction)
- Recipient (Bob) creates the payment secret:
- Adaptor signature concept (simplified math):
- BUG: Encoding a Unix timestamp as if it were a block height
Standard Script Types
Deconstructing the original Pay-to-Public-Key (P2PK) script type used by Satoshi in the early days of Bitcoin.
Explore Module Lessons
- P2PK Script - Full Anatomy and Execution
- P2PKH Script - Full Anatomy and Execution
- P2SH Script - Full Anatomy and Execution
- P2MS Bare Multisig - Full Anatomy
- P2WPKH Script - Full Witness Execution
- P2WSH Script - Full Witness Execution
- P2SH-P2WPKH Nested SegWit - Full Execution
- P2SH-P2WSH Nested Multisig - Full Execution
- P2TR Key Path - Full Taproot Execution
- P2TR Script Path - Full Taproot Execution
- How Script Type is Detected by Wallets
- Bitcoin Core policy limits (src/policy/policy.h):
- Bare OP_TRUE Scripts (Anyone Can Spend)
- Puzzle Scripts - Hash Collision Bounties
- Pay-to-Contract Scripts - Advanced Pattern
- Simplified Taproot DLC structure
- Atomic Swap Scripts - Cross-Chain Pattern
- MuSig2 key aggregation
- Lock funds, pre-commit to specific distribution transactions
- Taproot vault key structure
Script Debugging & Analysis
Learning the foundational skill of parsing hexadecimal Bitcoin scripts by hand, including opcode and data push encoding rules.
Explore Module Lessons
- How to Read a Raw Script in Hex
- Test
- 52 = OP_2, 53 = OP_3, ae = OP_CHECKMULTISIG
- Using Bitcoin Core to Test Scripts
- Clone the repository
- Tracing Stack State Step by Step
- Error: stack underflow — OP_ADD requires 2 items
- Script Validation Failures - What They Mean
- a8 = OP_SHA256, 20 = push 32 bytes, 87 = OP_EQUAL
- Example: Genesis block coinbase transaction
- Decoding Witness Data from Raw Transactions
- Finding Script Type from Address Format
- How Miniscript Simplifies Script Writing
- Install Rust and miniscript CLI
- script_classifier.py
Tapscript Opcodes
Introduction to Tapscript, the refined scripting language for Taproot's script path, fixing legacy quirks and enabling future upgradeability.
Explore Module Lessons
- What is Tapscript? (BIP 342)
- Tapscript sighash commits to (simplified):
- OP_SUCCESS Opcodes - The Upgrade Mechanism
- Disabled Opcodes in Tapscript
- Example tags used in Tapscript:
- From the sighash algorithm:
- Parsing the leaf version from control block:
- Example control block for a leaf at depth 2:
- MAST - Hiding Unexecuted Script Branches
- Pseudocode for validation weight accounting:
- OP_CHECKSIGADD in Tapscript Multisig
- Conceptual MuSig2 key aggregation (not production code):
- Conceptual adaptor signature (not production code):
- Tapscript and Lightning Network Upgrades
- OP_CAT enables covenants when combined with OP_CHECKSIG:
Real World Examples
Complete line-by-line trace of a legacy P2PKH transaction execution.
Explore Module Lessons
- The data that gets hashed and signed in P2PKH:
- The redeem script (the actual spending conditions):
- HTLC execution — Bob claiming with preimage:
- Alice watches the Bitcoin blockchain
- Watchtower monitoring logic for vault:
- Fully Annotated P2TR Key Path Execution
- Creating a Taproot output with a 2-of-2 multisig script:
- Example: embed a hash
- ========================
- The Complete Bitcoin Script Reference Cheatsheet
Bitcoin Core
An overview of Bitcoin Core's architecture, framing it as a complex machine with 20 specialized departments.
Explore Module Lessons
- Welcome to the Engine Room
- The Master Map of the Code
- The Brain of the Machine
- The Librarian (Database)
- The Watchman (Validation)
- The Postman (P2P Network)
- The Safe (Wallet)
- The Translator (RPC)
- The Architect (Initialization)
- The Mathematician (Cryptography)
- The Scriptwriter (Script)
- The Memory Bank (Mempool)
- The Indexer (TxIndex)
- The Consensus Guard
- The Policy Maker
- The Archaeologist (Reorgs)
- The Bodyguard (Security)
- The Lab (Testing)
- The Turbo (Performance)
- The Visionary (Future)
- Glossary of Terms
- Welcome to the Engine Room: An Overview of Bitcoin Core
- The Master Map: Understanding the Top-Level Directory Structure
- The Brain (src/): Where the Magic Happens
- The Librarian (src/dbwrapper.h): How Bitcoin Remembers Everything
- The Watchman (src/validation.cpp): Ensuring Nobody Breaks the Rules
- The Postman (src/net.cpp): How Nodes Talk to Each Other
- The Safe (src/wallet/): How Bitcoin Keeps Your Money Secure
- The Translator (src/rpc/): How Humans and Machines Communicate
- The Architect (src/init.cpp): How the Building is Constructed at Startup
- The Mathematician (src/crypto/): The Foundation of Digital Truth
- The Scriptwriter (src/script/): The Language of Bitcoin Smart Contracts
- The Memory Bank (src/txmempool.cpp): Where Transactions Wait for Their Turn
- The Indexer (src/index/): Finding Information in a Billion-Byte Haystack
- The Consensus Guard (src/consensus/): Defining the "Laws of Physics"for Bitcoin
- The Policy Maker (src/policy/): Standardizing the Unstandardized
- The Archaeologist (src/rev*.dat): Handling Reorgs and Undo Data
- The Bodyguard (src/random.cpp / src/support/): Security and Hardening
- The Lab (test/): Ensuring the Engine Never Fails
- The Turbo (src/util/): Performance and Optimization
- The Visionary (src/kernel/): The Future of Bitcoin Core
Bitcoin-CLI and the Bridge
Master the architecture of Bitcoin Core. Chapter 1: The Messenger's Journey: Introduction to the Bitcoin-CLI. An in-depth technical analysis of the protocol's cli bridge logic.
Explore Module Lessons
- The Messenger's Journey: Introduction to the Bitcoin-CLI
- The Language of JSON: How the Client and Server Speak
- The Bridge's Blueprint: Analyzing `bitcoin-cli.cpp`
- The First Handshake: How the CLI Finds the Node
- The Secret Cookie: Simple Authentication Explained
- The Envelope of a Request: Building a JSON Message
- The Post Office: How `CallRPC` Delivers the Message
- The Waiting Room: How the Node Receives a Request
- The Interpreter: Mapping Words to Code Actions
- The Batching Miracle: Sending Many Orders at Once
- The Performance Engine: Why RPC Speed Matters
- The Wallet Connection: Navigating the `/wallet/` Endpoint
- The Named Argument Puzzle: Improving the Human Experience
- The Command-Line Wizardry: Built-in Aliases like `-getinfo`
- The Secure Shutdown: How the Bridge Closes Gracefully
- The Async Revolution: Exploring the Non-blocking Future
- The Bridge to the World: Using Bitcoin-CLI in Scripts and Apps
- The Legacy of the Bridge: A Philosophical Conclusion
- The Technical Reference: A Deep-Dive Appendix for the Sovereign Engineer
Bitcoin Node Operations
Master the architecture of Bitcoin Core. Chapter 1: The Builder\u2019s Foundation: Environment Setup and Toolchains. An in-depth technical analysis of the protocol's node operations logic.
Explore Module Lessons
- The Foundation: Installing the core build tools
- Installing the Homebrew package manager (if not already installed)
- Updating the MSYS2 package database
- Understanding the standard make output:
- The Dependency Maze: BerkeleyDB, SQLite, and Boost Logic
- On your Ubuntu/Debian Desktop PC:
- Starting the bitcoind daemon
- Performance
- Data Directory Anatomy: Understanding Blocks, Chainstate, and Indexes
- Example: Mounting a 2TB External SSD and running bitcoind
- Prune the blockchain to 10GB
- Backup Cryptography: Securing wallet.dat, HD Seeds, and Descriptors
- bitcoin.conf settings for total Tor isolation
- Nitro Boost for IBD
- AssumeUTXO: The Architecture of Instant-On Deployment
- Example logrotate config for Bitcoin (/etc/logrotate.d/bitcoin)
- Stage 1: Build the binary in a heavy environment
- The Upgrade Path: Handling Database Migrations and Fork Safety
- Sovereignty Checklist: Ensuring 99.9% Uptime and Network Health
- Advanced Appendix A: The LevelDB Internal Mechanics
- Advanced Appendix B: The Anatomy of a P2P Message
- Advanced Appendix C: Customizing the Build for High-Frequency Trading
- Advanced Appendix D: The 21 Million Supply Enforcement Code
- The Future of Operations: Stratum V2 and Beyond
- Detailed Hardware Benchmarks: From Raspberry Pi to Threadripper
- The Evolution of the RPC Interface: From JSON to REST
- Troubleshooting the "Stuck"Node: A Diagnostic Guide
- The Philosophy of the Full Node: Why 21 Million Matters
- Conclusion: The Path of the Sovereign Individual
- The Complete bitcoin.conf Reference Dictionary (Advanced Edition)
- Final Summary of Operations
- Supplemental: Step-by-Step Installation Walkthroughs
- The Operator's Mental Model: Verification Levels
Bitcoind Lifecycle
Master the architecture of Bitcoin Core. Chapter 1: The First Breath: How bitcoind Wakes Up. An in-depth technical analysis of the protocol's bitcoind lifecycle logic.
Explore Module Lessons
- The First Breath: How bitcoind Wakes Up
- The Memory Forge: Preparing the High-Speed Databases
- The Librarian’s Desk: Loading the Block Index and UTXOs
- The Networking Handshake: Starting the P2P Communication
- The Internal Clock: How the Node Keeps Time and Heartbeats
- The Workhorse Threads: How the Node Multitasks
- The Guard at the Gate: Peer Discovery and Connection Logic
- The Steady State: What the Node Does When All is Quiet
- The Memory Sweep: How the Node Manages Its Own Resources
- Handling the Crowds: Managing Hundreds of Peer Connections
- The Signal Listener: How the Node Hears Your Commands
- The Critical Pause: What Happens When You Press "Stop\Stop"
- The Orderly Exit: The Step-by-Step Shutdown Sequence
- Locking the Vault: Database Safety and Atomic Writes
- The Crash Protocol: Recovering from Unexpected Shutdowns
- The Garbage Collector: Final Resource Cleanup
- The Last Goodbye: Releasing the Process Identifier
- Conclusion: The Heartbeat of a New World
- The Oracles of Consensus: Soft Forks and Rule Changes
- The Watchman's Journal: The `debug.log` and Monitoring
- The Secret Passageways: Tor, I2P, and Privacy Networks
- The Distributed Brain: Headers-First Sync and Parallel Downloads
- The Mempool’s Guardians: Fee Estimation and RBF
- The Signature Architects: Schnorr, Taproot, and Witness Logic
- The Time Locks: CheckLockTimeVerify and Sequence Rules
- The Defensive Fortress: Banman and Discouraging Bad Peers
- The Wallet's Anchor: Rescan and Birthday Filters
- The Eternal Return: Reindexing and Total Reconstruction
- The Lighting Bridge: How bitcoind supports L2
- The Mining Pool Protocol: Stratum and Block Templates
- The Security Audit: How developers find bugs
- The Global Hashrate: How bitcoind reacts to mining power
- The Energy of the Bit: Proof of Work and Physics
- The Human Interface: CLI vs GUI vs RPC
- The Scripting Language: Forth-like Logic and Opcodes
- The Governance of the Code: BIPs and the Community
- The Legacy of Satoshi: Looking back at v0.1
- The Infinite Horizon: Bitcoin in the year 2140
- The Architectural Encyclopedia Summary: A Synthesis of the Soul
Blockchain Essentials
Master the architecture of Bitcoin Core. Chapter 1: The Digital Ledger: Introduction to Blockchain RPCs. An in-depth technical analysis of the protocol's blockchain essentials logic.
Explore Module Lessons
- The Digital Ledger: Introduction to Blockchain RPCs
- The State of the Union: Understanding `getblockchaininfo`
- The Height of Success: Measuring Progress with `getblockcount`
- The Golden Hash: Tracking the Tip with `getbestblockhash`
- The Library of Reality: How `getblock` Retrieves History
- The Skeleton of Truth: Exploring `getblockheader`
- The Anatomy of a Block: Headers, Transactions, and Witnesses
- The Difficulty Engine: How `getdifficulty` Measures Network Heat
- The Pulse of the Network: Using `waitfornewblock`
- The Fork in the Road: Understanding `getchaintips`
- The Accountant's View: Exploring `gettxoutsetinfo`
- The Specifics of Wealth: Using `gettxout`
- The Self-Audit: Ensuring Integrity with `verifychain`
- The State Capturer: Using `dumptxoutset`
- The Diet for the Librarian: Understanding `pruneblockchain`
- The State Capturer: Photographer of the Vault (`dumptxoutset`)
- The Vigilance of the Vault: Auditing with `verifychain`
- The Sovereign Record: Conclusion of the Essentials
- Appendix: The Laws of Physics (Consensus Rules)
- The Final Word: The Portal to Sovereignty
Consensus: The Heart of Bitcoin
Master the architecture of Bitcoin Core. Chapter 1: The Constitution of the Network: Introduction to Consensus. An in-depth technical analysis of the protocol's consensus heart logic.
Explore Module Lessons
- The Constitution of the Network: Introduction to Consensus
- The Entry Gate: Understanding `ProcessNewBlock`
- The Guardian's Checklist: The Anatomy of `CheckBlock`
- The Assembly of the Truth: How Blocks are Connected to the Chain
- The Final Verification: Verifying the Merkle Root and POW
- The Contextual Audit: Validating Headers and Timing
- The Memory of the Chain: Understanding the `BlockIndex` and `BlockMap`
- The Race for the Tip: How `ActivateBestChain` resolves forks
- The Transaction Sieve: Verifying Inputs in `CheckInputScripts`
- The Script Engine: Understanding the validation of Locking/Unlocking scripts
- The Inflation Barrier: Enforcement of the 21-Million Limit
- The Double-Spend Sentinel: The role of `view.SpendInputs`
- The Coinbase Maturation: Why newly mined coins are "Locked"
- The Block Undo: Understanding `DisconnectBlock` and `UndoData`
- The Memory Pool (Mempool): Validating transactions before the block
- The Checkpoint Anchor: Why old history is "Hardened."
- The Pruning Mechanism: Managing consensus with "Limited Space."
- The Validation Cache: Speeding up the heartbeat with `ValidationCache`
- The Script Flags: Understanding "Soft Fork"activation logic
- Technical Pedagogy of validation.cpp: The Life Cycle of the Truth
The Future of Bitcoin
Master the architecture of Bitcoin Core. Chapter 1: The Vision of Modular Sovereignty: Beyond the Monolith. An in-depth technical analysis of the protocol's future logic.
Explore Module Lessons
- The Vision of Modular Sovereignty: Beyond the Monolith
- The libbitcoinkernel Project: Decoupling the Engine of Consensus
- The Purity of the Kernel: Minimizing Dependencies for Resilience
- Utreexo: The Zero-Knowledge Revolution and Stateless Nodes
- AssumeUTXO: The Instant-On Future and Background Validation
- The Evolution of Communication: From JSON-RPC to Modern REST
- The Modular Mempool: Cluster Mempool Patterns and Fee Logic
- Erlay: Bandwidth Optimization for the Next Decade
- The Multi-Process Architecture: Isolating the Wallet and the Node
- Descriptor Wallets: The Future of Key Management and Output Scripts
- Miniscript: Programmable Sovereignty for the Next Generation
- The libsecp256k1 Evolution: Preparing for MuSig2 and Beyond
- Fuzzing and Formal Verification: The Armor of the Future
- The FlatFile Versioning Strategy: Managing Decades of History
- The CDataStream Refactor: Modernizing the Serialization Engine
- The Package Relay Strategy: Solving the CPFP Limits
- Network Privacy: Tor, I2P, and the Shadow Network
- ASMAP and Eclipse Attack Defense: Territorial Sovereignty
- The Rust Transition and Memory Safety: The Safe Foundation
- The "Unending Mesh"Synthesis: The Digital Nervous System of Humanity
Mempool and Transaction Flow
Master the architecture of Bitcoin Core. Chapter 1: The Waiting Room of Truth: Introduction to the Mempool. An in-depth technical analysis of the protocol's mempool logic.
Explore Module Lessons
- The Waiting Room of Truth: Introduction to the Mempool
- The Anatomy of an Entry: Analyzing `CTxMemPoolEntry`
- The Price of Priority: How fee-rates define the order of transactions
- The Ancestry Logic: How the node tracks "Parents"of a transaction
- The Descendant Logic: How the node tracks "Children"of a transaction
- Child Pays For Parent (CPFP): The technical bridge between ancestors and descendants
- The Mempool Map: Understanding the internal indexing
- The Eviction Engine: How the node handles a full house
- The Persistence of Memory: Analyzing `mempool.dat`
- The Replace-By-Fee (RBF) Mechanics: Upgrading the priority of a transaction
- The Conflict Manager: How the mempool handles double-spend attempts
- The Fee Estimation Engine: How the node predicts the future of the block
- The Block Assembly Handshake: How miners pick from the mempool
- The Virtual Size (vSize): How SegWit changed mempool priority
- The Memory Limits: Managing the RAM footprint of the transactions
- The Privacy of the Pool: How the mempool avoids "Fingerprinting"
- The Validation Handoff: How transactions move from the network to the mempool
- The Orphan Pool: Handling transactions with missing parents
- The Network Security Hardening: Defending against mempool-based DoS attacks
- Masterclass Module 1: The CPFP Mathematical Deep Dive
Mining Control and Logic
Master the architecture of Bitcoin Core. Chapter 1: The Heart of the Network: Introduction to Bitcoin Mining. An in-depth technical analysis of the protocol's mining control logic.
Network Processing
Master the architecture of Bitcoin Core. Chapter 1: The Diplomat of the Core: Introduction to `net_processing.cpp`. An in-depth technical analysis of the protocol's net processing logic.
Explore Module Lessons
- The Diplomat of the Core: Introduction to `net_processing.cpp`
- The Message Router: Understanding `ProcessMessage`
- The Block Intake Logic: How `block` messages are verified before validation
- The Transaction Gatekeeper: Handling `tx` messages and mempool entry
- The Header-First Strategy: The logic of `headers` and `getheaders`
- The DoS Score System: How the node counts "Mistakes"
- The Banning Mechanics: Analysis of `Misbehaving()` and `BanMan`
- The Inventory Manager: Advanced `inv` processing and `getdata` fulfillment
- The Compact Blocks Innovation: Overview of BIP 152
- The Sketch Reconstruction: How `CMPCTBLOCK` is rebuilt in memory
- The Missing Transaction Hunt: The `GETBLOCKTXN` and `BLOCKTXN` handshake
- The "High-Bandwidth"Mode: Understanding `SENDCMPCT` options
- The Orphanage: How the node handles blocks that arrive out of order
- The Stalling Protection: Preventing peers from slowing down the sync
- The Fee Filter Logic: How `FEEFILTER` saves bandwidth
- The Block Reorganization: How `net_processing` reacts to chain splits
- The Witness Relay: Managing SegWit data in the network
- The Peer Inventory Tracking: How the node remembers what each peer has
- The Network Security Hardening: Defending against sophisticated P2P attacks
- Masterclass Module 1: The Transaction Acceptance Deep Dive
P2P Network Mechanics
Master the architecture of Bitcoin Core. Chapter 1: The Global Nervous System: Introduction to Bitcoin P2P. An in-depth technical analysis of the protocol's network p2p logic.
Explore Module Lessons
- The Global Nervous System: Introduction to Bitcoin P2P
- The Pulse of the Network: Overview of Network RPCs
- The Architect\u2019s Compass: Understanding `getnetworkinfo`
- Mapping the Connections: Deep Dive into `getpeerinfo`
- The Logic of Connectivity: How Nodes Find Each Other
- Manual Intervention: The `addnode` vs `connect` Commands
- The Anatomy of a Peer: Analyzing the `CNode` Structure
- The Librarian of Addresses: The Role of `AddrMan`
- Managing the Flow: Network Bandwidth and Throttling
- The Echo of the Block: Monitoring Transaction Propagation
- Latency and the Speed of Light: Measuring Network Distance
- The Handshake: How Two Nodes Become Peers
- Message Processing: The Heartbeat of `net_processing.cpp`
- The Defense Perimeter: Banning and Misbehavior Logic
- Privacy in the Shadows: Tor, I2P, and Proxy Support
- The Witness of Connectivity: Monitoring Peer Health
- The Scaling Challenge: Managing Hundreds of Connections
- The Protocol Version: Ensuring Language Compatibility
- From Bytes to Consensus: The Journey of a P2P Message
- The Sovereign Network: Final Reflection on Decentralized Connectivity
P2P Networking Layer
Master the architecture of Bitcoin Core. Chapter 1: The Digital Nervous System: Introduction to P2P Networking. An in-depth technical analysis of the protocol's p2p networking logic.
Explore Module Lessons
- The Digital Nervous System: Introduction to P2P Networking
- The Universal Language: Understanding Serialization (`serialize.h`)
- The Message Packet: The anatomy of a Bitcoin network message
- The Handshake: How two nodes introduce themselves (`VERSION`/`VERACK`)
- The Peer Discovery: How nodes find each other (`ADDR`/`GETADDR`)
- The Connection Manager: Understanding `CConnman`
- The Node Data Structure: Analysis of `CNode`
- The Inbound and Outbound Logic: How the node balances its connections
- The Eviction Policy: How the node decides which peers to kick out
- The Inventory System: The concept of `inv` messages
- The Data Propagation: How `getdata` and `block`/`tx` messages flow
- The Socket Interface: How Bitcoin talks to the operating system
- The Message Deserializer: Decoding binary data back into objects
- The Network Address Manager: Understanding `AddrMan`
- The Peer Misbehavior System: A brief look at `net.cpp`'s role in banning
- The Threading Model: How networking runs in the background
- The Flow Control: Managing bandwidth and avoiding congestion
- The Poisoning Protection: Defending against eclipse and sybil attacks
- The Network Parameters: Mainnet vs Testnet vs Signet networking
- Masterclass Module 1: The Net Processing Deep Dive (`src/net_processing.cpp`)
Performance and Optimization
Master the architecture of Bitcoin Core. Chapter 2: The Multi-Threaded Mind: Understanding Parallel Execution in Core. An in-depth technical analysis of the protocol's performance logic.
Explore Module Lessons
- The Multi-Threaded Mind: Understanding Parallel Execution in Core
- The Synchronization Guard: Introduction to Locks and Mutexes
- The Lock-Free Revolution: Understanding `std::atomic` and Wait-Free Logic
- The `CCheckQueue` Orchestrator: Multi-threaded Signature Verification
- The Validation Bottleneck: How Parallelism Solves the Block Verification Challenge
- The Memory Architecture: How the Node Manages its Internal Library
- The `dbcache` Strategy: Tuning the UTXO Database Performance
- The LevelDB Accelerator: How the Node Optimizes Disk Reads
- The Cache Consistency Protocol: Ensuring Truth Across Multiple Threads
- The Lock-Free Mempool: Optimizing Transaction Relay Speed
- The Work Queue Processor: Managing Asynchronous Tasks in the Background
- The `CThreadInterrupt` Sentinel: Graceful Stop in a Parallel World
- The `RecursiveMutex` Audit: Why Core Uses (and Avoids) Complex Locks
- The Memory-Pool Allocator: Minimizing the Cost of Object Creation
- The Network Thread Architecture: Handling Thousands of Peer Messages Simultaneously
- The Bloom Filter Optimizer: Auditing the Performance of Data Filtering
- The IO-Bound Challenge: Navigating Disk and Network Bottlenecks during Block-Sync
- The Security: The Full Technical Specifications of `src/checkqueue.h` Multi-threading Architecture
Raw Transactions Deep Dive
Master the architecture of Bitcoin Core. Chapter 1: The Master Craftsman: Introduction to Raw Transactions. An in-depth technical analysis of the protocol's raw transactions logic.
Explore Module Lessons
- The Master Craftsman: Introduction to Raw Transactions
- The Anatomy of a Transaction: Inputs, Outputs, and the Flow of Value
- The Messenger's Toolkit: Overview of Raw RPCs
- Retrieving the Digital DNA: The `getrawtransaction` Command
- The Librarian's Index: Locating the Needle in the Blockchain Haystack
- Decoding the Secret Code: Understanding decoderawtransaction
- The Logic of the Blueprint: Deserialization in the Core
- Crafting the Future: The createrawtransaction Command
- Selecting the Stones: Choosing Inputs for the Masterpiece
- Directing the Stream: Defining Outputs in the Ledger
- The Budgeter of the Vault: How fundrawtransaction Balances the Books
- Estimating the Toll: Transaction Fees and the Messenger's Reward
- The Change Maker: Managing the Remainder of the Vault
- The Witness Data: SegWit and the Modern Proof of Ownership
- Serialization Secrets: How the Messenger Packs for Travel
- The Version Number: Ensuring Compatibility with the Network's Laws
- Locktime: The Digital Escrow and the Time-Released Ledger
- Sequence Numbers: Replace-By-Fee and the Flexibility of the Core
- From Raw Bytes to Global Consensus: The Journey of a Transaction
- The Sovereign Signer: Finality and the Power of the Individual
- The Architect's Duty: A Code of Ethics for the Ledger
Script VM and Opcodes
Master the architecture of Bitcoin Core. Chapter 1: The Heart of the Machine: Introduction to the Script VM. An in-depth technical analysis of the protocol's script vm logic.
Explore Module Lessons
- The Heart of the Machine: Introduction to the Script VM
- The Stack and the Script: How the "LIFO"logic works
- The Life of an Opcode: Analyzing the main loop in `interpreter.cpp`
- The Simple Truth: Basic Opcodes (OP_TRUE, OP_FALSE, OP_NOP)
- The Arithmetic of the Vault: Math Opcodes (OP_ADD, OP_SUB, OP_EQUAL)
- The Branching Paths: Flow Control (OP_IF, OP_ELSE, OP_ENDIF)
- The Cryptographic Keys: Signature Opcodes (OP_CHECKSIG, OP_CHECKMULTISIG)
- The Hashing Engine: Hash Opcodes (OP_SHA256, OP_HASH160)
- The Signature Cache: How the node remembers "Checked"math
- The Evolution of the Machine: Introduction to Soft Forks
- The Segregated Witness (SegWit): How BIP 141 changed the VM
- The Witness Versioning: Preparing the VM for the future
- The Taproot Revolution: BIP 341 and the Schnorr Upgrade
- The Tapscript Logic: Fine-grained controls in the Taproot era
- The Script Resource Limits: Preventing "Infinite Loops"and "Memory Bombs"
- The Stack Limits: Managing the "RAM"of the VM
- The Cleanstack Rule: Ensuring no "Leftover Truth"remains
- The Timelock Logic: OP_CLTV and OP_CSV (Locking time into the code)
- The Security Hardening: Defending against malicious scripts
- Masterclass Module 1: The Opcode Mathematical Deep Dive
Security and Attack Vectors
Essential practices for securing your keys. Discover BIP 39 passphrases, backing up seed phrases on steel, and rules of personal security and privacy.
Explore Module Lessons
- The Armor of the Sovereign: Introduction to Security
- The Safe C++ Paradigm: RAII and Smart Pointers in Core
- The Sanitization of Inputs: Preventing Buffer Overflows
- The Denial of Service (DoS) Guard: Resource exhaustion limits
- The Timing Attack Shield: Constant-time cryptography
- The Fuzzing Engine: Introduction to `src/test/fuzz`
- The Chaos of the Mesh: How fuzzer creates "Insane"inputs
- PEDAGOGICAL ANALYSIS: THE PERMANENT GUARDRAIL
- The Assertions of Truth: `Assert()` and `assume()` in the code
- The Memory Safety: Avoiding the "Dangling Pointer"threat
- Network Security: P2P message validation and handshake hardening
- The Script VM Isolation: Security boundaries of the logical engine
- The Lock Discipline: Preventing Deadlocks in the multi-threaded mind
- PEDAGOGICAL ANALYSIS: THE RECIPE
- The Hardening of the RPC: Protecting the control interface
- The Privacy by Design: Mitigating identity leaks
- The Oracle Resistance: Protecting the node from fake price feeds
- The Forensic Audit of Attacks: Analyzing historical security incidents
- PEDAGOGICAL ANALYSIS: THE GATEKEEPER
- Masterclass Module 1: The Libsecp256k1 Security Audit
Storage and Database Layer
Master the architecture of Bitcoin Core. Chapter 1: The Memory of the Sovereign: Introduction to Persistent Storage. An in-depth technical analysis of the protocol's storage logic.
Explore Module Lessons
- The Memory of the Sovereign: Introduction to Persistent Storage
- The Foundation of the Ledger: LevelDB and the `dbwrapper`
- The Current Truth: Introduction to the UTXO Set (Chainstate)
- The Map of Wealth: Analyzing the `CCoinsView` Architecture
- The Constant Search: How UTXOs are indexed for O(1) speed
- The Anatomy of a Coin: Analyzing `src/coins.h`
- The Key-Value Pairs of the Machine: How LevelDB stores `COutPoint`
- The Cache and the Disk: The `dbcache` and `FlushStateToDisk`
- The Block Index DB: Storing the headers and locations of blocks
- The Archival History: Introduction to `blk*.dat` and `rev*.dat`
- The Undo Mechanics: How `rev*.dat` allows for "Chain Reorganization\Chain Reorganization"
- The Disconnecting of Blocks: Analyzing `DisconnectBlock` logic
- The Pruning Logic: How nodes survive with limited disk space
- The Serialization Engine: How C++ objects become bytes on disk
- The Resilience of the DB: Handling crashes and corrupted data
- The UTXO Set Snapshots: Speeding up sync with pre-computed truth
- The Performance Tuning: LevelDB write buffers and compaction
- The Forensic Audit of the DB: Using `gettxoutsetinfo` to verify the supply
- The Security of the Storage: Protecting the database from unauthorized access
- The Permanent Archive: Conclusion and the future of Bitcoin storage
- The UTXO Set Snapshots: Speeding up sync with pre-computed truth
- The Performance Tuning: LevelDB write buffers and compaction
- The Forensic Audit of the DB: Using `gettxoutsetinfo` to verify the supply
- The Security of the Storage: Protecting the database from unauthorized access
- The Permanent Archive: Conclusion and the future of Bitcoin storage
Testing and QA in Core
Master the architecture of Bitcoin Core. Chapter 1: The Laboratory of the Sovereign: Introduction to the Testing Philosophy. An in-depth technical analysis of the protocol's testing logic.
Explore Module Lessons
- The Laboratory of the Sovereign: Introduction to the Testing Philosophy
- The Atomic Audit: Understanding Unit Tests in C++
- The `BOOST_AUTO_TEST_CASE`: The Syntax of Verification
- The Mocking of the World: Isolating Code in the Lab
- The Functional Simulation: Introduction to the Python Test Suite
- The `BitcoinTestFramework`: The Architecture of the Virtual Network
- The Nodes in the Box: Orchestrating Multiple Instances
- The P2P Puppet Master: Testing Network Logic with Python
- The RPC Oracle: Verifying the Control Interface
- The Regression Guard: Preventing the Return of Past Bugs
- The Benchmarking Engine: Measuring the Speed of the Machine
- The Sanitizer Audit: Finding Memory Leaks and Data Races
- The Code Coverage Map: Finding the Dark Corners of the Repo
- The CI/CD Pipeline: The Automated Gatekeeper of the Fortress
- The Fuzzing Integration: How Randomness Strengthens the Code
- The Wallet Forensic Test: Verifying the Safety of the Vault
- The Script VM Testbed: Ensuring the Logic is Unbreakable
- The Database Resilience Test: Verifying the Memory of the Sovereign
- The Collaborative Review: How Tests Facilitate Human Trust
- The Unshakable Foundation: Conclusion and the Future of Verification
Wallet Logic and Management
Master the architecture of Bitcoin Core. Chapter 1: The Personal Sovereign: Introduction to Wallet Logic. An in-depth technical analysis of the protocol's wallet logic logic.
Explore Module Lessons
- The Personal Sovereign: Introduction to Wallet Logic
- The Wallet Control Center: Understanding the `wallet.cpp` Architecture
- The Manager of Action: The Lifecycle of the `CWallet` Class
- The Ledger of Memory: How the Wallet Tracks Transactions (`CWalletTx`)
- The Vigilant Watcher: The Science of Block Filters and Scanning
- The Identity Book: Legacy Labels vs. Modern Address Management
- The Vault’s Inventory: Tracking Unspent Transaction Outputs (UTXOs)
- The Strategy of Selection: Introduction to Coin Selection Algorithms
- The Perfect Fit: The Branch and Bound (BnB) Algorithm Explained
- The Legacy Solver: The Knapsack Algorithm for Subset Sums
- The Random Draw: Simple Random Selection for Privacy and Speed
- The Coin Grinder: Optimizing for Minimum Transaction Weight
- The Art of the Group: Grouping Outputs to Avoid Address Reuse
- The Cost of Movement: Fee Calculation and Estimation Logic
- The Change Architect: Calculating and Managing Change Outputs
- The Draftsmanship of Truth: Building the Transaction Template
- The Safety Audit: Validation and Consistency Checks
- The Privacy Shield: Avoiding Common Input Ownership Heuristics
- The Wallet RPC Interface: Controlling the Bank through Code
- The Sovereign Banker’s Oath: Reflections on Self-Custody and Code
Wallet Storage and Encryption
Master the architecture of Bitcoin Core. Chapter 1: The Persistence of Power: How the Internal Bank Saves its Truth. An in-depth technical analysis of the protocol's wallet storage logic.
Explore Module Lessons
- The Persistence of Power: How the Internal Bank Saves its Truth
- The Old Guardian: The BerkeleyDB Legacy Architecture
- The Modern Vault: The SQLite and Descriptor Revolution
- The Seamless Transition: The Logic of Wallet Migration
- The Fortress of Secrets: Introduction to Wallet Encryption
- The Stretching of the Key: Scrypt and Computational Hardness
- The Symmetric Shield: AES-256 and the Master Key
- The Source of Infinity: The HD Seed and Master Secret
- The Tree of Wealth: BIP32 and Hierarchical Determinism
- The Key Manager's Ledger: The Role of `ScriptPubKeyMan`
- The Blueprint of Ownership: Storing Descriptor-Based Wallets
- The Anatomy of `wallet.dat`: Records, Keys, and Metadata
- The Atomic Transaction: How Database Batches Prevent Corruption
- The Art of the Recovery: Mnemonic Seeds and Path Logic
- The Memory Sanitizer: Protecting Keys from Physical Memory Leaks
- The Encrypted Master Key: How the Node Unlocks its Wealth
- The Salt of the Earth: Randomness and Salt in Key Generation
- The Storage of Identity: How Labels and Purpose are Saved
- The Powerless Observer: Storing Watch-Only Data Safely
- The Architect's Final Decree: Sovereignty Through Persistence
Digital Nervous System: Validation
Master the architecture of Bitcoin Core. Chapter 1: The Vision of Modular Sovereignty: Beyond the Monolith. An in-depth technical analysis of the protocol's core validation engine logic.
Explore Module Lessons
Digital Nervous System: Network & Memory
Master the architecture of Bitcoin Core. Chapter 6: The Evolution of Communication: From JSON-RPC to Modern REST. An in-depth technical analysis of the protocol's network memory mechanics logic.
Digital Nervous System: Sovereignty & Crypto
Master the architecture of Bitcoin Core. Chapter 10: Descriptor Wallets: The Future of Key Management and Output Scripts. An in-depth technical analysis of the protocol's programmable sovereignty crypto logic.
Explore Module Lessons
- Descriptor Wallets: The Future of Key Management and Output Scripts
- Miniscript: Programmable Sovereignty for the Next Generation
- The libsecp256k1 Evolution: Preparing for MuSig2 and Beyond
- Fuzzing and Formal Verification: The Armor of the Future
- The FlatFile Versioning Strategy: Managing Decades of History
- The CDataStream Refactor: Modernizing the Serialization Engine
Digital Nervous System: Resilience
Master the architecture of Bitcoin Core. Chapter 16: The Package Relay Strategy: Solving the CPFP Limits. An in-depth technical analysis of the protocol's network resilience synthesis logic.
Explore Module Lessons
Core Source Explanation
Deep-dive analysis of Bitcoin Core source code. Technical Context: `private_broadcast.h` | Lines 141-147
Explore Module Lessons
- The Architecture of Priority: Tracking Attempts and Confirmations
- The Inquiry of Certainty: Boolean Success and the Peer Audit
- The Chronology of Truth: Time-Stamping and Transaction Referencing
- The Unroutable Void and the Support for CJDNS
- The Collection of Worlds: Iterating the Network Topology
- The Feedback Loop: Confirmation Timeouts and Peer Identity
- The Convenience Wrapper: Bonding Transactions and Status
- The Data Repositories and the Mission Statement
- The Dependency Matrix: Networking, Synchronization, and Time
- The Equality Contract and the Derivation of Priority
- The Exclusive Contract: Thread Safety and the Art of Forgetting
- The Filtered Registry and the Boundary of Visibility
- The Full Audit: Transparency through `GetBroadcastInfo` and the Boundary of Privacy
- Functional Logic and the Unix Domain Socket Bridge
- The Genesis Copyright: Satoshi Nakamoto and the Build Foundation
- The Graceful Retreat: Handling Irrecoverable Network Failure
- The Guardian and the Map: The Core of the Private Broadcast Engine
- Intent Memory: The `GetTxForNode` Inquiry and Architectural State
- The Interface and the Compatibility Layer: Connecting to the World
- The Moment of Selection: Timestamps and the Internal Constructor
- Internal Networks and the Compiler's Warning
- Internal Status: The Const Identity of Network Peers
- The Global Future: IPv6 and the Scope of the Connection
- The Cleanup of the Kernel and the Global Callback
- The Linked List Traversal and the IPv4 Extraction
- The Logic of the Hash: Determinism and Memory Safety
- The Loopback Workaround: Resilience through Recursive Failure Handling
- The Internal Contract: Mandatory Locking and the `TxSendStatus` Record
- The Numerical Shield and the Execution of the Search
- The Recipient Roster and the Admission Protocol
- The Signal of Action: Monitoring the Pending Queue
- The Physics of Patience: Timeouts and Thread Interrupts
- The Confirmation Handshake: PING, PONG, and the Proof of Reception
- The `PrivateBroadcast` Class and the Architecture of Stall Detection
- The Sovereignty of the License: An Architectural Prelude
- The Architectural Synthesis of Private Broadcasting
- The Protocol Choice and the Family of Addresses
- The Proxy Engine: Global State and the Guardian of Privacy
- The Topology of Reachability: Mapping the Global Network
- The Metrics of Removal: Success Tracking and Optionality
- The Fairness Algorithm: Picking the Next Transaction
- The Semantic Mirror: Reflecting Enums into Human Language
- The Spaceship Operator: Modern C++ and the Logic of Inverted Priority
- The Inventory of the Stale: Resilience through Systematic Re-evaluation
- The Static Engine: Deriving Priority from Peer Context
- String Encoding and the Atomic Nature of Time
- The Taxonomy of Networks: Categorizing the Global Internet
- The Transaction Lifecycle: From Admission to Confirmation
- The Urgency Metric: Delivering the Payload
- The Witness Hash and the Logic of Identity
TeachMeBitcoin is an ad-free, open-source educational repository curated by a passionate team of Bitcoin researchers and educators for public benefit. If you found our articles helpful, please consider supporting our hosting and ongoing content updates with a clean donation: