区块链共识机制 —— PoW共识的Python实现
原始实现(python2 版本)
https://github.com/santisiri/proof-of-work
依据python3特性改进后:
#!/usr/bin/env python # example of proof of work algorithm import hashlib import time max_nonce = 2 ** 32 # 4 billion def 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 nonce if __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 )
运行结果:
注:
具体原理不知。
====================================
参考:
简述目前相对成熟的区块链共识算法
====================================
本博客是博主个人学习时的一些记录,不保证是为原创,个别文章加入了转载的源地址,还有个别文章是汇总网上多份资料所成,在这之中也必有疏漏未加标注处,如有侵权请与博主联系。
如果未特殊标注则为原创,遵循 CC 4.0 BY-SA 版权协议。
标签:
区块链
posted on 2021-05-15 21:37 Angry_Panda 阅读(717) 评论(0) 编辑 收藏 举报
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
2017-05-15 Linux环境下 多线程下载 (Python 实现版)