-
Notifications
You must be signed in to change notification settings - Fork 1
/
mine.py
65 lines (52 loc) · 1.76 KB
/
mine.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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import hashlib
import requests
from decouple import config
import json
from uuid import uuid4
from time import sleep
import random
import sys
api_key = config('API_KEY')
headers = {
'Authorization': api_key
}
def proof_of_work(last_proof, difficulty):
print("Searching for next proof")
block_string = json.dumps(last_proof, sort_keys=True)
# print(block_string, last_proof, difficulty)
proof = random.randint(0, 10000000000)
while valid_proof(block_string, proof, difficulty) is False:
proof += 1
print("Proof found: " + str(proof))
return proof
def valid_proof(last_hash, proof, difficulty):
difficult = '0' * difficulty
guess = f"{last_hash}{proof}".encode()
guess_hash = hashlib.sha256(guess).hexdigest()
return guess_hash[:difficulty] == difficult
if __name__ == '__main__':
# What node are we interacting with?
if len(sys.argv) > 1:
node = sys.argv[1]
else:
node = 'https://lambda-treasure-hunt.herokuapp.com/api/bc/'
coins_mined = 0
# Run forever until interrupted
while True:
# Get the last proof from the server
r = requests.get(url=node + "/last_proof", headers={'Authorization': api_key})
data = r.json()
# print(data)
new_proof = proof_of_work(data.get('proof'), data.get('difficulty'))
post_data = {"proof": new_proof}
print(post_data)
r = requests.post(url=node + "/mine", json=post_data, headers={'Authorization': api_key})
data = r.json()
sleep(data['cooldown'])
print('data', data)
if data.get('message') == 'New Block Forged':
coins_mined += 1
print("Total coins mined: " + str(coins_mined))
else:
print('Breaking...')
break