草プログラマー、それはつまり草

CS 会計 法律 サッカー 野球 bitcoin 数学 物理学 などいろいろやってます

proof-of-work のpython スクリプト

Mastering Bitcoinの proof-of-work アルゴリズムのPythonスクリプトにコメントをつけてみました。

特に難しくはないですね。

import hashlib 
import time

max_nonce = 2 ** 32 # 4 billion

def proof_of_work(header, difficulty_bits):
    
    # target は difficulty target のこと
    # target = 0x10000000000...の場合
    # 0x1000000000... より小さい値のハッシュが見つかるまで
    # nonce をループさせる
    target = 2 ** (256 - difficulty_bits)
    
    for nonce in xrange(max_nonce):
        hash_result = hashlib.sha256(str(header)+str(nonce)).hexdigest()
        
        if long(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__': 今回はrepl.itで実行してるので省略 

nonce = 0
hash_result = ''

# difficulty が高くなるほどマイニングに時間がかかる=難しくなる
for difficulty_bits in xrange(32):
    difficulty = 2 ** difficulty_bits
    print "Difficuty: %ld (%d bits)" % (difficulty, difficulty_bits)
    print "starting search..."
    
    # マイニングにかかるスピードを計る
    start_time = time.time()
    
    # new_blockがheaderになる header + nonce でハッシュをとる
    new_block = 'test block with transactions' + hash_result
    
    # proof-of-work 実行
    (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
    
    # nonce を マイニングにかかった時間で割ったのがハッシュパワー
    if elapsed_time > 0:
        hash_power = float(long(nonce)/elapsed_time)
        print "Hashing Power: %ld hashes per second" % hash_power
Copyright © 2016 へなちょこプログラマー All rights reserved.