-
Notifications
You must be signed in to change notification settings - Fork 15
/
node.py
2171 lines (1764 loc) · 104 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
# c = hyperblock in ram OR hyperblock file when running only hyperblocks without ram mode on
# h = ledger file or hyperblock clone in hyperblock mode
# h2 = hyperblock file
# 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
# issues with db? perhaps you missed a commit() or two
VERSION = "4.4.0.8" # Post fork candidate 8
import functools
import glob
import platform
import shutil
import socketserver
import sqlite3
import tarfile
import threading
from sys import version_info
import aliases # PREFORK_ALIASES
# import aliasesv2 as aliases # POSTFORK_ALIASES
# Bis specific modules
import apihandler
import connectionmanager
import dbhandler
import log
import options
import peershandler
import plugins
import tokensv2 as tokens # TODO: unused here
import wallet_keys
from connections import send, receive
from digest import *
from essentials import fee_calculate, download_file
from libs import node, logger, keys, client
from fork import Fork
#todo: migrate this to polysign\signer_crw.py
from Cryptodome.Hash import SHA
from Cryptodome.PublicKey import RSA
from Cryptodome.Signature import PKCS1_v1_5
import base64
#/todo
fork = Fork()
appname = "Bismuth"
appauthor = "Bismuth Foundation"
# nodes_ban_reset=config.nodes_ban_reset
def sql_trace_callback(log, id, statement):
line = f"SQL[{id}] {statement}"
log.warning(line)
def bootstrap():
# TODO: Candidate for single user mode
try:
types = ['static/*.db-wal', 'static/*.db-shm']
for t in types:
for f in glob.glob(t):
os.remove(f)
print(f, "deleted")
archive_path = node.ledger_path + ".tar.gz"
download_file("https://bismuth.cz/ledger.tar.gz", archive_path)
with tarfile.open(archive_path) as tar:
tar.extractall("static/") # NOT COMPATIBLE WITH CUSTOM PATH CONFS
except:
node.logger.app_log.warning("Something went wrong during bootstrapping, aborted")
raise
def check_integrity(database):
# TODO: Candidate for single user mode
# check ledger integrity
if not os.path.exists("static"):
os.mkdir("static")
with sqlite3.connect(database) as ledger_check:
if node.trace_db_calls:
ledger_check.set_trace_callback(functools.partial(sql_trace_callback,node.logger.app_log,"CHECK_INTEGRITY"))
ledger_check.text_factory = str
l = ledger_check.cursor()
try:
l.execute("PRAGMA table_info('transactions')")
redownload = False
except:
redownload = True
if len(l.fetchall()) != 12:
node.logger.app_log.warning(
f"Status: Integrity check on database {database} failed, bootstrapping from the website")
redownload = True
if redownload and node.is_mainnet:
bootstrap()
def rollback(node, db_handler, block_height):
node.logger.app_log.warning(f"Status: Rolling back below: {block_height}")
db_handler.rollback_under(block_height)
# rollback indices
db_handler.tokens_rollback(node, block_height)
db_handler.aliases_rollback(node, block_height)
# rollback indices
node.logger.app_log.warning(f"Status: Chain rolled back below {block_height} and will be resynchronized")
def recompress_ledger(node, rebuild=False, depth=15000):
# TODO: Candidate for single user mode
node.logger.app_log.warning(f"Status: Recompressing, please be patient")
files_remove = [node.ledger_path + '.temp',node.ledger_path + '.temp-shm',node.ledger_path + '.temp-wal']
for file in files_remove:
if os.path.exists(file):
os.remove(file)
node.logger.app_log.warning(f"Removed old {file}")
if rebuild:
node.logger.app_log.warning(f"Status: Hyperblocks will be rebuilt")
shutil.copy(node.ledger_path, node.ledger_path + '.temp')
hyper = sqlite3.connect(node.ledger_path + '.temp')
else:
shutil.copy(node.hyper_path, node.ledger_path + '.temp')
hyper = sqlite3.connect(node.ledger_path + '.temp')
if node.trace_db_calls:
hyper.set_trace_callback(functools.partial(sql_trace_callback,node.logger.app_log,"HYPER"))
hyper.text_factory = str
hyp = hyper.cursor()
hyp.execute("UPDATE transactions SET address = 'Hypoblock' WHERE address = 'Hyperblock'")
hyp.execute("SELECT max(block_height) FROM transactions")
db_block_height = int(hyp.fetchone()[0])
depth_specific = db_block_height - depth
hyp.execute(
"SELECT distinct(recipient) FROM transactions WHERE (block_height < ? AND block_height > ?) ORDER BY block_height;",
(depth_specific, -depth_specific,)) # new addresses will be ignored until depth passed
unique_addressess = hyp.fetchall()
for x in set(unique_addressess):
credit = Decimal("0")
for entry in hyp.execute(
"SELECT amount,reward FROM transactions WHERE recipient = ? AND (block_height < ? AND block_height > ?);",
(x[0],) + (depth_specific, -depth_specific,)):
try:
credit = quantize_eight(credit) + quantize_eight(entry[0]) + quantize_eight(entry[1])
credit = 0 if credit is None else credit
except Exception:
credit = 0
debit = Decimal("0")
for entry in hyp.execute(
"SELECT amount,fee FROM transactions WHERE address = ? AND (block_height < ? AND block_height > ?);",
(x[0],) + (depth_specific, -depth_specific,)):
try:
debit = quantize_eight(debit) + quantize_eight(entry[0]) + quantize_eight(entry[1])
debit = 0 if debit is None else debit
except Exception:
debit = 0
end_balance = quantize_eight(credit - debit)
if end_balance > 0:
timestamp = str(time.time())
hyp.execute("INSERT INTO transactions VALUES (?,?,?,?,?,?,?,?,?,?,?,?)", (
depth_specific - 1, timestamp, "Hyperblock", x[0], str(end_balance), "0", "0", "0", "0",
"0", "0", "0"))
hyper.commit()
hyp.execute(
"DELETE FROM transactions WHERE address != 'Hyperblock' AND (block_height < ? AND block_height > ?);",
(depth_specific, -depth_specific,))
hyper.commit()
hyp.execute("DELETE FROM misc WHERE (block_height < ? AND block_height > ?);",
(depth_specific, -depth_specific,)) # remove diff calc
hyper.commit()
hyp.execute("VACUUM")
hyper.close()
if os.path.exists(node.hyper_path):
os.remove(node.hyper_path) # remove the old hyperblocks to rebuild
os.rename(node.ledger_path + '.temp', node.hyper_path)
def ledger_check_heights(node, db_handler):
# TODO: Candidate for single user mode
"""conversion of normal blocks into hyperblocks from ledger.db or hyper.db to hyper.db"""
if os.path.exists(node.hyper_path):
# cross-integrity check
hdd_block_max = db_handler.block_height_max()
hdd_block_max_diff = db_handler.block_height_max_diff()
hdd2_block_last = db_handler.block_height_max_hyper()
hdd2_block_last_misc = db_handler.block_height_max_diff_hyper()
# cross-integrity check
if hdd_block_max == hdd2_block_last == hdd2_block_last_misc == hdd_block_max_diff and node.hyper_recompress: # cross-integrity check
node.logger.app_log.warning("Status: Recompressing hyperblocks (keeping full ledger)")
node.recompress = True
#print (hdd_block_max,hdd2_block_last,node.hyper_recompress)
elif hdd_block_max == hdd2_block_last and not node.hyper_recompress:
node.logger.app_log.warning("Status: Hyperblock recompression skipped")
node.recompress = False
else:
lowest_block = min(hdd_block_max, hdd2_block_last, hdd_block_max_diff, hdd2_block_last_misc)
highest_block = max(hdd_block_max, hdd2_block_last, hdd_block_max_diff, hdd2_block_last_misc)
node.logger.app_log.warning(
f"Status: Cross-integrity check failed, {highest_block} will be rolled back below {lowest_block}")
rollback(node,db_handler_initial,lowest_block) #rollback to the lowest value
node.recompress = False
else:
node.logger.app_log.warning("Status: Compressing ledger to Hyperblocks")
node.recompress = True
def bin_convert(string):
# TODO: Move to essentials.py
return ''.join(format(ord(x), '8b').replace(' ', '0') for x in string)
def balanceget(balance_address, db_handler):
# TODO: To move in db_handler, call by db_handler.balance_get(address)
# verify balance
# node.logger.app_log.info("Mempool: Verifying balance")
# node.logger.app_log.info("Mempool: Received address: " + str(balance_address))
base_mempool = mp.MEMPOOL.mp_get(balance_address)
# include mempool fees
debit_mempool = 0
if base_mempool:
for x in base_mempool:
debit_tx = Decimal(x[0])
fee = fee_calculate(x[1], x[2], node.last_block)
debit_mempool = quantize_eight(debit_mempool + debit_tx + fee)
else:
debit_mempool = 0
# include mempool fees
credit_ledger = Decimal("0")
try:
db_handler.execute_param(db_handler.h, "SELECT amount FROM transactions WHERE recipient = ?;", (balance_address,))
entries = db_handler.h.fetchall()
except:
entries = []
try:
for entry in entries:
credit_ledger = quantize_eight(credit_ledger) + quantize_eight(entry[0])
credit_ledger = 0 if credit_ledger is None else credit_ledger
except:
credit_ledger = 0
fees = Decimal("0")
debit_ledger = Decimal("0")
try:
db_handler.execute_param(db_handler.h, "SELECT fee, amount FROM transactions WHERE address = ?;", (balance_address,))
entries = db_handler.h.fetchall()
except:
entries = []
try:
for entry in entries:
fees = quantize_eight(fees) + quantize_eight(entry[0])
fees = 0 if fees is None else fees
except:
fees = 0
try:
for entry in entries:
debit_ledger = debit_ledger + Decimal(entry[1])
debit_ledger = 0 if debit_ledger is None else debit_ledger
except:
debit_ledger = 0
debit = quantize_eight(debit_ledger + debit_mempool)
rewards = Decimal("0")
try:
db_handler.execute_param(db_handler.h, "SELECT reward FROM transactions WHERE recipient = ?;", (balance_address,))
entries = db_handler.h.fetchall()
except:
entries = []
try:
for entry in entries:
rewards = quantize_eight(rewards) + quantize_eight(entry[0])
rewards = 0 if str(rewards) == "0E-8" else rewards
rewards = 0 if rewards is None else rewards
except:
rewards = 0
balance = quantize_eight(credit_ledger - debit - fees + rewards)
balance_no_mempool = float(credit_ledger) - float(debit_ledger) - float(fees) + float(rewards)
# node.logger.app_log.info("Mempool: Projected transction address balance: " + str(balance))
return str(balance), str(credit_ledger), str(debit), str(fees), str(rewards), str(balance_no_mempool)
def blocknf(node, block_hash_delete, peer_ip, db_handler, hyperblocks=False):
"""
Rolls back a single block, updates node object variables.
Rollback target must be above checkpoint.
Hash to rollback must match in case our ledger moved.
Not trusting hyperblock nodes for old blocks because of trimming,
they wouldn't find the hash and cause rollback.
"""
node.logger.app_log.info(f"Rollback operation on {block_hash_delete} initiated by {peer_ip}")
my_time = time.time()
if not node.db_lock.locked():
node.db_lock.acquire()
node.logger.app_log.warning(f"Database lock acquired")
backup_data = None # used in "finally" section
skip = False
reason = ""
try:
block_max_ram = db_handler.block_max_ram()
db_block_height = block_max_ram ['block_height']
db_block_hash = block_max_ram ['block_hash']
ip = {'ip': peer_ip}
node.plugin_manager.execute_filter_hook('filter_rollback_ip', ip)
if ip['ip'] == 'no':
reason = "Filter blocked this rollback"
skip = True
elif db_block_height < node.checkpoint:
reason = "Block is past checkpoint, will not be rolled back"
skip = True
elif db_block_hash != block_hash_delete:
# print db_block_hash
# print block_hash_delete
reason = "We moved away from the block to rollback, skipping"
skip = True
elif hyperblocks and node.last_block_ago > 30000: #more than 5000 minutes/target blocks away
reason = f"{peer_ip} is running on hyperblocks and our last block is too old, skipping"
skip = True
else:
backup_data = db_handler.backup_higher(db_block_height)
node.logger.app_log.warning(f"Node {peer_ip} didn't find block {db_block_height}({db_block_hash})")
# roll back hdd too
db_handler.rollback_under(db_block_height)
# /roll back hdd too
# rollback indices
db_handler.tokens_rollback(node, db_block_height)
db_handler.aliases_rollback(node, db_block_height)
# /rollback indices
node.last_block_timestamp = db_handler.last_block_timestamp()
node.last_block_hash = db_handler.last_block_hash()
node.last_block = db_block_height - 1
node.hdd_hash = db_handler.last_block_hash()
node.hdd_block = db_block_height - 1
tokens.tokens_update(node, db_handler)
except Exception as e:
node.logger.app_log.warning(e)
finally:
node.db_lock.release()
node.logger.app_log.warning(f"Database lock released")
if skip:
rollback = {"timestamp": my_time, "height": db_block_height, "ip": peer_ip,
"hash": db_block_hash, "skipped": True, "reason": reason}
node.plugin_manager.execute_action_hook('rollback', rollback)
node.logger.app_log.info(f"Skipping rollback: {reason}")
else:
try:
nb_tx = 0
for tx in backup_data:
tx_short = f"{tx[1]} - {tx[2]} to {tx[3]}: {tx[4]} ({tx[11]})"
if tx[9] == 0:
try:
nb_tx += 1
node.logger.app_log.info(
mp.MEMPOOL.merge((tx[1], tx[2], tx[3], tx[4], tx[5], tx[6], tx[10], tx[11]),
peer_ip, db_handler.c, False, revert=True)) # will get stuck if you change it to respect node.db_lock
node.logger.app_log.warning(f"Moved tx back to mempool: {tx_short}")
except Exception as e:
node.logger.app_log.warning(f"Error during moving tx back to mempool: {e}")
else:
# It's the coinbase tx, so we get the miner address
miner = tx[3]
height = tx[0]
rollback = {"timestamp": my_time, "height": height, "ip": peer_ip, "miner": miner,
"hash": db_block_hash, "tx_count": nb_tx, "skipped": False, "reason": ""}
node.plugin_manager.execute_action_hook('rollback', rollback)
except Exception as e:
node.logger.app_log.warning(f"Error during moving txs back to mempool: {e}")
else:
reason = "Skipping rollback, other ledger operation in progress"
rollback = {"timestamp": my_time, "ip": peer_ip, "skipped": True, "reason": reason}
node.plugin_manager.execute_action_hook('rollback', rollback)
node.logger.app_log.info(reason)
def sequencing_check(db_handler):
# TODO: Candidate for single user mode
try:
with open("sequencing_last", 'r') as filename:
sequencing_last = int(filename.read())
except:
node.logger.app_log.warning("Sequencing anchor not found, going through the whole chain")
sequencing_last = 0
node.logger.app_log.warning(f"Status: Testing chain sequencing, starting with block {sequencing_last}")
chains_to_check = [node.ledger_path, node.hyper_path]
for chain in chains_to_check:
conn = sqlite3.connect(chain)
if node.trace_db_calls:
conn.set_trace_callback(functools.partial(sql_trace_callback,node.logger.app_log,"SEQUENCE-CHECK-CHAIN"))
c = conn.cursor()
# perform test on transaction table
y = None
# Egg: not sure block_height != (0 OR 1) gives the proper result, 0 or 1 = 1. not in (0, 1) could be better.
for row in c.execute(
"SELECT block_height FROM transactions WHERE reward != 0 AND block_height > 1 AND block_height >= ? ORDER BY block_height ASC",
(sequencing_last,)):
y_init = row[0]
if y is None:
y = y_init
if row[0] != y:
for chain2 in chains_to_check:
conn2 = sqlite3.connect(chain2)
if node.trace_db_calls:
conn2.set_trace_callback(functools.partial(sql_trace_callback,node.logger.app_log,"SEQUENCE-CHECK-CHAIN2"))
c2 = conn2.cursor()
node.logger.app_log.warning(f"Status: Chain {chain} transaction sequencing error at: {row[0]}. {row[0]} instead of {y}")
c2.execute("DELETE FROM transactions WHERE block_height >= ? OR block_height <= ?", (row[0], -row[0],))
conn2.commit()
c2.execute("DELETE FROM misc WHERE block_height >= ?", (row[0],))
conn2.commit()
# rollback indices
db_handler.tokens_rollback(node, y)
db_handler.aliases_rollback(node, y)
# rollback indices
node.logger.app_log.warning(f"Status: Due to a sequencing issue at block {y}, {chain} has been rolled back and will be resynchronized")
break
y = y + 1
# perform test on misc table
y = None
for row in c.execute("SELECT block_height FROM misc WHERE block_height > ? ORDER BY block_height ASC",
(300000,)):
y_init = row[0]
if y is None:
y = y_init
# print("assigned")
# print(row[0], y)
if row[0] != y:
# print(row[0], y)
for chain2 in chains_to_check:
conn2 = sqlite3.connect(chain2)
if node.trace_db_calls:
conn2.set_trace_callback(functools.partial(sql_trace_callback,node.logger.app_log,"SEQUENCE-CHECK-CHAIN2B"))
c2 = conn2.cursor()
node.logger.app_log.warning(
f"Status: Chain {chain} difficulty sequencing error at: {row[0]}. {row[0]} instead of {y}")
c2.execute("DELETE FROM transactions WHERE block_height >= ?", (row[0],))
conn2.commit()
c2.execute("DELETE FROM misc WHERE block_height >= ?", (row[0],))
conn2.commit()
db_handler.execute_param(conn2, (
'DELETE FROM transactions WHERE address = "Development Reward" AND block_height <= ?'),
(-row[0],))
conn2.commit()
db_handler.execute_param(conn2, (
'DELETE FROM transactions WHERE address = "Hypernode Payouts" AND block_height <= ?'),
(-row[0],))
conn2.commit()
conn2.close()
# rollback indices
db_handler.tokens_rollback(node, y)
db_handler.aliases_rollback(node, y)
# rollback indices
node.logger.app_log.warning(f"Status: Due to a sequencing issue at block {y}, {chain} has been rolled back and will be resynchronized")
break
y = y + 1
node.logger.app_log.warning(f"Status: Chain sequencing test complete for {chain}")
conn.close()
if y:
with open("sequencing_last", 'w') as filename:
filename.write(str(y - 1000)) # room for rollbacks
# init
class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):
def handle(self):
# this is a dedicated thread for each client (not ip)
if node.IS_STOPPING:
node.logger.app_log.warning("Inbound: Rejected incoming cnx, node is stopping")
return
db_handler_instance = dbhandler.DbHandler(node.index_db, node.ledger_path, node.hyper_path, node.ram, node.ledger_ram_file, node.logger, trace_db_calls=node.trace_db_calls)
client_instance = client.Client()
try:
peer_ip = self.request.getpeername()[0]
except:
node.logger.app_log.warning("Inbound: Transport endpoint was not connected")
return
threading.current_thread().name = f"in_{peer_ip}"
# if threading.active_count() < node.thread_limit or peer_ip == "127.0.0.1":
# Always keep a slot for whitelisted (wallet could be there)
if threading.active_count() < node.thread_limit / 3 * 2 or node.peers.is_whitelisted(peer_ip): # inbound
client_instance.connected = True
else:
try:
node.logger.app_log.info(f"Free capacity for {peer_ip} unavailable, disconnected")
self.request.close()
# if you raise here, you kill the whole server
except Exception as e:
node.logger.app_log.warning(f"{e}")
pass
finally:
return
dict_ip = {'ip': peer_ip}
node.plugin_manager.execute_filter_hook('peer_ip', dict_ip)
if node.peers.is_banned(peer_ip) or dict_ip['ip'] == 'banned':
self.request.close()
node.logger.app_log.info(f"IP {peer_ip} banned, disconnected")
# TODO: I'd like to call
"""
node.peers.peersync({peer_ip: node.port})
so we can save the peers that connected to us.
But not ok in current architecture: would delay the command, and we're not even sure it would be saved.
TODO: Workaround: make sure our external ip and port is present in the peers we announce, or new nodes are likely never to be announced.
Warning: needs public ip/port, not local ones!
"""
timeout_operation = 120 # timeout
timer_operation = time.time() # start counting
while not node.peers.is_banned(peer_ip) and node.peers.version_allowed(peer_ip, node.version_allow) and client_instance.connected:
try:
# Failsafe
if self.request == -1:
raise ValueError(f"Inbound: Closed socket from {peer_ip}")
if not time.time() <= timer_operation + timeout_operation: # return on timeout
if node.peers.warning(self.request, peer_ip, "Operation timeout", 2):
node.logger.app_log.info(f"{peer_ip} banned")
break
raise ValueError(f"Inbound: Operation timeout from {peer_ip}")
data = receive(self.request)
node.logger.app_log.info(
f"Inbound: Received: {data} from {peer_ip}") # will add custom ports later
if data.startswith('regtest_'):
if not node.is_regnet:
send(self.request, "notok")
return
else:
db_handler_instance.execute(db_handler_instance.c, "SELECT block_hash FROM transactions WHERE block_height= (select max(block_height) from transactions)")
block_hash = db_handler_instance.c.fetchone()[0]
# feed regnet with current thread db handle. refactor needed.
regnet.conn, regnet.c, regnet.hdd, regnet.h, regnet.hdd2, regnet.h2, regnet.h = db_handler_instance.conn, db_handler_instance.c, db_handler_instance.hdd, db_handler_instance.h, db_handler_instance.hdd2, db_handler_instance.h2, db_handler_instance.h
regnet.command(self.request, data, block_hash, node, db_handler_instance)
if data == 'version':
data = receive(self.request)
if data not in node.version_allow:
node.logger.app_log.warning(
f"Protocol version mismatch: {data}, should be {node.version_allow}")
send(self.request, "notok")
return
else:
node.logger.app_log.warning(f"Inbound: Protocol version matched with {peer_ip}: {data}")
send(self.request, "ok")
node.peers.store_mainnet(peer_ip, data)
elif data == 'getversion':
send(self.request, node.version)
elif data == 'mempool':
# receive theirs
segments = receive(self.request)
node.logger.app_log.info(mp.MEMPOOL.merge(segments, peer_ip, db_handler_instance.c, False))
#improvement possible - pass peer_ip from worker
# receive theirs
# execute_param(m, ('SELECT timestamp,address,recipient,amount,signature,public_key,operation,openfield FROM transactions WHERE timeout < ? ORDER BY amount DESC;'), (int(time.time() - 5),))
if mp.MEMPOOL.sendable(peer_ip):
# Only send the diff
mempool_txs = mp.MEMPOOL.tx_to_send(peer_ip, segments)
# and note the time
mp.MEMPOOL.sent(peer_ip)
else:
# We already sent not long ago, send empy
mempool_txs = []
# send own
# node.logger.app_log.info("Inbound: Extracted from the mempool: " + str(mempool_txs)) # improve: sync based on signatures only
# if len(mempool_txs) > 0: same as the other
send(self.request, mempool_txs)
elif data == "hello":
if node.is_regnet:
node.logger.app_log.info("Inbound: Got hello but I'm in regtest mode, closing.")
return
send(self.request, "peers")
peers_send = node.peers.peer_list_disk_format()
send(self.request, peers_send)
while node.db_lock.locked():
time.sleep(quantize_two(node.pause))
node.logger.app_log.info("Inbound: Sending sync request")
send(self.request, "sync")
elif data == "sendsync":
while node.db_lock.locked():
time.sleep(quantize_two(node.pause))
while len(node.syncing) >= 3:
time.sleep(int(node.pause))
send(self.request, "sync")
elif data == "blocksfnd":
node.logger.app_log.info(f"Inbound: Client {peer_ip} has the block(s)") # node should start sending txs in this step
# node.logger.app_log.info("Inbound: Combined segments: " + segments)
# print peer_ip
if node.db_lock.locked():
node.logger.app_log.info(f"Skipping sync from {peer_ip}, syncing already in progress")
else:
node.last_block_timestamp = db_handler_instance.last_block_timestamp()
if node.last_block_timestamp < time.time() - 600:
# block_req = most_common(consensus_blockheight_list)
block_req = node.peers.consensus_most_common
node.logger.app_log.warning("Most common block rule triggered")
else:
# block_req = max(consensus_blockheight_list)
block_req = node.peers.consensus_max
node.logger.app_log.warning("Longest chain rule triggered")
if int(received_block_height) >= block_req and int(received_block_height) > node.last_block:
try: # they claim to have the longest chain, things must go smooth or ban
node.logger.app_log.warning(f"Confirming to sync from {peer_ip}")
node.plugin_manager.execute_action_hook('sync', {'what': 'syncing_from', 'ip': peer_ip})
send(self.request, "blockscf")
segments = receive(self.request)
except:
if node.peers.warning(self.request, peer_ip, "Failed to deliver the longest chain"):
node.logger.app_log.info(f"{peer_ip} banned")
break
else:
digest_block(node, segments, self.request, peer_ip, db_handler_instance)
else:
node.logger.app_log.warning(f"Rejecting to sync from {peer_ip}")
send(self.request, "blocksrj")
node.logger.app_log.info(
f"Inbound: Distant peer {peer_ip} is at {received_block_height}, should be at least {max(block_req,node.last_block+1)}")
send(self.request, "sync")
elif data == "blockheight":
try:
received_block_height = receive(self.request) # receive client's last block height
node.logger.app_log.info(
f"Inbound: Received block height {received_block_height} from {peer_ip} ")
# consensus pool 1 (connection from them)
consensus_blockheight = int(received_block_height) # str int to remove leading zeros
# consensus_add(peer_ip, consensus_blockheight, self.request)
node.peers.consensus_add(peer_ip, consensus_blockheight, self.request, node.hdd_block)
# consensus pool 1 (connection from them)
# append zeroes to get static length
send(self.request, node.hdd_block)
# send own block height
if int(received_block_height) > node.hdd_block:
node.logger.app_log.warning("Inbound: Client has higher block")
node.logger.app_log.info(f"Inbound: block_hash to send: {node.hdd_hash}")
send(self.request, node.hdd_hash)
# receive their latest sha_hash
# confirm you know that sha_hash or continue receiving
elif int(received_block_height) <= node.hdd_block:
if int(received_block_height) == node.hdd_block:
node.logger.app_log.info(
f"Inbound: We have the same height as {peer_ip} ({received_block_height}), hash will be verified")
else:
node.logger.app_log.warning(
f"Inbound: We have higher ({node.hdd_block}) block height than {peer_ip} ({received_block_height}), hash will be verified")
data = receive(self.request) # receive client's last block_hash
# send all our followup hashes
node.logger.app_log.info(f"Inbound: Will seek the following block: {data}")
client_block = db_handler_instance.block_height_from_hash(data)
if client_block is None:
node.logger.app_log.warning(f"Inbound: Block {data[:8]} of {peer_ip} not found")
if node.full_ledger:
send(self.request, "blocknf") # announce block hash was not found
else:
send(self.request, "blocknfhb") # announce we are on hyperblocks
send(self.request, data)
if node.peers.warning(self.request, peer_ip, "Forked", 2):
node.logger.app_log.info(f"{peer_ip} banned")
break
else:
node.logger.app_log.info(f"Inbound: Client is at block {client_block}") # now check if we have any newer
if node.hdd_hash == data or not node.egress:
if not node.egress:
node.logger.app_log.warning(f"Inbound: Egress disabled for {peer_ip}")
else:
node.logger.app_log.info(f"Inbound: Client {peer_ip} has the latest block")
time.sleep(int(node.pause)) # reduce CPU usage
send(self.request, "nonewblk")
else:
blocks_fetched = db_handler_instance.blocksync(client_block)
node.logger.app_log.info(f"Inbound: Selected {blocks_fetched}")
send(self.request, "blocksfnd")
confirmation = receive(self.request)
if confirmation == "blockscf":
node.logger.app_log.info("Inbound: Client confirmed they want to sync from us")
send(self.request, blocks_fetched)
elif confirmation == "blocksrj":
node.logger.app_log.info(
"Inbound: Client rejected to sync from us because we're don't have the latest block")
except Exception as e:
node.logger.app_log.warning(f"Inbound: Sync failed {e}")
elif data == "nonewblk":
send(self.request, "sync")
elif data == "blocknf":
block_hash_delete = receive(self.request)
# print peer_ip
if consensus_blockheight == node.peers.consensus_max:
blocknf(node, block_hash_delete, peer_ip, db_handler_instance)
if node.peers.warning(self.request, peer_ip, "Rollback", 2):
node.logger.app_log.info(f"{peer_ip} banned")
break
node.logger.app_log.info("Inbound: Deletion complete, sending sync request")
while node.db_lock.locked():
time.sleep(node.pause)
send(self.request, "sync")
elif data == "blocknfhb": #node announces it's running hyperblocks
block_hash_delete = receive(self.request)
# print peer_ip
if consensus_blockheight == node.peers.consensus_max:
blocknf(node, block_hash_delete, peer_ip, db_handler_instance, hyperblocks=True)
if node.peers.warning(self.request, peer_ip, "Rollback", 2):
node.logger.app_log.info(f"{peer_ip} banned")
break
node.logger.app_log.info("Inbound: Deletion complete, sending sync request")
while node.db_lock.locked():
time.sleep(node.pause)
send(self.request, "sync")
elif data == "block":
# if (peer_ip in allowed or "any" in allowed): # from miner
if node.peers.is_allowed(peer_ip, data): # from miner
# TODO: rights management could be done one level higher instead of repeating the same check everywhere
node.logger.app_log.info(f"Inbound: Received a block from miner {peer_ip}")
# receive block
segments = receive(self.request)
# node.logger.app_log.info("Inbound: Combined mined segments: " + segments)
mined = {"timestamp": time.time(), "last": node.last_block, "ip": peer_ip, "miner": "",
"result": False, "reason": ''}
try:
mined['miner'] = segments[0][-1][1] # sender, to be consistent with block event.
except:
# Block is sent by miners/pools, we can drop the connection
# If there is a reason not to, use "continue" here and below instead of returns.
return # missing info, bye
if node.is_mainnet:
if len(node.peers.connection_pool) < 5 and not node.peers.is_whitelisted(peer_ip):
reason = "Inbound: Mined block ignored, insufficient connections to the network"
mined['reason'] = reason
node.plugin_manager.execute_action_hook('mined', mined)
node.logger.app_log.info(reason)
return
elif node.db_lock.locked():
reason = "Inbound: Block from miner skipped because we are digesting already"
mined['reason'] = reason
node.plugin_manager.execute_action_hook('mined', mined)
node.logger.app_log.warning(reason)
return
elif node.last_block >= node.peers.consensus_max - 3:
mined['result'] = True
node.plugin_manager.execute_action_hook('mined', mined)
node.logger.app_log.info("Inbound: Processing block from miner")
try:
digest_block(node, segments, self.request, peer_ip, db_handler_instance)
except ValueError as e:
node.logger.app_log.warning("Inbound: block {}".format(str(e)))
return
except Exception as e:
node.logger.app_log.error("Inbound: Processing block from miner {}".format(e))
return
# This new block may change the int(diff). Trigger the hook whether it changed or not.
#node.difficulty = difficulty(node, db_handler_instance)
else:
reason = f"Inbound: Mined block was orphaned because node was not synced, " \
f"we are at block {node.last_block}, " \
f"should be at least {node.peers.consensus_max - 3}"
mined['reason'] = reason
node.plugin_manager.execute_action_hook('mined', mined)
node.logger.app_log.warning(reason)
else:
# Not mainnet
try:
digest_block(node, segments, self.request, peer_ip, db_handler_instance)
except ValueError as e:
node.logger.app_log.warning("Inbound: block {}".format(str(e)))
return
except Exception as e:
node.logger.app_log.error("Inbound: Processing block from miner {}".format(e))
return
else:
receive(self.request) # receive block, but do nothing about it
node.logger.app_log.info(f"{peer_ip} not whitelisted for block command")
elif data == "blocklast":
# if (peer_ip in allowed or "any" in allowed): # only sends the miner part of the block!
if node.peers.is_allowed(peer_ip, data):
db_handler_instance.execute(db_handler_instance.c, "SELECT * FROM transactions "
"WHERE reward != 0 "
"ORDER BY block_height DESC LIMIT 1;")
block_last = db_handler_instance.c.fetchall()[0]
send(self.request, block_last)
else:
node.logger.app_log.info(f"{peer_ip} not whitelisted for blocklast command")
elif data == "blocklastjson":
# if (peer_ip in allowed or "any" in allowed): # only sends the miner part of the block!
if node.peers.is_allowed(peer_ip, data):
db_handler_instance.execute(db_handler_instance.c,
"SELECT * FROM transactions WHERE reward != 0 ORDER BY block_height DESC LIMIT 1;")
block_last = db_handler_instance.c.fetchall()[0]
response = {"block_height": block_last[0],
"timestamp": block_last[1],
"address": block_last[2],
"recipient": block_last[3],
"amount": block_last[4],
"signature": block_last[5],
"public_key": block_last[6],
"block_hash": block_last[7],
"fee": block_last[8],
"reward": block_last[9],
"operation": block_last[10],
"nonce": block_last[11]}
send(self.request, response)
else:
node.logger.app_log.info(f"{peer_ip} not whitelisted for blocklastjson command")
elif data == "blockget":
# if (peer_ip in allowed or "any" in allowed):
if node.peers.is_allowed(peer_ip, data):
block_desired = receive(self.request)
db_handler_instance.execute_param(db_handler_instance.h, "SELECT * FROM transactions WHERE block_height = ?;",
(block_desired,))
block_desired_result = db_handler_instance.h.fetchall()
send(self.request, block_desired_result)
else:
node.logger.app_log.info(f"{peer_ip} not whitelisted for blockget command")
elif data == "blockgetjson":
# if (peer_ip in allowed or "any" in allowed):
if node.peers.is_allowed(peer_ip, data):
block_desired = receive(self.request)
db_handler_instance.execute_param(db_handler_instance.h, "SELECT * FROM transactions WHERE block_height = ?;",
(block_desired,))
block_desired_result = db_handler_instance.h.fetchall()
response_list = []
for transaction in block_desired_result:
response = {"block_height": transaction[0],
"timestamp": transaction[1],
"address": transaction[2],
"recipient": transaction[3],
"amount": transaction[4],
"signature": transaction[5],
"public_key": transaction[6],
"block_hash": transaction[7],
"fee": transaction[8],
"reward": transaction[9],
"operation": transaction[10],
"openfield": transaction[11]}
response_list.append(response)
send(self.request, response_list)
else:
node.logger.app_log.info(f"{peer_ip} not whitelisted for blockget command")