最近學習了一點python,那就試著做一做簡單的編程練習。
首先是這個編程的指導圖,如下:
對的,類似一個簡單區塊鏈的模擬。
代碼如下:
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 #對數據整體加密 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(): # 創世區塊 return DaDaBlockCoin(0, datetime.datetime.now(), "love dadacoin", "0") # last_block,上一個區塊 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) # 模擬交易數據 this_hash = last_block.self_hash # 取得上一塊的hash return DaDaBlockCoin(this_idex, this_timestamp, this_data, this_hash) DaDaBlockCoins = [create_first_DaDaBlock()] # 區塊鏈列表,只有一個創世區塊 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) # 創建一個區塊鏈的節點 DaDaBlockCoins.append(dadaBlock_add) head_block = dadaBlock_add print(dadaBlock_add.idex, dadaBlock_add.timestamp, dadaBlock_add.self_hash, dadaBlock_add.last_hash)
打印結果如下:
與開頭的指導思路完美契合,雖然只是很簡單的模擬。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
