目录
一、准备工作:
1、创建三个python文件:
2、创建nodes.json文件
3、transaction.json文件
4、打开三个控制台
二、在三个节点上进行交互。
二、添加交易发布请求(a向b发送10000coin)
一、准备工作:
1、创建三个python文件:
lancoin_node_5001.py、lancoin_node_5002.py、lancoin_node_5003.py。
它们每个都将连接到不同的端口,一个端口用于a,一个端口用于b,一个端口用于c。
a在端口5001上,b在端口5002上,c在端口5003上
代码示例(lancoin_node_5001.py):
# Module 1 -Create a Cryptocurrency
#To be installed:
#Flask==0.12.2:pip install Flask==0.12.2
#Postman HTrp Client:https://www.getpostman.com
#requests==2.18.4:pip install requests=-2.18.4
#时间戳
import datetime
import hashlib
import json
#Flask可以定义Web应用的路由(URL到Python函数的映射),并处理HTTP请求和响应。jsonify是一个函数,用于将Python对象转换为JSON格式的响应。当你在Flask路由函数中返回一个jsonify对象时,Flask会自动将该对象对应的数据转换为JSON格式,并设置合适的HTTP响应头,以便客户端可以正确解析响应内容。
from flask import Flask, jsonify,request
import requests
from uuid import uuid4
from urllib.parse import urlparse
# 1******Building a Blockchain
class Blockchain:
def __init__(self):
self.transactions=[]
self.chain=[]
self.create_block(proof=1,previous_hash='0')
self.nodes=set()
def create_block(self,proof,previous_hash):
block={'index':len(self.chain)+1,
'timestamp':str(datetime.datetime.now()),
'proof':proof,
'previous_hash':previous_hash,
'transactions':self.transactions}
self.transactions=[]
self.chain.append(block)
return block
def get_previous_block(self):
return self.chain[-1]
def proof_of_work(self,previous_proof):
new_proof=1
check_proof=False
while check_proof is False:
hash_oparation=hashlib.sha256(str(new_proof**2-previous_proof**2).encode()).hexdigest()
if hash_oparation[:4]=='0000':
check_proof=True
else:
new_proof+=1
return new_proof
def hash(self, block):
encode_block = json.dumps(block, sort_keys=True).encode()
return hashlib.sha256(encode_block).hexdigest()
def is_chain_valid(self,chain):
previous_block=chain[0]
block_index=1
while block_index<len(chain):
block=chain[block_index]
if block['previous_hash'] !=self.hash(previous_block):
return False
previous_proof=previous_block['proof']
proof=block['proof']
hash_oparation=hashlib.sha256(str(proof**2-previous_proof**2).encode()).hexdigest()
if hash_oparation[:4] !='0000':
return False
previous_block=block
block_index+=1
return True
def add_transaction(self,sender,receiver,amount):
self.transactions.append({'sender':sender,
'receiver':receiver,
'amount':amount})
previous_block=self.get_previous_block()
return previous_block['index']+1
def add_node(self,address):
parsed_url=urlparse(address)
self.nodes.add(parsed_url.netloc)
def replace_chain(self):
network = self.nodes
longest_chain = None
max_length = len(self.chain)
for node in network:
try:
response = requests.get(f'http://{node}/get_chain')
response.raise_for_status() # 这将抛出异常,如果请求失败
except requests.exceptions.RequestException as e:
print(f"Failed to get the chain from {node}. Exception: {e}")
continue
if response.status_code == 200:
length = response.json()['length']
chain = response.json()['chain']
if length > max_length and self.is_chain_valid(chain):
max_length = length
longest_chain = chain
if longest_chain:
self.chain = longest_chain
return True
return False
#Part 2 -Mining our Blockchain
#Creating a Web App
app = Flask(__name__)
#Creating an address for the node on Port 5000
node_address=str(uuid4()).replace('-', '')
#Creating a Blockchain
blockchain=Blockchain()
#Mining a new block
@app.route('/mine_block',methods=['GET'])
def mine_block():
previous_block=blockchain.get_previous_block()
previous_proof=previous_block['proof']
proof=blockchain.proof_of_work(previous_proof)
previous_hash=blockchain.hash(previous_block)
blockchain.add_transaction(sender=node_address,receiver='a',amount=1)
block=blockchain.create_block(proof, previous_hash)
response={'message':'Congratulation,you just mined a block',
'index':block['index'],
'timestamp':block['timestamp'],
'proof':block['proof'],
'previous_hash':block['previous_hash'],
'transactions':block['transactions']}
return jsonify(response),200
#Getting the full Blockchain
@app.route('/get_chain',methods=['GET'])
def get_chain():
response={'chain':blockchain.chain,
'length':len(blockchain.chain)}
return jsonify(response),200
#Checking if the Blockchain is valid
@app.route('/is_valid',methods=['GET'])
def get_valid():
is_valid=blockchain.is_chain_valid(blockchain.chain)
if is_valid:
response={'message':'All good. The Blockchain is valid.'}
else:
response={'message':'Houston,we have a problem.The Blockchain is not valid.'}
return jsonify(response),200
#Addling a new transaction to the Blockchain
@app.route('/add_transaction',methods=['POST'])
def add_transaction():
json =request.get_json()
transaction_keys=['sender','receiver','amount']
if not all(key in json for key in transaction_keys):
return 'Some elements of the transaction are missing',400
index=blockchain.add_transaction(json['sender'], json['receiver'],json['amount'])
response={'message':f'This transaction will be added to Block {index}'}
return jsonify(response),201
#Connecting new nodes
@app.route('/connect_node', methods=['POST'])
def connect_node():
json = request.get_json()
nodes = json.get('nodes')
if nodes is None:
return "No nodes provided", 400
for node in nodes:
blockchain.add_node(node)
# 将响应构建移到循环外,并在所有节点添加后才返回
response = {
'message': 'All the nodes are now connected. The Lancoin Blockchain now contains the following nodes:',
'total_nodes': list(blockchain.nodes)
}
return jsonify(response), 201
#Replacing the chain by the longest chain if needed
@app.route('/replace_chain', methods=['GET'])
def replace_chain():
is_chain_replaced = blockchain.replace_chain()
if is_chain_replaced:
response = {
'message': 'The nodes had different chains so the chain was replaced by the longest one.',
'new_chain': blockchain.chain
}
else:
response = {
'message': 'All good. the chain is the largest one.',
'actual_chain': blockchain.chain
}
return jsonify(response), 200
app.run(host='0.0.0.0',port=5001)
lancoin_node_5002.py、lancoin_node_5003.py则是lancoin_node_5001.py中的mine_block函数的blockchain.add_transaction(sender=node_address,receiver='a',amount=1),a改为b、c,然后app.run(host='0.0.0.0',port=5001)中的5001改为5002、5003
2、创建nodes.json文件
{
"nodes":["http://127.0.0.1:5001",
"http://127.0.0.1:5002",
"http://127.0.0.1:5003"]
}
3、transaction.json文件
{
"sender":"",
"receiver":"",
"amount":
}
4、打开三个控制台
在这里我用的是Spyder编译器,打开三个控制台,分别在控制台是运行各节点,控制台1运行5001节点,控制台2运行5002节点,控制台3运行5003节点,如图所示
二、在三个节点上进行交互。
(1)跳转到postman,创建三个测试,分别对应5001、5002、5003节点
(2)获取链来查看创世区块是否创建良好http://127.0.0.1:5001/get_chain、http://127.0.0.1:5002/get_chain、http://127.0.0.1:5003/get_chain
以5001为例子
(3)发出第一个请求(post),将发出我们的第一个发布请求以将节点相互连接。
我们现在想做的是连接节点,因此我将返回到nodes.json文件,复制后返回postman发出请求,
按照图内,将三个都按照图上进行相应的修改
(4)测试共识
首先在5001节点(也就是a)上挖一个块
可以通过获取链请求(get_chain)来查看它,就会发现我的新链
然后在5002节点上(也就是b)、5003节点(也就是a)选择替换链请求。下面以5002为例子
二、添加交易发布请求(a向b发送10000coin)
(1)先选择post请求,点开transaction.json文件,复制以后回到postman,在5001节点上,如图
2)然后再5001界面get一个http://127.0.0.1:5001/mine_block。创建这个包含两笔交易的新区块,其中一笔交易与我刚刚开采了这个新区块并因此给我一个addcoin有关,当然还有a给b的交易,给b10000coin
(3)查看5001是否开采区块,3个区块,如图
(4)查看5002的区块,2个区块
(5)查看5003的区块,2个区块
(6)达成共识,以确保区块链中的每个节点都具有相同的链。在postman的5002节点界面再运行一遍http://127.0.0.1:5002/replace_chain(get),然后在5003节点界面运行http://127.0.0.1:5003/replace_chain,然后5002、5003节点也会有3个节点
(7)最后在三个节点中分别get请求一下get_chain,以检查是否具有相同的链。以5002为例
注:本篇用的代码解释都可在我以往的文章中找到
“创建一个简单的区块链,并使用 Flask 框架提供一个简单的 Web 接口来与区块链交互。(持续更新)-CSDN博客”
“使用了Python语言和Flask框架。创建一个区块链网络,允许用户通过HTTP请求进行交互,如包括创建区块链、挖矿、验证区块链等功能。-CSDN博客”文章来源:https://www.toymoban.com/news/detail-861777.html
“使用Python,结合Flask框架,创建一个可以处理交易、挖矿新区块、验证区块链有效性,并能在网络节点间同步的区块链网络。(持续更新)-CSDN博客”文章来源地址https://www.toymoban.com/news/detail-861777.html
到了这里,关于创建一个区块链,是由三个节点组成的去中心化网络。的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!