Skip to content
Merged
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
3 changes: 2 additions & 1 deletion docs/mkdocs/docs/en/api/connection.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ A [`MoneroRpcConnection`][monero.MoneroRpcConnection] is how a daemon or a walle
[`is_online`][monero.MoneroRpcConnection.is_online], [`is_authenticated`][monero.MoneroRpcConnection.is_authenticated] and
[`response_time`][monero.MoneroRpcConnection.response_time] tell how it went. A method of the RPC that the library does not wrap is
called with [`send_json_request`][monero.MoneroRpcConnection.send_json_request], or `send_path_request` and `send_binary_request` for the
other interfaces of the daemon ([Connect to RPC Server](../examples/basics/connect_to_rpc_server.md)).
other interfaces of the daemon ([Connect to RPC Server](../examples/basics/connect_to_rpc_server.md)). Their response is parsed as Python's
`json` module parses it, and they run without the GIL: threads with a connection each send their requests at once.

::: monero.MoneroRpcConnection
1 change: 1 addition & 0 deletions docs/mkdocs/docs/en/tests/writing/helpers.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ title: Helpers
| `SingleTxSender`, `ToMultipleTxSender`, `FromMultipleTxSender`, `WalletSweeper` | send or sweep funds in a test, and check the result |
| `WalletNotificationsTester`, `WalletSyncTester`, `SyncSeedTester`, `MultisigSampleCodeTester`... | the scenarios that several tests share |
| `FakeDaemonRpcServer`, `FakeWalletRpcServer` | local rpc servers that answer with a new block or height at each request: the unit tests of the listeners and of the tx tracker run on them, with no network |
| `FakeRawRpcServer` | a local rpc server that answers each path with the raw body that the test sets, and keeps the requests: the unit tests of the requests of `MoneroRpcConnection` run on it |
| `WalletCall`, `WALLET_CALLS` | a call of each method of the wallet interface |

The data of a test (addresses, keys, seeds) goes in `tests/config`, in an `.ini` of its own or in the one of its topic.
Expand Down
108 changes: 63 additions & 45 deletions src/cpp/common/py_monero_common.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -65,68 +65,86 @@ 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 (...) {}

try {
std::size_t pos;
double d = std::stod(val, &pos);
if (pos == val.size()) return py::float_(d);
} catch (...) {}

return py::str(val);
// the message of an error response, as monero-cpp reads it from a property tree: the text of the value, or a message that names the
// request when it has no text
static std::string get_rpc_error_message(const py::handle& message, const std::string& method, const std::string& uri) {
std::string text;
if (py::isinstance<py::str>(message)) text = message.cast<std::string>();
else if (py::isinstance<py::bool_>(message)) text = message.cast<bool>() ? "true" : "false";
else if (py::isinstance<py::int_>(message) || py::isinstance<py::float_>(message)) text = py::str(message).cast<std::string>();
else if (message.is_none()) text = "null";
if (text.empty()) text = "Received error response from RPC request with method '" + method + "' to " + uri;
return text;
}

py::object PyGenUtils::ptree_to_pyobject(const boost::property_tree::ptree& tree) {
if (tree.empty()) {
return convert_value(tree.get_value<std::string>());
// the code of an error response, as monero-cpp reads it from a property tree: an integer, or -1
static int get_rpc_error_code(const py::handle& code) {
if (py::isinstance<py::bool_>(code)) return -1;
if (py::isinstance<py::int_>(code)) {
try {
return code.cast<int>();
} catch (...) {
return -1;
}
}
if (py::isinstance<py::str>(code)) {
std::string text = code.cast<std::string>();
try {
std::size_t pos;
int value = std::stoi(text, &pos);
if (pos == text.size()) return value;
} catch (...) {}
}
return -1;
}

bool is_array = true;
for (const auto& child : tree) {
if (child.first != "") {
is_array = false;
break;
}
py::object PyGenUtils::parse_rpc_response(const std::string& body, const std::string& method, const std::string& uri, bool json_rpc) {

// parse the body
py::object response;
try {
response = py::module_::import("json").attr("loads")(py::bytes(body));
} catch (py::error_already_set& e) {
if (!e.matches(PyExc_ValueError)) throw;
throw monero_error("Invalid JSON");
}

if (is_array) {
py::list lst;
for (const auto& child : tree) {
lst.append(ptree_to_pyobject(child.second));
// a response that is not an object has no result
if (!py::isinstance<py::dict>(response)) return json_rpc ? py::none() : response;
py::dict response_dict = response;

// raise an error response
if (response_dict.contains("error")) {
std::string message = "Unknown error";
int code = -1;
py::object error = response_dict["error"];
if (py::isinstance<py::dict>(error)) {
py::dict error_dict = error;
if (error_dict.contains("message")) message = get_rpc_error_message(error_dict["message"], method, uri);
if (error_dict.contains("code")) code = get_rpc_error_code(error_dict["code"]);
}
return lst;
throw monero_rpc_error(code, message);
}
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;
}
// return the result of a JSON-RPC response, or the whole response of a path request unless it is a JSON-RPC one, as monero-cpp does
if (json_rpc) return response_dict.contains("result") ? py::object(response_dict["result"]) : py::none();
return response_dict.contains("jsonrpc") ? py::none() : response;
}

// --------------------------- MONERO REQUEST PARAMS ---------------------------

PyMoneroRequestParams::PyMoneroRequestParams(const boost::optional<py::object>& py_params) {
if (py_params == boost::none || py_params->is_none()) return;
m_json = py::module_::import("json").attr("dumps")(py_params.get()).cast<std::string>();
}

rapidjson::Value PyMoneroRequestParams::to_rapidjson_val(rapidjson::Document::AllocatorType& allocator) const {
rapidjson::Value root(rapidjson::kObjectType);
if (m_py_params == boost::none) return root;
if (m_json == boost::none) return root;

// convert python dict params to rapidjson::Value
std::string json = PyGenUtils::serialize(m_py_params.get());
// parse the params that the constructor serialized
rapidjson::Document doc;
doc.Parse(json.c_str());
doc.Parse(m_json->c_str());
root.CopyFrom(doc, allocator);

return root;
Expand Down
23 changes: 19 additions & 4 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,16 +112,30 @@ 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 the raw body of a RPC response with python's json, which keeps the empty objects and arrays, the empty strings, null and
* the exact value of the integers, that a property tree loses. An error response raises as monero-cpp raises it.
*
* @param body is the raw body of the response
* @param method is the method of the request
* @param uri is the url path of the request
* @param json_rpc indicates if the request is a JSON-RPC one, which returns the result of the response
* @return the result of a JSON-RPC response, or the whole response of a path request
*/
static py::object parse_rpc_response(const std::string& body, const std::string& method, const std::string& uri, bool json_rpc);
};

/**
* Parameters of a RPC request, given from python. They are serialized to json when the request is built, with the GIL held, so that
* sending the request needs no python and runs without it.
*/
struct PyMoneroRequestParams : public monero_request_params {
public:
boost::optional<py::object> m_py_params;
boost::optional<std::string> m_json;

PyMoneroRequestParams() { }
PyMoneroRequestParams(const boost::optional<py::object>& py_params): m_py_params(py_params) { }
PyMoneroRequestParams(const boost::optional<py::object>& py_params);

rapidjson::Value to_rapidjson_val(rapidjson::Document::AllocatorType& allocator) const override;
};
30 changes: 21 additions & 9 deletions src/cpp/common/py_monero_common_bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -327,23 +327,35 @@ void py_monero_bind_common(py::module_& m, PyMoneroTypes& t) {
.def("check_connection", [](monero_rpc_connection& self, const boost::optional<uint32_t>& timeout_ms) {
MONERO_CATCH_AND_RETHROW(self.check_connection(timeout_ms));
}, py::arg("timeout_ms") = py::none(), py::call_guard<py::gil_scoped_release>())
// the parameters are serialized with the GIL held, then the request runs without it, so that the requests of other threads and a
// server in this process run meanwhile. The JSON responses are parsed from their raw body with python's json
.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;
{
py::gil_scoped_release release;
body = self.invoke_post("/json_rpc", request.serialize(), timeout_ms);
}
return PyGenUtils::parse_rpc_response(body, method, "/json_rpc", 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 uri = "/" + method;
std::string body;
{
py::gil_scoped_release release;
body = self.invoke_post(uri, request.serialize(), timeout_ms);
}
return PyGenUtils::parse_rpc_response(body, method, uri, 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);
auto response = self.send_binary_request(request, timeout_ms);
monero_rpc_response response;
{
py::gil_scoped_release release;
response = self.send_binary_request(request, timeout_ms);
}
boost::optional<py::bytes> result;

if (response.m_binary != boost::none && !response.m_binary->empty()) {
Expand Down
3 changes: 3 additions & 0 deletions src/cpp/daemon/py_monero_daemon_bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -574,6 +574,9 @@ void py_monero_bind_daemon(py::module_& m, PyMoneroTypes& t) {
.def_readwrite("stealth_public_key", &monero_output::m_stealth_public_key)
.def_readwrite("mask", &monero_output::m_mask)
.def_readwrite("ring_output_indices", &monero_output::m_ring_output_indices)
.def_property_readonly("is_locked", [](const monero_output& self) {
MONERO_CATCH_AND_RETHROW(self.is_locked());
})
.def("copy", [](const std::shared_ptr<monero_output>& self) {
auto tgt = std::make_shared<monero_output>();
MONERO_CATCH_AND_RETHROW(self->copy(self, tgt));
Expand Down
5 changes: 5 additions & 0 deletions src/monero/monero_output.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@ class MoneroOutput(SerializableStruct):
tx: MoneroTx | None
"""The transaction related to this output."""

@property
def is_locked(self) -> bool | None:
"""Indicates if the tx of this output is locked (`True`) or not (`False`), `None` if it is unknown."""
...

@staticmethod
def deserialize(json: str) -> MoneroOutput:
"""
Expand Down
20 changes: 14 additions & 6 deletions src/monero/monero_rpc_connection.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -158,29 +158,37 @@ class MoneroRpcConnection(SerializableStruct):
"""
Send a request to the JSON-RPC API.

The request runs without the GIL, so the other threads run meanwhile: the requests of different connections run at once, the
ones of a connection one at a time. The response is parsed as Python's `json` module parses it, so an object is a `dict`, an
array a `list`, `null` is `None`, and an integer keeps its exact value.

:param str method: is the method to request.
:param Optional[object] parameters: are the request's input parameters (default `None`).
:param Optional[object] parameters: are the request's input parameters, anything that `json.dumps()` serializes (default `None`).
:param Optional[int] timeout_ms: request timeout in milliseconds.
:returns object | None: the RPC API response as a map.
:returns object | None: the result of the response, `None` if it has none.
:raises MoneroRpcError: if the response is an error, with its code and message.
:raises MoneroError: if the server does not answer, or the response is not valid JSON.
"""
...

def send_path_request(self, method: str, parameters: object | None = None, timeout_ms: int | None = None) -> object | None:
"""
Send a RPC request to the given path and with the given parameters.

E.g. `/get_transactions` with params.
E.g. `/get_transactions` with params. It runs without the GIL and parses the response as `send_json_request()` does.

: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[object] parameters: are request parameters sent in the body, anything that `json.dumps()` serializes.
:param Optional[int] timeout_ms: request timeout in milliseconds.
:returns object | None: the request's deserialized response.
:returns object | None: the response, `None` if it is a JSON-RPC one.
:raises MoneroRpcError: if the response is an error, with its code and message.
:raises MoneroError: if the server does not answer, or the response is not valid JSON.
"""
...

def send_binary_request(self, method: str, parameters: object | None = None, timeout_ms: int | None = None) -> bytes | None:
"""
Send a binary RPC request.
Send a binary RPC request. It runs without the GIL, as `send_json_request()` does.

:param str method: is the path of the binary RPC method to invoke.
:param Optional[object] parameters: are the request parameters (default `None`).
Expand Down
7 changes: 4 additions & 3 deletions src/monero/monero_wallet_rpc.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@ class MoneroWalletRpc(MoneroWallet):
"""
Implements a Monero wallet using `monero-wallet-rpc`_.

Note: the listeners are notified by polling the server every sync period. The outputs of the txs in the pool are not notified
yet: the outputs spent and received by a tx are notified when it is confirmed and when it unlocks. The balance notifications
include the txs in the pool.
Note: the listeners are notified by polling the server every sync period. The outputs of a tx are notified when it is in the
pool, when it is confirmed and when it unlocks. monero-wallet-rpc does not return the inputs of a tx, nor the outputs of a tx in
the pool: the spent outputs are notified as one input with the outgoing amount and the fee, and the outputs received by a tx in
the pool as one output for each incoming transfer. The balance notifications include the txs in the pool.

.. _monero-wallet-rpc: https://docs.getmonero.org/rpc-library/wallet-rpc/
"""
Expand Down
Loading
Loading