1. 程式人生 > >簡易區塊鏈的python實現

簡易區塊鏈的python實現

import hashlib
import datetime


class TTBlockCoin:
    def __init__(self,
                 index,  # 索引
                 timeStamp,  # 時間戳
                 data,  # 交易資料
                 lastHash):  # 上一個塊的hash值
        self.index = index
        self.timeStamp = timeStamp
        self.data = data
        self.lastHash = lastHash
        self.selfHash = self.hash_TTBlockCoin()

    # 產生加密串,產生一個加密串就是產生一個幣
def hash_TTBlockCoin(self): # sha = hashlib.sha256() # sha = hashlib.sha512() sha = hashlib.md5() datastr = str(self.index) + str(self.timeStamp) + str(self.data) + str(self.lastHash) sha.update(datastr.encode("utf-8")) return sha.hexdigest() def
create_first_TTBlock():
# 創造一個創世區塊 return TTBlockCoin(0, datetime.datetime.now(), "TT COIN", "tt001") def create_money_TTBlock(last_block): # 區塊鏈的其他塊 last_block 上一個區塊 this_index = last_block.index + 1 this_timestamp = datetime.datetime.now() this_data = "taotao coin" + str(this_index) # 模擬交易資料
last_hash = last_block.selfHash #lastHash =上一個block的selfHash return TTBlockCoin(this_index, this_timestamp, this_data, last_hash) TTBlockCoins = [create_first_TTBlock()] # 區塊鏈連結串列 nums = 100 head_block = TTBlockCoins[0] print("創世區塊TT幣來啦") print(head_block.index, head_block.data, head_block.timeStamp, head_block.lastHash, head_block.selfHash) for i in range(nums): ttBlock_another = create_money_TTBlock(head_block) # 根據第一個區塊創造下一個區塊 TTBlockCoins.append(ttBlock_another) # 區塊加入鏈 head_block = ttBlock_another print(ttBlock_another.index, ttBlock_another.data, ttBlock_another.timeStamp, ttBlock_another.lastHash, ttBlock_another.selfHash)