談到比特幣,我們都知道挖礦,有些人并不太明白挖礦的含義。這里的挖礦其實就是哈希的碰撞,舉個簡單例子:
import hashlib
x = 11
y = 1
#這里可以調節挖礦難度,也就是哈希的長度
while hashlib.sha256(f'{x*y}'.encode("utf-8")).hexdigest()[5:7]!="00":
print(x*y)
y +=1
print("找到了:",(x*y))
結果如下:
當然比特幣的挖礦要比這個復雜太多,但是原理差不多,有個大概的認知。
關于節點的同步,是取整個節點中最長的區塊鏈進行同步,如圖所示:
有了以上內容鋪墊,代碼實現和理解就容易了,代碼如下:
#挖礦原理與網絡共識
import datetime
import hashlib
import json
import requests
class Blockchain2:
def __init__(self):
self.chain = [] #區塊鏈列表
self.nodes = set() #節點集合
self.current_tranactions = [] #交易列表
self.new_block(proof=100,preHash=1) #創建第一個區塊
#新建一個區塊,需要計算,才能追加
def new_block(self,proof,preHash = None):
block={
"index":len(self.chain)+1,#區塊索引
"timestamp":datetime.datetiem.now(),#區塊時間戳
"transactions":self.current_tranactions,#區塊交易記錄集合
"proof":proof,#算力憑證
"preHash":preHash or self.hash(self.chain[-1]), #上一塊的哈希
}
self.current_tranactions = [] #開辟新的區塊,初始化區塊交易記錄
self.chain.append(block)
@staticmethod
def hash(block):
#處理為json字符串格式的哈希
block_str = json.dumps(block,sort_keys=True).encode("utf-8")
return hashlib.sha256(block_str).hexdigest()
#新增交易記錄
def new_transaction(self,sender,receiver,amount):
transaction ={
"sender":sender,
"receiver":receiver,
"amount":amount,
}
self.current_tranactions.append(transaction)
return self.last_block["index"]+1
@property
def last_block(self):
return self.chain[-1]
#挖礦,依賴上一個模塊,獲取工作量證明,即POW共識機制
def proof_of_work(self,last_block):
last_proof = last_block["proof"]
last_hash = self.hash(last_block)
proof = 0
while self.valid_proof(last_proof,proof,last_hash) is False:
proof +=1
return proof
#校驗工作量
@staticmethod
def valid_proof(last_proof,proof,last_hash):
guess = f'{last_proof}{proof}{last_hash}'.encode("utf-8")
guess_hash = hashlib.sha256(guess).hexdigest()
return guess_hash[:6] =="000000" #可以調整計算難度
#區塊一致性,同步算法,
def resolve_conflicts(self):
neighbours = self.nodes
new_chain = None
max_length = len(self.chain)
#遍歷所有節點,找出最長的鏈
for node in neighbours:
#獲取節點區塊鏈信息
response = requests.get(f'http://{node}/chain')
if response.status_code ==200:
length = response.json()["length"]
chain = response.json()["chain"]
if length>max_length and self.valid_chain(chain):
max_length = length
new_chain = chain
if new_chain:
self.chain = new_chain
return True
else:
return False
#校驗區塊鏈的合法性
def valid_chain(self,chain):
last_block = chain[0]
current_index = 1
#校驗每一個區塊的prehash,proof合法性
while current_index
算力校驗和pow共識基本實現了
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

