比特币核心技术解析:从区块链到交易验证
比特币核心技术解析:从区块链到交易验证
ZlionWelcome to the technical world of Bitcoin! This post dives into the core technologies that power Bitcoin’s decentralized system. For more details, check Bitcoin Developer Documentation or discuss on Bitcoin Stack Exchange.
Bitcoin Core Technologies
- Blockchain: The Decentralized Ledger
Bitcoin’s blockchain is a distributed, immutable ledger that records all transactions. Each “block” contains transaction data and links to the previous block, forming a chain.
Key Structure of a Bitcoin Block
Component
Description
Magic Number
4-byte identifier (0xD9B4BEF9) to mark the start of a block
Block Size
4-byte field indicating block length (max 4MB since SegWit)
Block Header
80-byte metadata (version, previous block hash, merkle root, timestamp, etc.)
Transaction Count
Variable-length integer of transactions in the block
Transactions
List of transactions (coinbase transaction first)
Merkle Tree: Efficient Transaction Verification
Merkle Tree (or Hash Tree) compresses transaction data into a single merkle root (32-byte hash) in the block header. Example of hash calculation:
import hashlib
def double_sha256(data):
# Bitcoin uses SHA-256 twice for hashing
return hashlib.sha256(hashlib.sha256(data).digest()).digest()
Simulate 4 transactions (Tx1-Tx4)
tx_hashes = [
double_sha256(b”Transaction 1 Data”),
double_sha256(b”Transaction 2 Data”),
double_sha256(b”Transaction 3 Data”),
double_sha256(b”Transaction 4 Data”)
]
Calculate merkle root (pair and hash recursively)
def compute_merkle_root(tx_hashes):
if len(tx_hashes) == 1:
return tx_hashes[0]
new_hashes = []
# Pair hashes (duplicate last if odd count)
for i in range(0, len(tx_hashes), 2):
if i+1 == len(tx_hashes):
combined = tx_hashes[i] + tx_hashes[i]
else:
combined = tx_hashes[i] + tx_hashes[i+1]
new_hashes.append(double_sha256(combined))
return compute_merkle_root(new_hashes)
merkle_root = compute_merkle_root(tx_hashes)
print(f”Merkle Root (hex): {merkle_root.hex()}”)
More info: Bitcoin Block Structure
2. Proof of Work (PoW): Securing the Network
PoW is Bitcoin’s consensus mechanism to validate blocks and prevent double-spending. Miners compete to solve a cryptographic puzzle:
The PoW Puzzle
Find a nonce (32-bit number) such that the block header’s double SHA-256 hash meets a difficulty target (starts with N leading zeros):
Example: Check if a block header hash meets target (simplified)
Target: Hash must start with “000000” (adjusted dynamically by the network)
block_header = “0100000000000000000000000000000000000000000000000000000000000000000000003ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a29ab5f49ffff001d1dac2b7c”
nonce = 2573394689 # Valid nonce for the first Bitcoin block (Genesis Block)
Combine header and nonce, compute double SHA-256
combined = block_header + format(nonce, ‘08x’) # Nonce as 8-byte hex
hash_result = hashlib.sha256(hashlib.sha256(bytes.fromhex(combined)).digest()).digest()
hash_hex = hash_result[::-1].hex() # Bitcoin uses little-endian for hash display
print(f”Block Hash: {hash_hex}”) # Should start with “000000000019d6689c085ae165831e93…”
Difficulty Adjustment
The network adjusts the PoW difficulty every 2016 blocks (≈2 weeks) to keep the block time at ~10 minutes:
New Difficulty = Old Difficulty * (2016 * 10 minutes) / Actual Time to Mine 2016 Blocks
More info: Bitcoin Proof of Work
3. Transaction Verification: How Bitcoin Moves
Bitcoin transactions transfer ownership of “unspent transaction outputs” (UTXOs) — no actual “coins” exist, only records of UTXOs.
Step 1: Transaction Structure
A valid transaction includes:
Version: Transaction format version
Inputs: List of UTXOs to spend (each with previous transaction hash, output index, and signature)
Outputs: List of new UTXOs (each with recipient’s public key hash and amount)
Locktime: Time/block when the transaction becomes valid
Step 2: Signature Verification (ECDSA)
Bitcoin uses ECDSA (Elliptic Curve Digital Signature Algorithm) with the secp256k1 curve to verify ownership:
from ecdsa import SigningKey, VerifyingKey, SECP256k1
Simulate a user’s key pair (private key → public key → address)
private_key = SigningKey.generate(curve=SECP256k1) # User’s private key
public_key = private_key.get_verifying_key() # Public key (shared openly)
User signs a transaction hash
tx_hash = double_sha256(b”Transaction Data: Send 0.5 BTC to Address X”)
signature = private_key.sign(tx_hash)
Network verifies the signature (only needs public key and tx hash)
is_valid = public_key.verify(signature, tx_hash)
print(f”Signature Valid: {is_valid}”) # Returns True if ownership is confirmed
Step 3: UTXO Validation
Nodes check:
The referenced UTXOs exist and are unspent
The signature matches the UTXO’s owner’s public key
Total outputs ≤ total inputs (no double-spending)
More info: Bitcoin Transaction Format
4. P2P Network: Decentralized Communication
Bitcoin nodes (miners, full nodes, light nodes) communicate via a peer-to-peer network to:
Propagate transactions (unconfirmed txs go to the “mempool”)
Sync blocks (new blocks are broadcast to all nodes)
Discover peers (via DNS seeds or existing peers)
Key P2P Protocol Messages
Message Type
Purpose
version
Handshake: Exchange node version/block height
inv
Notify peers of new blocks/transactions
getdata
Request full block/transaction data
block
Send full block data
More info: Bitcoin P2P Protocol






