diff --git a/.gitmodules b/.gitmodules index 5a1bf50..671bf81 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,3 @@ [submodule "external/monero-cpp"] path = external/monero-cpp - url = https://github.com/woodser/monero-cpp + url = https://github.com/mycomputercrashsalot/monero-cpp diff --git a/external/monero-cpp b/external/monero-cpp index 6178753..a529b4d 160000 --- a/external/monero-cpp +++ b/external/monero-cpp @@ -1 +1 @@ -Subproject commit 6178753bc9b1956b4d2e834507b6ff4cb55229c7 +Subproject commit a529b4dd6eb358f04334856e34b7207cd69cf210 diff --git a/src/cpp/common/py_monero_common.cpp b/src/cpp/common/py_monero_common.cpp index c68de50..c1db382 100644 --- a/src/cpp/common/py_monero_common.cpp +++ b/src/cpp/common/py_monero_common.cpp @@ -65,56 +65,23 @@ py::dict PyGenUtils::deserialize(const std::string& s) { return fn(s).cast(); } -py::object PyGenUtils::convert_value(const std::string& val) { - if (val == "true") return py::bool_(true); - if (val == "false") return py::bool_(false); - - try { - std::size_t pos; - int i = std::stoi(val, &pos); - if (pos == val.size()) return py::int_(i); - } catch (...) {} - +py::object PyGenUtils::parse_rpc_response(const std::string& body, bool json_rpc) { + // parse the raw body with python's own json parsing, which keeps the empty containers and the + // exact numbers that a property tree walk cannot represent + py::object response; try { - std::size_t pos; - double d = std::stod(val, &pos); - if (pos == val.size()) return py::float_(d); - } catch (...) {} - - return py::str(val); -} - -py::object PyGenUtils::ptree_to_pyobject(const boost::property_tree::ptree& tree) { - if (tree.empty()) { - return convert_value(tree.get_value()); - } - - bool is_array = true; - for (const auto& child : tree) { - if (child.first != "") { - is_array = false; - break; - } - } - - if (is_array) { - py::list lst; - for (const auto& child : tree) { - lst.append(ptree_to_pyobject(child.second)); - } - return lst; - } - else { - py::dict d; - if (!tree.get_value().empty()) { - d["__value__"] = convert_value(tree.get_value()); - } - for (const auto& child : tree) { - d[py::str(child.first)] = ptree_to_pyobject(child.second); - } - - return d; + response = py::module_::import("json").attr("loads")(py::bytes(body)); + } catch (const py::error_already_set& e) { + // a body that is not json is not a decode error of python, it is a bad answer of the server + throw monero_error(std::string("Failed to parse the RPC response as json: ") + e.what()); } + // a non-object answer carries no json rpc result + if (!py::isinstance(response)) return json_rpc ? py::none() : response; + py::dict answer = response; + // return the result of a json rpc response, which raise_rpc_error checked for an error already + if (json_rpc) return answer.contains("result") ? py::object(answer["result"]) : py::none(); + // a response that carries the jsonrpc key was already answered as a json rpc one + return answer.contains("jsonrpc") ? py::none() : response; } // --------------------------- MONERO REQUEST PARAMS --------------------------- diff --git a/src/cpp/common/py_monero_common.h b/src/cpp/common/py_monero_common.h index df59de1..b8efd74 100644 --- a/src/cpp/common/py_monero_common.h +++ b/src/cpp/common/py_monero_common.h @@ -57,6 +57,7 @@ #include #include +#include "common/monero_error.h" #include "common/monero_rpc_connection.h" #include "daemon/monero_daemon_model.h" @@ -111,8 +112,16 @@ class PyGenUtils { public: static std::string serialize(const py::dict& d); static py::dict deserialize(const std::string& s); - static py::object convert_value(const std::string& val); - static py::object ptree_to_pyobject(const boost::property_tree::ptree& tree); + /** + * Parse a raw RPC response body with python's own json, which keeps the empty containers + * and the exact numbers that a property tree walk cannot represent. The error check of the + * body belongs to monero-cpp's raise_rpc_error, which the caller runs before this parse. + * + * @param body is the raw response body to parse + * @param json_rpc is true if the body answers a json rpc request, which carries its result + * @return py::object the parsed response, the result of a json rpc one + */ + static py::object parse_rpc_response(const std::string& body, bool json_rpc); }; struct PyMoneroRequestParams : public monero_request_params { @@ -124,3 +133,4 @@ struct PyMoneroRequestParams : public monero_request_params { rapidjson::Value to_rapidjson_val(rapidjson::Document::AllocatorType& allocator) const override; }; + diff --git a/src/cpp/common/py_monero_common_bindings.cpp b/src/cpp/common/py_monero_common_bindings.cpp index 4d06773..fd6f09d 100644 --- a/src/cpp/common/py_monero_common_bindings.cpp +++ b/src/cpp/common/py_monero_common_bindings.cpp @@ -52,6 +52,7 @@ * Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers */ #include "py_monero_types.h" +#include "utils/gen_utils.h" void py_monero_bind_vectors_and_maps(py::module_& m) { @@ -329,17 +330,36 @@ void py_monero_bind_common(py::module_& m, PyMoneroTypes& t) { }, py::arg("timeout_ms") = py::none(), py::call_guard()) .def("send_json_request", [](monero_rpc_connection& self, const std::string &method, const boost::optional& parameters, const boost::optional& timeout_ms) { monero_rpc_request request(method, std::make_shared(parameters)); - auto response = self.send_json_request(request, timeout_ms); - boost::optional res; - if (response.m_result != boost::none) res = PyGenUtils::ptree_to_pyobject(*response.m_result); - return res; + std::string body = request.serialize(); + std::string raw_response; + { + // the parameters are serialized under the gil, the request itself runs without it + py::gil_scoped_release release; + raw_response = self.invoke_post("/json_rpc", body, timeout_ms); + // the error check of the send request methods, so the error shape stays in one place + boost::property_tree::ptree node; + gen_utils::deserialize(raw_response, node); + boost::optional error_node = node.get_child_optional("error"); + if (error_node != boost::none) monero_rpc_connection::raise_rpc_error(error_node.get(), "/json_rpc", method); + } + return PyGenUtils::parse_rpc_response(raw_response, true); }, py::arg("method"), py::arg("parameters") = py::none(), py::arg("timeout_ms") = py::none()) .def("send_path_request", [](monero_rpc_connection& self, const std::string &method, const boost::optional& parameters, const boost::optional& timeout_ms) { + if (method.empty()) throw monero_error("No RPC method set in path request"); monero_rpc_request request(method, std::make_shared(parameters), false); - auto response = self.send_path_request(request, timeout_ms); - boost::optional res; - if (response.m_response != boost::none) res = PyGenUtils::ptree_to_pyobject(*response.m_response); - return res; + std::string body = request.serialize(); + std::string raw_response; + { + // the parameters are serialized under the gil, the request itself runs without it + py::gil_scoped_release release; + raw_response = self.invoke_post("/" + method, body, timeout_ms); + // the error check of the send request methods, so the error shape stays in one place + boost::property_tree::ptree node; + gen_utils::deserialize(raw_response, node); + boost::optional error_node = node.get_child_optional("error"); + if (error_node != boost::none) monero_rpc_connection::raise_rpc_error(error_node.get(), "/" + method, method); + } + return PyGenUtils::parse_rpc_response(raw_response, false); }, py::arg("method"), py::arg("parameters") = py::none(), py::arg("timeout_ms") = py::none()) .def("send_binary_request", [](monero_rpc_connection& self, const std::string &method, const boost::optional& parameters, const boost::optional& timeout_ms) { monero_rpc_request request(method, std::make_shared(parameters), false); diff --git a/src/cpp/wallet/py_monero_wallet_bindings.cpp b/src/cpp/wallet/py_monero_wallet_bindings.cpp index bff4e06..a45fcbe 100644 --- a/src/cpp/wallet/py_monero_wallet_bindings.cpp +++ b/src/cpp/wallet/py_monero_wallet_bindings.cpp @@ -953,12 +953,7 @@ void py_monero_bind_wallet(py::module_& m, PyMoneroTypes& t) { MONERO_CATCH_AND_RETHROW(self.sign_message(msg, signature_type, account_idx, subaddress_idx)); }, py::arg("msg"), py::arg("signature_type"), py::arg("account_idx") = 0, py::arg("subaddress_idx") = 0, py::call_guard()) .def("verify_message", [](PyMoneroWallet& self, const std::string& msg, const std::string& address, const std::string& signature) { - try { - return self.verify_message(msg, address, signature); - } catch (...) { - // TODO wallet full can differentiate incorrect from invalid address, but rpc returns -2 for both, so returning bad result for consistency - return monero_message_signature_result(); - } + MONERO_CATCH_AND_RETHROW(self.verify_message(msg, address, signature)); }, py::arg("msg"), py::arg("address"), py::arg("signature"), py::call_guard()) .def("get_tx_key", [](PyMoneroWallet& self, const std::string& tx_hash) { MONERO_CATCH_AND_RETHROW(self.get_tx_key(tx_hash)); diff --git a/src/monero/monero_rpc_connection.pyi b/src/monero/monero_rpc_connection.pyi index 9ed2423..7cea9e8 100644 --- a/src/monero/monero_rpc_connection.pyi +++ b/src/monero/monero_rpc_connection.pyi @@ -93,7 +93,11 @@ class MoneroRpcConnection(SerializableStruct): """ Check the connection and update online, authentication, and response time status. - :param int|None timeout_ms: the maximum response time before considered offline. + :param int|None timeout_ms: the maximum response time before considered offline. Applies + to the request itself, not to the initial connection: a fresh connection to an + unreachable host can block for the connect timeout of the operating system (about 75 + seconds on some platforms) before this timeout applies. A value of `0` means an + indefinite timeout. :returns bool: `True` if there is a change in status, `False` otherwise. """ ... @@ -160,7 +164,10 @@ class MoneroRpcConnection(SerializableStruct): :param str method: is the method to request. :param Optional[object] parameters: are the request's input parameters (default `None`). - :param Optional[int] timeout_ms: request timeout in milliseconds. + :param Optional[int] timeout_ms: request timeout in milliseconds. Applies to the request + itself, not to the initial connection: a fresh connection to an unreachable host can + block for the connect timeout of the operating system (about 75 seconds on some + platforms) before this timeout applies. A value of `0` means an indefinite timeout. :returns object | None: the RPC API response as a map. """ ... @@ -173,7 +180,10 @@ class MoneroRpcConnection(SerializableStruct): :param str method: is the url path of the request to invoke. :param Optional[object] parameters: are request parameters sent in the body. - :param Optional[int] timeout_ms: request timeout in milliseconds. + :param Optional[int] timeout_ms: request timeout in milliseconds. Applies to the request + itself, not to the initial connection: a fresh connection to an unreachable host can + block for the connect timeout of the operating system (about 75 seconds on some + platforms) before this timeout applies. A value of `0` means an indefinite timeout. :returns object | None: the request's deserialized response. """ ... @@ -184,7 +194,10 @@ class MoneroRpcConnection(SerializableStruct): :param str method: is the path of the binary RPC method to invoke. :param Optional[object] parameters: are the request parameters (default `None`). - :param Optional[int] timeout_ms: request timeout in milliseconds. + :param Optional[int] timeout_ms: request timeout in milliseconds. Applies to the request + itself, not to the initial connection: a fresh connection to an unreachable host can + block for the connect timeout of the operating system (about 75 seconds on some + platforms) before this timeout applies. A value of `0` means an indefinite timeout. :returns bytes | None: the request's deserialized binary response. """ ... diff --git a/tests/common/test_rpc_connection.py b/tests/common/test_rpc_connection.py index 0678d9c..6a5e3a6 100644 --- a/tests/common/test_rpc_connection.py +++ b/tests/common/test_rpc_connection.py @@ -1,6 +1,13 @@ import pytest import logging +import json +import threading +import time + +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from typing import Any + from monero import MoneroRpcConnection, MoneroConnectionType, MoneroError, MoneroRpcError, MoneroUtils from utils import ( TestUtils as Utils, RpcConnectionUtils, @@ -9,6 +16,88 @@ logger: logging.Logger = logging.getLogger("TestMoneroRpcConnection") +# The crafted result of the raw response tests: every value is one that a property tree walk +# cannot represent, so the response objects must be built from the raw bodies with python's +# own json parsing to keep the types +RAW_RESPONSE_TYPES: dict[str, Any] = { + "empty_object": {}, + "empty_array": [], + "empty_string": "", + "zero": 0, + "nested": {"list": [], "dict": {}}, + "amount": 123456789012345678, + "uint64_max_plus_one": 18446744073709551616, + "int64_min_minus_one": -9223372036854775809, + "negative_float": -1.8e19, +} + + +class RawResponseHandler(BaseHTTPRequestHandler): + """Answers the requests with crafted raw response bodies, and delays the ones of the slow + method. A stand-in for a real rpc server in the raw response tests only: the connection + under test is the real one, the peer is not. + """ + + protocol_version = "HTTP/1.1" + + def do_POST(self) -> None: + """Answer a request with the crafted body of its method.""" + length: int = int(self.headers.get("Content-Length", "0")) + request: dict[str, Any] = json.loads(self.rfile.read(length) or b"{}") + method: str = str(request.get("method", "")) + if self.path == "/json_rpc": + if method == "crafted_error_method": + response: dict[str, Any] = {"jsonrpc": "2.0", "id": "0", "error": {"code": -32601, "message": "Method not found"}} + elif method == "empty_message_error_method": + response = {"jsonrpc": "2.0", "id": "0", "error": {"code": -2, "message": ""}} + elif method == "code_only_error_method": + response = {"jsonrpc": "2.0", "id": "0", "error": {"code": -2}} + elif method == "slow_method": + time.sleep(0.5) + response = {"jsonrpc": "2.0", "id": "0", "result": {"status": "OK"}} + else: + response = {"jsonrpc": "2.0", "id": "0", "result": RAW_RESPONSE_TYPES} + else: + # a path request: the whole body is the response + response = RAW_RESPONSE_TYPES + body: bytes = json.dumps(response).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, format: str, *args: Any) -> None: + pass + + +class RawResponseServer(ThreadingHTTPServer): + """A rpc server that answers with the crafted raw response bodies. Use it as a context + manager. + """ + + def __init__(self) -> None: + """Initialize a new RawResponseServer on an ephemeral port.""" + super().__init__(("127.0.0.1", 0), RawResponseHandler) + self._thread: threading.Thread = threading.Thread(target=self.serve_forever, daemon=True) + + @property + def uri(self) -> str: + """Uri of the server. + + :returns str: uri to give to the rpc connection. + """ + return f"http://127.0.0.1:{self.server_address[1]}" + + def __enter__(self) -> "RawResponseServer": + self._thread.start() + return self + + def __exit__(self, *args: Any) -> None: + self.shutdown() + self.server_close() + self._thread.join(timeout=5) + @pytest.mark.integration class TestMoneroRpcConnection(BaseTestClass): @@ -271,6 +360,92 @@ def test_send_path_request(self, node_connection: MoneroRpcConnection) -> None: node_connection.send_path_request("invalid_method") assert exc_info.value.code == 404 + # Can send json requests that keep the types of the raw response + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_send_json_request_preserves_response_types(self) -> None: + with RawResponseServer() as server: + connection: MoneroRpcConnection = MoneroRpcConnection(server.uri) + result: object = connection.send_json_request("get_info") + self._test_raw_response_types(result) + + # Can send path requests that keep the types of the raw response + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_send_path_request_preserves_response_types(self) -> None: + with RawResponseServer() as server: + connection: MoneroRpcConnection = MoneroRpcConnection(server.uri) + result: object = connection.send_path_request("get_info") + self._test_raw_response_types(result) + + # Can keep the empty string of a live response, which is not retyped by the raw path + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_send_json_request_preserves_the_empty_string_of_a_live_response(self, node_connection: MoneroRpcConnection) -> None: + RpcConnectionUtils.setup_rpc_connection(node_connection) + result: object = node_connection.send_json_request("get_info") + assert isinstance(result, dict) + + # the top hash of the regtest chain tip is a real empty string + top_hash: object = result["top_hash"] + assert top_hash == "" + assert isinstance(top_hash, str) + + # Can raise the error response of a raw json request with the code and message of the property tree walk + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_send_json_request_raises_the_error_response(self) -> None: + with RawResponseServer() as server: + connection: MoneroRpcConnection = MoneroRpcConnection(server.uri) + + # test the error with a code and a message + with pytest.raises(MoneroRpcError) as exc_info: + connection.send_json_request("crafted_error_method") + assert str(exc_info.value) == "Method not found" + assert exc_info.value.code == -32601 + + # test the error with an empty message, which carries a generic one + with pytest.raises(MoneroRpcError) as exc_info: + connection.send_json_request("empty_message_error_method") + assert str(exc_info.value) == "Received error response from RPC request with method 'empty_message_error_method' to /json_rpc" + assert exc_info.value.code == -2 + + # test the error with a code only, which carries an unknown message + with pytest.raises(MoneroRpcError) as exc_info: + connection.send_json_request("code_only_error_method") + assert str(exc_info.value) == "Unknown error" + assert exc_info.value.code == -2 + + # Can apply the timeout of a raw json request to the request itself + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_send_json_request_times_out(self) -> None: + with RawResponseServer() as server: + connection: MoneroRpcConnection = MoneroRpcConnection(server.uri) + + # a request that outlives its timeout raises the network error + with pytest.raises(RuntimeError, match=r"Network error: no response from .* \(timeout: 100ms\)"): + connection.send_json_request("slow_method", timeout_ms=100) + + # the same request completes under a longer timeout + result: object = connection.send_json_request("slow_method", timeout_ms=Utils.AUTO_CONNECT_TIMEOUT_MS * 5) + assert result is not None + + # Test the types of a raw response that a property tree walk cannot represent + def _test_raw_response_types(self, result: object) -> None: + assert result == RAW_RESPONSE_TYPES + + # the empty containers keep their own types instead of collapsing to an empty string + assert isinstance(result, dict) + assert isinstance(result["empty_object"], dict) + assert isinstance(result["empty_array"], list) + assert isinstance(result["empty_string"], str) + assert isinstance(result["nested"]["list"], list) + assert isinstance(result["nested"]["dict"], dict) + + # the numbers beyond the 64 bit ranges keep their exact value instead of a lossy float + assert isinstance(result["uint64_max_plus_one"], int) + assert result["uint64_max_plus_one"] == 18446744073709551616 + assert isinstance(result["int64_min_minus_one"], int) + assert result["int64_min_minus_one"] == -9223372036854775809 + assert isinstance(result["negative_float"], float) + assert result["negative_float"] == -1.8e19 + #endregion diff --git a/tests/wallet/test_keys_and_addresses.py b/tests/wallet/test_keys_and_addresses.py index 6639085..0664b1f 100644 --- a/tests/wallet/test_keys_and_addresses.py +++ b/tests/wallet/test_keys_and_addresses.py @@ -498,3 +498,24 @@ def test_verify_message_wrong_decoded_size(self) -> None: WalletUtils.test_message_signature_result(result, False) finally: w.close() + + # A python override of import_multisig_hex receives the caller's refresh flag in every call form + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_import_multisig_hex_forwards_refresh_after_import(self) -> None: + forwarded: list[bool] = [] + + class MultisigWallet(MoneroWallet): + def import_multisig_hex(self, multisig_hexes: list[str], refresh_after_import: bool = True) -> int: + forwarded.append(refresh_after_import) + return 42 + + wallet: MoneroWallet = MultisigWallet() + + # calling through the binding dispatches to the python override over the trampoline + assert MoneroWallet.import_multisig_hex(wallet, ["ab"], False) == 42 + assert MoneroWallet.import_multisig_hex(wallet, ["cd"], True) == 42 + assert MoneroWallet.import_multisig_hex(wallet, ["ef"]) == 42 + assert MoneroWallet.import_multisig_hex(wallet, multisig_hexes=["gh"], refresh_after_import=False) == 42 + + # the caller's value is forwarded in the positional, keyword, and omitted forms + assert forwarded == [False, True, True, False]