# 区块链的基本概念和架构

## 1. 区块的概念和结构

• 前一区块的哈希值（previous_hash）：指向前一个区块的哈希值，确保区块之间的连接。
• 时间戳（timestamp）：记录区块的创建时间。
• 交易数据（transactions）：记录在该区块中包含的交易信息。
• 随机数（nonce）：用于工作量证明机制的计算过程中。

``````import hashlib
import time

class Block:
def __init__(self, previous_hash, transactions):
self.previous_hash = previous_hash
self.timestamp = time.time()
self.transactions = transactions
self.nonce = 0

def calculate_hash(self):
data = str(self.previous_hash) + str(self.timestamp) + str(self.transactions) + str(self.nonce)
return hashlib.sha256(data.encode()).hexdigest()

# 创建一个区块
block1 = Block("0", ["transaction1", "transaction2"])
print("Block 1 Hash:", block1.calculate_hash())
``````

## 2. 哈希函数和哈希指针

``````# 计算哈希值
data = "Hello, World!"
hash_value = hashlib.sha256(data.encode()).hexdigest()
print("Hash Value:", hash_value)
``````

## 3. 共识机制

``````import hashlib

def proof_of_work(block, difficulty):
target = "0" * difficulty  # 设置目标哈希前导零的个数
while True:
block.nonce += 1
block_hash = block.calculate_hash()
if block_hash[:difficulty] == target:
return block_hash

# 创建一个区块并进行工作量证明
block2 = Block(block1.calculate_hash(), ["transaction3", "transaction4"])
difficulty = 4  # 设置难度为4
block2_hash = proof_of_work(block2, difficulty)
print("Block 2 Hash:", block2_hash)
``````

## 4. 区块链网络

``````class Blockchain:
def __init__(self):
self.chain = [self.create_genesis_block()]

def create_genesis_block(self):
return Block("0", ["genesis"])

block.previous_hash = self.chain[-1].calculate_hash()
block_hash = proof_of_work(block, difficulty)
self.chain.append(block)

# 创建一个区块链并添加区块
blockchain = Blockchain()
print("Blockchain Length:", len(blockchain.chain))
``````

## 5. 实际应用示例

``````import hashlib
import time

class Transaction:
self.sender = sender
self.amount = amount
self.timestamp = time.time()

def calculate_hash(self):
data = str(self.sender) + str(self.receiver) + str(self.amount) + str(self.timestamp)
return hashlib.sha256(data.encode()).hexdigest()

class Block:
def __init__(self, previous_hash, transactions):
self.previous_hash = previous_hash
self.timestamp = time.time()
self.transactions = transactions
self.nonce = 0
self.hash = self.calculate_hash()

def calculate_hash(self):
data = str(self.previous_hash) + str(self.timestamp) + str(self.transactions) + str(self.nonce)
return hashlib.sha256(data.encode()).hexdigest()

class Blockchain:
def __init__(self):
self.chain = [self.create_genesis_block()]

def create_genesis_block(self):
return Block("0", ["genesis"])

block.previous_hash = self.chain[-1].hash
block.hash = block.calculate_hash()
self.chain.append(block)

return transaction

# 创建一个供应链的区块链
blockchain = Blockchain()

# 创建并添加第一个区块
transaction1 = blockchain.create_transaction("Manufacturer A", "Distributor A", 100)
block1 = Block(blockchain.chain[-1].hash, [transaction1])

# 创建并添加第二个区块
transaction2 = blockchain.create_transaction("Distributor A", "Retailer A", 50)
transaction3 = blockchain.create_transaction("Distributor A", "Retailer B", 50)
block2 = Block(blockchain.chain[-1].hash, [transaction2, transaction3])

# 输出整个供应链的区块链信息
for block in blockchain.chain:
print("Block Hash:", block.hash)
print("Transactions:")
for transaction in block.transactions:
if "genesis" == transaction:
continue
print("- Sender:", transaction.sender)
print("- Amount:", transaction.amount)
print("- Timestamp:", transaction.timestamp)
print("----------")
``````

THE END