用python实现区块链功能
时间: 2023-09-20 20:05:02 浏览: 103
实现区块链需要使用Python编程语言,下面是一个简单的示例。
首先,我们需要定义一个Block类来表示区块:
```python
import hashlib
import datetime as date
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 = hashlib.sha256()
sha.update(str(self.index).encode('utf-8') +
str(self.timestamp).encode('utf-8') +
str(self.data).encode('utf-8') +
str(self.previous_hash).encode('utf-8'))
return sha.hexdigest()
```
然后,我们需要定义一个Blockchain类来表示整个区块链:
```python
class Blockchain:
def __init__(self):
self.chain = [self.create_genesis_block()]
def create_genesis_block(self):
# Manually construct a block with
# index zero and arbitrary previous hash
return Block(0, date.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
```
现在,我们可以创建一个区块链并添加一些块:
```python
# Create the blockchain and add the genesis block
blockchain = Blockchain()
# Add some blocks to the chain
blockchain.add_block(Block(1, date.datetime.now(), "Block 1", ""))
blockchain.add_block(Block(2, date.datetime.now(), "Block 2", ""))
blockchain.add_block(Block(3, date.datetime.now(), "Block 3", ""))
```
最后,我们可以验证整个区块链是否有效:
```python
# Check if the blockchain is valid
print("Is blockchain valid? ", blockchain.is_chain_valid())
```
完整的代码如下:
```python
import hashlib
import datetime as date
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 = hashlib.sha256()
sha.update(str(self.index).encode('utf-8') +
str(self.timestamp).encode('utf-8') +
str(self.data).encode('utf-8') +
str(self.previous_hash).encode('utf-8'))
return sha.hexdigest()
class Blockchain:
def __init__(self):
self.chain = [self.create_genesis_block()]
def create_genesis_block(self):
# Manually construct a block with
# index zero and arbitrary previous hash
return Block(0, date.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
# Create the blockchain and add the genesis block
blockchain = Blockchain()
# Add some blocks to the chain
blockchain.add_block(Block(1, date.datetime.now(), "Block 1", ""))
blockchain.add_block(Block(2, date.datetime.now(), "Block 2", ""))
blockchain.add_block(Block(3, date.datetime.now(), "Block 3", ""))
# Check if the blockchain is valid
print("Is blockchain valid? ", blockchain.is_chain_valid())
```
阅读全文