-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
716 lines (611 loc) · 32.2 KB
/
main.py
File metadata and controls
716 lines (611 loc) · 32.2 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
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
"""
Main entry point for the blockchain node. Parses command-line arguments,
initializes components, and starts the main threads.
"""
import sys
import socket
import threading
import argparse
import json
import time
import struct
import queue
import logging # Added for logging
from network import send_message, recv_message
from blockchain import get_confirmed_nonce, create_block
from mempool import add_transaction, pool_snapshot, get_all_transactions as get_mempool_transactions_for_proposal
from validation import validate_transaction
from consensus import ConsensusThread
# Configure logging
logging.basicConfig(
level=logging.CRITICAL,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
datefmt='%H:%M:%S',
handlers=[
logging.StreamHandler(sys.stderr)
]
)
logger = logging.getLogger(__name__)
# Uncomment to enable debug logging
# logging.getLogger().setLevel(logging.DEBUG)
# Global transaction queue for client connections
global_tx_queue = queue.Queue()
global_tx_queue_lock = threading.Lock()
def handle_transaction_core(tx: dict, consensus_instance: 'ConsensusThread',
peers_dict: dict, peers_lock: threading.Lock):
"""
Core logic extracted from PeerHandlerThread._handle_transaction.
Validates, adds, prints, forwards transactions, and triggers consensus.
This function is used by both the transaction queue processor and PeerHandlerThread.
"""
nonce_store_for_validation = {}
current_mempool_snapshot = pool_snapshot()
logger.debug(f"Transaction Core: Current mempool snapshot before validation: {json.dumps(current_mempool_snapshot, sort_keys=True)}")
sender = tx.get('sender')
if sender is None:
logger.debug(f"Transaction Core: Sender is None in tx, tx malformed.")
return False
logger.debug(f"Transaction Core: Sender from tx: {sender}")
confirmed_nonce_from_chain = get_confirmed_nonce(sender)
logger.debug(f"Transaction Core: Confirmed nonce for {sender} from blockchain.py (state): {confirmed_nonce_from_chain}")
nonce_store_for_validation = {sender: confirmed_nonce_from_chain}
# Perform validation
is_valid = validate_transaction(
tx,
nonce_store_for_validation,
current_mempool_snapshot
)
if is_valid:
add_transaction(tx)
# Print transaction for autograder
print(json.dumps({"type": "transaction", "payload": tx}, sort_keys=True, indent=2, separators=(',', ': ')), flush=True)
# Forward to peers
forward_message = {"type": "forwarded_transaction", "payload": tx}
current_peers_snapshot = []
with peers_lock:
current_peers_snapshot = list(peers_dict.items())
for peer_addr, peer_sock in current_peers_snapshot:
if peer_sock.fileno() == -1:
continue
try:
send_message(peer_sock, forward_message)
except socket.error:
# Just log and continue with other peers if one fails
logger.debug(f"Transaction Core: Failed to forward transaction to {peer_addr}")
continue
# Trigger consensus
consensus_instance.consensus_event.set()
return True
else:
return False
def process_client_transactions_thread(tx_queue: queue.Queue, queue_lock: threading.Lock,
consensus_instance: 'ConsensusThread',
peers_dict: dict, peers_lock: threading.Lock,
system_fully_connected_event: threading.Event):
"""
Thread function to process transactions from the global queue.
Waits for the system to be fully connected.
Checks if consensus is busy, otherwise processes transactions.
"""
logger.info("Transaction queue processor thread started")
# Wait for the system to be fully connected before starting to process transactions
if not system_fully_connected_event.is_set():
logger.info("Transaction queue processor: Waiting for system to be fully connected...")
system_fully_connected_event.wait()
logger.info("Transaction queue processor: System is fully connected. Starting transaction processing.")
while True:
try:
# Check if consensus is busy
if consensus_instance.consensus_event.is_set(): # Check if consensus round is active
time.sleep(0.05) # Short sleep if consensus is busy
continue
# Try to get a transaction from the queue
tx_to_process = None
with queue_lock:
if not tx_queue.empty():
tx_to_process = tx_queue.get(block=False)
if tx_to_process:
# Log with INFO level when a transaction is actually being popped and processed
logger.info(f"Processing transaction from queue: {tx_to_process.get('transaction_id', 'unknown_id')}")
handle_transaction_core(tx_to_process, consensus_instance, peers_dict, peers_lock)
tx_queue.task_done() # Mark task as done for queue management
else:
# No transactions to process, sleep a bit
time.sleep(0.1)
except queue.Empty: # Should not happen with block=False and check, but good practice
time.sleep(0.1)
except Exception as e:
logger.error(f"Error in transaction queue processor: {type(e).__name__} - {e}")
time.sleep(0.5) # Sleep on error to avoid tight loop
def parse_args():
"""
Parse command-line arguments:
- port: The TCP port this node will listen on for incoming peer connections
- node_list_file: Path to file containing peer addresses (host:port)
"""
parser = argparse.ArgumentParser(description="Blockchain Node")
parser.add_argument("port", type=int, help="Port to listen for incoming connections")
parser.add_argument("node_list_file", type=str, help="Path to file with peer addresses")
return parser.parse_args()
class PeerHandlerThread(threading.Thread):
"""
Thread to handle communication with a single peer.
"""
def __init__(self, sock: socket.socket, addr: str,
peer_id: str,
all_peers_dict: dict, peers_lock: threading.Lock,
consensus_instance: 'ConsensusThread',
num_nodes_from_file: int,
system_fully_connected_event: threading.Event = None,
is_outbound: bool = False,
expected_peer_ports: set = None):
super().__init__(daemon=True)
self.sock = sock
self.addr = addr
self.peer_id = peer_id
self.all_peers_dict = all_peers_dict
self.peers_lock = peers_lock
self.consensus_instance = consensus_instance
self.num_nodes_from_file = num_nodes_from_file
self.system_fully_connected_event = system_fully_connected_event
self.is_outbound = is_outbound
self.expected_peer_ports = expected_peer_ports if expected_peer_ports else set()
self.is_confirmed_peer = self.is_outbound # Outbound connections are to peers, so initially confirmed
self.peer_listening_port = None # Set by handshake for inbound peers
def run(self):
try:
# Wait for system to be fully connected before proceeding
if not self.system_fully_connected_event.is_set():
logger.debug(f"PHT [{self.peer_id}]: Waiting for system_fully_connected_event...")
self.system_fully_connected_event.wait()
logger.debug(f"PHT [{self.peer_id}]: system_fully_connected_event is set!")
# Main message handling loop - all connections managed by this PHT are confirmed peers
logger.debug(f"PHT [{self.peer_id}]: Entering main message loop.")
while True:
message = recv_message(self.sock)
if message is None: # Connection closed by peer
logger.debug(f"PHT [{self.peer_id}]: Connection closed by peer.")
break
self._process_message(message)
except (ConnectionError, socket.error, struct.error, json.JSONDecodeError) as e:
logger.debug(f"PHT [{self.peer_id}]: Network/protocol error in main run: {e}")
except Exception as e:
logger.error(f"PHT [{self.peer_id}]: Unexpected exception in run: {type(e).__name__} - {e}")
finally:
logger.debug(f"PHT [{self.peer_id}]: Cleaning up connection.")
self.sock.close()
with self.peers_lock:
# Try removing by self.peer_id (which might have been updated)
if self.peer_id in self.all_peers_dict and self.all_peers_dict[self.peer_id] == self.sock:
self.all_peers_dict.pop(self.peer_id, None)
logger.debug(f"PHT [{self.peer_id}]: Removed from all_peers_dict using self.peer_id.")
# Else, try removing by original self.addr (if it was an ephemeral ID for an inbound connection that failed handshake)
elif self.addr != self.peer_id and self.addr in self.all_peers_dict and self.all_peers_dict[self.addr] == self.sock:
self.all_peers_dict.pop(self.addr, None)
logger.debug(f"PHT [{self.peer_id}]: Removed from all_peers_dict using self.addr ({self.addr}).")
def _process_message(self, message):
"""
Process a received message.
Returns True if the message was processed, False otherwise.
"""
if message is None:
return False
msg_type = message.get("type")
if msg_type == "forwarded_transaction":
self._handle_forwarded_transaction(message.get("payload", {}))
elif msg_type == "values_request": # Handle new "values_request"
self._handle_values_message(message.get("payload", {}), is_request=True)
elif msg_type == "values_response": # Handle new "values_response"
self._handle_values_message(message.get("payload", {}), is_request=False)
# Add other message types as needed
return True
def _handle_forwarded_transaction(self, tx_payload: dict):
"""
Handles a transaction received through forwarding.
"""
# Validate the transaction
nonce_store_for_validation = {}
sender = tx_payload.get('sender')
if sender is None:
logger.debug(f"NODE {self.addr}: Sender is None in forwarded tx, tx malformed.")
return
confirmed_nonce_from_chain = get_confirmed_nonce(sender)
nonce_store_for_validation = {sender: confirmed_nonce_from_chain}
validation_mempool_snapshot = pool_snapshot()
is_valid = validate_transaction(
tx_payload,
nonce_store_for_validation,
validation_mempool_snapshot
)
if is_valid:
logger.debug(f"PeerHandler [{self.addr}]: Forwarded transaction {tx_payload.get('transaction_id', 'N/A')} is valid. Adding to mempool.")
print(json.dumps({"type": "transaction", "payload": tx_payload}, sort_keys=True, indent=2, separators=(',', ': ')), flush=True)
def _handle_values_message(self, received_message_payload: dict, is_request: bool): # Renamed and added is_request
"""
Handles an incoming "values_request" or "values_response" message.
- For "values_request": records sender's proposal, replies with own proposal, triggers consensus.
- For "values_response": records sender's proposal, triggers consensus (no reply).
"""
logger.debug(f"PeerHandler [{self.addr}]: Handling \'values\' message (is_request={is_request}).")
# 1. Extract received data
received_proposal = received_message_payload.get("proposal")
incoming_round_id = received_message_payload.get("round")
if received_proposal is None or incoming_round_id is None:
logger.debug(f"PeerHandler [{self.addr}]: Received malformed \'values\' payload: {received_message_payload}")
return # Ignore malformed message
logger.debug(f"PeerHandler [{self.addr}]: Received proposal for round {incoming_round_id} (is_request={is_request})")
# 2. Check if the consensus thread's proposal submission gate is open and try to store the received proposal.
# Note: We don't block waiting for the gate to open here; we try once.
# If the gate is closed, the proposal is ignored. This is to prevent
# the PeerHandlerThread from being blocked from processing other messages.
gate_is_open = False
# Attempt to access the consensus thread's proposal submission gate
try:
with self.consensus_instance.proposals_gate_lock:
if incoming_round_id == self.consensus_instance.round_counter:
gate_is_open = self.consensus_instance.proposals_submission_gate_event.is_set()
if gate_is_open: # Only record proposals if it's a response
# Gate is open, record the proposal
logger.debug(f"PeerHandler [{self.addr}]: Proposal submission gate is open, recording proposal from {self.peer_id}")
self.consensus_instance.record_peer_proposal(self.peer_id, received_proposal, incoming_round_id)
# else:
# logger.debug(f"PeerHandler [{self.addr}]: Proposal submission gate not open or round mismatch (round={incoming_round_id}), ignoring proposal")
except AttributeError:
# If the consensus thread doesn't have the proposals_submission_gate_event attribute,
# fall back to the old method of recording proposals for backward compatibility.
#self.consensus_instance.record_peer_proposal(self.peer_id, received_proposal, incoming_round_id)
logger.debug(f"PeerHandler [{self.addr}]: Consensus thread does not implement proposal submission gate mechanism, using old method to record proposal")
pass
# 3. If it's a request, prepare and send reply with our proposal for the same round4
if is_request:
current_transactions = get_mempool_transactions_for_proposal()
my_current_proposal = create_block(current_transactions)
try:
logger.debug(f"PeerHandler [{self.addr}]: Replying with own proposal (type: values_response) for round {incoming_round_id}")
send_message(self.sock, {
"type": "values_response", # Reply with "values_response"
"payload": {
"proposal": my_current_proposal,
"round": incoming_round_id
}
})
except socket.error as e:
logger.debug(f"PeerHandler [{self.addr}]: Socket error sending values_response: {e}")
raise # Re-raise to allow cleanup in run()
if not gate_is_open:
self.consensus_instance.record_peer_proposal(self.peer_id, received_proposal, incoming_round_id)
# 4. Trigger consensus locally
self.consensus_instance.consensus_event.set()
logger.debug(f"PeerHandler [{self.addr}]: Triggered consensus check after handling values message (is_request={is_request}). work_to_do=True")
class ServerThread(threading.Thread):
"""
Thread to accept incoming peer connections.
"""
def __init__(self, port: int,
peers: dict, peers_lock: threading.Lock,
consensus_instance_ref: ConsensusThread,
num_nodes_from_file: int,
system_fully_connected_event: threading.Event = None,
expected_peer_ports: set = None,
tx_queue: queue.Queue = None,
tx_queue_lock: threading.Lock = None):
super().__init__(daemon=True)
self.port = port
self.peers = peers
self.peers_lock = peers_lock
self.consensus_instance_ref = consensus_instance_ref
self.num_nodes_from_file = num_nodes_from_file
self.system_fully_connected_event = system_fully_connected_event
self.expected_peer_ports = expected_peer_ports
self.tx_queue = tx_queue
self.tx_queue_lock = tx_queue_lock
def run(self):
"""
Accept connections, determine if they are peers or clients,
and handle them accordingly.
"""
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
server_socket.bind(('localhost', self.port))
server_socket.listen(10)
logger.info(f"Server listening on port {self.port}")
while True:
client_sock, client_addr = server_socket.accept()
addr_str = f"{client_addr[0]}:{client_addr[1]}"
logger.debug(f"New connection from {addr_str}")
# Set timeout for initial message
client_sock.settimeout(2.0)
# Try to receive initial message to determine if this is a peer or client
try:
initial_message = recv_message(client_sock)
client_sock.settimeout(None) # Reset timeout after receiving
if initial_message is None:
logger.debug(f"Connection closed by {addr_str} during initial message wait.")
client_sock.close()
continue
msg_type = initial_message.get("type")
payload = initial_message.get("payload", {})
if msg_type == "handshake" and "listening_port" in payload:
# This is a peer connection
try:
# Extract real peer port from handshake message
peer_listening_port = int(payload["listening_port"])
remote_ip = client_addr[0]
confirmed_id = f"{remote_ip}:{peer_listening_port}"
logger.debug(f"Received handshake from {addr_str}, confirmed peer ID: {confirmed_id}")
# Update peers dictionary with confirmed ID
with self.peers_lock:
# Store with confirmed ID
self.peers[confirmed_id] = client_sock
# Create a PeerHandlerThread for this confirmed peer
handler = PeerHandlerThread(
client_sock,
confirmed_id, # Use confirmed ID as both addr and peer_id
confirmed_id,
self.peers,
self.peers_lock,
self.consensus_instance_ref,
self.num_nodes_from_file,
self.system_fully_connected_event,
is_outbound=False,
expected_peer_ports=self.expected_peer_ports
)
handler.is_confirmed_peer = True # Mark as confirmed peer
handler.start()
logger.debug(f"Started PeerHandlerThread for peer {confirmed_id}")
except (ValueError, OSError) as e:
logger.debug(f"Error processing handshake from {addr_str}: {e}")
client_sock.close()
continue
elif msg_type == "transaction":
# This is a client connection sending a transaction
logger.debug(f"Received transaction from client {addr_str}")
# Add the transaction to the global queue
with self.tx_queue_lock:
self.tx_queue.put(payload)
logger.debug(f"Transaction from {addr_str} queued for processing")
# Send response to client
try:
# For client convenience, we'll respond with a dummy success
send_message(client_sock, {"type": "transaction_response", "payload": True})
logger.debug(f"Sent initial acknowledgement to client {addr_str}")
except Exception as e:
logger.debug(f"Failed to send response to client {addr_str}: {e}")
# Close connection with client, no need for a PeerHandlerThread
client_sock.close()
logger.debug(f"Closed connection with client {addr_str}")
else:
# Unknown or malformed message
logger.debug(f"Received unknown/malformed message type: {msg_type} from {addr_str}")
client_sock.close()
continue
except socket.timeout:
logger.debug(f"Timeout waiting for initial message from {addr_str}")
client_sock.close()
continue
except (ConnectionError, socket.error, struct.error, json.JSONDecodeError) as e:
logger.debug(f"Protocol error receiving initial message from {addr_str}: {e}")
client_sock.close()
continue
except Exception as e:
logger.error(f"Unexpected error handling connection from {addr_str}: {type(e).__name__} - {e}")
client_sock.close()
continue
except (socket.error, OSError) as e:
logger.error(f"ServerThread: Socket/OS exception: {type(e).__name__} - {e}")
except Exception as e:
logger.error(f"ServerThread: Unexpected critical exception: {type(e).__name__} - {e}")
finally:
server_socket.close()
def connect_to_peers(
node_list_file: str,
my_listening_port: int,
my_comparable_address: str,
peers_lock: threading.Lock,
shared_peers_dict: dict,
consensus_instance: ConsensusThread,
system_fully_connected_event: threading.Event = None,
expected_peer_ports: set = None
):
"""
Read peer addresses, try to connect, and FOR EACH SUCCESSFUL OUTGOING CONNECTION,
start a PeerHandlerThread to handle incoming messages on that connection.
Modifies shared_peers_dict directly.
Returns the total number of unique peer addresses found in the node_list_file and
a set of expected peer ports.
"""
peer_addresses = []
n_total_nodes_from_file = 0
try:
my_host_for_self_skip, _ = my_comparable_address.split(':', 1)
except ValueError:
my_host_for_self_skip = "127.0.0.1"
try:
with open(node_list_file, 'r') as f:
peer_addresses = [line.strip() for line in f if line.strip()]
n_total_nodes_from_file = len(expected_peer_ports)
for addr_str in peer_addresses:
try:
peer_host, peer_port_str = addr_str.split(':', 1)
peer_port_int = int(peer_port_str)
except ValueError:
logger.warning(f"Could not parse peer address '{addr_str}'. Skipping.")
continue
if my_listening_port < peer_port_int:
logger.debug(f"Skipping outbound to {addr_str} (my port {my_listening_port} < peer port {peer_port_int})")
continue
# Retry logic for connection
max_retries = 3
retry_delay_seconds = 0.2
for attempt in range(1, max_retries + 1):
sock = None # Initialize sock to None
try:
logger.debug(f"Outbound attempt {attempt}/{max_retries} to {addr_str}")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((peer_host, peer_port_int))
# Send handshake message
handshake_msg = {
"type": "handshake",
"payload": {
"listening_port": my_listening_port
}
}
send_message(sock, handshake_msg)
logger.debug(f"Successfully connected outbound to {addr_str}")
with peers_lock:
shared_peers_dict[addr_str] = sock
logger.debug(f"Starting PeerHandlerThread for OUTGOING connection to {addr_str}")
handler = PeerHandlerThread(
sock, addr_str, # sock and addr_str - remote peer node
addr_str, # Initial peer_id is the connection string
shared_peers_dict,
peers_lock,
consensus_instance,
n_total_nodes_from_file, # num_nodes_from_file context for this PHT
system_fully_connected_event, # Pass event
is_outbound=True,
expected_peer_ports=expected_peer_ports
)
handler.start()
break
except ConnectionRefusedError:
if sock: sock.close()
if attempt < max_retries: time.sleep(retry_delay_seconds)
else: logger.debug(f"Max retries for {addr_str}. Could not connect.")
except OSError as e:
if sock: sock.close()
logger.debug(f"OS error connecting to {addr_str}: {e}. Not retrying.")
break
except Exception as e:
if sock: sock.close()
logger.debug(f"Unexpected error connecting to {addr_str}: {e}. Not retrying.")
break
except FileNotFoundError:
logger.error(f"Node list file '{node_list_file}' not found.")
n_total_nodes_from_file = 0
except Exception as e:
logger.error(f"Reading peer list '{node_list_file}': {e}")
n_total_nodes_from_file = 0
def main():
args = parse_args()
my_host_for_comparison = 'localhost'
my_comparable_address = f"{my_host_for_comparison}:{args.port}"
logger.info(f"Starting blockchain node on port {args.port}")
peers_shared_dict = {}
peers_lock = threading.Lock()
system_fully_connected_event = threading.Event()
temp_n_from_file = 0
expected_peer_ports = set()
# Read node list file and parse peer information
try:
with open(args.node_list_file, 'r') as f:
peer_addrs_in_file = [line.strip() for line in f if line.strip()]
unique_peers = set()
for addr_str in peer_addrs_in_file:
try:
peer_host, peer_port_str = addr_str.split(':', 1)
peer_port_int = int(peer_port_str)
is_self = False
if peer_port_int == args.port:
if peer_host == my_host_for_comparison: is_self = True
elif (my_host_for_comparison == "127.0.0.1" and peer_host == "localhost") or \
(my_host_for_comparison == "localhost" and peer_host == "127.0.0.1"): is_self = True
if not is_self:
unique_peers.add(addr_str)
expected_peer_ports.add(peer_port_int)
except ValueError:
pass
temp_n_from_file = len(unique_peers)
except FileNotFoundError:
logger.info(f"Node list file '{args.node_list_file}' not found. Assuming 0 nodes from file.")
n_for_consensus: int
if temp_n_from_file == 0:
n_for_consensus = 1 # If no peers in file, only this node exists
else:
n_for_consensus = temp_n_from_file + 1 # other peers + self
# Start consensus thread
logger.info(f"Starting consensus thread with network size: {n_for_consensus}")
consensus_thread = ConsensusThread(peers_shared_dict, n_for_consensus, peers_lock)
consensus_thread.start()
# Start transaction queue processor thread
logger.info("Starting transaction queue processor thread")
tx_processor_thread = threading.Thread(
target=process_client_transactions_thread,
args=(global_tx_queue, global_tx_queue_lock, consensus_thread,
peers_shared_dict, peers_lock, system_fully_connected_event),
daemon=True
)
tx_processor_thread.start()
# Start server thread with transaction queue
logger.info(f"Starting server thread on port {args.port}")
server_thread = ServerThread(
args.port,
peers_shared_dict,
peers_lock,
consensus_thread,
temp_n_from_file,
system_fully_connected_event,
expected_peer_ports,
global_tx_queue,
global_tx_queue_lock
)
server_thread.start()
# Connect to peers
logger.info("Connecting to peers")
connect_to_peers(
args.node_list_file,
args.port,
my_comparable_address,
peers_lock,
peers_shared_dict,
consensus_thread,
system_fully_connected_event,
expected_peer_ports
)
# Wait for all expected peers to connect and handshake before proceeding
logger.info(f"Initial expected peers from file: {expected_peer_ports}")
if not expected_peer_ports:
logger.info("No expected peers. Setting system_fully_connected_event immediately.")
system_fully_connected_event.set()
else:
logger.info(f"Waiting for {len(expected_peer_ports)} peers to be confirmed...")
while not system_fully_connected_event.is_set():
confirmed_this_iteration_ports = set()
with peers_lock:
logger.debug(f"Current peers connections: {list(peers_shared_dict.keys())}")
for peer_key in peers_shared_dict.keys():
try:
port = int(peer_key.split(':')[1])
if port in expected_peer_ports:
confirmed_this_iteration_ports.add(port)
except (ValueError, IndexError):
pass
logger.debug(f"Confirmed peer ports this iteration: {confirmed_this_iteration_ports}")
if len(confirmed_this_iteration_ports) == len(expected_peer_ports) and confirmed_this_iteration_ports.issubset(expected_peer_ports):
system_fully_connected_event.set()
logger.info(f"All {len(expected_peer_ports)} expected peers confirmed. Network fully connected.")
break
if not system_fully_connected_event.is_set():
logger.debug(f"Still waiting for peers... Confirmed: {len(confirmed_this_iteration_ports)}/{len(expected_peer_ports)}.")
time.sleep(0.02)
logger.info("Node startup complete, running main loop")
try:
while True:
if not server_thread.is_alive() or not consensus_thread.is_alive() or not tx_processor_thread.is_alive():
logger.error("A critical thread has died. Shutting down.")
break
time.sleep(1)
except KeyboardInterrupt:
logger.info("Shutting down...")
finally:
with peers_lock:
for addr, sock in list(peers_shared_dict.items()):
try:
logger.debug(f"Closing socket for {addr}")
sock.close()
except Exception:
pass
sys.exit(0)
if __name__ == "__main__":
main()