-
Notifications
You must be signed in to change notification settings - Fork 0
/
Miner.py
43 lines (37 loc) · 1.38 KB
/
Miner.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
"""
project: PyBlockchain
author: Abdel Rahman Hussein
email: abdelrahman146@outlook.com
github: http://github.com/abdelrahman146
This class defines a Miner
The Miner is the machine that creates new blocks and add it to the Blockchain
"""
import json
from Mempool import get_mempool
from Blockchain.Block import Block
from Blockchain.Blockchain import get_blockchain
from helpers import hashing
from threading import Thread
class Miner(Thread):
def __init__(self, owner_public_key, owner_message):
Thread.__init__(self)
self.mempool = get_mempool()
self.blockchain = get_blockchain()
self.owner_public_key = owner_public_key
self.owner_message = owner_message
def run(self):
while True:
self.mine()
def mine(self):
if len(self.mempool.contracts) == 5:
previous_block = json.loads(self.blockchain.peak())
previous_block_hash = previous_block['block_hash']
block = Block(
previous_block_hash=previous_block_hash,
contracts=self.mempool.contracts,
miner_public_key=hashing.hash(self.owner_public_key),
miner_message=self.owner_message
)
self.blockchain.insert_block(block)
print("Block %d is successfully added by the miner" % self.blockchain.get_height())
self.mempool.clean_pool()