Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import hashlib
- import time
- def proof_of_work(header, difficulty_bits):
- # calculate the difficulty target
- # the target decreases as the difficulty_bits increases
- target = 2 ** (256 - difficulty_bits)
- for nonce in range(max_nonce):
- input = str(header) + str(nonce)
- hash_result: str = hashlib.sha256(input.encode()).hexdigest()
- # assert that the hash_result hex is less than target
- if int(hash_result, 16) < target:
- print(f'Success with nonce {nonce}')
- print(f'Hash is {hash_result}')
- return (hash_result, nonce)
- print(f'Failed after {nonce} (max_nonce) tries')
- return nonce
- max_nonce = 2 ** 32 # 4 billion
- nonce = 0
- hash_result = ''
- try:
- # difficulty from 0 to 31 bits
- for difficulty_bits in range(32):
- difficulty: int = 2 ** difficulty_bits
- print(f'\n\nDifficulty: {difficulty} ({difficulty_bits} bits)')
- print('Starting search...')
- # check current time
- start_time: float = time.time()
- # make a new block which incldes the hash from previous block
- # we fake a block of transactions - just a string
- new_block: str = 'test block with transactions' + hash_result
- # find a valid nonce for the new block
- hash_result, nonce = proof_of_work(new_block, difficulty_bits)
- # check how long it took to find the result
- end_time: float = time.time()
- elapsed_time: float = end_time - start_time
- print(f'Elapsed Time: {elapsed_time} seconds')
- if elapsed_time > 0:
- # estimate the hashes per second
- hash_power = float(nonce / elapsed_time)
- print(f'Hashing Power: {hash_power} hashes per second')
- except KeyboardInterrupt:
- exit()
Add Comment
Please, Sign In to add comment