Chapter 2: Blockchain Technology Principles

Haiyue
9min

Chapter 2: Blockchain Technology Principles

Learning Objectives
  • Understand the basic structure and working principles of blockchain
  • Master core concepts such as hash functions and digital signatures
  • Learn about the characteristics of decentralized networks
  • Understand the role of consensus mechanisms

Basic Blockchain Structure

Block Structure

Blockchain is a chain data structure composed of a series of blocks, with each block containing the following main components:

import hashlib
import time
import json
from typing import List, Dict, Any

class Block:
    """Block class definition"""
    def __init__(self, index: int, transactions: List[Dict], previous_hash: str, nonce: int = 0):
        self.index = index                    # Block index
        self.timestamp = time.time()          # Timestamp
        self.transactions = transactions      # Transaction list
        self.previous_hash = previous_hash    # Previous block hash
        self.nonce = nonce                   # Nonce (for mining)
        self.merkle_root = self._calculate_merkle_root()  # Merkle root
        self.hash = self._calculate_hash()    # Block hash

    def _calculate_hash(self) -> str:
        """Calculate block hash"""
        block_string = json.dumps({
            "index": self.index,
            "timestamp": self.timestamp,
            "transactions": self.transactions,
            "previous_hash": self.previous_hash,
            "merkle_root": self.merkle_root,
            "nonce": self.nonce
        }, sort_keys=True)

        return hashlib.sha256(block_string.encode()).hexdigest()

    def _calculate_merkle_root(self) -> str:
        """Calculate Merkle root"""
        if not self.transactions:
            return hashlib.sha256("".encode()).hexdigest()

        # Simplified Merkle tree calculation
        tx_hashes = [
            hashlib.sha256(json.dumps(tx, sort_keys=True).encode()).hexdigest()
            for tx in self.transactions
        ]

        while len(tx_hashes) > 1:
            new_hashes = []
            for i in range(0, len(tx_hashes), 2):
                if i + 1 < len(tx_hashes):
                    combined = tx_hashes[i] + tx_hashes[i + 1]
                else:
                    combined = tx_hashes[i] + tx_hashes[i]  # Duplicate last one if odd
                new_hashes.append(hashlib.sha256(combined.encode()).hexdigest())
            tx_hashes = new_hashes

        return tx_hashes[0]

    def mine_block(self, difficulty: int) -> None:
        """Mining process: finding a hash that meets difficulty requirements"""
        target = "0" * difficulty

        print(f"Starting to mine block #{self.index}, difficulty: {difficulty}")
        start_time = time.time()

        while self.hash[:difficulty] != target:
            self.nonce += 1
            self.hash = self._calculate_hash()

        end_time = time.time()
        print(f"Mining successful! Time elapsed: {end_time - start_time:.2f} seconds, nonce: {self.nonce}")
        print(f"Block hash: {self.hash}")

# Create example block
transactions = [
    {"from": "Alice", "to": "Bob", "amount": 50, "fee": 1},
    {"from": "Bob", "to": "Charlie", "amount": 25, "fee": 0.5}
]

genesis_block = Block(0, [], "0")  # Genesis block
print(f"Genesis block hash: {genesis_block.hash}")

# Create second block and mine
block1 = Block(1, transactions, genesis_block.hash)
block1.mine_block(difficulty=4)  # Difficulty of 4 (needs 4 leading zeros)

Blockchain Data Structure

🔄 正在渲染 Mermaid 图表...

Hash Functions and Cryptographic Fundamentals

Hash Function Properties

Hash functions are core cryptographic tools of blockchain with the following important properties:

import hashlib

class HashFunction:
    """Hash function demonstration class"""

    @staticmethod
    def sha256_hash(data: str) -> str:
        """Calculate SHA-256 hash"""
        return hashlib.sha256(data.encode()).hexdigest()

    @staticmethod
    def demonstrate_properties():
        """Demonstrate important properties of hash functions"""
        print("=== Hash Function Properties Demo ===\n")

        # 1. Deterministic: same input produces same output
        message1 = "Hello, Blockchain!"
        hash1_a = HashFunction.sha256_hash(message1)
        hash1_b = HashFunction.sha256_hash(message1)
        print(f"Deterministic test:")
        print(f"Input: {message1}")
        print(f"Hash1: {hash1_a}")
        print(f"Hash2: {hash1_b}")
        print(f"Same? {hash1_a == hash1_b}\n")

        # 2. Avalanche effect: tiny change leads to completely different output
        message2 = "Hello, Blockchain!"  # Exactly the same
        message3 = "Hello, blockchain!"  # Only case difference
        hash2 = HashFunction.sha256_hash(message2)
        hash3 = HashFunction.sha256_hash(message3)
        print(f"Avalanche effect test:")
        print(f"Message1: {message2}")
        print(f"Hash1: {hash2}")
        print(f"Message2: {message3}")
        print(f"Hash2: {hash3}")
        print(f"Hamming distance: {HashFunction.hamming_distance(hash2, hash3)}\n")

        # 3. Fixed-length output
        short_msg = "Hi"
        long_msg = "This is a very long message that contains much more information than the previous short message, but the hash output length remains the same."
        short_hash = HashFunction.sha256_hash(short_msg)
        long_hash = HashFunction.sha256_hash(long_msg)
        print(f"Fixed-length output test:")
        print(f"Short message hash length: {len(short_hash)}")
        print(f"Long message hash length: {len(long_hash)}")
        print(f"Same length? {len(short_hash) == len(long_hash)}\n")

        # 4. Computational efficiency
        import time
        test_data = "Blockchain" * 1000  # Repeated 1000 times
        start_time = time.time()
        for _ in range(10000):  # Calculate 10000 times
            HashFunction.sha256_hash(test_data)
        end_time = time.time()
        print(f"Computational efficiency test:")
        print(f"Time for 10000 hash calculations: {end_time - start_time:.4f} seconds")

    @staticmethod
    def hamming_distance(hash1: str, hash2: str) -> int:
        """Calculate Hamming distance between two hashes"""
        # Convert to binary and count different bits
        bin1 = bin(int(hash1, 16))[2:].zfill(256)
        bin2 = bin(int(hash2, 16))[2:].zfill(256)
        return sum(b1 != b2 for b1, b2 in zip(bin1, bin2))

# Demonstrate hash function properties
HashFunction.demonstrate_properties()

(Content continues with Merkle Trees, Digital Signatures, P2P Networks, and Consensus Mechanisms sections - truncated for brevity)

Chapter Summary

Through this chapter, we have gained in-depth understanding of the core principles of blockchain technology:

  1. Blockchain Structure:

    • Basic components of a block: block header, transaction list, Merkle root
    • Chain structure: previous block hash ensures data integrity
  2. Cryptographic Fundamentals:

    • Hash functions: deterministic, avalanche effect, fixed output length
    • Merkle tree: efficiently verify integrity of large amounts of data
    • Digital signatures: ensure transaction authenticity and non-repudiation
  3. Decentralized Networks:

    • P2P architecture: no single point of failure, data redundancy
    • Node types: full nodes, light nodes, miner nodes
    • Message propagation: broadcast mechanism for transactions and blocks
  4. Consensus Mechanisms:

    • Proof of Work (PoW): obtaining accounting rights through computational competition
    • Proof of Stake (PoS): selecting validators based on stake

These technical components together form the technological foundation of the blockchain system, providing reliable guarantees for the secure operation of cryptocurrency. In the next chapter, we will analyze the implementation details of the first successful cryptocurrency system using Bitcoin as an example.