2019-01-31 22:58:44 Python

オレオレBlockchain最低限実装。 結構そのままだとマズイ部分が…。

Copy Copied! Full
# encoding: utf-8 from types import MappingProxy from hashlib import sha256 from json import dumps class Block: def __init__( self, prev: str, data: dict, nonce: int, difficulty: int): self.prev = prev self.data = data self.nonce = nonce self.difficulty = MappingProxy(difficulty) def serialize(self): return dumps({ 'prev': self.prev or '', 'data': self.data, 'difficulty': self.difficulty, 'nonce': self.nonce }) @property def hash(self): return sha256(self.serialize().encode('ascii')).hexdigest() @property def is_valid(self): h = sha256(self.serialize().encode('ascii')) d = self.difficulty d = d if d < 256 else 255 return 2**(256-d) > int.from_bytes(h.digest(), 'big') def __setattr__(self, key, val): if key == 'nonce' or key in ('prev', 'data', 'difficulty') and not hasattr(self, key): super().__setattr__(key, val) raise AttributeError("Block object is readonly.") def __delattr__(self, key): raise AttributeError("Block object attribute is not deletable.") class BlockChain: def __init__(self): self.blocks = {} self.last_hash = None self.difficulty = 2 self._lock = RLock() def append(self, data: dict, nonce: int): b = Block(self.last_hash, data, nonce, self.difficulty) if not b.is_valid: return False h = b.hash self.last_hash = h self.blocks[h] = b return True
オレオレBlockchain最低限実装。
結構そのままだとマズイ部分が…。