Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .gitmodules
Original file line number Diff line number Diff line change
@@ -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
63 changes: 15 additions & 48 deletions src/cpp/common/py_monero_common.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -65,56 +65,23 @@ py::dict PyGenUtils::deserialize(const std::string& s) {
return fn(s).cast<py::dict>();
}

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<std::string>());
}

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<std::string>().empty()) {
d["__value__"] = convert_value(tree.get_value<std::string>());
}
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<py::dict>(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 ---------------------------
Expand Down
14 changes: 12 additions & 2 deletions src/cpp/common/py_monero_common.h
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
#include <pybind11/stl.h>
#include <boost/optional.hpp>

#include "common/monero_error.h"
#include "common/monero_rpc_connection.h"
#include "daemon/monero_daemon_model.h"

Expand Down Expand Up @@ -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 {
Expand All @@ -124,3 +133,4 @@ struct PyMoneroRequestParams : public monero_request_params {

rapidjson::Value to_rapidjson_val(rapidjson::Document::AllocatorType& allocator) const override;
};

36 changes: 28 additions & 8 deletions src/cpp/common/py_monero_common_bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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) {

Expand Down Expand Up @@ -329,17 +330,36 @@ void py_monero_bind_common(py::module_& m, PyMoneroTypes& t) {
}, py::arg("timeout_ms") = py::none(), py::call_guard<py::gil_scoped_release>())
.def("send_json_request", [](monero_rpc_connection& self, const std::string &method, const boost::optional<py::object>& parameters, const boost::optional<uint32_t>& timeout_ms) {
monero_rpc_request request(method, std::make_shared<PyMoneroRequestParams>(parameters));
auto response = self.send_json_request(request, timeout_ms);
boost::optional<py::object> 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<boost::property_tree::ptree&> 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<py::object>& parameters, const boost::optional<uint32_t>& timeout_ms) {
if (method.empty()) throw monero_error("No RPC method set in path request");
monero_rpc_request request(method, std::make_shared<PyMoneroRequestParams>(parameters), false);
auto response = self.send_path_request(request, timeout_ms);
boost::optional<py::object> 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<boost::property_tree::ptree&> 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<py::object>& parameters, const boost::optional<uint32_t>& timeout_ms) {
monero_rpc_request request(method, std::make_shared<PyMoneroRequestParams>(parameters), false);
Expand Down
7 changes: 1 addition & 6 deletions src/cpp/wallet/py_monero_wallet_bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<py::gil_scoped_release>())
.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<py::gil_scoped_release>())
.def("get_tx_key", [](PyMoneroWallet& self, const std::string& tx_hash) {
MONERO_CATCH_AND_RETHROW(self.get_tx_key(tx_hash));
Expand Down
21 changes: 17 additions & 4 deletions src/monero/monero_rpc_connection.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -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.
"""
...
Expand Down Expand Up @@ -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.
"""
...
Expand All @@ -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.
"""
...
Expand All @@ -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.
"""
...
Expand Down
Loading
Loading