python 区块链代码实现
时间: 2023-08-04 08:09:51 浏览: 220
python实现简单的区块链
区块链是一个分布式的、不可篡改的数据库,可以用于记录交易或其他数据的链式结构。下面是一个简单的 Python 区块链代码实现示例:
```python
import hashlib
import json
from time import time
class Blockchain:
def __init__(self):
self.chain = []
self.current_transactions = []
self.create_block(proof=1, previous_hash='0')
def create_block(self, proof, previous_hash):
block = {
'index': len(self.chain) + 1,
'timestamp': time(),
'transactions': self.current_transactions,
'proof': proof,
'previous_hash': previous_hash
}
self.current_transactions = []
self.chain.append(block)
return block
def new_transaction(self, sender, recipient, amount):
self.current_transactions.append({
'sender': sender,
'recipient': recipient,
'amount': amount
})
return self.last_block['index'] + 1
@staticmethod
def hash(block):
block_string = json.dumps(block, sort_keys=True).encode()
return hashlib.sha256(block_string).hexdigest()
@property
def last_block(self):
return self.chain[-1]
def proof_of_work(self, last_proof):
proof = 0
while self.valid_proof(last_proof, proof) is False:
proof += 1
return proof
@staticmethod
def valid_proof(last_proof, proof):
guess = f'{last_proof}{proof}'.encode()
guess_hash = hashlib.sha256(guess).hexdigest()
return guess_hash[:4] == "0000"
```
这是一个简单的区块链实现,包括创建区块、添加交易、工作量证明和验证等功能。你可以使用该代码作为起点,进一步扩展和优化实现。请注意,这只是一个演示示例,不适用于生产环境。
阅读全文