工作量证明算法

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. 区块链中一种工作量证明算法  
[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #!/usr/bin/env python  
  2. # example of proof-of-work algorithm  
  3. import hashlib  
  4. import time  
  5. max_nonce = 2 ** 32 # 4 billion  
  6. def proof_of_work(header, difficulty_bits):  
  7. # calculate the difficulty target  
  8. target = 2 ** (256-difficulty_bits)  
  9. for nonce in xrange(max_nonce):  
  10. hash_result = hashlib.sha256(str(header)+str(nonce)).hexdigest()  
  11. # check if this is a valid result, below the target  
  12. if long(hash_result, 16) < target:  
  13. print "Success with nonce %d" % nonce  
  14. print "Hash is %s" % hash_result  
  15. return (hash_result,nonce)  
  16. print "Failed after %d (max_nonce) tries" % nonce  
  17. return nonce  
  18. if __name__ == '__main__':  
  19. nonce = 0  
  20. hash_result = ''  
  21. # difficulty from 0 to 31 bits  
  22. for difficulty_bits in xrange(32):  
  23. difficulty = 2 ** difficulty_bits  
  24. print "Difficulty: %ld (%d bits)" % (difficulty, difficulty_bits)  
  25. print "Starting search..."  
  26. # checkpoint the current time  
  27. start_time = time.time()  
  28. # make a new block which includes the hash from the previous block  
  29. # we fake a block of transactions - just a string  
  30. new_block = 'test block with transactions' + hash_result  
  31. # find a valid nonce for the new block  
  32. (hash_result, nonce) = proof_of_work(new_block, difficulty_bits)  
  33. # checkpoint how long it took to find a result  
  34. end_time = time.time()  
  35. elapsed_time = end_time - start_time  
  36. print "Elapsed Time: %.4f seconds" % elapsed_time  
  37. if elapsed_time > 0:  
  38. # estimate the hashes per second  
  39. hash_power = float(long(nonce)/elapsed_time)  
  40. print "Hashing Power: %ld hashes per second" % hash_power  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值