python簡單區(qū)塊鏈模擬詳解
更新時間:2019年07月03日 14:55:59 作者:charles_lun
這篇文章主要介紹了python簡單區(qū)塊鏈模擬詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
最近學習了一點python,那就試著做一做簡單的編程練習。
首先是這個編程的指導(dǎo)圖,如下:
對的,類似一個簡單區(qū)塊鏈的模擬。
代碼如下:
class DaDaBlockCoin: #index 索引,timestamp 時間戳,data 交易記錄,self_hash交易hash,last_hash,上個hash def __init__(self,idex,timestamp,data,last_hash): self.idex = idex self.timestamp = timestamp self.data = data self.last_hash = last_hash self.self_hash=self.hash_DaDaBlockCoin() def hash_DaDaBlockCoin(self): sha = hashlib.md5()#加密算法,這里可以選擇sha256,sha512,為了打印方便,所以選了md5 #對數(shù)據(jù)整體加密 datastr = str(self.idex)+str(self.timestamp)+str(self.data)+str(self.last_hash) sha.update(datastr.encode("utf-8")) return sha.hexdigest() def create_first_DaDaBlock(): # 創(chuàng)世區(qū)塊 return DaDaBlockCoin(0, datetime.datetime.now(), "love dadacoin", "0") # last_block,上一個區(qū)塊 def create_money_DadaBlock(last_block): # 其它塊 this_idex = last_block.idex + 1 # 索引加1 this_timestamp = datetime.datetime.now() this_data = "love dada" + str(this_idex) # 模擬交易數(shù)據(jù) this_hash = last_block.self_hash # 取得上一塊的hash return DaDaBlockCoin(this_idex, this_timestamp, this_data, this_hash) DaDaBlockCoins = [create_first_DaDaBlock()] # 區(qū)塊鏈列表,只有一個創(chuàng)世區(qū)塊 nums = 10 head_block = DaDaBlockCoins[0] print(head_block.idex, head_block.timestamp, head_block.self_hash, head_block.last_hash) for i in range(nums): dadaBlock_add = create_money_DadaBlock(head_block) # 創(chuàng)建一個區(qū)塊鏈的節(jié)點 DaDaBlockCoins.append(dadaBlock_add) head_block = dadaBlock_add print(dadaBlock_add.idex, dadaBlock_add.timestamp, dadaBlock_add.self_hash, dadaBlock_add.last_hash)
打印結(jié)果如下:
與開頭的指導(dǎo)思路完美契合,雖然只是很簡單的模擬。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python解析json之ValueError: Expecting property name enclosed in
這篇文章主要給大家介紹了關(guān)于Python解析json報錯:ValueError: Expecting property name enclosed in double quotes: line 1 column 2(char 1)的解決方法,文中介紹的非常詳細,需要的朋友們可以參考借鑒,下面來一起看看吧。2017-07-07