工作量证明算法

[python]  view plain  copy
 
  1. 区块链中一种工作量证明算法  
[python]  view plain  copy
 
  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  

你可能感兴趣的:(区块链)