-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmining.py
69 lines (55 loc) · 2.1 KB
/
mining.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
66
67
68
69
import data
import threading
import broadcast
import time
import copy
import utilities
from random import seed,randint
def mine():
x = threading.Thread(target=mine_thread)
with data.miningLock:
if not data.someoneIsMining:
data.someoneIsMining=True
x.start()
else:
print("Mining is already taking place")
return
def mine_thread():
with data.benchmarkLock:
t1=time.time()
seed()
with data.lock:
if len(data.current_transactions)<data.capacity:
with data.miningLock:
data.someoneIsMining=False
return
listOfTrans=[]
for trans in data.current_transactions.values():
listOfTrans.append(trans.asDictionary())
if len(listOfTrans)==data.capacity:# ωστε να μπαινουν παντα ακριβως capacity transactions σε ενα block
break
dictionary={
'index':copy.deepcopy(data.blockchain.chain[-1].index+1),
'timestamp':copy.deepcopy(time.time()),
'transactions':listOfTrans,
'nonce': (randint(0, 100000)),
'current_hash':'1234',
'previous_hash':copy.deepcopy(data.blockchain.chain[-1].current_hash)
}
testingBlock=utilities.asObject(dictionary,"block")
magicNonce=proof_of_work(testingBlock)#εδω θα κατσουμε για αρκετη ωρα
with data.benchmarkLock:
data.miningTimes.append(time.time()-t1)
testingBlock.current_hash=testingBlock.hash()#εχουμε το σωστο hash πλεον
print(f"I mined this block {testingBlock.index} {testingBlock.current_hash} {testingBlock.nonce}")
with data.miningLock:
data.someoneIsMining=False
broadcast.broadcast_a_block(testingBlock)
return
def proof_of_work(block):#βρισκει το καταλληλο nonce και το αποθηκευει
while valid_proof(block) is False:
block.nonce += 1
return block.nonce
def valid_proof(block):
guess_hash = block.hash()
return guess_hash[:data.difficulty] == '0'*data.difficulty