Python構(gòu)建區(qū)塊鏈的方法詳解
區(qū)塊鏈
區(qū)塊鏈?zhǔn)窃谟嬎銠C網(wǎng)絡(luò)的節(jié)點之間共享數(shù)據(jù)的分類賬(分布式數(shù)據(jù)庫)。作為數(shù)據(jù)庫,區(qū)塊鏈以電子格式儲存信息。區(qū)塊鏈的創(chuàng)新之處在于它保證了數(shù)據(jù)記錄的安全性和真實性,可信性(不需要沒有可信任的第三方)。
區(qū)塊鏈和典型數(shù)據(jù)庫的區(qū)別是數(shù)據(jù)結(jié)構(gòu)。區(qū)塊鏈以block的方式收集信息。
block
block是一種能永久記錄加密貨幣交易數(shù)據(jù)(或其他用途)的一種數(shù)據(jù)結(jié)構(gòu)。類似于鏈表。一個block記錄了一些火所有尚未被驗證的最新交易。驗證數(shù)據(jù)后,block將關(guān)閉,之后會創(chuàng)建一個新的block來輸入和驗證新的交易。因此,一旦寫入,永久不能更改和刪除。
block是區(qū)塊鏈中存儲和加密信息的地方block由長數(shù)字標(biāo)識,其中包括先前加密塊的加密交易信息和新的交易信息- 在創(chuàng)建之前,
block以及其中的信息必須由網(wǎng)絡(luò)驗證
以下是一個簡單的例子:
block = {
'index': 1,
'timestamp': 1506057125.900785,
'transactions': [
{
'sender': "8527147fe1f5426f9dd545de4b27ee00",
'recipient': "a77f5cdfa2934df3954a5c7c7da5df1f",
'amount': 5,
}
],
'proof': 324984774000,
'previous_hash': "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
}
目標(biāo)
區(qū)塊鏈的目標(biāo)是允許數(shù)字信息被記錄和分發(fā),但不能編輯。通過這種方式,區(qū)塊鏈成為了不可變分類賬或無法更改、刪除和銷毀的交易記錄的基礎(chǔ)。
去中心化
想象一下,一家公司擁有10000臺服務(wù)器,用于維護一個包含所有客戶信息的數(shù)據(jù)庫。公司的所有服務(wù)器都在一個倉庫中,可以完全控制每臺服務(wù)器。這就提供了單點故障。如果那個地方停電了怎么辦?如果他的網(wǎng)絡(luò)連接被切斷了怎么辦?在任何情況下,數(shù)據(jù)都會丟失或損壞。
構(gòu)建
區(qū)塊鏈類
我們將創(chuàng)建一個BlockChain類,構(gòu)造函數(shù)創(chuàng)建一個空列表來存儲區(qū)塊鏈,再創(chuàng)建一個空列表來存儲交易。創(chuàng)建block_chain.py
# block_chain.py
class Blockchain:
def __init__(self) -> None:
self.chain = []
self.current_transactions = []
def new_block(self):
# Creates a new Block and adds it to the chain
pass
def new_transaction(self):
# Adds a new transaction to the list of transactions
pass
@staticmethod
def hash(block):
# Hashes a Block
pass
@property
def last_block(self):
# Returns the last Block in the chain
pass
添加交易
我們需要一種將交易添加到區(qū)塊的方法。new_transaction負(fù)責(zé)這個
class Blockchain(object):
...
def new_transaction(self, sender, recipient, amount) -> int:
self.current_transactions.append({
'sender': sender,
'recipient': recipient,
'amount': amount,
})
return self.last_block['index'] + 1
在 new_transaction 將交易添加到列表后,它返回交易將被添加到的塊的索引——下一個要挖掘的塊。這將在以后對提交交易的用戶有用。
創(chuàng)建新blocks
當(dāng)我們的區(qū)塊鏈被實例化時,我們需要為它播種一個創(chuàng)世塊——一個沒有前輩的塊。我們還需要向我們的創(chuàng)世塊添加一個“證明”,這是挖掘的結(jié)果(或工作量證明)。除了在我們的構(gòu)造函數(shù)中創(chuàng)建創(chuàng)世塊之外,我們還將充實 new_block()、new_transaction() 和 hash() 的方法:
import hashlib
import json
from time import time
class Blockchain:
def __init__(self) -> None:
self.chain = []
self.current_transactions = []
# Create the genesis block
self.new_block(previous_hash=1, proof=100)
def new_block(self, proof, previous_hash=None) -> dict:
block = {
'index': len(self.chain) + 1,
'timestamp': time(),
'transactions': self.current_transactions,
'proof': proof,
'previous_hash': previous_hash or self.hash(self.chain[-1]),
}
self.current_transactions = []
self.chain.append(block)
return block
def new_transaction(self, sender, recipient, amount) -> int:
self.current_transactions.append(
{
'sender': sender,
'recipient': recipient,
'amount': amount,
}
)
return self.last_block['index'] + 1
@property
def last_block(self) -> dict:
# Returns the last Block in the chain
return self.chain[-1]
@staticmethod
def hash(block) -> str:
block_string = json.dumps(block, sort_keys=True).encode()
return hashlib.sha256(block_string).hexdigest()
到這里,我們幾乎完成了代表我們的區(qū)塊鏈。但此時,你一定想知道新區(qū)塊是如何創(chuàng)建、鍛造或開采的。
POW
工作量證明算法 (PoW) 是在區(qū)塊鏈上創(chuàng)建或挖掘新塊的方式,它的目標(biāo)是發(fā)現(xiàn)一個解決問題的數(shù)字。這個數(shù)字必須很難找到但很容易被網(wǎng)絡(luò)上的任何人驗證。PoW廣泛用于加密貨幣挖掘,用于驗證交易和挖掘新代幣。由于PoW,比特幣和其他加密貨幣交易可以以安全的方式進行點對點處理,而無需受信任的第三方。
讓我們實現(xiàn)一個類似的算法:
class Blockchain(object):
def proof_of_work(self, last_proof) -> int:
proof = 0
while self.valid_proof(last_proof, proof) is False:
proof += 1
return proof
@staticmethod
def valid_proof(last_proof, proof) -> bool:
guess = f'{last_proof}{proof}'.encode()
guess_hash = hashlib.sha256(guess).hexdigest()
return guess_hash[:4] == '0000'
API
為了使區(qū)塊鏈能夠交互,我們需要一個將其置于web服務(wù)器上。這里我們是用Flask框架。
如果沒有安裝,需要安裝flask
pip install flask
我們的服務(wù)器將在我們的區(qū)塊鏈網(wǎng)絡(luò)中形成單一節(jié)點,在同級目錄下創(chuàng)建一個app.py:
from uuid import uuid4
from time import time
from textwrap import dedent
from flask import Flask, jsonify, request
from block_chain import Blockchain
# 實例化應(yīng)用
app = Flask(__name__)
# 創(chuàng)建隨機節(jié)點名稱
node_identifier = str(uuid4()).replace('_', '')
# 實例化block_chain類
block_chain = Blockchain()
# 創(chuàng)建/mine端點
@app.route('/mine', methods=['GET'])
def mine():
block_chain.new_transaction(
sender="0",
recipient=node_identifier,
amount=1,
)
last_block = block_chain.last_block
last_proof = last_block['proof']
proof = block_chain.proof_of_work(last_proof)
previous_hash = block_chain.hash(last_block)
block = block_chain.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
@app.route('/transactions/new', methods=['POST'])
def new_transaction():
return "We'll add a new transaction"
@app.route('/chain', methods=['GET'])
def full_chain():
response = {
'chain': block_chain.chain,
'length': len(block_chain.chain),
}
return jsonify(response), 200
# 修改端口號
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
然后運行
flask run
通過api軟件(本次使用的是api fox)來發(fā)送請求:


注冊新節(jié)點
區(qū)塊鏈的全部意義在于它們應(yīng)該去中心化。如果想要網(wǎng)絡(luò)中有多個節(jié)點,必須采用共識算法。在我們可以實施共識算法之前,我們需要一種方法讓節(jié)點知道網(wǎng)絡(luò)上的相鄰節(jié)點。我們網(wǎng)絡(luò)上的每個節(jié)點都應(yīng)該保留網(wǎng)絡(luò)上其他節(jié)點的注冊表。因此,我們需要更多的端點:
...
from urllib.parse import urlparse
...
class Blockchain:
def __init__(self) -> None:
...
self.nodes = set()
...
def register_node(self, address) -> None:
parsed_url = urlparse(address)
self.nodes.add(parsed_url.netloc)
沖突
沖突是指一個節(jié)點與另一個節(jié)點有不同的鏈。為了解決這個問題,我們將制定最長有效鏈為權(quán)威的規(guī)則。使用此算法,我們在網(wǎng)絡(luò)中的節(jié)點之間達成共識。
...
import requests
class Blockchain:
...
def valid_chain(self, chain):
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
if block['previous_hash'] != self.hash(last_block):
return False
# Check that the Proof of Work is correct
if not self.valid_proof(last_block['proof'], block['proof']):
return False
last_block = block
current_index += 1
return True
def resolve_conflicts(self):
"""
This is our Consensus Algorithm, it resolves conflicts
by replacing our chain with the longest one in the network.
:return: <bool> True if our chain was replaced, False if not
"""
neighbours = self.nodes
new_chain = None
# We're only looking for chains longer than ours
max_length = len(self.chain)
# Grab and verify the chains from all the nodes in our network
for node in neighbours:
response = requests.get(f'http://{node}/chain')
if response.status_code == 200:
length = response.json()['length']
chain = response.json()['chain']
# Check if the length is longer and the chain is valid
if length > max_length and self.valid_chain(chain):
max_length = length
new_chain = chain
# Replace our chain if we discovered a new, valid chain longer than ours
if new_chain:
self.chain = new_chain
return True
return False
第一個方法 valid_chain() 負(fù)責(zé)通過遍歷每個塊并驗證哈希和證明來檢查鏈?zhǔn)欠裼行?。resolve_conflicts() 是一種循環(huán)遍歷我們所有相鄰節(jié)點、下載它們的鏈并使用上述方法驗證它們的方法。如果找到一個有效的鏈,其長度大于我們的,我們將替換我們的。
讓我們將兩個端點注冊到我們的 API,一個用于添加相鄰節(jié)點,另一個用于解決沖突:
@app.route('/nodes/register', methods=['POST'])
def register_nodes():
values = request.get_json()
nodes = values.get('nodes')
if nodes is None:
return "Error: Please supply a valid list of nodes", 400
for node in nodes:
blockchain.register_node(node)
response = {
'message': 'New nodes have been added',
'total_nodes': list(blockchain.nodes),
}
return jsonify(response), 201
@app.route('/nodes/resolve', methods=['GET'])
def consensus():
replaced = blockchain.resolve_conflicts()
if replaced:
response = {
'message': 'Our chain was replaced',
'new_chain': blockchain.chain
}
else:
response = {
'message': 'Our chain is authoritative',
'chain': blockchain.chain
}
return jsonify(response), 200
在這一點上,如果你愿意,你可以拿一臺不同的機器,并在你的網(wǎng)絡(luò)上啟動不同的節(jié)點?;蛘咴谕慌_機器上使用不同的端口啟動進程。比如創(chuàng)建兩個端口5000和6000來進行嘗試。
到此這篇關(guān)于Python構(gòu)建區(qū)塊鏈的方法詳解的文章就介紹到這了,更多相關(guān)Python構(gòu)建區(qū)塊鏈內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用Python實現(xiàn)Excel文件轉(zhuǎn)換為SVG格式
SVG(Scalable Vector Graphics)是一種基于XML的矢量圖像格式,這種格式在Web開發(fā)和其他圖形應(yīng)用中非常流行,提供了一種高效的方式來呈現(xiàn)復(fù)雜的矢量圖形,本文將介紹如何使用Python轉(zhuǎn)換Excel文件為SVG格式,需要的朋友可以參考下2024-07-07
tensorflow之獲取tensor的shape作為max_pool的ksize實例
今天小編就為大家分享一篇tensorflow之獲取tensor的shape作為max_pool的ksize實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01
python調(diào)用xlsxwriter創(chuàng)建xlsx的方法
今天小編就為大家分享一篇python調(diào)用xlsxwriter創(chuàng)建xlsx的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-05-05
python web自制框架之接受url傳遞過來的參數(shù)實例
今天小編就為大家分享一篇python web自制框架之接受url傳遞過來的參數(shù)實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-12-12
深入解析Python中的descriptor描述器的作用及用法
在Python中描述器也被稱為描述符,描述器能夠?qū)崿F(xiàn)對對象屬性的訪問控制,下面我們就來深入解析Python中的descriptor描述器的作用及用法2016-06-06

