-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblockchain.py
More file actions
148 lines (121 loc) · 4.96 KB
/
blockchain.py
File metadata and controls
148 lines (121 loc) · 4.96 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
import contextlib
import hashlib
import json
import logging
import sys
import time
import threading
from ecdsa import NIST256p
from ecdsa import VerifyingKey
import utils
MINING_DIFFICULTY = 3
MINING_SENDER = 'THE BLOCKCHAIN'
MINING_REWARD = 1.0
MINING_TIMER_SEC = 20
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
logger = logging.getLogger(__name__)
class BlockChain(object):
def __init__(self, blockchain_address=None, port=None):
self.transaction_pool = []
self.chain = []
self.create_block(0, self.hash({}))
self.blockchain_address = blockchain_address
self.port = port
self.mining_semaphore = threading.Semaphore(1)
def create_block(self, nonce, previous_hash):
block = utils.sorted_dict_by_key({
'timestamp': time.time(),
'transactions': self.transaction_pool,
'nonce': nonce,
'previous_hash': previous_hash
})
self.chain.append(block)
self.transaction_pool = []
return block
def hash(self, block):
sorted_block = json.dumps(block, sort_keys=True)
return hashlib.sha256(sorted_block.encode()).hexdigest()
def add_transaction(self, sender_blockchain_address,
recipient_blockchain_address, value,
sender_public_key=None, signature=None):
transaction = utils.sorted_dict_by_key({
'sender_blockchain_address': sender_blockchain_address,
'recipient_blockchain_address': recipient_blockchain_address,
'value': float(value)
})
if sender_blockchain_address == MINING_SENDER:
self.transaction_pool.append(transaction)
return True
if self.verify_transaction_signature(
sender_public_key, signature, transaction):
# if self.calculate_total_amount(sender_blockchain_address) < float(value):
# logger.error({'action': 'add_transaction', 'error': 'no_value'})
# return False
self.transaction_pool.append(transaction)
return True
return False
def create_transaction(self, sender_blockchain_address,
recipient_blockchain_address, value,
sender_public_key, signature):
is_transacted = self.add_transaction(
sender_blockchain_address, recipient_blockchain_address,
value, sender_public_key, signature)
# TODO
# Sync
return is_transacted
def verify_transaction_signature(
self, sender_public_key, signature, transaction):
sha256 = hashlib.sha256()
sha256.update(str(transaction).encode('utf-8'))
message = sha256.digest()
signature_bytes = bytes().fromhex(signature)
verifying_key = VerifyingKey.from_string(
bytes().fromhex(sender_public_key), curve=NIST256p)
verified_key = verifying_key.verify(signature_bytes, message)
return verified_key
def valid_proof(self, transactions, previous_hash, nonce,
difficulty=MINING_DIFFICULTY):
guess_block = utils.sorted_dict_by_key({
'transactions': transactions,
'nonce': nonce,
'previous_hash': previous_hash
})
guess_hash = self.hash(guess_block)
return guess_hash[:difficulty] == '0'*difficulty
def proof_of_work(self):
transactions = self.transaction_pool.copy()
previous_hash = self.hash(self.chain[-1])
nonce = 0
while self.valid_proof(transactions, previous_hash, nonce) is False:
nonce += 1
return nonce
def mining(self):
if not self.transaction_pool:
return False
nonce = self.proof_of_work()
self.add_transaction(
sender_blockchain_address=MINING_SENDER,
recipient_blockchain_address=self.blockchain_address,
value=MINING_REWARD)
previous_hash = self.hash(self.chain[-1])
self.create_block(nonce, previous_hash)
logger.info({'action': 'mining', 'status': 'success'})
return True
def start_mining(self):
is_acquire = self.mining_semaphore.acquire(blocking=False)
if is_acquire:
with contextlib.ExitStack() as stack:
stack.callback(self.mining_semaphore.release)
self.mining()
loop = threading.Timer(MINING_TIMER_SEC, self.start_mining)
loop.start()
def calculate_total_amount(self, blockchain_address):
total_amount = 0.0
for block in self.chain:
for transaction in block['transactions']:
value = float(transaction['value'])
if blockchain_address == transaction['recipient_blockchain_address']:
total_amount += value
if blockchain_address == transaction['sender_blockchain_address']:
total_amount -= value
return total_amount