区块链做食品溯源
构建区块链水产品溯源系统的代码示例
```python
from hashlib import sha256
import json
import datetime
class Block:
def __init__(self, index, timestamp, data, previous_hash):
self.index = index
self.timestamp = timestamp
self.data = data
self.previous_hash = previous_hash
self.hash = self.calculate_hash()
def calculate_hash(self):
sha = sha256()
sha.update((str(self.index)
str(self.timestamp)
str(self.data)
str(self.previous_hash)).encode())
return sha.hexdigest()
class Blockchain:
def __init__(self):
self.chain = [self.create_genesis_block()]
def create_genesis_block(self):
return Block(0, datetime.datetime.now(), "Genesis Block", "0")
def get_latest_block(self):
return self.chain[1]
def add_block(self, new_block):
new_block.previous_hash = self.get_latest_block().hash
new_block.hash = new_block.calculate_hash()
self.chain.append(new_block)
def is_chain_valid(self):
for i in range(1, len(self.chain)):
current_block = self.chain[i]
previous_block = self.chain[i 1]
if current_block.hash != current_block.calculate_hash():
return False
if current_block.previous_hash != previous_block.hash:
return False
return True
示例:水产品溯源
class WaterProduct:
def __init__(self, producer, product_name, production_date, location):
self.producer = producer
self.product_name = product_name
self.production_date = production_date
self.location = location
def to_dict(self):
return {
"producer": self.producer,
"product_name": self.product_name,
"production_date": self.production_date,
"location": self.location
}
示例:创建水产品
water_product_1 = WaterProduct("Ocean Farms Ltd.", "Atlantic Salmon", "20240425", "Norway")
water_product_2 = WaterProduct("Fresh Catch Inc.", "Tuna", "20240426", "Pacific Ocean")
示例:创建区块链
blockchain = Blockchain()
示例:添加水产品溯源信息到区块链
blockchain.add_block(Block(1, datetime.datetime.now(), water_product_1.to_dict(), ""))
blockchain.add_block(Block(2, datetime.datetime.now(), water_product_2.to_dict(), ""))
示例:验证区块链有效性
print("Is blockchain valid? ", blockchain.is_chain_valid())
示例:输出区块链信息
print(json.dumps([vars(block) for block in blockchain.chain], indent=4))
```
此示例演示了如何使用Python构建简单的区块链系统,用于水产品溯源。在这个示例中,定义了区块和区块链的类,以及一个水产品类。水产品类用于表示水产品的基本信息,如生产商、产品名称、生产日期和地点。示例创建了两个水产品对象,并将其添加到区块链中。验证了区块链的有效性,并输出了区块链的信息。