用python实现区块链系统
时间: 2023-10-15 16:04:29 浏览: 171
实现一个完整的区块链系统需要多个部分,包括区块、交易、钱包、网络传输等。下面是一个简单的示例代码,实现了一个简化版的区块链系统。
1. 定义区块类
```python
import hashlib
import json
from time import time
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):
block_string = json.dumps(self.__dict__, sort_keys=True)
return hashlib.sha256(block_string.encode()).hexdigest()
```
2. 定义区块链类
```python
class Blockchain:
def __init__(self):
self.chain = [self.create_genesis_block()]
def create_genesis_block(self):
return Block(0, time(), "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
```
3. 测试代码
```python
blockchain = Blockchain()
blockchain.add_block(Block(1, time(), {"amount": 4}))
blockchain.add_block(Block(2, time(), {"amount": 8}))
print("Blockchain is valid: ", blockchain.is_chain_valid())
# 修改区块数据,测试区块链是否仍然有效
blockchain.chain[1].data = {"amount": 100}
print("Blockchain is valid: ", blockchain.is_chain_valid())
```
运行上面的测试代码,会输出以下结果:
```
Blockchain is valid: True
Blockchain is valid: False
```
以上是一个简化版的区块链系统实现,真正的区块链系统需要更复杂的设计和实现。
阅读全文