forked from hclivess/Bismuth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
node.py
2683 lines (2077 loc) · 122 KB
/
node.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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# it's recommended to only use code from the "release" state, running master blob may have issues
# never remove the str() conversion in data evaluation or database inserts or you will debug for 14 days as signed types mismatch
# if you raise in the server thread, the server will die and node will stop
# never use codecs, they are bugged and do not provide proper serialization
# must unify node and client now that connections parameters are function parameters
# if you have a block of data and want to insert it into sqlite, you must use a single "commit" for the whole batch, it's 100x faster
# do not isolation_level=None/WAL hdd levels, it makes saving slow
VERSION = "4.1.9"
from itertools import groupby
from operator import itemgetter
import shutil, socketserver, base64, hashlib, os, re, sqlite3, sys, threading, time, socks, log, options, connections, random, keys, math, requests, tarfile, essentials
import statistics
from Crypto.Hash import SHA
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
# load config
# global ban_threshold
global hdd_block
dl_lock = threading.Lock()
db_lock = threading.Lock()
mem_lock = threading.Lock()
peersync_lock = threading.Lock()
config = options.Get()
config.read()
debug_level = config.debug_level_conf
port = config.port
genesis_conf = config.genesis_conf
verify_conf = config.verify_conf
thread_limit_conf = config.thread_limit_conf
rebuild_db_conf = config.rebuild_db_conf
debug_conf = config.debug_conf
node_ip_conf = config.node_ip_conf
purge_conf = config.purge_conf
pause_conf = config.pause_conf
ledger_path_conf = config.ledger_path_conf
hyper_path_conf = config.hyper_path_conf
hyper_recompress_conf = config.hyper_recompress_conf
ban_threshold = config.ban_threshold
tor_conf = config.tor_conf
debug_level_conf = config.debug_level_conf
allowed = config.allowed_conf
pool_ip_conf = config.pool_ip_conf
sync_conf = config.sync_conf
pool_percentage_conf = config.pool_percentage_conf
mining_threads_conf = config.mining_threads_conf
diff_recalc_conf = config.diff_recalc_conf
pool_conf = config.pool_conf
ram_conf = config.ram_conf
pool_address = config.pool_address_conf
version = config.version_conf
version_allow = config.version_allow
full_ledger = config.full_ledger_conf
reveal_address=config.reveal_address
accept_peers=config.accept_peers
nodes_ban_reset=config.nodes_ban_reset
global banlist
banlist=config.banlist
global whitelist
whitelist=config.whitelist
def validate_pem(public_key):
# verify pem as cryptodome does
pem_data = base64.b64decode(public_key).decode("utf-8")
regex = re.compile("\s*-----BEGIN (.*)-----\s+")
match = regex.match(pem_data)
if not match:
raise ValueError("Not a valid PEM pre boundary")
marker = match.group(1)
regex = re.compile("-----END (.*)-----\s*$")
match = regex.search(pem_data)
if not match or match.group(1) != marker:
raise ValueError("Not a valid PEM post boundary")
# verify pem as cryptodome does
def fee_calculate(openfield, keep):
fee = '%.8f' % float(0.01 + (float(len(openfield)) / 100000)) # 0.01 dust
if "token:issue:" in openfield:
fee = '%.8f' % (float(fee) + 10)
if "alias=" in openfield:
fee = '%.8f' % (float(fee) + 1)
return fee
def download_file(url, filename):
try:
r = requests.get(url, stream=True)
total_size = int(r.headers.get('content-length'))/1024
with open(filename, 'wb') as filename:
chunkno = 0
for chunk in r.iter_content(chunk_size=1024):
if chunk:
chunkno = chunkno + 1
if chunkno % 10000 == 0: # every x chunks
print("Downloaded {} %".format(int(100 * ((chunkno) / total_size))))
filename.write(chunk)
filename.flush()
print ("Downloaded 100 %")
return filename
except:
raise
if "testnet" in version: #overwrite for testnet
port = 2829
full_ledger = 0
hyper_path_conf = "static/test.db"
hyper_recompress_conf = 0
peerlist = "peers_test.txt"
redownload_test = input("Welcome to the testnet. Redownload test ledger? y/n")
if redownload_test == "y" or not os.path.exists("static/test.db"):
download_file("http://bismuth.cz/test.db", "static/test.db")
else:
print("Not redownloading test db")
else:
peerlist = "peers.txt"
# load config
def most_common(lst):
return max(set(lst), key=lst.count)
def bootstrap():
try:
archive_path = ledger_path_conf + ".tar.gz"
download_file("http://bismuth.cz/ledger.tar.gz", archive_path)
tar = tarfile.open(archive_path)
tar.extractall("static/") # NOT COMPATIBLE WITH CUSTOM PATH CONFS
tar.close()
except:
app_log.warning("Something went wrong during bootstrapping, aborted")
raise
def check_integrity(database):
# check ledger integrity
ledger_check = sqlite3.connect(database)
ledger_check.text_factory = str
l = ledger_check.cursor()
try:
l.execute("PRAGMA table_info('transactions')")
redownload = 0
except:
redownload = 1
if len(l.fetchall()) != 12:
app_log.warning("Integrity check on database failed, bootstrapping from the website")
redownload = 1
else:
ledger_check.close()
if redownload == 1:
bootstrap()
def percentage(percent, whole):
return float((percent * whole) / 100)
def db_to_drive(hdd, h, hdd2, h2):
global hdd_block
app_log.warning("Moving new data to HDD")
if ram_conf == 1: #select RAM as source database
source_db = sqlite3.connect('file::memory:?cache=shared', uri=True, timeout=1)
else: #select hyper.db as source database
source_db = sqlite3.connect(hyper_path_conf, timeout=1)
source_db.text_factory = str
sc = source_db.cursor()
execute_param(sc, ("SELECT * FROM transactions WHERE block_height > ? ORDER BY block_height ASC"), (hdd_block,))
result1 = sc.fetchall()
if full_ledger == 1: #we want to save to ledger.db from hyper.db
for x in result1:
h.execute("INSERT INTO transactions VALUES (?,?,?,?,?,?,?,?,?,?,?,?)", (x[0], x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11]))
commit(hdd)
if ram_conf == 1: #we want to save to hyper.db from RAM
for x in result1:
h2.execute("INSERT INTO transactions VALUES (?,?,?,?,?,?,?,?,?,?,?,?)", (x[0], x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11]))
commit(hdd2)
execute_param(sc, ("SELECT * FROM misc WHERE block_height > ? ORDER BY block_height ASC"), (hdd_block,))
result2 = sc.fetchall()
if full_ledger == 1: #we want to save to ledger.db from hyper.db
for x in result2:
h.execute("INSERT INTO misc VALUES (?,?)", (x[0], x[1]))
commit(hdd)
if ram_conf == 1: #we want to save to hyper.db from RAM
for x in result2:
h2.execute("INSERT INTO misc VALUES (?,?)", (x[0], x[1]))
commit(hdd2)
# reward
execute_param(sc, ('SELECT * FROM transactions WHERE address = "Development Reward" AND CAST(openfield AS INTEGER) > ?'), (hdd_block,))
result3 = sc.fetchall()
if full_ledger == 1: #we want to save to ledger.db from hyper.db
for x in result3:
h.execute("INSERT INTO transactions VALUES (?,?,?,?,?,?,?,?,?,?,?,?)", (x[0], x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11]))
commit(hdd)
elif ram_conf == 1: #we want to save to hyper.db from RAM
for x in result3:
h2.execute("INSERT INTO transactions VALUES (?,?,?,?,?,?,?,?,?,?,?,?)", (x[0], x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11]))
commit(hdd2)
# reward
h2.execute("SELECT block_height FROM transactions ORDER BY block_height DESC LIMIT 1")
hdd_block = h2.fetchone()[0]
app_log.warning("Ledger updated successfully")
def db_h_define():
hdd = sqlite3.connect(ledger_path_conf, timeout=1)
hdd.text_factory = str
h = hdd.cursor()
hdd.execute("PRAGMA page_size = 4096;")
return hdd, h
def db_h2_define():
hdd2 = sqlite3.connect(hyper_path_conf, timeout=1)
hdd2.text_factory = str
h2 = hdd2.cursor()
hdd2.execute("PRAGMA page_size = 4096;")
return hdd2, h2
def db_c_define():
global hdd_block
try:
if ram_conf == 1:
conn = sqlite3.connect('file::memory:?cache=shared', uri=True, timeout=1, isolation_level=None)
else:
conn = sqlite3.connect(hyper_path_conf, uri=True, timeout=1, isolation_level=None)
conn.execute('PRAGMA journal_mode = WAL;')
conn.execute("PRAGMA page_size = 4096;")
conn.text_factory = str
c = conn.cursor()
except Exception as e:
app_log.info(e)
return conn, c
def db_b_define():
backup = sqlite3.connect('backup.db', timeout=1)
backup.text_factory = str
b = backup.cursor()
return backup, b
def db_m_define():
mempool = sqlite3.connect('mempool.db', timeout=1)
mempool.text_factory = str
m = mempool.cursor()
return mempool, m
app_log = log.log("node.log", debug_level_conf)
app_log.warning("Configuration settings loaded")
def unban(peer_ip):
global warning_list
#global banlist
# warning_list = [x for x in warning_list if x != peer_ip] #delete all
# banlist = [x for x in banlist if x != peer_ip]
if peer_ip in warning_list:
warning_list.remove(peer_ip)
app_log.warning("Removed a warning for {}".format(peer_ip))
def warning(sdef, ip, reason, count):
global banlist
global warning_list
global ban_threshold
if ip not in whitelist:
for x in range(count):
warning_list.append(ip)
app_log.warning("Added {} warning(s) to {}: {} ({} / {})".format(count, ip, reason, warning_list.count(ip), ban_threshold))
if warning_list.count(ip) >= ban_threshold:
banlist.append(ip)
sdef.close()
app_log.warning("{} is banned: {}".format(ip, reason))
return "banned"
def ledger_convert(ledger_path_conf, hyper_path_conf):
try:
if os.path.exists(hyper_path_conf):
if full_ledger == 1:
# cross-integrity check
hdd = sqlite3.connect(ledger_path_conf, timeout=1)
hdd.text_factory = str
h = hdd.cursor()
h.execute("SELECT block_height FROM transactions ORDER BY block_height DESC LIMIT 1")
hdd_block_last = h.fetchone()[0]
hdd.close()
hdd2 = sqlite3.connect(hyper_path_conf, timeout=1)
hdd2.text_factory = str
h2 = hdd2.cursor()
h2.execute("SELECT block_height FROM transactions ORDER BY block_height DESC LIMIT 1")
hdd2_block_last = h2.fetchone()[0]
hdd2.close()
# cross-integrity check
if hdd_block_last == hdd2_block_last and hyper_recompress_conf == 1: # cross-integrity check
ledger_path_conf = hyper_path_conf # only valid within the function
app_log.warning("Recompressing hyperblocks (keeping full ledger)")
recompress = 1
elif hdd_block_last == hdd2_block_last and hyper_recompress_conf == 0:
app_log.warning("Hyperblock recompression skipped")
recompress = 0
else:
app_log.warning("Cross-integrity check failed, hyperblocks will be rebuilt from full ledger")
recompress = 1
else:
if hyper_recompress_conf == 1:
app_log.warning("Recompressing hyperblocks (without full ledger)")
recompress = 1
else:
app_log.warning("Hyperblock recompression skipped")
recompress = 0
else:
app_log.warning("Compressing ledger to Hyperblocks")
recompress = 1
if recompress == 1:
depth = 10000 # REWORK TO REFLECT TIME INSTEAD OF BLOCKS
# if os.path.exists(ledger_path_conf + '.temp'):
# os.remove(ledger_path_conf + '.temp')
if full_ledger == 1:
shutil.copy(ledger_path_conf, ledger_path_conf + '.temp')
hyper = sqlite3.connect(ledger_path_conf + '.temp')
else:
shutil.copy(hyper_path_conf, ledger_path_conf + '.temp')
hyper = sqlite3.connect(ledger_path_conf + '.temp')
hyper.text_factory = str
hyp = hyper.cursor()
end_balance = 0
addresses = []
hyp.execute("UPDATE transactions SET address = 'Hypoblock' WHERE address = 'Hyperblock'")
hyp.execute("SELECT block_height FROM transactions ORDER BY block_height DESC LIMIT 1;")
db_block_height = hyp.fetchone()[0]
for row in hyp.execute("SELECT * FROM transactions WHERE (block_height < ?) ORDER BY block_height;",
(str(int(db_block_height) - depth),)):
db_address = row[2]
db_recipient = row[3]
addresses.append(db_address.strip())
addresses.append(db_recipient.strip())
unique_addressess = set(addresses)
for x in set(unique_addressess):
hyp.execute("SELECT sum(amount) FROM transactions WHERE (recipient = ? AND block_height < ?);", (x,) + (str(int(db_block_height) - depth),))
credit = hyp.fetchone()[0]
credit = 0 if credit is None else float('%.8f' % credit)
hyp.execute("SELECT sum(amount),sum(fee),sum(reward) FROM transactions WHERE (address = ? AND block_height < ?);", (x,) + (str(int(db_block_height) - depth),))
result = hyp.fetchall()
debit = result[0][0]
debit = 0 if debit is None else float('%.8f' % debit)
fees = result[0][1]
fees = 0 if fees is None else float('%.8f' % fees)
rewards = result[0][2]
rewards = 0 if rewards is None else float('%.8f' % rewards)
end_balance = float('%.8f' % (float(credit) - float(debit) - float(fees) + float(rewards)))
# app_log.info("Address: "+ str(x))
# app_log.info("Credit: " + str(credit))
# app_log.info("Debit: " + str(debit))
# app_log.info("Fees: " + str(fees))
# app_log.info("Rewards: " + str(rewards))
# app_log.info("Balance: " + str(end_balance))
# test for keep positivity
#hyp.execute("SELECT block_height FROM transactions WHERE address OR recipient = ?", (x,))
#keep_is = 1
#try:
# hyp.fetchone()[0]
#except:
# keep_is = 0
# test for keep positivity
if end_balance > 0:
timestamp = str(time.time())
hyp.execute("INSERT INTO transactions VALUES (?,?,?,?,?,?,?,?,?,?,?,?)", (db_block_height - depth - 1, timestamp, "Hyperblock", x, float(end_balance), "0", "0", "0", "0", "0",
"0", "0"))
hyper.commit()
hyp.execute("DELETE FROM transactions WHERE block_height < ? AND address != 'Hyperblock';", (str(int(db_block_height) - depth),))
hyper.commit()
hyp.execute("DELETE FROM misc WHERE block_height < ?;", (str(int(db_block_height) - depth),)) #remove diff calc
hyper.commit()
hyp.execute("VACUUM")
hyper.close()
if os.path.exists(hyper_path_conf):
os.remove(hyper_path_conf) # remove the old hyperblocks
os.rename(ledger_path_conf + '.temp', hyper_path_conf)
if full_ledger == 0 and os.path.exists(ledger_path_conf) and "testnet" not in version:
os.remove(ledger_path_conf)
app_log.warning("Removed full ledger and only kept hyperblocks")
except Exception as e:
raise ValueError("There was an issue converting to Hyperblocks: {}".format(e))
def most_common(lst):
return max(set(lst), key=lst.count)
def bin_convert(string):
return ''.join(format(ord(x), '8b').replace(' ', '0') for x in string)
def commit(cursor):
"""Secure commit for slow nodes"""
while True:
try:
cursor.commit()
break
except Exception as e:
app_log.warning("Database cursor: {}".format(cursor))
app_log.warning("Database retry reason: {}".format(e))
time.sleep(random.uniform(0, 1))
def execute(cursor, query):
"""Secure execute for slow nodes"""
while True:
try:
cursor.execute(query)
break
except Exception as e:
app_log.warning("Database query: {} {}".format(cursor, query))
app_log.warning("Database retry reason: {}".format(e))
time.sleep(random.uniform(0, 1))
return cursor
def execute_param(cursor, query, param):
"""Secure execute w/ param for slow nodes"""
while True:
try:
cursor.execute(query, param)
break
except Exception as e:
app_log.warning("Database query: {} {} {}".format(cursor, query, param))
app_log.warning("Database retry reason: {}".format(e))
time.sleep(random.random())
return cursor
def difficulty(c, mode):
execute(c, "SELECT * FROM transactions ORDER BY block_height DESC LIMIT 2")
result = c.fetchone()
timestamp_last = float(result[1])
block_height = int(result[0])
timestamp_before_last = float(c.fetchone()[1])
if block_height < 400000: #REMOVE THIS AFTER HF
execute_param(c, ("SELECT block_height FROM transactions WHERE CAST(timestamp AS INTEGER) > ? AND reward != 0 ORDER BY block_height ASC"), (timestamp_last - 86400,)) # 86400=24h
blocks_list_1440 = c.fetchall()
blocks_per_1440 = len(blocks_list_1440)
block_time = (1440 / blocks_per_1440) * 60
execute(c, ("SELECT difficulty FROM misc ORDER BY block_height DESC LIMIT 1"))
diff_block_previous = float(c.fetchone()[0])
try:
log = float('%.13f' % math.log2(blocks_per_1440 / 1440))
except:
log = float('%.13f' % math.log2(0.5 / 1440))
app_log.info("Difficulty exception triggered! This should not happen!")
difficulty = float('%.13f' % (diff_block_previous + log)) # increase/decrease diff by a little
# min diff
execute_param(c, ("SELECT cast(difficulty as FLOAT) FROM misc WHERE block_height >= ?"), (blocks_list_1440[0][0],))
try:
diff_blocks_list_1440 = c.fetchall()
diff_blocks_list_1440 = [i[0] for i in diff_blocks_list_1440]
min_diff = statistics.mean(diff_blocks_list_1440)
except Exception:
min_diff = 90
# print(min_diff)
# min diff
if difficulty < min_diff:
difficulty = float('%.13f' % min_diff)
if mode == "verbose":
app_log.warning("Difficulty floor reached, difficulty readjusted to {}".format(difficulty))
time_now = time.time()
if time_now > timestamp_last + 600: # if 10 minutes passed
execute(c, ("SELECT difficulty FROM misc ORDER BY block_height DESC LIMIT 5"))
diff_5 = c.fetchall()[0]
diff_lowest_5 = float(min(diff_5))
if diff_lowest_5 < difficulty:
candidate = diff_lowest_5 # if lowest of last 5 is lower than calculated diff
else:
candidate = difficulty
difficulty2 = float('%.13f' % percentage(95, candidate)) # candidate -5%
else:
difficulty2 = difficulty
if difficulty < 90:
difficulty = 90
if difficulty2 < 90:
difficulty2 = 90
if mode == "verbose":
app_log.warning("Blocks per day: {}".format(blocks_per_1440))
app_log.warning("Daily block time: {}".format(block_time))
app_log.warning("Difficulty retargeting: {}".format(log))
app_log.warning("Difficulty: {} {}".format(difficulty, difficulty2))
# return (float(50), float(50)) #TEST ONLY
return (float(difficulty), float(difficulty2))
else: #KEEP THIS AFTER HF
execute_param(c, ("SELECT timestamp FROM transactions WHERE CAST(block_height AS INTEGER) > ? AND reward != 0 ORDER BY timestamp ASC LIMIT 2"), (block_height - 1441,))
timestamp_1441 = float(c.fetchone()[0])
block_time_prev = (timestamp_before_last - timestamp_1441)/1440
timestamp_1440 = float(c.fetchone()[0])
block_time = (timestamp_last - timestamp_1440)/1440
execute(c, ("SELECT difficulty FROM misc ORDER BY block_height DESC LIMIT 1"))
diff_block_previous = float(c.fetchone()[0])
# Assume current difficulty D is known
D = diff_block_previous
# Assume current blocktime is known, calculcated from historic data, for example last 1440 blocks
T = block_time
# Calculcate network hashrate
H = pow(2, D / 2.0) / (T * math.ceil(28 - D / 16.0))
# Calculate new difficulty for desired blocktime of 60 seconds
Td = 60.00
D0 = D
Dnew = (2 / math.log(2)) * math.log(H * Td * math.ceil(28 - D0 / 16.0))
# Feedback controller
Kd = 10
Dnew = Dnew - Kd*(block_time - block_time_prev)
diff_adjustment = (Dnew - D)/720 #reduce by factor of 720
Dnew_adjusted = D + diff_adjustment
difficulty = float('%.13f' % (Dnew_adjusted))
difficulty2 = difficulty
time_now = time.time()
if block_time > 70.0:
if time_now > timestamp_last + 300: # if more than 5 minutes passed
difficulty2 = difficulty - 1.0
if difficulty < 80:
difficulty = 80
if difficulty2 < 80:
difficulty2 = 80
if mode == "verbose":
app_log.warning("Time to generate block {}: {}".format(block_height,timestamp_last - timestamp_before_last))
app_log.warning("Current difficulty: {}".format(D))
app_log.warning("Current blocktime: {}".format(T))
app_log.warning("Current hashrate: {}".format(H))
app_log.warning("New difficulty after adjustment: {}".format(Dnew_adjusted))
app_log.warning("Difficulty: {} {}".format(difficulty, difficulty2))
return (float(difficulty), float(difficulty2))
global connection_pool
connection_pool = []
global peer_ip_list
peer_ip_list = []
global consensus_blockheight_list
consensus_blockheight_list = []
global tried
tried = []
global consensus_percentage
consensus_percentage = ""
global warning_list
warning_list = []
global consensus
consensus = ""
global syncing
syncing = []
# port = 2829 now defined by config
def mempool_merge(data, peer_ip, c, mempool, m):
if mem_lock.locked() == False:
mem_lock.acquire()
if not data:
app_log.info("Mempool from {} was empty".format(peer_ip))
mem_lock.release()
else:
app_log.info("Mempool merging started from {}".format(peer_ip))
while db_lock.locked() == True: # prevent transactions which are just being digested from being added to mempool
app_log.info("Waiting for block digestion to finish before merging mempool")
time.sleep(1)
# merge mempool
try:
block_list = data
for transaction in block_list: # set means unique
mempool_timestamp = '%.2f' % float(transaction[0])
mempool_address = str(transaction[1])[:56]
mempool_recipient = str(transaction[2])[:56]
mempool_amount = '%.8f' % float(transaction[3])
mempool_signature_enc = str(transaction[4])[:684]
mempool_public_key_hashed = str(transaction[5])[:1068]
mempool_keep = str(transaction[6])[:1]
mempool_openfield = str(transaction[7])
mempool_public_key = RSA.importKey(base64.b64decode(mempool_public_key_hashed)) # convert readable key to instance
mempool_signature_dec = base64.b64decode(mempool_signature_enc)
acceptable = 1
execute_param(m, ("SELECT * FROM transactions WHERE signature = ?;"), (mempool_signature_enc,)) # condition 1)
try:
dummy1 = m.fetchall()[0]
# app_log.info("That transaction is already in our mempool")
acceptable = 0
mempool_in = 1
except:
mempool_in = 0
# reject transactions which are already in the ledger
execute_param(c, ("SELECT * FROM transactions WHERE signature = ?;"), (mempool_signature_enc,)) # condition 2
try:
dummy2 = c.fetchall()[0]
# app_log.info("That transaction is already in our ledger")
# reject transactions which are already in the ledger
acceptable = 0
ledger_in = 1
except:
ledger_in = 0
if mempool_keep != "1" and mempool_keep != "0":
app_log.info = ("Mempool: Wrong keep value {}".format(mempool_keep))
acceptable = 0
if mempool_address != hashlib.sha224(base64.b64decode(mempool_public_key_hashed)).hexdigest():
app_log.info("Mempool: Attempt to spend from a wrong address")
acceptable = 0
if float(mempool_amount) < 0:
acceptable = 0
app_log.info("Mempool: Negative balance spend attempt")
if float(mempool_timestamp) > time.time() + 30: # dont accept future txs
acceptable = 0
if float(mempool_timestamp) < time.time() - 82800: # dont accept old txs, mempool needs to be harsher than ledger
acceptable = 0
if (mempool_in == 1) and (ledger_in == 1): # remove from mempool if it's in both ledger and mempool already
try:
execute_param(m, ("DELETE FROM transactions WHERE signature = ?;"), (mempool_signature_enc,))
commit(mempool)
app_log.info("Mempool: Transaction deleted from our mempool")
except: # experimental try and except
app_log.info("Mempool: Transaction was not present in the pool anymore")
pass # continue to mempool finished message
# verify signatures and balances
validate_pem(mempool_public_key_hashed)
# verify signature
verifier = PKCS1_v1_5.new(mempool_public_key)
hash = SHA.new(str((mempool_timestamp, mempool_address, mempool_recipient, mempool_amount, mempool_keep, mempool_openfield)).encode("utf-8"))
if not verifier.verify(hash, mempool_signature_dec):
acceptable = 0
app_log.info("Mempool: Wrong signature in mempool insert attempt: {}".format(transaction))
# verify signature
if acceptable == 1:
# verify balance
# app_log.info("Mempool: Verifying balance")
app_log.info("Mempool: Received address: {}".format(mempool_address))
# include mempool fees
execute_param(m, ("SELECT amount, keep, openfield FROM transactions WHERE address = ?;"), (mempool_address,))
result = m.fetchall()
debit_mempool = 0
if result != None:
for x in result:
debit_tx = float(x[0])
fee = fee_calculate(x[2], x[1])
debit_mempool = debit_mempool + debit_tx + float(fee)
else:
debit_mempool = 0
# include mempool fees
# include the new block
execute_param(c, ("SELECT sum(amount) FROM transactions WHERE recipient = ?;"), (mempool_address,))
credit_ledger = c.fetchone()[0]
credit_ledger = 0 if credit_ledger is None else float('%.8f' % credit_ledger)
credit = float(credit_ledger)
execute_param(c, ("SELECT sum(amount) FROM transactions WHERE address = ?;"), (mempool_address,))
debit_ledger = c.fetchone()[0]
debit_ledger = 0 if debit_ledger is None else float('%.8f' % debit_ledger)
debit = float(debit_ledger) + float(debit_mempool)
execute_param(c, ("SELECT sum(fee),sum(reward) FROM transactions WHERE address = ?;"), (mempool_address,))
result = c.fetchall()[0]
fees = result[0]
fees = 0 if fees is None else float('%.8f' % fees)
rewards = result[1]
rewards = 0 if rewards is None else float('%.8f' % rewards)
# app_log.info("Mempool: Total credit: " + str(credit))
# app_log.info("Mempool: Total debit: " + str(debit))
balance = float('%.8f' % (float(credit) - float(debit) - float(fees) + float(rewards) - float(mempool_amount)))
balance_pre = float('%.8f' % (float(credit_ledger) - float(debit_ledger) - float(fees) + float(rewards)))
# app_log.info("Mempool: Projected transction address balance: " + str(balance))
#fee = '%.8f' % float(0.01 + (float(len(mempool_openfield)) / 100000) + int(mempool_keep)) # 0.01 dust
fee = fee_calculate(mempool_openfield, mempool_keep)
time_now = time.time()
if float(mempool_timestamp) > float(time_now) + 30:
app_log.info("Mempool: Future transaction not allowed, timestamp {} minutes in the future".format((float(mempool_timestamp) - float(time_now)) / 60))
elif float(time_now) - 86400 > float(mempool_timestamp):
app_log.info("Mempool: Transaction older than 24h not allowed.")
elif float(mempool_amount) > float(balance_pre):
app_log.info("Mempool: Sending more than owned")
elif (float(balance)) - (float(fee)) < 0:
app_log.info("Mempool: Cannot afford to pay fees")
# verify signatures and balances
else:
execute_param(m, "INSERT INTO transactions VALUES (?,?,?,?,?,?,?,?)", (str(mempool_timestamp), str(mempool_address), str(mempool_recipient), str(mempool_amount),
str(mempool_signature_enc), str(mempool_public_key_hashed), str(mempool_keep), str(mempool_openfield)))
app_log.info("Mempool updated with a received transaction from {}".format(peer_ip))
commit(mempool) # Save (commit) the changes
# merge mempool
# receive mempool
# app_log.info("Mempool: Finished with {} received transactions from {}".format(len(block_list),peer_ip))
except:
app_log.info("Mempool: Error processing")
if debug_conf == 1:
raise
else:
return
finally:
mem_lock.release()
def peers_get():
peer_dict = {}
with open(peerlist) as f:
for line in f:
try:
line = re.sub("[\)\(\:\\n\'\s]", "", line)
peer_dict[line.split(",")[0]] = line.split(",")[1]
except Exception as e:
app_log.warning("Skipping peerlist entry because of wrong format: {}".format(line))
return peer_dict
def purge_old_peers():
drop_peer_dict = []
peer_dict = peers_get()
for key, value in peer_dict.items():
HOST = key
# app_log.info(HOST)
PORT = int(value)
# app_log.info(PORT)
try:
s = socks.socksocket()
s.settimeout(0.6)
if tor_conf == 1:
s.settimeout(5)
s.setproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
# s.setblocking(0)
s.connect((HOST, PORT))
s.close()
except:
if purge_conf == 1 and "testnet" not in version:
# remove from peerlist if not connectible
drop_peer_dict.append(key)
print("Removed formerly active peer {} {}".format(HOST, PORT))
pass
output = open(peerlist, 'w')
for key, value in peer_dict.items():
if key not in drop_peer_dict:
output.write("('" + key + "', '" + value + "')\n")
output.close()
def verify(c):
try:
# verify blockchain
execute(c, ("SELECT Count(*) FROM transactions"))
db_rows = c.fetchone()[0]
app_log.warning("Total steps: {}".format(db_rows))
# verify genesis
execute(c, ("SELECT recipient FROM transactions ORDER BY block_height ASC LIMIT 1"))
genesis = c.fetchone()[0]
app_log.warning("Genesis: {}".format(genesis))
if str(genesis) != genesis_conf: # change this line to your genesis address if you want to clone
app_log.info("Invalid genesis address")
sys.exit(1)
# verify genesis
invalid = 0
for row in execute(c, ('SELECT * FROM transactions WHERE block_height > 0 and ORDER BY block_height')):
db_block_height = row[0]
db_timestamp = '%.2f' % float(row[1])
db_address = row[2]
db_recipient = row[3]
db_amount = row[4]
db_signature_enc = row[5]
db_public_key_hashed = row[6]
db_public_key = RSA.importKey(base64.b64decode(db_public_key_hashed))
db_keep = str(row[10])
db_openfield = row[11]
db_transaction = (str(db_timestamp), str(db_address), str(db_recipient), '%.8f' % float(db_amount), str(db_keep), str(db_openfield))
db_signature_dec = base64.b64decode(db_signature_enc)
verifier = PKCS1_v1_5.new(db_public_key)
hash = SHA.new(str(db_transaction).encode("utf-8"))
if verifier.verify(hash, db_signature_dec):
pass
else:
app_log.warning("The following transaction is invalid: {}".format(row))
invalid = invalid + 1
if db_block_height == str(1):
app_log.warning("Your genesis signature is invalid, someone meddled with the database")
sys.exit(1)
if invalid == 0:
app_log.warning("All transacitons in the local ledger are valid")
except sqlite3.Error as e:
app_log.info("Error %s:" % e.args[0])
sys.exit(1)
def blocknf(block_hash_delete, peer_ip, conn, c, hdd, h, hdd2, h2, backup, b):
global hdd_block
if db_lock.locked() == False:
db_lock.acquire()
try:
execute(c, ('SELECT * FROM transactions ORDER BY block_height DESC LIMIT 1'))
results = c.fetchone()
db_block_height = results[0]
db_block_hash = results[7]
if db_block_height < 2:
app_log.info("Will not roll back this block")
elif (db_block_hash != block_hash_delete):
# print db_block_hash
# print block_hash_delete
app_log.info("We moved away from the block to rollback, skipping")
else:
# backup
execute_param(c, ("SELECT * FROM transactions WHERE block_height >= ?;"), (str(db_block_height),))
backup_data = c.fetchall()
for x in backup_data:
execute_param(b, ("INSERT INTO transactions VALUES (?,?,?,?,?,?,?,?,?,?,?,?);"), (x[0], x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11],))
commit(backup)
execute_param(c, ("SELECT * FROM misc WHERE block_height >= ?;"), (str(db_block_height),))
backup_data = c.fetchall()
for x in backup_data:
execute_param(b, ("INSERT INTO misc VALUES (?,?);"), (x[0], x[1],))
commit(backup)
# backup
# delete followups
execute_param(c, ("DELETE FROM transactions WHERE block_height >= ?;"), (str(db_block_height),))
commit(conn)
execute_param(c, ("DELETE FROM misc WHERE block_height >= ?;"), (str(db_block_height),))
commit(conn)
execute_param(c, ('DELETE FROM transactions WHERE address = "Development Reward" AND CAST(openfield AS INTEGER) >= ?'), (str(db_block_height),))
commit(conn)
app_log.warning("Node {} didn't find block {}({}), rolled back".format(peer_ip, db_block_height, db_block_hash))
# roll back hdd too
if full_ledger == 1: #rollback ledger.db
execute_param(h, ("DELETE FROM transactions WHERE block_height >= ?;"), (str(db_block_height),))
commit(hdd)
execute_param(h, ("DELETE FROM misc WHERE block_height >= ?;"), (str(db_block_height),))
commit(hdd)
if ram_conf == 1: #rollback hyper.db
execute_param(h2, ("DELETE FROM transactions WHERE block_height >= ?;"), (str(db_block_height),))
commit(hdd2)
execute_param(h2, ("DELETE FROM misc WHERE block_height >= ?;"), (str(db_block_height),))
commit(hdd2)
hdd_block = int(db_block_height) - 1
# roll back hdd too
# roll back reward too
if full_ledger == 1: #rollback ledger.db
execute_param(h, ('DELETE FROM transactions WHERE address = "Development Reward" AND CAST(openfield AS INTEGER) >= ?'), (str(db_block_height),))
commit(hdd)
if ram_conf == 1: #rollback hyper.db
execute_param(h2, ('DELETE FROM transactions WHERE address = "Development Reward" AND CAST(openfield AS INTEGER) >= ?'), (str(db_block_height),))
commit(hdd2)
# roll back reward too
except:
pass
finally:
db_lock.release()
# delete followups
def consensus_add(peer_ip, consensus_blockheight, sdef):
try:
global peer_ip_list
global consensus_blockheight_list
global consensus_percentage
global consensus
if peer_ip not in peer_ip_list:
app_log.info("Adding {} to consensus peer list".format(peer_ip))
peer_ip_list.append(peer_ip)