-
Notifications
You must be signed in to change notification settings - Fork 79
Expand file tree
/
Copy pathminer.py
More file actions
62 lines (56 loc) · 1.66 KB
/
miner.py
File metadata and controls
62 lines (56 loc) · 1.66 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
# coding:utf-8
from block import Block
import time
from transaction import Vout, Transaction
from account import get_account
from database import BlockChainDB, TransactionDB, UnTransactionDB
from lib.common import unlock_sig, lock_sig
MAX_COIN = 21000000
REWARD = 20
def reward():
reward = Vout(get_account()['address'], REWARD)
tx = Transaction([], reward)
return tx
def coinbase():
"""
First block generate.
"""
rw = reward()
cb = Block(0, int(time.time()), [rw.hash], "")
nouce = cb.pow()
cb.make(nouce)
# Save block and transactions to database.
BlockChainDB().insert(cb.to_dict())
TransactionDB().insert(rw.to_dict())
return cb
def get_all_untransactions():
UnTransactionDB().all_hashes()
def mine():
"""
Main miner method.
"""
# Found last block and unchecked transactions.
last_block = BlockChainDB().last()
if len(last_block) == 0:
last_block = coinbase().to_dict()
untxdb = UnTransactionDB()
# Miner reward
rw = reward()
untxs = untxdb.find_all()
untxs.append(rw.to_dict())
# untxs_dict = [untx.to_dict() for untx in untxs]
untx_hashes = untxdb.all_hashes()
# Clear the untransaction database.
untxdb.clear()
# Miner reward is the first transaction.
untx_hashes.insert(0,rw.hash)
cb = Block( last_block['index'] + 1, int(time.time()), untx_hashes, last_block['hash'])
nouce = cb.pow()
cb.make(nouce)
# Save block and transactions to database.
BlockChainDB().insert(cb.to_dict())
TransactionDB().insert(untxs)
# Broadcast to other nodes
Block.spread(cb.to_dict())
Transaction.blocked_spread(untxs)
return cb