从零开始:用简单代码理解区块链的核心应用


区块链,这个近年来炙手可热的技术名词,常常与比特币、加密货币等联系在一起,给人一种高深莫测的感觉,但实际上,区块链的核心思想——去中心化、不可篡改、透明可追溯——可以通过一些简单的代码应用来直观地理解,本文将带您抛开复杂的理论,通过一个基础的“简单区块链”实现和一个小型应用示例,感受区块链的魅力。

什么是区块链?简单来说

想象一个公开的、由多人共同维护的账本,每一页账页(称为“区块”)都记录了一段时间内的所有交易信息,当这一页记满后,它会通过一种特殊的加密方式(哈希算法)与前一页账页“链接”起来,形成一个链条(即“区块链”),任何人都很难篡改某一页的信息,因为一旦改动,后面所有的链接都会断裂,会被其他维护者轻易发现,这就是区块链的“不可篡改”和“去中心化”特性。

一个简单的区块链Python实现

为了更好地理解,我们用Python来构建一个极简版的区块链,这个区块链将包含区块的基本结构:索引、时间戳、数据、前一个区块的哈希值,以及当前区块的哈希值。

import hashlib
import time
class Block:
    def __init__(self, index, previous_hash, timestamp, data, hash):
        self.index = index
        self.previous_hash = previous_hash
        self.timestamp = timestamp
        self.data = data
        self.hash = hash
def calculate_hash(index, previous_hash, timestamp, data):
    """
    计算区块的哈希值
    """
    value = str(index) + str(previous_hash) + str(timestamp) + str(data)
    return hashlib.sha256(value.encode('utf-8')).hexdigest()
def create_genesis_block():
    """
    创建创世区块(第一个区块)
    """
    return Block(0, "0", time.time(), "Genesis Block", calculate_hash(0, "0", time.time(), "Genesis Block"))
def create_new_block(previous_block, data):
    """
    创建新区块
    """
    index = previous_block.index + 1
    timestamp = time.time()
    hash = calculate_hash(index, previous_block.hash, timestamp, data)
    return Block(index, previous_block.hash, timestamp, data, hash)
blockchain = [create_genesis_block()]
previous_block = blockchain[0]
# 添加几个区块
for i in range(1, 4):
    new_data = f"Block {i} data: This is a simple transaction {i}"
    new_block = create_new_block(previous_block, new_data)
    blockchain.append(new_block)
    previous_block = new_block
    print(f"Block #{new_block.index} has been added to the blockchain!")
    print(f"Hash: {new_block.hash}\n")
# 打印区块链
print("Blockchain:")
for block in blockchain:
    print(f"Index: {block.index}")
    print(f"Previous Hash: {block.previous_hash}")
    print(f"Timestamp: {block.timestamp}")
    print(f"Data: {block.data}")
    print(f"Hash: {block.hash}")
    print("-" * 20)

代码解析:

  1. Block类:定义了区块的属性,包括索引、前一个哈希、时间戳、数据和当前哈希。
  2. calculate_hash函数:使用SHA-256哈希算法,根据区块的各项内容计算出一个唯一的哈希值,这个哈希值是区块的“身份证”。
  3. 随机配图