区块链共识机制 —— PoW共识的Python实现(区块链共识机制的主要作用不是确保)

网友投稿 324 2022-09-03


区块链共识机制 —— PoW共识的Python实现(区块链共识机制的主要作用不是确保)

原始实现(python2 版本)

​​python# example of proof of work algorithmimport hashlibimport timemax_nonce = 2 ** 32 # 4 billiondef proof_of_work(header, difficulty_bits): target = 2 ** (256-difficulty_bits) for nonce in range(max_nonce): hash_result = hashlib.sha256((str(header)+str(nonce)).encode("utf-8")).hexdigest() if int(hash_result, 16) < target: print( "Success with nonce %d" % nonce ) print( "Hash is %s" % hash_result ) return (hash_result, nonce) print( "Failed after %d (max_nonce) tries" % nonce ) return nonceif __name__ == '__main__': nonce = 0 hash_result = '' for difficulty_bits in range(32): difficulty = 2 ** difficulty_bits print( "" ) print( "Difficulty: %ld (%d bits)" % (difficulty, difficulty_bits) ) print( "Starting search..." ) start_time = time.time() new_block = 'test block with transactions' + hash_result (hash_result, nonce) = proof_of_work(new_block, difficulty_bits) end_time = time.time() elapsed_time = end_time - start_time print( "Elapsed time: %.4f seconds" % elapsed_time ) if elapsed_time > 0: hash_power = float(int(nonce)/elapsed_time) print( "Hashing power: %ld hashes per second" % hash_power )

运行结果:

注:

具体原理不知。

参考:

​​简述目前相对成熟的区块链共识算法​​


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:分享某Python下的mpi教程 —— A Python Introduction to Parallel Programming with MPI 1.0.2 documentation(mpi python)
下一篇:SpringBootAdmin+actuator实现服务监控
相关文章

 发表评论

暂时没有评论,来抢沙发吧~