python簡(jiǎn)單區(qū)塊鏈模擬詳解
最近學(xué)習(xí)了一點(diǎn)python,那就試著做一做簡(jiǎn)單的編程練習(xí)。
首先是這個(gè)編程的指導(dǎo)圖,如下:
對(duì)的,類似一個(gè)簡(jiǎn)單區(qū)塊鏈的模擬。
代碼如下:
class DaDaBlockCoin: #index 索引,timestamp 時(shí)間戳,data 交易記錄,self_hash交易hash,last_hash,上個(gè)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 #對(duì)數(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,上一個(gè)區(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ū)塊鏈列表,只有一個(gè)創(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)建一個(gè)區(qū)塊鏈的節(jié)點(diǎn) 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)思路完美契合,雖然只是很簡(jiǎn)單的模擬。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python實(shí)現(xiàn)停車管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)停車管理系統(tǒng),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-11-11wxPython實(shí)現(xiàn)整點(diǎn)報(bào)時(shí)
這篇文章主要為大家詳細(xì)介紹了wxPython實(shí)現(xiàn)整點(diǎn)報(bào)時(shí),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-11-11Python?Ruby?等語(yǔ)言棄用自增運(yùn)算符原因剖析
這篇文章主要為大家介紹了Python?Ruby?等語(yǔ)言棄用自增運(yùn)算符原因剖析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08Python解析json之ValueError: Expecting property name enclosed in
這篇文章主要給大家介紹了關(guān)于Python解析json報(bào)錯(cuò):ValueError: Expecting property name enclosed in double quotes: line 1 column 2(char 1)的解決方法,文中介紹的非常詳細(xì),需要的朋友們可以參考借鑒,下面來(lái)一起看看吧。2017-07-07