Guest User

Untitled

a guest
Jan 21st, 2018
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. import hashlib
  2. import time
  3.  
  4.  
  5. def proof_of_work(header, difficulty_bits):
  6. # calculate the difficulty target
  7. # the target decreases as the difficulty_bits increases
  8. target = 2 ** (256 - difficulty_bits)
  9.  
  10. for nonce in range(max_nonce):
  11. input = str(header) + str(nonce)
  12. hash_result: str = hashlib.sha256(input.encode()).hexdigest()
  13.  
  14. # assert that the hash_result hex is less than target
  15. if int(hash_result, 16) < target:
  16. print(f'Success with nonce {nonce}')
  17. print(f'Hash is {hash_result}')
  18. return (hash_result, nonce)
  19.  
  20. print(f'Failed after {nonce} (max_nonce) tries')
  21. return nonce
  22.  
  23.  
  24. max_nonce = 2 ** 32 # 4 billion
  25. nonce = 0
  26. hash_result = ''
  27.  
  28.  
  29. try:
  30. # difficulty from 0 to 31 bits
  31. for difficulty_bits in range(32):
  32.  
  33. difficulty: int = 2 ** difficulty_bits
  34. print(f'\n\nDifficulty: {difficulty} ({difficulty_bits} bits)')
  35.  
  36. print('Starting search...')
  37.  
  38. # check current time
  39. start_time: float = time.time()
  40.  
  41. # make a new block which incldes the hash from previous block
  42. # we fake a block of transactions - just a string
  43. new_block: str = 'test block with transactions' + hash_result
  44.  
  45. # find a valid nonce for the new block
  46. hash_result, nonce = proof_of_work(new_block, difficulty_bits)
  47.  
  48. # check how long it took to find the result
  49. end_time: float = time.time()
  50.  
  51. elapsed_time: float = end_time - start_time
  52. print(f'Elapsed Time: {elapsed_time} seconds')
  53.  
  54. if elapsed_time > 0:
  55. # estimate the hashes per second
  56. hash_power = float(nonce / elapsed_time)
  57. print(f'Hashing Power: {hash_power} hashes per second')
  58.  
  59. except KeyboardInterrupt:
  60. exit()
Add Comment
Please, Sign In to add comment