-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminingThread.py
More file actions
57 lines (46 loc) · 1.73 KB
/
miningThread.py
File metadata and controls
57 lines (46 loc) · 1.73 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
import threading
from time import sleep
from typing import TYPE_CHECKING
from chain.block import Block
from util.helpers import CHAIN_SIZE, DIFFICULTY_LEVEL
if TYPE_CHECKING:
from model import Model
class MiningThread(threading.Thread):
def __init__(self, model: 'Model'):
super(MiningThread, self).__init__()
self.__model = model
self.__stop_event = threading.Event()
self.__transactions = []
self.__prev_hash = ""
self.__diff = DIFFICULTY_LEVEL
# self.__block = None
# def set_data(self, transactions, prev_block_hash, difficulty):
# self.__transactions = transactions
# self.__prev_hash = prev_block_hash
# self.__diff = difficulty
# def get_block(self):
# return self.__block
def stop(self):
self.__stop_event.set()
def stopped(self):
return self.__stop_event.is_set()
def run(self):
self.__transactions = self.__model.unconfirmed_tx_pool[0:CHAIN_SIZE]
self.__prev_hash = self.__model.blockchain.get_head_of_chain().block.block_hash
pow_found = False
nonce = 0
block = None
while not pow_found:
if self.stopped():
break
block = Block(transactions=self.__transactions, previous_hash=self.__prev_hash, nonce=nonce)
if block.hash_difficulty() == self.__diff:
pow_found = True
nonce += 1
if pow_found:
self.__model.unconfirmed_tx_pool[0:CHAIN_SIZE] = []
self.__model.blockchain.add_block(block)
self.__model.broadcast_new_block(block)
print(str(block))
# TODO: broadcast new block
# self.__model.verify_block(block)