簡易區塊鏈的python實現

2021-08-19 03:20:50 字數 1810 閱讀 6805

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()

# 產生加密串,產生乙個加密串就是產生乙個幣

defhash_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()

defcreate_first_ttblock

():# 創造乙個創世區塊

return ttblockcoin(0, datetime.datetime.now(), "tt coin", "tt001")

defcreate_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) # 根據第乙個區塊創造下乙個區塊

head_block = ttblock_another

print(ttblock_another.index, ttblock_another.data,

ttblock_another.timestamp, ttblock_another.lasthash,

ttblock_another.selfhash)

簡易區塊鏈

迷你區塊鏈 moniu chain 區塊鏈的生成,新建,校驗 交易 非對稱加密 挖礦 p2p網路 const crypto require crypto 的加密函式庫 創世區塊 const initblock class blockchain 獲取最新區塊 getlastblock transfer...

python 區塊鏈 區塊鏈Python實現

區塊鏈是如同鍊錶的一組記錄。每個區塊含有一些資訊以及與其他區塊關聯的方法。每個區塊有前乙個區塊的雜湊值 時間戳 資料。class block def init self,timestamp,data,previous hash self.timestamp timestamp self.data d...

C 簡易區塊鏈

自學c 和區塊鏈後的小實踐 using system.collections using system using static system.console 簡易區塊鏈 namespace test public block string traninfo,int previousblockhas...