-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproof_of_work.py
35 lines (28 loc) · 1.1 KB
/
proof_of_work.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
from hashlib import sha256
MINING_DIFFICULTY = 3
def find_proof_of_work(transactions, prev_hash, nonce):
"""
Utility function to check if a given nonce solves the PoW problem
"""
hasheable_transactions = [tx.__dict__ for tx in transactions]
input_string = (str(hasheable_transactions) + str(prev_hash) + str(nonce)).encode()
hash = sha256(input_string).hexdigest()
return hash[0:MINING_DIFFICULTY] == "000"
def verify_proof_of_work(transactions, prev_hash, nonce):
"""
Verifies whether the PoW solution is correct
"""
hasheable_transactions = [tx.__dict__ for tx in transactions]
input_string = (str(hasheable_transactions) + str(prev_hash) + str(nonce)).encode()
hash = sha256(input_string).hexdigest()
return hash[0:MINING_DIFFICULTY] == "000"
def proof_of_work(transactions, prev_hash):
"""
Attempts to solve the PoW problem by brute force
"""
nonce = 1
print("⛏ Mining started")
while not find_proof_of_work(transactions, prev_hash, nonce):
nonce += 1
print("⛏Mining ended with nonce " + str(nonce))
return nonce