-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmine.py
More file actions
90 lines (76 loc) · 2.79 KB
/
mine.py
File metadata and controls
90 lines (76 loc) · 2.79 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import hashlib
from decouple import config
import sys
import json
from main_functions import cooldown
from uuid import uuid4
from timeit import default_timer as timer
import random
from endpoints import *
import time
def proof_of_work(last_proof, difficulty):
"""
Multi-Ouroboros of Work Algorithm
- Find a number p' such that the last six digits of hash(p) are equal
to the first six digits of hash(p')
- IE: last_hash: ...AE9123456, new hash 123456888...
- p is the previous proof, and p' is the new proof
- Use the same method to generate SHA-256 hashes as the examples in class
"""
block_string = json.dumps(last_proof, sort_keys=True)
# print(block_string, last_proof, difficulty)
proof = random.randint(0, 10000000000)
start = timer()
while valid_proof(block_string, proof, difficulty) == False and timer() - start < 5:
proof += 1
if valid_proof(block_string, proof, difficulty) == True:
print("Proof found: " + str(proof) + " in " + str(timer() - start))
return proof
else:
return None
def valid_proof(last_hash, proof, difficulty):
"""
Validates the Proof: Multi-ouroborus: Do the last six characters of
the hash of the last proof match the first six characters of the hash
of the new proof?
IE: last_hash: ...AE9123456, new hash 123456E88...
"""
difficultStr = '0' * difficulty
guess = f"{last_hash}{proof}".encode()
guess_hash = hashlib.sha256(guess).hexdigest()
# encoded_hash = f"{last_hash}".encode()
# hash_last_hash = hashlib.sha256(encoded_hash).hexdigest()
# print(guess_hash, difficultStr)
return guess_hash[:difficulty] == difficultStr
if __name__ == '__main__':
# What node are we interacting with?
if len(sys.argv) > 1:
node = sys.argv[1]
else:
node = bc_url
# Run forever until interrupted
while True:
print('Searching for new proof...')
new_proof = None
while new_proof == None:
# Get the last proof from the server
last_proof_res = last_proof()
time.sleep(last_proof_res['cooldown']) # still add CD just in case find proof > 1s
new_proof = proof_of_work(last_proof_res['proof'], last_proof_res['difficulty'])
# Check to see if mining with found proof works
mine_res = mine(new_proof)
cooldown(mine_res)
if not mine_res['errors']:
if mine_res['messages']:
if 'New Block Forged' in mine_res['messages']:
print('''
>!!!!!!!!!!!!!!!!!!!!<
>!!! !!!<
>!!! Coin Mined !!!<
>!!! !!!<
>!!!!!!!!!!!!!!!!!!!!<
''')
break
else:
print(mine_res['errors'][0])
print('Trying again...\n')