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
24 changes: 24 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,28 @@ message(STATUS "Using HIDAPI include dir at ${HIDAPI_INCLUDE_DIR}")
find_library(SODIUM_LIBRARY sodium REQUIRED)
message(STATUS "Using libsodium library at ${SODIUM_LIBRARY}")

############
# libzmq
############

# link before libsodium, which static libzmq depends on
find_library(ZMQ_LIBRARY zmq REQUIRED)
set(ZMQ_LIBRARIES ${ZMQ_LIBRARY})
if (ZMQ_LIBRARY MATCHES "\\.a$")
# optional transports of static libzmq
foreach(zmq_dep pgm norm gssapi_krb5 protolib protokit bsd md)
string(TOUPPER ${zmq_dep} zmq_dep_var)
find_library(ZMQ_DEP_${zmq_dep_var} ${zmq_dep})
if (ZMQ_DEP_${zmq_dep_var})
list(APPEND ZMQ_LIBRARIES ${ZMQ_DEP_${zmq_dep_var}})
endif()
endforeach()
endif()
if (WIN32)
list(APPEND ZMQ_LIBRARIES ws2_32 rpcrt4 iphlpapi)
endif()
message(STATUS "Using libzmq libraries: ${ZMQ_LIBRARIES}")

############
# Protobuf
############
Expand Down Expand Up @@ -403,6 +425,8 @@ set(MONERO_PYTHON_LINK_LIBS
${Boost_LIBRARIES}
${OPENSSL_LIBRARIES}
${Protobuf_LIBRARY}
# before libsodium, which static libzmq depends on
${ZMQ_LIBRARIES}
${SODIUM_LIBRARY}
# after hidapi, which uses it: with --as-needed the linker keeps a shared library only for what comes before it
${HIDAPI_LIBRARIES}
Expand Down
37 changes: 37 additions & 0 deletions docs/mkdocs/docs/en/api/connection.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ A [`MoneroRpcConnection`][monero.MoneroRpcConnection] is how a daemon or a walle
| `uri` | the address of the server, `http://host:port` or `https://...` |
| `username`, `password` | the login of its RPC, `--rpc-login` of the server ([`set_credentials`][monero.MoneroRpcConnection.set_credentials]) |
| `proxy_uri` | a proxy for the requests, as the SOCKS of Tor to reach an onion address |
| `zmq_uri` | the ZMQ publisher of a daemon, `--zmq-pub` of `monerod`, as `tcp://127.0.0.1:18083`: [ZMQ](#zmq) |
| `timeout_ms` | how long a request waits for the answer: 3 minutes when not set |
| `ssl_verify` | whether the certificate of an `https` server is checked |

Expand All @@ -20,4 +21,40 @@ called with [`send_json_request`][monero.MoneroRpcConnection.send_json_request],
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.

## ZMQ

A `monerod` that runs with `--zmq-pub` publishes what happens on its chain and in its pool over ZMQ: a block added to the chain, a
transaction that enters the pool. It is the `zmq_uri` of the connection, which is not the one of `--zmq-rpc-bind-port`, and
[`subscribe_zmq`][monero.MoneroRpcConnection.subscribe_zmq] connects to it and returns a
[`MoneroZmqSubscriber`][monero.MoneroZmqSubscriber], which gives the [`MoneroZmqPublication`][monero.MoneroZmqPublication] of the topics that
it was asked for. The `json` of a publication is the text that the daemon published:

```python
import json

from monero import MoneroRpcConnection

connection = MoneroRpcConnection("http://localhost:18081", zmq_uri="tcp://127.0.0.1:18083")
subscriber = connection.subscribe_zmq(["json-minimal-chain_main"])

publication = subscriber.wait_for_publication(10000)
if publication is not None:
print(publication.topic, json.loads(publication.json))
```

- [`wait_for_publication`][monero.MoneroZmqSubscriber.wait_for_publication] waits as long as it is told for the next publication, and gives
`None` if there is none by then. It runs without the GIL, as the requests do.
[`discard_publications`][monero.MoneroZmqSubscriber.discard_publications] drops those that are waiting, for a program that only cares for
what happens next.
- ZMQ matches a topic by its start: `json-minimal` takes all the publications of the minimal JSON, and `json-minimal-chain_main` only the
ones of the blocks that are added to the main chain.
- The subscriber connects in the background, and again every second if it loses the daemon: `subscribe_zmq` does not fail because the
daemon is not there. A publication that the daemon makes while the subscriber is not connected is lost, and ZMQ does not send it again: a
program that can not miss a block reads the chain from the daemon too.
- A subscriber is used by one thread at a time.
- `subscribe_zmq` raises a [`MoneroError`][monero.MoneroError] if the connection has no `zmq_uri`, and if it has a `proxy_uri`: ZMQ connects
directly, and would skip the proxy.

A [`MoneroDaemonRpc`][monero.MoneroDaemonRpc] uses it to learn of the new blocks sooner: [Daemon RPC](daemon_rpc.md#zmq).

::: monero.MoneroRpcConnection
18 changes: 18 additions & 0 deletions docs/mkdocs/docs/en/api/daemon_rpc.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,22 @@ The client of the RPC of a `monerod` ([Interact with RPC Daemon](../examples/bas
of the daemon and its credentials, or with a [`MoneroRpcConnection`][monero.MoneroRpcConnection], and polls the daemon for its
[listeners](../examples/basics/listening_to_a_wallet.md#a-daemon).

## ZMQ

A daemon is polled every [`set_poll_period_in_ms`][monero.MoneroDaemonRpc.set_poll_period_in_ms], 10 seconds when it is not set, to tell its
listeners of a new block, which may then be one period late. If its connection has a `zmq_uri`, the `--zmq-pub` of the `monerod`
([ZMQ](connection.md#zmq)), the daemon is polled also each time the `monerod` publishes a block, and the listeners are told as it is added:

```python
from monero import MoneroDaemonRpc

daemon = MoneroDaemonRpc("http://localhost:18081", zmq_uri="tcp://127.0.0.1:18083")
```

The period still holds: ZMQ does not guarantee that a publication arrives, so the daemon is polled every period whether the `monerod`
publishes or not, and a block that it did not publish is told at most a period late. The daemon is polled by the period alone when the
connection has no `zmq_uri`, when it has a `proxy_uri` (ZMQ connects directly, and would skip it), and when the subscription fails, which is
logged. The `zmq_uri` and the `proxy_uri` are read at each poll, so a connection that changes them while the daemon is listened to is
followed.

::: monero.MoneroDaemonRpc
6 changes: 6 additions & 0 deletions docs/mkdocs/docs/en/api/data_model/connection.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,13 @@ The classes around a [`MoneroRpcConnection`][monero.MoneroRpcConnection], the co
| --- | --- |
| [`SslOptions`][monero.SslOptions] | the SSL of a connection: the certificates, and how the one of the server is checked; passed to [`MoneroWalletRpc.set_daemon_connection`][monero.MoneroWalletRpc.set_daemon_connection] |
| [`MoneroConnectionType`][monero.MoneroConnectionType] | how a peer of a daemon is connected, IPv4, IPv6, Tor or I2P: the `connection_type` of a [`MoneroPeer`][monero.MoneroPeer] |
| [`MoneroZmqSubscriber`][monero.MoneroZmqSubscriber] | what [`subscribe_zmq`][monero.MoneroRpcConnection.subscribe_zmq] returns: it waits for the publications of the ZMQ publisher of a daemon ([ZMQ](../connection.md#zmq)) |
| [`MoneroZmqPublication`][monero.MoneroZmqPublication] | a publication of a daemon: its `topic` and its `json`, which a [`MoneroZmqSubscriber`][monero.MoneroZmqSubscriber] gives |

::: monero.SslOptions

::: monero.MoneroConnectionType

::: monero.MoneroZmqSubscriber

::: monero.MoneroZmqPublication
3 changes: 3 additions & 0 deletions docs/mkdocs/docs/en/examples/basics/listening_to_a_wallet.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,4 +111,7 @@ daemon = MoneroDaemonRpc("http://localhost:38081")
daemon.add_listener(NewBlocks())
```

The daemon is polled every few seconds. Given the `zmq_uri` of a `monerod` that runs with `--zmq-pub`, it is also polled when the `monerod`
publishes a block, and the listener is told as it is added: [ZMQ](../../api/daemon_rpc.md#zmq).

A shop that watches the payments of its orders uses them: [Accepting Payments in a Shop](../scenarios/accepting_payments.md).
18 changes: 18 additions & 0 deletions src/cpp/common/py_monero_common_bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,21 @@ void py_monero_bind_common(py::module_& m, PyMoneroTypes& t) {
.def_readwrite("ssl_allowed_fingerprints", &ssl_options::m_ssl_allowed_fingerprints)
.def_readwrite("ssl_allow_any_cert", &ssl_options::m_ssl_allow_any_cert);

// monero_zmq_publication
t.py_monero_zmq_publication
.def(py::init<>())
.def_readwrite("topic", &monero_zmq_publication::m_topic)
.def_readwrite("json", &monero_zmq_publication::m_json);

// monero_zmq_subscriber
t.py_monero_zmq_subscriber
.def("wait_for_publication", [](monero_zmq_subscriber& self, int timeout_ms) {
MONERO_CATCH_AND_RETHROW(self.wait_for_publication(timeout_ms));
}, py::arg("timeout_ms"), py::call_guard<py::gil_scoped_release>())
.def("discard_publications", [](monero_zmq_subscriber& self) {
MONERO_CATCH_AND_RETHROW(self.discard_publications());
}, py::call_guard<py::gil_scoped_release>());

// monero_rpc_connection
t.py_monero_rpc_connection
.def(py::init<const std::string&, const std::string&, const::std::string&, const std::string&, const std::string&, int, const boost::optional<uint32_t>&>(), py::arg("uri") = "", py::arg("username") = "", py::arg("password") = "", py::arg("proxy_uri") = "", py::arg("zmq_uri") = "", py::arg("priority") = 0, py::arg("timeout_ms") = py::none())
Expand Down Expand Up @@ -344,6 +359,9 @@ 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>())
.def("subscribe_zmq", [](const monero_rpc_connection& self, const std::vector<std::string>& topics) {
MONERO_CATCH_AND_RETHROW(std::shared_ptr<monero_zmq_subscriber>(self.subscribe_zmq(topics)));
}, py::arg("topics"), 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) {
Expand Down
4 changes: 4 additions & 0 deletions src/cpp/py_monero_types.h
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,8 @@ struct PyMoneroTypes {
py::class_<monero_rpc_payment_info, serializable_struct, std::shared_ptr<monero_rpc_payment_info>> py_monero_rpc_payment_info;
py::class_<monero_rpc_connection, serializable_struct, std::shared_ptr<monero_rpc_connection>> py_monero_rpc_connection;

py::class_<monero_zmq_publication, std::shared_ptr<monero_zmq_publication>> py_monero_zmq_publication;
py::class_<monero_zmq_subscriber, std::shared_ptr<monero_zmq_subscriber>> py_monero_zmq_subscriber;
py::class_<ssl_options, serializable_struct, std::shared_ptr<ssl_options>> py_monero_ssl_options;
py::class_<monero_version, serializable_struct, std::shared_ptr<monero_version>> py_monero_version;
py::class_<monero_block_header, serializable_struct, std::shared_ptr<monero_block_header>> py_monero_block_header;
Expand Down Expand Up @@ -188,6 +190,8 @@ struct PyMoneroTypes {
py_serializable_struct(m, "SerializableStruct"),
py_monero_rpc_payment_info(m, "MoneroRpcPaymentInfo"),
py_monero_rpc_connection(m, "MoneroRpcConnection"),
py_monero_zmq_publication(m, "MoneroZmqPublication"),
py_monero_zmq_subscriber(m, "MoneroZmqSubscriber"),
py_monero_ssl_options(m, "SslOptions"),
py_monero_version(m, "MoneroVersion"),
py_monero_block_header(m, "MoneroBlockHeader"),
Expand Down
4 changes: 4 additions & 0 deletions src/monero/__init__.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,8 @@ from .monero_peer import MoneroPeer
from .monero_prune_result import MoneroPruneResult
from .monero_rpc_connection import MoneroRpcConnection
from .monero_rpc_error import MoneroRpcError
from .monero_zmq_publication import MoneroZmqPublication
from .monero_zmq_subscriber import MoneroZmqSubscriber
from .ssl_options import SslOptions
from .monero_subaddress import MoneroSubaddress
from .monero_submit_tx_result import MoneroSubmitTxResult
Expand Down Expand Up @@ -204,6 +206,8 @@ __all__ = [
'MoneroPruneResult',
'MoneroRpcConnection',
'MoneroRpcError',
'MoneroZmqPublication',
'MoneroZmqSubscriber',
'MoneroSubaddress',
'MoneroSubmitTxResult',
'MoneroSyncResult',
Expand Down
4 changes: 3 additions & 1 deletion src/monero/monero_daemon_rpc.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ class MoneroDaemonRpc(MoneroDaemon):
:param str username: Authentication username for daemon RPC.
:param str password: Authentication password for daemon RPC.
:param str proxy_uri: Connection proxy.
:param str zmq_uri: RPC ZMQ uri.
:param str zmq_uri: uri of the ZMQ publisher of the daemon (`--zmq-pub` of `monerod`), which makes the daemon poll when a block is published.
:param int timeout_ms: Connection timeout in milliseconds (default 3 minutes).
"""
...
Expand All @@ -50,6 +50,8 @@ class MoneroDaemonRpc(MoneroDaemon):
"""
Set the period between polls of the daemon for block notifications.

With a ZMQ uri the daemon is also polled when `monerod` publishes a block, and a block that it did not publish is notified at most a period late.

:param int period_ms: the poll period in milliseconds.
"""
...
Expand Down
15 changes: 13 additions & 2 deletions src/monero/monero_rpc_connection.pyi
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import typing

from .monero_zmq_subscriber import MoneroZmqSubscriber
from .serializable_struct import SerializableStruct


Expand All @@ -11,7 +12,7 @@ class MoneroRpcConnection(SerializableStruct):
proxy_uri: str | None
"""Connection proxy address."""
zmq_uri: str | None
"""ZMQ connection uri."""
"""Uri of the ZMQ publisher of the daemon, `--zmq-pub` of `monerod`, e.g. `tcp://127.0.0.1:18083`."""
timeout_ms: int | None
"""Connection timeout (milliseconds): `None` waits the default of 3 minutes."""
ssl_verify: bool
Expand Down Expand Up @@ -95,7 +96,7 @@ class MoneroRpcConnection(SerializableStruct):
:param str username: username used for authentication.
:param str password: password used for authentication.
:param str proxy_uri: proxy uri.
:param str zmq_uri: ZMQ uri.
:param str zmq_uri: uri of the ZMQ publisher of the daemon (`--zmq-pub` of `monerod`).
:param int priority: priorioty of the connection.
:param int|None timeout_ms: connection timeout in milliseconds.
"""
Expand Down Expand Up @@ -192,6 +193,16 @@ class MoneroRpcConnection(SerializableStruct):
"""
...

def subscribe_zmq(self, topics: list[str]) -> MoneroZmqSubscriber:
"""
Subscribe to the publications of the connection's zmq uri.

:param list[str] topics: topics to receive, e.g. `json-minimal-chain_main`.
:returns MoneroZmqSubscriber: the subscriber.
:raises MoneroError: if the connection has no zmq uri, uses a proxy (zmq would connect directly), or the subscription fails.
"""
...

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.
Expand Down
11 changes: 11 additions & 0 deletions src/monero/monero_zmq_publication.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
class MoneroZmqPublication:
"""Models a publication of a daemon's zmq publisher."""

topic: str
"""Publication topic."""
json: str
"""Publication content in JSON format."""

def __init__(self) -> None:
"""Initialize a new publication."""
...
23 changes: 23 additions & 0 deletions src/monero/monero_zmq_subscriber.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
from .monero_zmq_publication import MoneroZmqPublication


class MoneroZmqSubscriber:
"""
Receives the publications of a daemon's zmq publisher, can only be used by one thread at a time.

Made by `MoneroRpcConnection.subscribe_zmq()`. It connects in the background and again if it loses the daemon, and a publication
that is made while it is not connected is lost.
"""

def wait_for_publication(self, timeout_ms: int) -> MoneroZmqPublication | None:
"""
Wait for a publication.

:param int timeout_ms: the maximum time to wait.
:returns MoneroZmqPublication | None: the publication, or `None` if there is none before the timeout.
"""
...

def discard_publications(self) -> None:
"""Discard the publications which are pending."""
...
38 changes: 37 additions & 1 deletion tests/common/test_rpc_connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from time import monotonic
from typing import Any, Callable

from monero import MoneroRpcConnection, MoneroConnectionType, MoneroError, MoneroRpcError, MoneroUtils
from monero import MoneroRpcConnection, MoneroConnectionType, MoneroError, MoneroRpcError, MoneroUtils, MoneroZmqPublication, MoneroZmqSubscriber
from utils import (
TestUtils as Utils, RpcConnectionUtils,
StringUtils, BaseTestClass, FakeRawRpcServer
Expand Down Expand Up @@ -162,6 +162,42 @@ def test_node_rpc_connection(self, node_connection: MoneroRpcConnection) -> None
def test_wallet_rpc_connection(self, wallet_connection: MoneroRpcConnection) -> None:
RpcConnectionUtils.test_rpc_connection(wallet_connection, Utils.WALLET_RPC_URI, True, MoneroConnectionType.IPV4)

# Can subscribe to the zmq publisher of the daemon
@pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled")
@pytest.mark.skipif(not Utils.DAEMON_RPC_ZMQ_PUB_URI, reason="daemon ZMQ publisher is not configured")
def test_subscribe_zmq(self) -> None:
connection: MoneroRpcConnection = MoneroRpcConnection(
Utils.DAEMON_RPC_URI,
Utils.DAEMON_RPC_USERNAME,
Utils.DAEMON_RPC_PASSWORD,
zmq_uri=Utils.DAEMON_RPC_ZMQ_PUB_URI
)
subscriber: MoneroZmqSubscriber = connection.subscribe_zmq(["json-minimal-chain_main"])

# a publication is only there when a block was added meanwhile, and it is of the topic that was subscribed to
publication: MoneroZmqPublication | None = subscriber.wait_for_publication(100)
if publication is not None:
assert publication.topic == "json-minimal-chain_main"
assert publication.json

subscriber.discard_publications()

# Cannot subscribe to zmq without a zmq uri
@pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled")
def test_subscribe_zmq_without_zmq_uri(self) -> None:
connection: MoneroRpcConnection = MoneroRpcConnection("http://127.0.0.1:18081")
with pytest.raises(MoneroError, match="no zmq uri"):
connection.subscribe_zmq(["json-minimal-chain_main"])

# Cannot subscribe to zmq through a proxy, zmq would connect directly
@pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled")
def test_subscribe_zmq_through_proxy(self) -> None:
connection: MoneroRpcConnection = MoneroRpcConnection(
"http://127.0.0.1:18081", proxy_uri="127.0.0.1:9050", zmq_uri="tcp://127.0.0.1:18086"
)
with pytest.raises(MoneroError, match="proxy"):
connection.subscribe_zmq(["json-minimal-chain_main"])

# Test invalid connection
@pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled")
def test_invalid_connection(self) -> None:
Expand Down
9 changes: 7 additions & 2 deletions tests/utils/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,7 @@ def get_daemon_rpc(cls) -> MoneroDaemonRpc:
"""

if cls._DAEMON_RPC is None:
cls._DAEMON_RPC = MoneroDaemonRpc(cls.DAEMON_RPC_URI, cls.DAEMON_RPC_USERNAME, cls.DAEMON_RPC_PASSWORD)
cls._DAEMON_RPC = MoneroDaemonRpc(cls.get_daemon_rpc_connection())

return cls._DAEMON_RPC

Expand Down Expand Up @@ -331,7 +331,12 @@ def get_daemon_rpc_connection(cls) -> MoneroRpcConnection:

:returns MoneroRpcConnection: new test daemon rpc connection instance.
"""
return MoneroRpcConnection(cls.DAEMON_RPC_URI, cls.DAEMON_RPC_USERNAME, cls.DAEMON_RPC_PASSWORD)
return MoneroRpcConnection(
cls.DAEMON_RPC_URI,
cls.DAEMON_RPC_USERNAME,
cls.DAEMON_RPC_PASSWORD,
zmq_uri=cls.DAEMON_RPC_ZMQ_PUB_URI
)

@classmethod
def close_wallets(cls) -> None:
Expand Down
Loading