区块链共识机制 —— 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 )
复制代码

 

 

 

 

 

 

 

运行结果:

 

 

 

 

 

 

 

 

 

注:

具体原理不知。

 

 

 

====================================

 

 

 

 

参考:

 

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

 

 

 

====================================

 

posted on   Angry_Panda  阅读(717)  评论(0编辑  收藏  举报

编辑推荐:
· 从 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 实现版)

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示