[ad_1]
I am developing a blockchain using python. Here is the constructor of the Block class
class Block:
def __init__(self, timestamp, prev_hash, data, present_hash, nonce, difficulty):
self.timestamp = timestamp
self.prev_hash = prev_hash
self.data = data
self.present_hash = present_hash
self.nonce = nonce
self.difficulty = difficulty
and here is the method to extract the block
@staticmethod
def mine_block(prev_block, data):
nonce = 0
difficulty = prev_block.difficulty
print('Mining in progress......')
while True:
nonce += 1
timestamp = time()
difficulty = Block.adjust_difficulty(prev_block, timestamp)
new_hash = Block.gen_hash(timestamp, prev_block.present_hash, data, nonce, difficulty)
if new_hash[:difficulty] == '0'*difficulty:
break
print('Mining is complete.')
return Block(timestamp, prev_block.present_hash, data, new_hash, nonce, difficulty)
To resolve its difficulty I use
@staticmethod
def adjust_difficulty(block, timestamp):
if timestamp - float(block.timestamp) < MINE_RATE:
return block.difficulty + 1
else:
return block.difficulty - 1
I keep constant data to extract the block. However, every time I mine the block I get a different hash. Indeed, the difficulty of announcement and the timestamp will always change.
Question:
- How to know which hash is correct if multiple miners generated a different hash for the same data.
- If I can figure out the number of leading zeros in the hash (difficult in my case), then why bother running the code. Why not just give it a go and give it a try. Suppose you start with 0xxx .. then 00xx, 000x, 0000, …… One of them should extract the block. If the hash length is 32. Then you will need 32 tries to break it.
PS I am new to Blockchain.
[ad_2]
Source Link