-
Notifications
You must be signed in to change notification settings - Fork 0
/
datatypes.py
212 lines (185 loc) · 7.89 KB
/
datatypes.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
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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
import multiprocessing
import pickle
import sys
import threading
import time
import config
import crypto
import database
import interface
import utils
def transaction(wallet_in: str, wallet_out: str, amount: int, index: int,
private_key=None, cache=False, signature=None, data_type='transaction'):
if data_type != 'transaction':
raise UserWarning
transaction_dict = {'wallet_in': wallet_in, 'wallet_out': wallet_out,
'amount': amount, 'index': index, 'data_type': 'transaction',
'signature': signature
}
signer, verifier, _ = crypto.eddsa(wallet_in, private_key)
validated = [None]
transaction_hash = [None]
def sign():
transaction_dict['signature'] = signer(crypto.pickle_hash(transaction_dict))
def verify():
updated_signature = transaction_dict.pop('signature')
transaction_dict['signature'] = None
if not verifier(crypto.pickle_hash(transaction_dict), updated_signature):
transaction_dict['signature'] = updated_signature
return False
transaction_dict['signature'] = updated_signature
try:
if not database.read('wallet', wallet_in) >= amount:
return False
except TypeError:
return False
tx_hash = crypto.pickle_hash(transaction_dict).decode(errors='ignore')
if database.read('transaction', tx_hash) is not None:
return False
validated[0] = True
transaction_hash[0] = tx_hash
return True
def store():
if validated[0] or (validated[0] is None and verify()):
if cache:
database.append(transaction_dict, 'transaction', 'cache')
else:
database.write(transaction_dict, 'transaction', transaction_hash[0])
database.sub('wallet', wallet_in, amount)
database.add('wallet', wallet_out, amount)
return transaction_dict
return sign, verify, store
def block(block_index, wallet, transactions: list, difficulty, block_previous,
timestamp=None, nonce=None, signature=None, private_key=None):
header = {'wallet': wallet, 'transactions': transactions, 'nonce': nonce,
'timestamp': int(time.time()) if timestamp is None else timestamp,
'difficulty': difficulty, 'block_index': str(block_index),
'signature': signature, 'block_previous': block_previous
}
signer, verifier, _ = crypto.eddsa(wallet, private_key)
def sign():
header['signature'] = None
header['signature'] = signer(crypto.pickle_hash(header))
if signature is None:
sign()
diff = 2 ** 256 - 1
diff //= difficulty
mining_manager = multiprocessing.Manager()
mining = mining_manager.list()
mining.append(False)
mining_thread = []
verified = [None]
nonce_maximum = interface.balance(wallet, True) - 1
def update_timestamp():
if mining[0]:
header['timestamp'] = int(time.time())
while mining[0]:
time.sleep(1)
header['timestamp'] += 1
def add_transactions():
while mining[0]:
new_transactions = database.read('transaction', 'cache')
transactions.extend(new_transactions)
database.write([], 'transaction', 'cache')
database.append(new_transactions, 'transaction', 'mined')
time.sleep(1)
def check_hash(header_hash):
return utils.bytes_to_int(header_hash) < diff
def random_hash():
header['nonce'] += 1
sign()
return crypto.pickle_hash(header)
def mining_process(event, callback, start: int, end: int):
try:
header['nonce'] = start
prev_timestamp = header['timestamp']
header_hash = random_hash()
threading.Thread(target=add_transactions, daemon=True).start()
threading.Thread(target=update_timestamp, daemon=True).start()
while not check_hash(header_hash):
if header['nonce'] >= end:
while header['timestamp'] == prev_timestamp:
time.sleep(1e-3)
prev_timestamp = header['timestamp']
header['nonce'] = start
header_hash = random_hash()
multiprocessing.Process(target=callback, args=(header,)).start()
event.set()
except Exception as exc:
import traceback
traceback.print_exc()
def mining_handler(callback, threads):
try:
found_block = multiprocessing.Event()
individual_end = nonce_maximum / threads
processes = [multiprocessing.Process(target=mining_process,
args=(found_block, callback,
int(individual_end * idx),
int(individual_end * (idx + 1))))
for idx in range(threads)]
any(proc.start() for proc in processes)
while not found_block.wait(
1e-3) and interface.block_height() <= block_index:
time.sleep(1e-3)
any(proc.terminate() for proc in processes)
any(proc.join() for proc in processes)
except Exception as exc:
import traceback
traceback.print_exc()
def mine(state, callback=None, threads=16):
mining[0] = state
if state and len(mining_thread) < threads:
mining_thread.append(threading.Thread(target=mining_handler,
args=(callback, threads)))
mining_thread[-1].start()
elif not state and mining_thread:
mining_thread.clear()
def _verify():
if not check_hash(crypto.pickle_hash(header)):
print("H1")
return False
if header['nonce'] > nonce_maximum:
return False
header['signature'] = None
if not verifier(crypto.pickle_hash(header), signature):
header['signature'] = signature
print("H2")
return False
header['signature'] = signature
for tx in transactions:
if not isinstance(tx, dict):
raise UserWarning
if not transaction(**tx)[1]():
print("H3")
return False
return True
def verify():
if verified[0] is None:
verified[0] = _verify()
return verified[0]
def store():
if verify():
database.write(header, 'block',
crypto.pickle_hash(header).decode(errors='ignore'))
for tx in transactions:
transaction(**tx)[2]()
block_size = sys.getsizeof(pickle.dumps(header, protocol=4))
old_mean = interface.add_mean_block_size(block_size)
reward = config.reward_function(block_index, block_size, old_mean)
database.add('wallet', wallet, reward)
height = database.read('block_height', 'main')
if block_index == height: # < implies insertion | > does not exist
database.add('block_height', 'main', 1)
return
return False
return check_hash, mine, verify, store
def block_at_index(block_index, wallet, transactions: list, timestamp=None, nonce=None,
signature=None, private_key=None, **kwargs):
return block(block_index, wallet, transactions,
interface.difficulty_at_index(block_index),
interface.block_hash_at_index(int(block_index) - 1), timestamp, nonce,
signature,
private_key)
def top_block(wallet, transactions, **kwargs):
kwargs['block_index'] = interface.block_height()
return block_at_index(wallet=wallet, transactions=transactions, **kwargs)