astreum 0.3.9__py3-none-any.whl → 0.3.46__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. astreum/__init__.py +5 -4
  2. astreum/communication/__init__.py +15 -11
  3. astreum/communication/difficulty.py +39 -0
  4. astreum/communication/disconnect.py +57 -0
  5. astreum/communication/handlers/handshake.py +105 -89
  6. astreum/communication/handlers/object_request.py +179 -149
  7. astreum/communication/handlers/object_response.py +7 -1
  8. astreum/communication/handlers/ping.py +9 -0
  9. astreum/communication/handlers/route_request.py +7 -1
  10. astreum/communication/handlers/route_response.py +7 -1
  11. astreum/communication/incoming_queue.py +96 -0
  12. astreum/communication/message_pow.py +36 -0
  13. astreum/communication/models/peer.py +4 -0
  14. astreum/communication/models/ping.py +27 -6
  15. astreum/communication/models/route.py +4 -0
  16. astreum/communication/{start.py → node.py} +10 -11
  17. astreum/communication/outgoing_queue.py +108 -0
  18. astreum/communication/processors/incoming.py +110 -37
  19. astreum/communication/processors/outgoing.py +35 -2
  20. astreum/communication/processors/peer.py +134 -0
  21. astreum/communication/setup.py +273 -112
  22. astreum/communication/util.py +14 -0
  23. astreum/node.py +99 -89
  24. astreum/storage/actions/get.py +79 -48
  25. astreum/storage/actions/set.py +171 -156
  26. astreum/storage/providers.py +24 -0
  27. astreum/storage/setup.py +23 -22
  28. astreum/utils/config.py +247 -30
  29. astreum/utils/logging.py +1 -1
  30. astreum/{consensus → validation}/__init__.py +0 -4
  31. astreum/validation/constants.py +2 -0
  32. astreum/{consensus → validation}/genesis.py +4 -6
  33. astreum/validation/models/block.py +544 -0
  34. astreum/validation/models/fork.py +511 -0
  35. astreum/{consensus → validation}/models/receipt.py +17 -4
  36. astreum/{consensus → validation}/models/transaction.py +45 -3
  37. astreum/validation/node.py +190 -0
  38. astreum/{consensus → validation}/validator.py +18 -9
  39. astreum/validation/workers/__init__.py +8 -0
  40. astreum/{consensus → validation}/workers/validation.py +361 -307
  41. astreum/verification/__init__.py +4 -0
  42. astreum/{consensus/workers/discovery.py → verification/discover.py} +1 -1
  43. astreum/verification/node.py +61 -0
  44. astreum/verification/worker.py +183 -0
  45. {astreum-0.3.9.dist-info → astreum-0.3.46.dist-info}/METADATA +43 -9
  46. astreum-0.3.46.dist-info/RECORD +79 -0
  47. astreum/consensus/models/block.py +0 -364
  48. astreum/consensus/models/chain.py +0 -66
  49. astreum/consensus/models/fork.py +0 -100
  50. astreum/consensus/setup.py +0 -83
  51. astreum/consensus/start.py +0 -67
  52. astreum/consensus/workers/__init__.py +0 -9
  53. astreum/consensus/workers/verify.py +0 -90
  54. astreum-0.3.9.dist-info/RECORD +0 -71
  55. /astreum/{consensus → validation}/models/__init__.py +0 -0
  56. /astreum/{consensus → validation}/models/account.py +0 -0
  57. /astreum/{consensus → validation}/models/accounts.py +0 -0
  58. {astreum-0.3.9.dist-info → astreum-0.3.46.dist-info}/WHEEL +0 -0
  59. {astreum-0.3.9.dist-info → astreum-0.3.46.dist-info}/licenses/LICENSE +0 -0
  60. {astreum-0.3.9.dist-info → astreum-0.3.46.dist-info}/top_level.txt +0 -0
@@ -1,19 +1,18 @@
1
- def connect_to_network_and_verify(self):
1
+
2
+ def connect_node(self):
2
3
  """Initialize communication and consensus components, then load latest block state."""
4
+ if self.is_connected:
5
+ self.logger.debug("Node already connected; skipping communication setup")
6
+ return
7
+
3
8
  self.logger.info("Starting communication and consensus setup")
4
9
  try:
5
10
  from astreum.communication import communication_setup # type: ignore
6
11
  communication_setup(node=self, config=self.config)
7
12
  self.logger.info("Communication setup completed")
8
- except Exception:
9
- self.logger.exception("Communication setup failed")
10
-
11
- try:
12
- from astreum.consensus import consensus_setup # type: ignore
13
- consensus_setup(node=self, config=self.config)
14
- self.logger.info("Consensus setup completed")
15
- except Exception:
16
- self.logger.exception("Consensus setup failed")
13
+ except Exception as exc:
14
+ self.logger.exception("Communication setup failed: %s", exc)
15
+ return exc
17
16
 
18
17
  # Load latest_block_hash from config
19
18
  self.latest_block_hash = getattr(self, "latest_block_hash", None)
@@ -30,7 +29,7 @@ def connect_to_network_and_verify(self):
30
29
 
31
30
  if self.latest_block_hash and self.latest_block is None:
32
31
  try:
33
- from astreum.consensus.models.block import Block
32
+ from astreum.validation.models.block import Block
34
33
  self.latest_block = Block.from_atom(self, self.latest_block_hash)
35
34
  self.logger.info("Loaded latest block %s from storage", self.latest_block_hash.hex())
36
35
  except Exception as exc:
@@ -0,0 +1,108 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING, Optional, Tuple
4
+
5
+ from .message_pow import NONCE_SIZE, calculate_message_nonce
6
+
7
+ if TYPE_CHECKING:
8
+ from .models.message import Message
9
+ from .. import Node
10
+
11
+
12
+ OUTGOING_QUEUE_ITEM_OVERHEAD_BYTES = 6
13
+ def enqueue_outgoing(
14
+ node: "Node",
15
+ address: Tuple[str, int],
16
+ message: Optional["Message"] = None,
17
+ message_bytes: Optional[bytes] = None,
18
+ difficulty: int = 1,
19
+ ) -> bool:
20
+ """Enqueue an outgoing UDP payload while tracking queued bytes.
21
+ When used, it increments `node.outgoing_queue_size` by `len(payload) + 6` and enforces
22
+ `node.outgoing_queue_size_limit` (bytes) as a soft cap by dropping enqueues that
23
+ would exceed the limit. If `node.outgoing_queue_timeout` is > 0, it waits up to
24
+ that many seconds (using `communication_stop_event.wait`) for space before dropping.
25
+ """
26
+ if not node.is_connected:
27
+ raise RuntimeError("node is not connected; call node.connect() (communication_setup) first")
28
+
29
+ if message is not None and message_bytes is not None:
30
+ raise ValueError("Specify only one of message or message_bytes")
31
+
32
+ if message_bytes is not None:
33
+ payload = message_bytes
34
+ elif message is not None:
35
+ payload = message.to_bytes()
36
+ else:
37
+ raise ValueError("Either message or message_bytes must be provided")
38
+
39
+ try:
40
+ difficulty_value = int(difficulty)
41
+ except Exception:
42
+ difficulty_value = 1
43
+ if difficulty_value < 1:
44
+ difficulty_value = 1
45
+
46
+ try:
47
+ nonce = calculate_message_nonce(payload, difficulty_value)
48
+ except Exception as exc:
49
+ node.logger.warning(
50
+ "Failed generating message nonce (difficulty=%s bytes=%s): %s",
51
+ difficulty_value,
52
+ len(payload),
53
+ exc,
54
+ )
55
+ return False
56
+
57
+ payload = int(nonce).to_bytes(NONCE_SIZE, "big", signed=False) + payload
58
+
59
+ accounted_size = len(payload) + OUTGOING_QUEUE_ITEM_OVERHEAD_BYTES
60
+
61
+ timeout = float(node.outgoing_queue_timeout or 0)
62
+
63
+ with node.outgoing_queue_size_lock:
64
+ current_size = int(node.outgoing_queue_size)
65
+ limit = int(node.outgoing_queue_size_limit)
66
+ projected_size = current_size + accounted_size
67
+ if projected_size > limit:
68
+ if timeout <= 0:
69
+ node.logger.warning(
70
+ "Outgoing queue size limit reached (%s > %s); dropping outbound payload (bytes=%s)",
71
+ projected_size,
72
+ limit,
73
+ len(payload),
74
+ )
75
+ return False
76
+ wait_for_space = True
77
+ else:
78
+ node.outgoing_queue_size = projected_size
79
+ wait_for_space = False
80
+
81
+ if wait_for_space:
82
+ if node.communication_stop_event.wait(timeout):
83
+ return False
84
+ if not node.is_connected:
85
+ return False
86
+ with node.outgoing_queue_size_lock:
87
+ current_size = int(node.outgoing_queue_size)
88
+ limit = int(node.outgoing_queue_size_limit)
89
+ projected_size = current_size + accounted_size
90
+ if limit and projected_size > limit:
91
+ node.logger.warning(
92
+ "Outgoing queue still full after waiting %ss (%s > %s); dropping outbound payload (bytes=%s)",
93
+ timeout,
94
+ projected_size,
95
+ limit,
96
+ len(payload),
97
+ )
98
+ return False
99
+ node.outgoing_queue_size = projected_size
100
+
101
+ try:
102
+ node.outgoing_queue.put((payload, address, accounted_size))
103
+ except Exception:
104
+ with node.outgoing_queue_size_lock:
105
+ node.outgoing_queue_size = max(0, int(node.outgoing_queue_size) - accounted_size)
106
+ raise
107
+
108
+ return True
@@ -1,30 +1,56 @@
1
- from __future__ import annotations
2
-
3
- from typing import TYPE_CHECKING
4
-
5
- from ..handlers.handshake import handle_handshake
1
+ from __future__ import annotations
2
+
3
+ import socket
4
+ from queue import Empty
5
+ from typing import TYPE_CHECKING
6
+
7
+ from ..handlers.handshake import handle_handshake
6
8
  from ..handlers.object_request import handle_object_request
7
9
  from ..handlers.object_response import handle_object_response
8
10
  from ..handlers.ping import handle_ping
9
11
  from ..handlers.route_request import handle_route_request
10
12
  from ..handlers.route_response import handle_route_response
13
+ from ..incoming_queue import enqueue_incoming
11
14
  from ..models.message import Message, MessageTopic
12
15
  from ..models.peer import Peer
16
+ from ..outgoing_queue import enqueue_outgoing
13
17
  from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PublicKey
14
18
 
15
19
  if TYPE_CHECKING:
16
- from .. import Node
17
-
18
-
20
+ from .. import Node
21
+
22
+
19
23
  def process_incoming_messages(node: "Node") -> None:
20
24
  """Process incoming messages (placeholder)."""
21
- while True:
25
+ stop = getattr(node, "communication_stop_event", None)
26
+ while stop is None or not stop.is_set():
22
27
  try:
23
- data, addr = node.incoming_queue.get()
24
- except Exception as exc:
28
+ item = node.incoming_queue.get(timeout=0.5)
29
+ except Empty:
30
+ continue
31
+ except Exception:
25
32
  node.logger.exception("Error taking from incoming queue")
26
33
  continue
27
34
 
35
+ data = None
36
+ addr = None
37
+ accounted_size = None
38
+
39
+ if isinstance(item, tuple) and len(item) == 3:
40
+ data, addr, accounted_size = item
41
+ else:
42
+ node.logger.warning("Incoming queue item has unexpected shape: %r", item)
43
+ continue
44
+
45
+ if stop is not None and stop.is_set():
46
+ if accounted_size is not None:
47
+ try:
48
+ with node.incoming_queue_size_lock:
49
+ node.incoming_queue_size = max(0, node.incoming_queue_size - int(accounted_size))
50
+ except Exception:
51
+ node.logger.exception("Failed updating incoming_queue_size on shutdown")
52
+ break
53
+
28
54
  try:
29
55
  message = Message.from_bytes(data)
30
56
  except Exception as exc:
@@ -34,7 +60,7 @@ def process_incoming_messages(node: "Node") -> None:
34
60
  if message.handshake:
35
61
  if handle_handshake(node, addr, message):
36
62
  continue
37
-
63
+
38
64
  peer = None
39
65
  try:
40
66
  peer = node.get_peer(message.sender_bytes)
@@ -44,10 +70,13 @@ def process_incoming_messages(node: "Node") -> None:
44
70
  try:
45
71
  peer_key = X25519PublicKey.from_public_bytes(message.sender_bytes)
46
72
  host, port = addr[0], int(addr[1])
73
+ default_seed_ips = getattr(node, "default_seed_ips", None)
74
+ is_default_seed = bool(default_seed_ips) and host in default_seed_ips
47
75
  peer = Peer(
48
76
  node_secret_key=node.relay_secret_key,
49
77
  peer_public_key=peer_key,
50
78
  address=(host, port),
79
+ is_default_seed=is_default_seed,
51
80
  )
52
81
  except Exception:
53
82
  peer = None
@@ -60,39 +89,83 @@ def process_incoming_messages(node: "Node") -> None:
60
89
  try:
61
90
  message.decrypt(peer.shared_key_bytes)
62
91
  except Exception as exc:
63
- node.logger.warning("Error decrypting message from %s: %s", peer.address, exc)
92
+ node.logger.warning(
93
+ "Error decrypting message from %s (len=%s, enc_len=%s, exc=%s)",
94
+ peer.address,
95
+ len(data),
96
+ len(message.encrypted) if message.encrypted is not None else None,
97
+ exc,
98
+ )
99
+ try:
100
+ host, port = addr[0], int(addr[1])
101
+ handshake_message = Message(
102
+ handshake=True,
103
+ sender=node.relay_public_key,
104
+ content=int(node.config["incoming_port"]).to_bytes(2, "big", signed=False),
105
+ )
106
+ enqueue_outgoing(
107
+ node,
108
+ (host, port),
109
+ message=handshake_message,
110
+ difficulty=1,
111
+ )
112
+ except Exception as handshake_exc:
113
+ node.logger.debug(
114
+ "Failed queueing rekey handshake to %s: %s",
115
+ addr,
116
+ handshake_exc,
117
+ )
64
118
  continue
65
119
 
66
- match message.topic:
67
- case MessageTopic.PING:
68
- handle_ping(node, peer, message.content)
69
-
70
- case MessageTopic.OBJECT_REQUEST:
71
- handle_object_request(node, peer, message)
72
-
73
- case MessageTopic.OBJECT_RESPONSE:
74
- handle_object_response(node, peer, message)
120
+ try:
121
+ match message.topic:
122
+ case MessageTopic.PING:
123
+ handle_ping(node, peer, message.content)
75
124
 
76
- case MessageTopic.ROUTE_REQUEST:
77
- handle_route_request(node, peer, message)
125
+ case MessageTopic.OBJECT_REQUEST:
126
+ handle_object_request(node, peer, message)
78
127
 
79
- case MessageTopic.ROUTE_RESPONSE:
80
- handle_route_response(node, peer, message)
128
+ case MessageTopic.OBJECT_RESPONSE:
129
+ handle_object_response(node, peer, message)
81
130
 
82
- case MessageTopic.TRANSACTION:
83
- if node.validation_secret_key is None:
84
- continue
85
- node._validation_transaction_queue.put(message.content)
131
+ case MessageTopic.ROUTE_REQUEST:
132
+ handle_route_request(node, peer, message)
86
133
 
87
- case _:
88
- continue
134
+ case MessageTopic.ROUTE_RESPONSE:
135
+ handle_route_response(node, peer, message)
89
136
 
137
+ case MessageTopic.TRANSACTION:
138
+ if node.validation_secret_key is None:
139
+ continue
140
+ node._validation_transaction_queue.put(message.content)
90
141
 
91
- def populate_incoming_messages(node: "Node") -> None:
142
+ case _:
143
+ continue
144
+ finally:
145
+ if accounted_size is not None:
146
+ try:
147
+ with node.incoming_queue_size_lock:
148
+ node.incoming_queue_size = max(0, node.incoming_queue_size - int(accounted_size))
149
+ except Exception:
150
+ node.logger.exception("Failed updating incoming_queue_size")
151
+
152
+ node.logger.info("Incoming message processor stopped")
153
+
154
+
155
+ def populate_incoming_messages(node: "Node") -> None:
92
156
  """Receive UDP packets and feed the incoming queue."""
93
- while True:
157
+ stop = getattr(node, "communication_stop_event", None)
158
+ while stop is None or not stop.is_set():
94
159
  try:
95
160
  data, addr = node.incoming_socket.recvfrom(4096)
96
- node.incoming_queue.put((data, addr))
97
- except Exception as exc:
98
- node.logger.warning("Error populating incoming queue: %s", exc)
161
+ enqueue_incoming(node, addr, payload=data)
162
+ except socket.timeout:
163
+ continue
164
+ except OSError:
165
+ if stop is not None and stop.is_set():
166
+ break
167
+ node.logger.warning("Error populating incoming queue: socket closed")
168
+ except Exception as exc:
169
+ node.logger.warning("Error populating incoming queue: %s", exc)
170
+
171
+ node.logger.info("Incoming message populator stopped")
@@ -1,5 +1,6 @@
1
1
  from __future__ import annotations
2
2
 
3
+ from queue import Empty
3
4
  from typing import TYPE_CHECKING, Tuple
4
5
 
5
6
  if TYPE_CHECKING:
@@ -7,14 +8,46 @@ if TYPE_CHECKING:
7
8
 
8
9
  def process_outgoing_messages(node: "Node") -> None:
9
10
  """Send queued outbound packets."""
10
- while True:
11
+ stop = getattr(node, "communication_stop_event", None)
12
+ while stop is None or not stop.is_set():
11
13
  try:
12
- payload, addr = node.outgoing_queue.get()
14
+ item = node.outgoing_queue.get(timeout=0.5)
15
+ except Empty:
16
+ continue
13
17
  except Exception:
14
18
  node.logger.exception("Error taking from outgoing queue")
15
19
  continue
16
20
 
21
+ payload = None
22
+ addr = None
23
+ accounted_size = None
24
+ if isinstance(item, tuple) and len(item) == 3:
25
+ payload, addr, accounted_size = item
26
+ elif isinstance(item, tuple) and len(item) == 2:
27
+ payload, addr = item
28
+ else:
29
+ node.logger.warning("Outgoing queue item has unexpected shape: %r", item)
30
+ continue
31
+
32
+ if stop is not None and stop.is_set():
33
+ if accounted_size is not None:
34
+ try:
35
+ with node.outgoing_queue_size_lock:
36
+ node.outgoing_queue_size = max(0, node.outgoing_queue_size - int(accounted_size))
37
+ except Exception:
38
+ node.logger.exception("Failed updating outgoing_queue_size on shutdown")
39
+ break
40
+
17
41
  try:
18
42
  node.outgoing_socket.sendto(payload, addr)
19
43
  except Exception as exc:
20
44
  node.logger.warning("Error sending message to %s: %s", addr, exc)
45
+ finally:
46
+ if accounted_size is not None:
47
+ try:
48
+ with node.outgoing_queue_size_lock:
49
+ node.outgoing_queue_size = max(0, node.outgoing_queue_size - int(accounted_size))
50
+ except Exception:
51
+ node.logger.exception("Failed updating outgoing_queue_size")
52
+
53
+ node.logger.info("Outgoing message processor stopped")
@@ -0,0 +1,134 @@
1
+ from __future__ import annotations
2
+
3
+ import time
4
+ from datetime import datetime, timedelta, timezone
5
+ from typing import TYPE_CHECKING, Any
6
+
7
+ from ..models.message import Message
8
+ from ..outgoing_queue import enqueue_outgoing
9
+ from ..util import address_str_to_host_and_port
10
+
11
+ if TYPE_CHECKING:
12
+ from .. import Node
13
+
14
+
15
+ def _queue_bootstrap_handshakes(node: "Node") -> int:
16
+ relay_public_key = node.relay_public_key
17
+
18
+ bootstrap_peers = node.bootstrap_peers
19
+ if not bootstrap_peers:
20
+ return 0
21
+
22
+ try:
23
+ incoming_port = int(node.config.get("incoming_port", 0))
24
+ content = incoming_port.to_bytes(2, "big", signed=False)
25
+ except (TypeError, ValueError, OverflowError):
26
+ return 0
27
+
28
+ handshake_message = Message(
29
+ handshake=True,
30
+ sender=relay_public_key,
31
+ content=content,
32
+ )
33
+ handshake_bytes = handshake_message.to_bytes()
34
+ sent = 0
35
+ for addr in bootstrap_peers:
36
+ try:
37
+ host, port = address_str_to_host_and_port(addr)
38
+ except Exception as exc:
39
+ node.logger.warning("Invalid bootstrap address %s: %s", addr, exc)
40
+ continue
41
+ try:
42
+ queued = enqueue_outgoing(
43
+ node,
44
+ (host, port),
45
+ message_bytes=handshake_bytes,
46
+ difficulty=1,
47
+ )
48
+ except Exception as exc:
49
+ node.logger.debug(
50
+ "Failed queueing bootstrap handshake to %s:%s: %s",
51
+ host,
52
+ port,
53
+ exc,
54
+ )
55
+ continue
56
+ if queued:
57
+ node.logger.info("Retrying bootstrap handshake to %s:%s", host, port)
58
+ sent += 1
59
+ else:
60
+ node.logger.debug(
61
+ "Bootstrap handshake queue rejected for %s:%s",
62
+ host,
63
+ port,
64
+ )
65
+ return sent
66
+
67
+
68
+ def manage_peer(node: "Node") -> None:
69
+ """Continuously evict peers whose timestamps exceed the configured timeout."""
70
+ node.logger.info(
71
+ "Peer manager started (timeout=%3ds, interval=%3ds)",
72
+ node.config["peer_timeout"],
73
+ node.config["peer_timeout_interval"],
74
+ )
75
+ stop = getattr(node, "communication_stop_event", None)
76
+ while stop is None or not stop.is_set():
77
+ timeout_seconds = node.config["peer_timeout"]
78
+ interval_seconds = node.config["peer_timeout_interval"]
79
+ try:
80
+ peers = getattr(node, "peers", None)
81
+ peer_route = getattr(node, "peer_route", None)
82
+ if not isinstance(peers, dict) or peer_route is None:
83
+ time.sleep(interval_seconds)
84
+ continue
85
+
86
+ cutoff = datetime.now(timezone.utc) - timedelta(seconds=timeout_seconds)
87
+ stale_keys = []
88
+ with node.peers_lock:
89
+ for peer_key, peer in list(peers.items()):
90
+ if peer.timestamp < cutoff:
91
+ stale_keys.append(peer_key)
92
+
93
+ removed_count = 0
94
+ for peer_key in stale_keys:
95
+ removed = node.remove_peer(peer_key)
96
+ if removed is None:
97
+ continue
98
+ removed_count += 1
99
+ try:
100
+ peer_route.remove_peer(peer_key)
101
+ except Exception:
102
+ node.logger.debug(
103
+ "Unable to remove peer %s from route",
104
+ peer_key.hex(),
105
+ )
106
+ node.logger.debug(
107
+ "Evicted stale peer %s last seen at %s",
108
+ peer_key.hex(),
109
+ getattr(removed, "timestamp", None),
110
+ )
111
+
112
+ if removed_count:
113
+ node.logger.info("Peer manager removed %s stale peer(s)", removed_count)
114
+
115
+ try:
116
+ with node.peers_lock:
117
+ peer_count = len(peers)
118
+ except Exception:
119
+ peer_count = len(getattr(node, "peers", {}) or {})
120
+ if peer_count == 0:
121
+ bootstrap_interval = node.config.get("bootstrap_retry_interval", 0)
122
+ now = time.time()
123
+ last_attempt = getattr(node, "_bootstrap_last_attempt", 0.0)
124
+ if bootstrap_interval and (now - last_attempt) >= bootstrap_interval:
125
+ sent = _queue_bootstrap_handshakes(node)
126
+ if sent:
127
+ node._bootstrap_last_attempt = now
128
+ except Exception:
129
+ node.logger.exception("Peer manager iteration failed")
130
+
131
+ if stop is not None and stop.wait(interval_seconds):
132
+ break
133
+
134
+ node.logger.info("Peer manager stopped")