Python構(gòu)建區(qū)塊鏈的方法詳解
區(qū)塊鏈
區(qū)塊鏈?zhǔn)窃谟?jì)算機(jī)網(wǎng)絡(luò)的節(jié)點(diǎn)之間共享數(shù)據(jù)的分類賬(分布式數(shù)據(jù)庫)。作為數(shù)據(jù)庫,區(qū)塊鏈以電子格式儲存信息。區(qū)塊鏈的創(chuàng)新之處在于它保證了數(shù)據(jù)記錄的安全性和真實(shí)性,可信性(不需要沒有可信任的第三方)。
區(qū)塊鏈和典型數(shù)據(jù)庫的區(qū)別是數(shù)據(jù)結(jié)構(gòu)。區(qū)塊鏈以block
的方式收集信息。
block
block
是一種能永久記錄加密貨幣交易數(shù)據(jù)(或其他用途)的一種數(shù)據(jù)結(jié)構(gòu)。類似于鏈表。一個(gè)block
記錄了一些火所有尚未被驗(yàn)證的最新交易。驗(yàn)證數(shù)據(jù)后,block
將關(guān)閉,之后會創(chuàng)建一個(gè)新的block
來輸入和驗(yàn)證新的交易。因此,一旦寫入,永久不能更改和刪除。
block
是區(qū)塊鏈中存儲和加密信息的地方block
由長數(shù)字標(biāo)識,其中包括先前加密塊的加密交易信息和新的交易信息- 在創(chuàng)建之前,
block
以及其中的信息必須由網(wǎng)絡(luò)驗(yàn)證
以下是一個(gè)簡單的例子:
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ù)器,用于維護(hù)一個(gè)包含所有客戶信息的數(shù)據(jù)庫。公司的所有服務(wù)器都在一個(gè)倉庫中,可以完全控制每臺服務(wù)器。這就提供了單點(diǎn)故障。如果那個(gè)地方停電了怎么辦?如果他的網(wǎng)絡(luò)連接被切斷了怎么辦?在任何情況下,數(shù)據(jù)都會丟失或損壞。
構(gòu)建
區(qū)塊鏈類
我們將創(chuàng)建一個(gè)BlockChain
類,構(gòu)造函數(shù)創(chuàng)建一個(gè)空列表來存儲區(qū)塊鏈,再創(chuàng)建一個(gè)空列表來存儲交易。創(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é)這個(gè)
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
將交易添加到列表后,它返回交易將被添加到的塊的索引——下一個(gè)要挖掘的塊。這將在以后對提交交易的用戶有用。
創(chuàng)建新blocks
當(dāng)我們的區(qū)塊鏈被實(shí)例化時(shí),我們需要為它播種一個(gè)創(chuàng)世塊——一個(gè)沒有前輩的塊。我們還需要向我們的創(chuàng)世塊添加一個(gè)“證明”,這是挖掘的結(jié)果(或工作量證明)。除了在我們的構(gòu)造函數(shù)中創(chuàng)建創(chuàng)世塊之外,我們還將充實(shí) 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ū)塊鏈。但此時(shí),你一定想知道新區(qū)塊是如何創(chuàng)建、鍛造或開采的。
POW
工作量證明算法 (PoW) 是在區(qū)塊鏈上創(chuàng)建或挖掘新塊的方式,它的目標(biāo)是發(fā)現(xiàn)一個(gè)解決問題的數(shù)字。這個(gè)數(shù)字必須很難找到但很容易被網(wǎng)絡(luò)上的任何人驗(yàn)證。PoW廣泛用于加密貨幣挖掘,用于驗(yàn)證交易和挖掘新代幣。由于PoW,比特幣和其他加密貨幣交易可以以安全的方式進(jìn)行點(diǎn)對點(diǎn)處理,而無需受信任的第三方。
讓我們實(shí)現(xiàn)一個(gè)類似的算法:
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ū)塊鏈能夠交互,我們需要一個(gè)將其置于web服務(wù)器上。這里我們是用Flask
框架。
如果沒有安裝,需要安裝flask
pip install flask
我們的服務(wù)器將在我們的區(qū)塊鏈網(wǎng)絡(luò)中形成單一節(jié)點(diǎn),在同級目錄下創(chuàng)建一個(gè)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 # 實(shí)例化應(yīng)用 app = Flask(__name__) # 創(chuàng)建隨機(jī)節(jié)點(diǎn)名稱 node_identifier = str(uuid4()).replace('_', '') # 實(shí)例化block_chain類 block_chain = Blockchain() # 創(chuàng)建/mine端點(diǎn) @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)
然后運(yùn)行
flask run
通過api軟件(本次使用的是api fox)來發(fā)送請求:
注冊新節(jié)點(diǎn)
區(qū)塊鏈的全部意義在于它們應(yīng)該去中心化。如果想要網(wǎng)絡(luò)中有多個(gè)節(jié)點(diǎn),必須采用共識算法。在我們可以實(shí)施共識算法之前,我們需要一種方法讓節(jié)點(diǎn)知道網(wǎng)絡(luò)上的相鄰節(jié)點(diǎn)。我們網(wǎng)絡(luò)上的每個(gè)節(jié)點(diǎn)都應(yīng)該保留網(wǎng)絡(luò)上其他節(jié)點(diǎn)的注冊表。因此,我們需要更多的端點(diǎn):
... 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)
沖突
沖突是指一個(gè)節(jié)點(diǎn)與另一個(gè)節(jié)點(diǎn)有不同的鏈。為了解決這個(gè)問題,我們將制定最長有效鏈為權(quán)威的規(guī)則。使用此算法,我們在網(wǎng)絡(luò)中的節(jié)點(diǎn)之間達(dá)成共識。
... 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
第一個(gè)方法 valid_chain() 負(fù)責(zé)通過遍歷每個(gè)塊并驗(yàn)證哈希和證明來檢查鏈?zhǔn)欠裼行?。resolve_conflicts() 是一種循環(huán)遍歷我們所有相鄰節(jié)點(diǎn)、下載它們的鏈并使用上述方法驗(yàn)證它們的方法。如果找到一個(gè)有效的鏈,其長度大于我們的,我們將替換我們的。
讓我們將兩個(gè)端點(diǎn)注冊到我們的 API,一個(gè)用于添加相鄰節(jié)點(diǎn),另一個(gè)用于解決沖突:
@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
在這一點(diǎn)上,如果你愿意,你可以拿一臺不同的機(jī)器,并在你的網(wǎng)絡(luò)上啟動不同的節(jié)點(diǎn)。或者在同一臺機(jī)器上使用不同的端口啟動進(jìn)程。比如創(chuàng)建兩個(gè)端口5000和6000來進(jìn)行嘗試。
到此這篇關(guān)于Python構(gòu)建區(qū)塊鏈的方法詳解的文章就介紹到這了,更多相關(guān)Python構(gòu)建區(qū)塊鏈內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python使用paramiko模塊通過ssh2協(xié)議對交換機(jī)進(jìn)行配置的方法
今天小編就為大家分享一篇python使用paramiko模塊通過ssh2協(xié)議對交換機(jī)進(jìn)行配置的方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07python使用PySimpleGUI設(shè)置進(jìn)度條及控件使用
PySimpleGUI是一個(gè)在tkinter基礎(chǔ)上的,足夠簡單,方便,pythonic的GUI庫.本文給大家介紹python使用PySimpleGUI設(shè)置進(jìn)度條的方法及進(jìn)度條控件使用代碼,感興趣的朋友跟隨小編一起看看吧2021-06-06Python?OpenCV實(shí)現(xiàn)簡單的顏色識別功能(對紅色和藍(lán)色識別并輸出)
Python?OpenCV可以用來進(jìn)行顏色識別,可以通過讀取圖像的像素值,來判斷像素點(diǎn)的顏色,從而實(shí)現(xiàn)顏色識別,這篇文章主要給大家介紹了關(guān)于Python?OpenCV實(shí)現(xiàn)簡單的顏色識別功能(對紅色和藍(lán)色識別并輸出)的相關(guān)資料,需要的朋友可以參考下2023-12-12python根據(jù)京東商品url獲取產(chǎn)品價(jià)格
閑著沒事嘗試抓一下京東的數(shù)據(jù),需要使用到的庫有:BeautifulSoup,urllib2,在Python2下測試通過2015-08-08Python實(shí)現(xiàn)視頻分解成圖片+圖片合成視頻
這篇文章主要介紹了如何利用Python實(shí)現(xiàn)視頻分解成圖片以及將圖片合成為視頻,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2022-04-04Django項(xiàng)目中實(shí)現(xiàn)使用qq第三方登錄功能
使用qq登錄的前提是已經(jīng)在qq互聯(lián)官網(wǎng)創(chuàng)建網(wǎng)站應(yīng)用并獲取到QQ互聯(lián)中網(wǎng)站應(yīng)用的APP ID和APP KEY。這篇文章主要介紹了Django項(xiàng)目中實(shí)現(xiàn)使用qq第三方登錄功能,需要的朋友可以參考下2019-08-08