下面是“用不到50行的Python代码构建最小的区块链”的完整攻略。
1. 准备工作
我们需要在本地安装Python3和Flask框架。
2. 创建一个最小的区块链
我们需要定义一些模块,包括区块、链和挖矿。具体代码如下:
import datetime
import hashlib
import json
from flask import Flask, jsonify
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()
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_valid_chain(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
def __str__(self):
return json.dumps([block.__dict__ for block in self.chain], indent=2)
blockchain = Blockchain()
class Mining:
@staticmethod
def mine_block(data):
new_block = Block(len(blockchain.chain), datetime.datetime.now(), data, blockchain.get_latest_block().hash)
blockchain.add_block(new_block)
app = Flask(__name__)
@app.route('/')
def index():
return "Welcome to the blockchain!"
@app.route('/blockchain', methods=['GET'])
def get_blockchain():
return blockchain.__str__()
@app.route('/mine_block/<data>', methods=['GET'])
def mine_block(data):
Mining.mine_block(data)
return "Block mined and added to the blockchain!"
if __name__ == '__main__':
app.run(debug=True, port=5000)
3. 运行应用程序
运行上述代码后,在浏览器中访问http://localhost:5000/
,即可看到“Welcome to the blockchain!”的欢迎信息。
此时,我们已经成功创建了一个最小的区块链,并可以通过访问http://localhost:5000/blockchain
获取到区块链的详细信息。
4. 挖掘新块
我们可以通过访问http://localhost:5000/mine_block/<data>
来挖掘一个新块,并将其添加到区块链中。
例如,我们访问http://localhost:5000/mine_block/Hello%20World!
即可挖掘一个包含“Hello World!”数据的新块。
5. 示例说明
下面是两个关于如何使用该区块链的示例说明:
示例1
我们可以用这个区块链来记录一些重要事件的发生时间,如下所示:
@app.route('/event/<event_name>', methods=['POST'])
def add_event(event_name):
event_time = datetime.datetime.now()
Mining.mine_block(f"{event_name} occurred at {event_time}.")
return "Event added to the blockchain!"
这个路由可以将一个事件的名称作为URL参数传递,然后在区块链上创建一个包含事件名称和发生时间的新块。
示例2
我们可以用这个区块链来记录一些重要的交易,如下所示:
class Transaction:
def __init__(self, sender, receiver, amount):
self.sender = sender
self.receiver = receiver
self.amount = amount
transactions = []
@app.route('/transaction', methods=['POST'])
def add_transaction():
data = request.get_json()
new_transaction = Transaction(data['sender'], data['receiver'], data['amount'])
transactions.append(new_transaction)
return "Transaction added to the pending transactions!"
@app.route('/mine_transactions', methods=['GET'])
def mine_transactions():
Mining.mine_block(json.dumps([transaction.__dict__ for transaction in transactions]))
transactions.clear()
return "Transactions mined and added to the blockchain!"
@app.route('/pending_transactions', methods=['GET'])
def get_pending_transactions():
return json.dumps([transaction.__dict__ for transaction in transactions])
这些路由允许我们添加新的交易到待处理的交易列表中,在适当的时候挖掘这些交易,并将它们添加到区块链中。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:用不到50行的Python代码构建最小的区块链 - Python技术站