掌趣電競系統開發案例介紹
簡而言之,區塊鏈是一種分布式的資料庫,具有去中心化、不可篡改、可以追溯等特點,這些特點保證了區塊鏈節點的“誠實”和“透明”,解決了資訊不對稱問題,實作了多個主體之間的信任協作和行動一致,為了方便理解區塊和區塊鏈的概念,可以參考如下簡化的Python代碼實作:
class Block:
def init(self, index, transactions, timestamp, previous_hash, nonce=0):
self.index = index
self.transactions = transactions
self.timestamp = timestamp
self.previous_hash = previous_hash
self.nonce = nonce def compute_hash(self):
block_string = json.dumps(self.dict, sort_keys=True) return sha256(block_string.encode()).hexdigest()class Blockchain:
difficulty = 2
def init(self):
self.unconfirmed_transactions = []
self.chain = [] def create_genesis_block(self):
genesis_block = Block(0, [], 0, “0”)
genesis_block.hash = genesis_block.compute_hash()
self.chain.append(genesis_block) @property
def last_block(self):
return self.chain[-1] def add_block(self, block, proof):
previous_hash = self.last_block.hash if previous_hash != block.previous_hash: return False
if not Blockchain.is_valid_proof(block, proof): return False
block.hash = proof
self.chain.append(block) return True @staticmethod
def proof_of_work(block):
block.nonce = 0
computed_hash = block.compute_hash() while not computed_hash.startswith('0' * Blockchain.difficulty):
block.nonce += 1
computed_hash = block.compute_hash() return computed_hash def add_new_transaction(self, transaction):
self.unconfirmed_transactions.append(transaction) @classmethod
def is_valid_proof(cls, block, block_hash):
return (block_hash.startswith(‘0’ * Blockchain.difficulty) and
block_hash == block.compute_hash())
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/258480.html
標籤:區塊鏈
上一篇:一致性HASH演算法筆記
