index = blockchain.new_transaction(values["sender"], values["recipient"], values["amount"])
response = {"message": f"Transaction will be added to Block {index}"}
return jsonify(response), 201
创建交易的方法
挖矿端点
我们的挖矿端点是见证奇迹的地方,它实现起来很容易。它要做三件事情:
☉ 计算工作量证明☉ 因为矿工(我们)添加一个交易而获得报酬,奖励矿工(我们) 1 个币☉ 通过将它添加到链上而打造一个新区块import hashlib
import json
from time import time
from uuid import uuid4
from flask import Flask, jsonify, request
...
@app.route("/mine", methods=["GET"])
def mine():
# We run the proof of work algorithm to get the next proof...
last_block = blockchain.last_block
last_proof = last_block["proof"]
proof = blockchain.proof_of_work(last_proof)
# We must receive a reward for finding the proof.
# The sender is "0" to signify that this node has mined a new coin.
blockchain.new_transaction(
sender="0",
recipient=node_identifier,
amount=1,
)
# Forge the new Block by adding it to the chain
previous_hash = blockchain.hash(last_block)
block = blockchain.new_block(proof, previous_hash)
response = {
"message": "New Block Forged",
"index": block["index"],
"transactions": block["transactions"],
"proof": block["proof"],
"previous_hash": block["previous_hash"],
}
return jsonify(response), 200
注意,挖掘出的区块的接收方是我们的节点地址。现在,我们所做的大部分工作都只是与我们的 Blockchain 类的方法进行交互的。到目前为止,我们已经做完了,现在开始与我们的区块链去交互。
第 3 步:与我们的区块链去交互
你可以使用简单的 cURL 或者 Postman 通过网络与我们的 API 去交互。
启动服务器:
$ python blockchain.py
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
我们通过生成一个 GET 请求到 http://localhost:5000/mine 去尝试挖一个区块:
使用 Postman 去生成一个 GET 请求
我们通过生成一个 POST 请求到 http://localhost:5000/transactions/new 去创建一个区块,请求数据包含我们的交易结构:
使用 Postman 去生成一个 POST 请求
如果你不使用 Postman,也可以使用 cURL 去生成一个等价的请求:
$ curl -X POST -H "Content-Type: application/json" -d "{
"sender": "d4ee26eee15148ee92c6cd394edd974e",
"recipient": "someone-other-address",
"amount": 5
}" "http://localhost:5000/transactions/new"
我重启动我的服务器,然后我挖到了两个区块,这样总共有了 3 个区块。我们通过请求 http://localhost:5000/chain 来检查整个区块链:
{
"chain": [
{
"index": 1,
"previous_hash": 1,
"proof": 100,
"timestamp": 1506280650.770839,
"transactions": []
},
{
"index": 2,
"previous_hash": "c099bc...bfb7",
"proof": 35293,
"timestamp": 1506280664.717925,
"transactions": [
{
"amount": 1,
"recipient": "8bbcb347e0634905b0cac7955bae152b",
"sender": "0"
}
]
},
{
"index": 3,
"previous_hash": "eff91a...10f2",
"proof": 35089,
"timestamp": 1506280666.1086972,
"transactions": [
{
"amount": 1,
"recipient": "8bbcb347e0634905b0cac7955bae152b",
"sender": "0"
}
]
}
],
"length": 3
}
第 4 步:共识
这是很酷的一个地方。我们已经有了一个基本的区块链,它可以接收交易并允许我们去挖掘出新区块。但是区块链的整个重点在于它是去中心化的decentralized。而如果它们是去中心化的,那我们如何才能确保它们表示在同一个区块链上?这就是共识Consensus问题,如果我们希望在我们的网络上有多于一个的节点运行,那么我们将必须去实现一个共识算法。
..新节点
在我们能实现一个共识算法之前,我们需要一个办法去让一个节点知道网络上的邻居节点。我们网络上的每个节点都保留有一个该网络上其它节点的..信息。因此,我们需要更多的端点:
☉ /nodes/register 以 URL 的形式去接受一个新节点列表☉ /nodes/resolve 去实现我们的共识算法,由它来解决任何的冲突 —— 确保节点有一个正确的链。我们需要去修改我们的区块链的构造函数,来提供一个..节点的方法:
...
from urllib.parse import urlparse
...
class Blockchain(object):
def __init__(self):
...
self.nodes = set()
...
def register_node(self, address):
"""
Add a new node to the list of nodes
:param address: <str> Address of node. Eg. "http://192.168.0.5:5000"
:return: None
"""
parsed_url = urlparse(address)
self.nodes.add(parsed_url.netloc)
一个添加邻居节点到我们的网络的方法
注意,我们将使用一个 set() 去保存节点列表。这是一个非常合算的方式,它将确保添加的节点是幂等idempotent的 —— 这意味着不论你将特定的节点添加多少次,它都是精确地只出现一次。
实现共识算法
正如前面提到的,当一个节点与另一个节点有不同的链时就会产生冲突。为解决冲突,我们制定一个规则,即最长的有效的链才是权威的链。换句话说就是,网络上最长的链就是事实上的区块链。使用这个算法,可以在我们的网络上节点之间达到共识。
...
import requests
class Blockchain(object)
...
def valid_chain(self, chain):
"""
Determine if a given blockchain is valid
:param chain: <list> A blockchain
:return: <bool> True if valid, False if not
"""
last_block = chain[0]
current_index = 1
while current_index < len(chain):
block = chain[current_index]
print(f"{last_block}")
print(f"{block}")
print("\n-----------\n")
# Check that the hash of the block is correct
本年5月12日是第16个全国防灾减灾日主题是“人人讲平安、个个会应急——出力提拔下层防灾避险能力”5月11日至17日为防灾减灾宣传周国度防灾减灾
近日由莆田市体育局荔城区文化体育和旅行局作为指导单元单子莆田市体育跳舞活动协会主办莆田市体育跳舞活动协会街舞专业委员会协办的“奔驰
叮!我预备了【京东卡】要给你!你的【福利】即将到账!叮!你有一张【京东卡】待查收天色逐渐转暖,属于炎天的康乐就要回来了!大排档里黏
大家好,小丽今天来为大家解答优秀护士工作总结以下问题,优秀护士工作总结自参加工作以来很多人还不知道,现在让我们一起来看看吧!1、轻基
《健康中国视察》2024年4月刊登载了题为《共建共享 健康姑苏——中国式现代化配景下的健康城市索求与实践》的封面文章聚焦姑苏健康城市扶植经
大家好,小乐今天来为大家解答送红包1314是什么意思以下问题,红包1314是多少钱很多人还不知道,现在让我们一起来看看吧!1、1314,即一生一世谐
Anna Armona 乌克兰艺术家她的水彩作品唯美、抽象且具有诗意那种布满着梦幻的色彩,灿烂斑斓,使人感受赞叹、震撼与晕眩!春:夏秋冬图文起原收
大家好,小娟今天来为大家解答辞退无固定期限合同员工的赔偿以下问题,辞退无固定期限合同员工的赔偿最高很多人还不知道,现在让我们一起来
Copyright 2024.依依自媒体,让大家了解更多图文资讯!