ハッシュ計算
@staticmethod def hash(block): """ Creates a SHA-256 hash of a Block :param block: Block """ # We must make sure that the Dictionary is Ordered, or we'll have inconsistent hashes block_string = json.dumps(block, sort_keys=True).encode() return hashlib.sha256(block_string).hexdigest() def proof_of_work(self, last_block): """ Simple Proof of Work Algorithm: - Find a number p' such that hash(pp') contains leading 4 zeroes - Where p is the previous proof, and p' is the new proof :param last_block: <dict> last Block :return: <int> """ last_proof = last_block['proof'] last_hash = self.hash(last_block) proof = 0 while self.valid_proof(last_proof, proof, last_hash) is False: proof += 1 return proof @staticmethod def valid_proof(last_proof, proof, last_hash): """ Validates the Proof :param last_proof: <int> Previous Proof :param proof: <int> Current Proof :param last_hash: <str> The hash of the Previous Block :return: <bool> True if correct, False if not. """ guess = f'{last_proof}{proof}{last_hash}'.encode() guess_hash = hashlib.sha256(guess).hexdigest() return guess_hash[:4] == "0000"obj を JSON 形式の str オブジェクトに直列化する。json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)hashlib:セキュアハッシュモジュール
常に使用できるハッシュアルゴリズムのコンストラクタは sha1()、 sha224()、 sha256()、 sha384()、 sha512()、 blake2b()、 blake2s()
hash.hexdigest():16進形式文字列を返します。ハッシュ値 = hashlib.sha256(文字列).hexdigest()