-
-
Notifications
You must be signed in to change notification settings - Fork 14
Fix P2P message validation and host parameter #64
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -43,7 +43,19 @@ def register_handler(self, handler_callback): | |
| raise ValueError("handler_callback must be callable") | ||
| self._handler_callback = handler_callback | ||
|
|
||
| async def start(self, port: int = 9000): | ||
| def register_on_peer_connected(self, handler_callback): | ||
| if not callable(handler_callback): | ||
| raise ValueError("handler_callback must be callable") | ||
| self._on_peer_connected = handler_callback | ||
|
|
||
| async def _notify_peer_connected(self, writer, error_message): | ||
| if self._on_peer_connected: | ||
| try: | ||
| await self._on_peer_connected(writer) | ||
| except Exception: | ||
| logger.exception(error_message) | ||
|
|
||
| async def start(self, port: int = 9000, host: str = "127.0.0.1"): | ||
| """Start listening for incoming peer connections on the given port.""" | ||
| self._port = port | ||
| self._server = await asyncio.start_server( | ||
|
|
@@ -80,11 +92,7 @@ async def connect_to_peer(self, host: str, port: int) -> bool: | |
| self._listen_to_peer(reader, writer, f"{host}:{port}") | ||
| ) | ||
| self._listen_tasks.append(task) | ||
| if self._on_peer_connected: | ||
| try: | ||
| await self._on_peer_connected(writer) | ||
| except Exception: | ||
| logger.exception("Network: Error during outbound peer sync") | ||
| await self._notify_peer_connected(writer, "Network: Error during outbound peer sync") | ||
| logger.info("Network: Connected to peer %s:%d", host, port) | ||
| return True | ||
| except Exception as exc: | ||
|
|
@@ -103,11 +111,7 @@ async def _handle_incoming( | |
| self._peers.append((reader, writer)) | ||
| task = asyncio.create_task(self._listen_to_peer(reader, writer, addr)) | ||
| self._listen_tasks.append(task) | ||
| if self._on_peer_connected: | ||
| try: | ||
| await self._on_peer_connected(writer) | ||
| except Exception: | ||
| logger.exception("Network: Error during peer sync") | ||
| await self._notify_peer_connected(writer, "Network: Error during peer sync") | ||
|
|
||
| def _validate_transaction_payload(self, payload): | ||
| if not isinstance(payload, dict): | ||
|
|
@@ -206,7 +210,10 @@ def _validate_block_payload(self, payload): | |
| def _validate_message(self, message): | ||
| if not isinstance(message, dict): | ||
| return False | ||
| if set(message) != {"type", "data"}: | ||
| required_fields = {"type", "data"} | ||
| if not required_fields.issubset(set(message)): | ||
| return False | ||
| if not set(message).issubset(required_fields): | ||
| return False | ||
|
Comment on lines
+213
to
217
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🧹 Nitpick | 🔵 Trivial Consider simplifying to a single equality check. The bidirectional subset checks ( This properly addresses the past review feedback to keep 🔧 Proposed simplification def _validate_message(self, message):
if not isinstance(message, dict):
return False
- required_fields = {"type", "data"}
- if not required_fields.issubset(set(message)):
- return False
- if not set(message).issubset(required_fields):
+ if set(message) != {"type", "data"}:
return False🤖 Prompt for AI Agents |
||
|
|
||
| msg_type = message.get("type") | ||
|
|
@@ -265,9 +272,6 @@ async def _listen_to_peer( | |
| except (json.JSONDecodeError, UnicodeDecodeError): | ||
| logger.warning("Network: Malformed message from %s", addr) | ||
| continue | ||
| if isinstance(data, dict): | ||
| data["_peer_addr"] = addr | ||
|
|
||
| if not self._validate_message(data): | ||
| logger.warning("Network: Invalid message schema from %s", addr) | ||
| continue | ||
|
|
@@ -278,6 +282,7 @@ async def _listen_to_peer( | |
| logger.info("Network: Duplicate %s ignored from %s", msg_type, addr) | ||
| continue | ||
| self._mark_seen(msg_type, payload) | ||
| data["_peer_addr"] = addr | ||
|
|
||
| if self._handler_callback: | ||
| try: | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧹 Nitpick | 🔵 Trivial
Consider adding return type annotation.
The helper centralizes callback invocation nicely. Adding
-> Nonewould satisfy type checkers and improve clarity.🔧 Proposed fix
🧰 Tools
🪛 Ruff (0.15.6)
[warning] 51-51: Missing return type annotation for private function
_notify_peer_connectedAdd return type annotation:
None(ANN202)
🤖 Prompt for AI Agents