-
Notifications
You must be signed in to change notification settings - Fork 16
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #94 from pipermerriam/piper/implement-JSON-RPC-pin…
…g-endpoint Piper/implement json rpc ping endpoint
- Loading branch information
Showing
9 changed files
with
342 additions
and
70 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,10 +1,23 @@ | ||
from socket import inet_ntoa | ||
from typing import NamedTuple | ||
|
||
from eth_enr import ENRAPI | ||
from eth_enr.constants import IP_V4_ADDRESS_ENR_KEY, UDP_PORT_ENR_KEY | ||
|
||
|
||
class Endpoint(NamedTuple): | ||
ip_address: bytes | ||
port: int | ||
|
||
def __str__(self) -> str: | ||
return f"{inet_ntoa(self.ip_address)}:{self.port}" | ||
|
||
@classmethod | ||
def from_enr(self, enr: ENRAPI) -> "Endpoint": | ||
try: | ||
ip_address = enr[IP_V4_ADDRESS_ENR_KEY] | ||
port = enr[UDP_PORT_ENR_KEY] | ||
except KeyError: | ||
raise Exception("Missing endpoint address information: ") | ||
|
||
return Endpoint(ip_address, port) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,111 @@ | ||
import ipaddress | ||
from socket import inet_ntoa | ||
from typing import Any, Iterable, Optional, Tuple, TypedDict | ||
|
||
from eth_enr import ENR | ||
from eth_typing import HexStr, NodeID | ||
from eth_utils import decode_hex, is_hex, remove_0x_prefix, to_dict | ||
|
||
from ddht.abc import RPCHandlerAPI | ||
from ddht.endpoint import Endpoint | ||
from ddht.rpc import RPCError, RPCHandler, RPCRequest | ||
from ddht.v5_1.abc import NetworkAPI | ||
|
||
|
||
class PongResponse(TypedDict): | ||
enr_seq: int | ||
packet_ip: str | ||
packet_port: int | ||
|
||
|
||
def is_hex_node_id(value: Any) -> bool: | ||
return ( | ||
isinstance(value, str) | ||
and is_hex(value) | ||
and len(remove_0x_prefix(HexStr(value))) == 64 | ||
) | ||
|
||
|
||
def validate_hex_node_id(value: Any) -> None: | ||
if not is_hex_node_id(value): | ||
raise RPCError(f"Invalid NodeID: {value}") | ||
|
||
|
||
def is_endpoint(value: Any) -> bool: | ||
if not isinstance(value, str): | ||
return False | ||
ip_address, _, port = value.rpartition(":") | ||
try: | ||
ipaddress.ip_address(ip_address) | ||
except ValueError: | ||
return False | ||
|
||
if not port.isdigit(): | ||
return False | ||
|
||
return True | ||
|
||
|
||
def validate_endpoint(value: Any) -> None: | ||
if not is_endpoint(value): | ||
raise RPCError(f"Invalid Endpoint: {value}") | ||
|
||
|
||
class PingHandler(RPCHandler[Tuple[NodeID, Optional[Endpoint]], PongResponse]): | ||
def __init__(self, network: NetworkAPI) -> None: | ||
self._network = network | ||
|
||
def extract_params(self, request: RPCRequest) -> Tuple[NodeID, Optional[Endpoint]]: | ||
try: | ||
raw_params = request["params"] | ||
except KeyError as err: | ||
raise RPCError(f"Missiing call params: {err}") | ||
|
||
if len(raw_params) != 1: | ||
raise RPCError( | ||
f"`ddht_ping` endpoint expects a single parameter: " | ||
f"Got {len(raw_params)} params: {raw_params}" | ||
) | ||
|
||
value = raw_params[0] | ||
|
||
node_id: NodeID | ||
endpoint: Optional[Endpoint] | ||
|
||
if is_hex_node_id(value): | ||
node_id = NodeID(decode_hex(value)) | ||
endpoint = None | ||
elif value.startswith("enode://"): | ||
raw_node_id, _, raw_endpoint = value[8:].partition("@") | ||
|
||
validate_hex_node_id(raw_node_id) | ||
validate_endpoint(raw_endpoint) | ||
|
||
node_id = NodeID(decode_hex(raw_node_id)) | ||
|
||
raw_ip_address, _, raw_port = raw_endpoint.partition(":") | ||
ip_address = ipaddress.ip_address(raw_ip_address) | ||
port = int(raw_port) | ||
endpoint = Endpoint(ip_address.packed, port) | ||
elif value.startswith("enr:"): | ||
enr = ENR.from_repr(value) | ||
node_id = enr.node_id | ||
endpoint = Endpoint.from_enr(enr) | ||
else: | ||
raise RPCError(f"Unrecognized node identifier: {value}") | ||
|
||
return node_id, endpoint | ||
|
||
async def do_call(self, params: Tuple[NodeID, Optional[Endpoint]]) -> PongResponse: | ||
node_id, endpoint = params | ||
pong = await self._network.ping(node_id, endpoint=endpoint) | ||
return PongResponse( | ||
enr_seq=pong.enr_seq, | ||
packet_ip=inet_ntoa(pong.packet_ip), | ||
packet_port=pong.packet_port, | ||
) | ||
|
||
|
||
@to_dict | ||
def get_v51_rpc_handlers(network: NetworkAPI) -> Iterable[Tuple[str, RPCHandlerAPI]]: | ||
yield ("discv5_ping", PingHandler(network)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
import io | ||
import itertools | ||
import json | ||
|
||
from eth_utils.toolz import take | ||
import pytest | ||
import trio | ||
|
||
from ddht.rpc import RPCRequest, read_json | ||
|
||
|
||
@pytest.fixture(name="make_raw_request") | ||
async def _make_raw_request(ipc_path, rpc_server): | ||
socket = await trio.open_unix_socket(str(ipc_path)) | ||
async with socket: | ||
buffer = io.StringIO() | ||
|
||
async def make_raw_request(raw_request: str): | ||
with trio.fail_after(2): | ||
data = raw_request.encode("utf8") | ||
data_iter = iter(data) | ||
while True: | ||
chunk = bytes(take(1024, data_iter)) | ||
if chunk: | ||
try: | ||
await socket.send_all(chunk) | ||
except trio.BrokenResourceError: | ||
break | ||
else: | ||
break | ||
return await read_json(socket.socket, buffer) | ||
|
||
yield make_raw_request | ||
|
||
|
||
@pytest.fixture(name="make_request") | ||
async def _make_request(make_raw_request): | ||
id_counter = itertools.count() | ||
|
||
async def make_request(method, params=None): | ||
if params is None: | ||
params = [] | ||
request = RPCRequest( | ||
jsonrpc="2.0", method=method, params=params, id=next(id_counter), | ||
) | ||
raw_request = json.dumps(request) | ||
|
||
raw_response = await make_raw_request(raw_request) | ||
|
||
if "error" in raw_response: | ||
raise Exception(raw_response) | ||
elif "result" in raw_response: | ||
return raw_response["result"] | ||
else: | ||
raise Exception("Invariant") | ||
|
||
yield make_request |
Oops, something went wrong.