Chapter 3: In-Depth Analysis of Bitcoin
Chapter 3: In-Depth Analysis of Bitcoin
- Understand the creation background and design philosophy of Bitcoin
- Master Bitcoin’s technical architecture
- Understand mining mechanism and reward system
- Learn Bitcoin transaction verification process
Bitcoin’s Creation Background
Historical Background and Motivation
Bitcoin was born during the 2008 global financial crisis. The whitepaper “Bitcoin: A Peer-to-Peer Electronic Cash System” published by Satoshi Nakamoto proposed a decentralized electronic cash system.
Bitcoin’s core design goals:
- Trustless: No need to rely on third-party financial institutions
- Decentralized: No single point of control
- Immutable: Uses cryptography to ensure security
- Limited Supply: Total cap of 21 million coins
- Global Circulation: 24/7 borderless transactions
Bitcoin Technical Architecture
UTXO Model
Bitcoin uses the UTXO (Unspent Transaction Output) model, which differs from traditional account models:
from typing import Dict, List, Optional, Tuple
import hashlib
import json
import time
from dataclasses import dataclass
@dataclass
class UTXO:
"""Unspent Transaction Output"""
txid: str # Transaction ID
output_index: int # Output index
amount: float # Amount
script_pubkey: str # Locking script
address: str # Receiving address
class UTXOSet:
"""UTXO set management"""
def __init__(self):
self.utxos: Dict[str, UTXO] = {} # key: txid:index
def add_utxo(self, utxo: UTXO):
"""Add UTXO"""
key = f"{utxo.txid}:{utxo.output_index}"
self.utxos[key] = utxo
def spend_utxo(self, txid: str, output_index: int) -> Optional[UTXO]:
"""Spend UTXO"""
key = f"{txid}:{output_index}"
return self.utxos.pop(key, None)
def get_balance(self, address: str) -> float:
"""Get address balance"""
balance = 0
for utxo in self.utxos.values():
if utxo.address == address:
balance += utxo.amount
return balance
def get_utxos_for_address(self, address: str) -> List[UTXO]:
"""Get all UTXOs for an address"""
return [utxo for utxo in self.utxos.values() if utxo.address == address]
class BitcoinTransaction:
"""Bitcoin transaction"""
def __init__(self):
self.version = 1
self.inputs: List[Dict] = []
self.outputs: List[Dict] = []
self.locktime = 0
self.txid: Optional[str] = None
def add_input(self, prev_txid: str, output_index: int, signature: str):
"""Add transaction input"""
tx_input = {
"prev_txid": prev_txid,
"output_index": output_index,
"signature_script": signature,
"sequence": 0xffffffff
}
self.inputs.append(tx_input)
def add_output(self, amount: float, recipient_address: str):
"""Add transaction output"""
tx_output = {
"amount": amount,
"script_pubkey": f"OP_DUP OP_HASH160 {recipient_address} OP_EQUALVERIFY OP_CHECKSIG"
}
self.outputs.append(tx_output)
def calculate_txid(self) -> str:
"""Calculate transaction ID"""
tx_data = {
"version": self.version,
"inputs": self.inputs,
"outputs": self.outputs,
"locktime": self.locktime
}
tx_string = json.dumps(tx_data, sort_keys=True)
self.txid = hashlib.sha256(tx_string.encode()).hexdigest()
return self.txid
def calculate_fee(self, utxo_set: UTXOSet) -> float:
"""Calculate transaction fee"""
input_total = 0
# Calculate total inputs
for tx_input in self.inputs:
key = f"{tx_input['prev_txid']}:{tx_input['output_index']}"
if key in utxo_set.utxos:
input_total += utxo_set.utxos[key].amount
# Calculate total outputs
output_total = sum(output["amount"] for output in self.outputs)
return input_total - output_total
# UTXO model demonstration
print("=== UTXO Model Demonstration ===")
# Initialize UTXO set
utxo_set = UTXOSet()
# Create genesis transaction (mining reward)
genesis_utxo = UTXO(
txid="genesis_tx",
output_index=0,
amount=50.0,
script_pubkey="OP_DUP OP_HASH160 alice_pubkey OP_EQUALVERIFY OP_CHECKSIG",
address="alice_address"
)
utxo_set.add_utxo(genesis_utxo)
print(f"Alice's initial balance: {utxo_set.get_balance('alice_address')} BTC")
# Alice sends 25 BTC to Bob
tx1 = BitcoinTransaction()
tx1.add_input("genesis_tx", 0, "alice_signature")
tx1.add_output(25.0, "bob_address") # To Bob
tx1.add_output(24.9, "alice_address") # Change to Alice
tx1.calculate_txid()
print(f"\nTransaction 1 ID: {tx1.txid}")
print(f"Transaction fee: {tx1.calculate_fee(utxo_set)} BTC")
# Update UTXO set
utxo_set.spend_utxo("genesis_tx", 0) # Spend original UTXO
utxo_set.add_utxo(UTXO(tx1.txid, 0, 25.0, "", "bob_address")) # Bob's new UTXO
utxo_set.add_utxo(UTXO(tx1.txid, 1, 24.9, "", "alice_address")) # Alice's change UTXO
print(f"\nBalances after transaction:")
print(f"Alice: {utxo_set.get_balance('alice_address')} BTC")
print(f"Bob: {utxo_set.get_balance('bob_address')} BTC")
(Content continues with Script System, Mining Mechanism, Transaction Validation, and Network Protocol sections)
Chapter Summary
This chapter provides in-depth analysis of Bitcoin system’s technical implementation:
-
UTXO Model:
- Differences from account model
- Transaction input/output structure
- Change mechanism
-
Script System:
- Stack-based scripting language
- Script types like P2PKH and multisig
- Time locks and conditional payments
-
Mining Mechanism:
- Double SHA-256 Proof of Work
- Block structure and nonce search
- Difficulty adjustment algorithm
-
Transaction Validation:
- Multi-layer verification mechanism
- Script execution validation
- Double-spend detection
-
Network Protocol:
- P2P message types
- Node discovery and communication
- Data synchronization mechanism
Bitcoin, as the first successful cryptocurrency, has laid the foundation for subsequent cryptocurrency development through its design philosophy and technical implementation. In the next chapter, we will learn about the innovative features of other mainstream cryptocurrencies.