From ad6dec6de536d6a34a565312f6d450b3643f4faf Mon Sep 17 00:00:00 2001 From: everoddandeven Date: Wed, 2 Dec 2026 01:07:20 +0100 Subject: [PATCH 1/8] tests: add a fake rpc server that answers by method --- tests/utils/fake_method_rpc_server.py | 145 ++++++++++++++++++++++++++ 1 file changed, 145 insertions(+) create mode 100644 tests/utils/fake_method_rpc_server.py diff --git a/tests/utils/fake_method_rpc_server.py b/tests/utils/fake_method_rpc_server.py new file mode 100644 index 0000000..f23c33f --- /dev/null +++ b/tests/utils/fake_method_rpc_server.py @@ -0,0 +1,145 @@ +import json + +from time import sleep # a server that takes its time to answer needs it +from typing import Any, Optional, Sequence, cast +from typing_extensions import override + +from .fake_raw_rpc_server import FakeRawRpcHandler, FakeRawRpcServer + + +class _MethodHandler(FakeRawRpcHandler): + """Answers a request with the response that the test set for its path, and for its json rpc method if it has one.""" + + server: "FakeMethodRpcServer" # pyright: ignore[reportIncompatibleVariableOverride] + + @override + def do_POST(self) -> None: + length: int = int(self.headers.get("Content-Length", "0")) + request: bytes = self.rfile.read(length) + self.server.add_request(self.path, request) + status, data = self.server.get_method_response(self.path, request) + if self.server.response_delay > 0: + sleep(self.server.response_delay) + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(data))) + # the http client of monero keeps a connection open unless the response says "close" (see FakeRawRpcHandler) + self.send_header("Connection", "close") + self.end_headers() + self.wfile.write(data) + + +class FakeMethodRpcServer(FakeRawRpcServer): + """A rpc server for unit tests that answers each json rpc method with the result that the test sets for it, so that a call that makes + many requests (an account has its balances and its addresses, each one from a method) gets a response for each. A method can have + a sequence of results, for a server whose answers change from a request to the next. The paths that are not json rpc keep + the responses of `set_response`. + + Use it as a context manager. + """ + + def __init__(self, response_delay: float = 0.0) -> None: + """Initialize a new FakeMethodRpcServer. + + :param float response_delay: seconds that the server takes to answer a request, to have requests in flight. + """ + super().__init__(response_delay) + self.RequestHandlerClass = _MethodHandler + self._methods: dict[str, list[tuple[int, bytes]]] = {} + self._counts: dict[str, int] = {} + + @override + def __enter__(self) -> "FakeMethodRpcServer": + # FakeRawRpcServer.__enter__ is typed to return a FakeRawRpcServer, which would hide the methods of this class from a type checker + super().__enter__() + return self + + @property + def methods(self) -> list[str]: + """The json rpc methods that were requested so far, in order. + + :returns list[str]: the methods. + """ + found: list[str] = [] + for path, body in self.requests: + method: Optional[str] = self._method_of(path, body) + if method is not None: + found.append(method) + return found + + def get_params(self, method: str) -> list[Any]: + """Get the parameters of the requests of a json rpc method. + + :param str method: json rpc method. + :returns list[Any]: the `params` of each request of the method, in order. + """ + params: list[Any] = [] + for path, body in self.requests: + if self._method_of(path, body) == method: + params.append(json.loads(body).get("params")) + return params + + def set_method(self, method: str, result: object, status: int = 200) -> None: + """Set the result of a json rpc method. + + :param str method: json rpc method. + :param object result: the `result` of the response. + :param int status: http status of the response. + """ + self.set_method_sequence(method, [result], status) + + def set_method_sequence(self, method: str, results: Sequence[object], status: int = 200) -> None: + """Set the results of a json rpc method: the first request gets the first, and so on, and the last one is the result of the + requests after it. + + :param str method: json rpc method. + :param list[object] results: the `result` of each response, in order. + :param int status: http status of the responses. + """ + replies: list[tuple[int, bytes]] = [(status, json.dumps({"jsonrpc": "2.0", "id": "0", "result": result}).encode()) for result in results] + with self._lock: + self._methods[method] = replies + self._counts[method] = 0 + + def set_method_error(self, method: str, code: int, message: str) -> None: + """Set an error as the response of a json rpc method. + + :param str method: json rpc method. + :param int code: code of the error. + :param str message: message of the error. + """ + data: bytes = json.dumps({"jsonrpc": "2.0", "id": "0", "error": {"code": code, "message": message}}).encode() + with self._lock: + self._methods[method] = [(200, data)] + self._counts[method] = 0 + + def get_method_response(self, path: str, request: bytes) -> tuple[int, bytes]: + """Get the response to a request. + + :param str path: url path of the request. + :param bytes request: body of the request. + :returns tuple[int, bytes]: http status and body of the response: the one of the json rpc method that was asked, else the one of the path. + """ + method: Optional[str] = self._method_of(path, request) + if method is not None: + with self._lock: + replies: Optional[list[tuple[int, bytes]]] = self._methods.get(method) + if replies: + index: int = self._counts[method] + self._counts[method] = index + 1 + return replies[min(index, len(replies) - 1)] + return self.get_response(path) + + @staticmethod + def _method_of(path: str, request: bytes) -> Optional[str]: + """The json rpc method of a request, `None` for one that is not a json rpc one.""" + if path != "/json_rpc": + return None + try: + parsed: Any = json.loads(request) + except ValueError: + return None + if not isinstance(parsed, dict): + return None + method: Any = cast("dict[str, Any]", parsed).get("method") + return method if isinstance(method, str) else None From 3174630ef8aa65c5cd7f75d730a0a79c82ee3b97 Mon Sep 17 00:00:00 2001 From: everoddandeven Date: Wed, 2 Dec 2026 01:07:20 +0100 Subject: [PATCH 2/8] tests: test the daemon rpc client with a fake server --- tests/daemon/test_rpc_client.py | 191 ++++++++++++++++++++++++++++++++ 1 file changed, 191 insertions(+) create mode 100644 tests/daemon/test_rpc_client.py diff --git a/tests/daemon/test_rpc_client.py b/tests/daemon/test_rpc_client.py new file mode 100644 index 0000000..c107a95 --- /dev/null +++ b/tests/daemon/test_rpc_client.py @@ -0,0 +1,191 @@ +from __future__ import annotations + +import logging + +from time import monotonic, sleep +from typing import Any +from typing_extensions import override + +import pytest +from monero import MoneroBlockHeader, MoneroDaemonListener, MoneroDaemonRpc, MoneroError + +from utils import BaseTestClass, FakeDaemonRpcServer, FakeRawRpcServer + +logger: logging.Logger = logging.getLogger("TestMoneroDaemonRpcClient") + +TX_HASH: str = "a" * 64 + + +def _json_rpc(result: object) -> dict[str, Any]: + """The JSON-RPC response of a daemon with a result.""" + return {"jsonrpc": "2.0", "id": "0", "result": result} + + +class _RaisingListener(MoneroDaemonListener): + """Listener that fails each time that it is notified.""" + + def __init__(self) -> None: + super().__init__() + self.calls: int = 0 + + @override + def on_block_header(self, header: MoneroBlockHeader) -> None: + self.calls += 1 + raise RuntimeError("listener failed") + + +@pytest.mark.unit +class TestMoneroDaemonRpcClient(BaseTestClass): + """Daemon rpc client unit tests, on a local rpc server that answers with the responses that the tests set: the ones that a daemon gives + when it has nothing to report or something wrong, which the daemon of the integration tests does not.""" + + #region Tests + + # Can raise an error for a response that has no status + def test_response_without_status(self) -> None: + with FakeRawRpcServer() as server: + server.set_response("/json_rpc", _json_rpc({"count": 5})) + with pytest.raises(MoneroError) as exc_info: + MoneroDaemonRpc(server.uri).get_height() + assert str(exc_info.value) == "Could not get JSON RPC response status" + + # Can raise the error of a response to a request for txs, when it is not the one of a hash that is not valid + def test_get_txs_raises_the_error_of_the_response(self) -> None: + with FakeRawRpcServer() as server: + server.set_response("/get_transactions", {"status": "Failed"}) + with pytest.raises(MoneroError) as exc_info: + MoneroDaemonRpc(server.uri).get_txs([TX_HASH]) + assert str(exc_info.value) != "Invalid transaction hash" + + # Can raise an error for a response to a request for blocks in chunks that cannot hold any block + def test_get_blocks_by_range_chunked_with_no_room_for_a_block(self) -> None: + with FakeRawRpcServer() as server: + with pytest.raises(MoneroError) as exc_info: + MoneroDaemonRpc(server.uri).get_blocks_by_range_chunked(0, 5, 0) + # only the request with which the client checks its connection + assert all(path.endswith(".bin") for path, _ in server.requests) + assert str(exc_info.value) == "Daemon returned an empty block chunk for a non-empty range at height 0" + + # Can get the bandwidth limits of a daemon + def test_get_limits(self) -> None: + with FakeRawRpcServer() as server: + server.set_response("/get_limit", {"status": "OK", "limit_down": 10, "limit_up": 20}) + daemon: MoneroDaemonRpc = MoneroDaemonRpc(server.uri) + assert daemon.get_download_limit() == 10 + assert daemon.get_upload_limit() == 20 + + # Can raise an error for a response to a request for the limits that has no limits + @pytest.mark.parametrize("name, message", [("get_download_limit", "Could not get download limit"), ("get_upload_limit", "Could not get upload limit")]) + def test_get_limit_without_limit(self, name: str, message: str) -> None: + with FakeRawRpcServer() as server: + server.set_response("/get_limit", {"status": "OK"}) + with pytest.raises(MoneroError) as exc_info: + getattr(MoneroDaemonRpc(server.uri), name)() + assert str(exc_info.value) == message + + # Can set the bandwidth limits, and get the ones that the daemon answers, or the ones that were asked if it answers none + # (the errors for a limit that is missing are never raised: the limits that the client sends are already in what it gets back) + @pytest.mark.parametrize("name, argument, expected", [ + ("set_download_limit", 10, 123), ("reset_download_limit", None, 123), ("set_upload_limit", 10, 456), ("reset_upload_limit", None, 456) + ]) + def test_set_limits(self, name: str, argument: int | None, expected: int) -> None: + with FakeRawRpcServer() as server: + daemon: MoneroDaemonRpc = MoneroDaemonRpc(server.uri) + server.set_response("/set_limit", {"status": "OK", "limit_down": 123, "limit_up": 456}) + assert getattr(daemon, name)(*([] if argument is None else [argument])) == expected + + # a response with no limit keeps the one that was asked + server.set_response("/set_limit", {"status": "OK"}) + kept: int = getattr(daemon, name)(*([] if argument is None else [argument])) + assert kept == (argument if argument is not None else -1) + + # Can raise an error for a response that has no height after popping blocks + def test_pop_blocks_without_height(self) -> None: + with FakeRawRpcServer() as server: + server.set_response("/pop_blocks", {"status": "OK"}) + with pytest.raises(MoneroError) as exc_info: + MoneroDaemonRpc(server.uri).pop_blocks(1) + assert str(exc_info.value) == "Could not get height after popping blocks" + + # Can get the height after popping blocks + def test_pop_blocks(self) -> None: + with FakeRawRpcServer() as server: + server.set_response("/pop_blocks", {"status": "OK", "height": 42}) + assert MoneroDaemonRpc(server.uri).pop_blocks(1) == 42 + + # Can get the categories that the daemon logs, and none if the response has no categories + def test_set_log_categories(self) -> None: + with FakeRawRpcServer() as server: + daemon: MoneroDaemonRpc = MoneroDaemonRpc(server.uri) + server.set_response("/set_log_categories", {"status": "OK", "categories": "*:INFO"}) + assert daemon.set_log_categories("*:INFO") == "*:INFO" + server.set_response("/set_log_categories", {"status": "OK"}) + assert daemon.set_log_categories("*:INFO") == "" + + # Can submit blocks + def test_submit_blocks(self) -> None: + with FakeRawRpcServer() as server: + server.set_response("/json_rpc", _json_rpc({"status": "OK"})) + MoneroDaemonRpc(server.uri).submit_blocks(["00"]) + assert len(server.requests) > 0 + assert all(path == "/json_rpc" for path, _ in server.requests if not path.endswith(".bin")) + + # Can check for an update, with what the daemon tells of it + def test_check_for_update(self) -> None: + with FakeRawRpcServer() as server: + daemon: MoneroDaemonRpc = MoneroDaemonRpc(server.uri) + server.set_response("/update", { + "status": "OK", "update": True, "version": "1.2.3", "hash": "b" * 64, "auto_uri": "https://auto.example/1.2.3", + "user_uri": "https://user.example/1.2.3" + }) + result = daemon.check_for_update() + assert result.is_update_available is True + assert result.version == "1.2.3" + assert result.hash == "b" * 64 + assert result.auto_uri == "https://auto.example/1.2.3" + assert result.user_uri == "https://user.example/1.2.3" + + # what the daemon leaves empty is not set + server.set_response("/update", {"status": "OK", "update": False, "version": "", "hash": "", "auto_uri": "", "user_uri": ""}) + result = daemon.check_for_update() + assert result.is_update_available is False + assert result.version is None + assert result.hash is None + assert result.auto_uri is None + assert result.user_uri is None + + # Can download an update, and get where it is + def test_download_update(self) -> None: + with FakeRawRpcServer() as server: + server.set_response("/update", { + "status": "OK", "update": True, "version": "1.2.3", "hash": "b" * 64, "auto_uri": "https://auto.example/1.2.3", + "user_uri": "https://user.example/1.2.3", "path": "/tmp/monero-1.2.3.tar.bz2" + }) + result = MoneroDaemonRpc(server.uri).download_update("/tmp") + assert result.is_update_available is True + assert result.version == "1.2.3" + assert result.download_path == "/tmp/monero-1.2.3.tar.bz2" + + # Can ask the daemon to stop + def test_stop(self) -> None: + with FakeRawRpcServer() as server: + server.set_response("/stop_daemon", {"status": "OK"}) + MoneroDaemonRpc(server.uri).stop() + assert [path for path, _ in server.requests if path == "/stop_daemon"] == ["/stop_daemon"] + + # Can go on polling after a listener fails, and notify it again + def test_poller_survives_a_failing_listener(self) -> None: + listener: _RaisingListener = _RaisingListener() + with FakeDaemonRpcServer() as server: + daemon: MoneroDaemonRpc = MoneroDaemonRpc(server.uri) + daemon.set_poll_period_in_ms(20) + daemon.add_listener(listener) + try: + deadline: float = monotonic() + 10 + while listener.calls < 3 and monotonic() < deadline: + sleep(0.02) + finally: + daemon.remove_listener(listener) + assert listener.calls >= 3, "The poller stopped after the first failure of the listener" + + #endregion From 27e0f86e6e5b5a2881144d5da7bc03a9f63c4237 Mon Sep 17 00:00:00 2001 From: everoddandeven Date: Wed, 2 Dec 2026 01:07:20 +0100 Subject: [PATCH 3/8] tests: test the wallet rpc client with a fake server --- tests/wallet/test_rpc_client.py | 422 ++++++++++++++++++++++++++++++++ 1 file changed, 422 insertions(+) create mode 100644 tests/wallet/test_rpc_client.py diff --git a/tests/wallet/test_rpc_client.py b/tests/wallet/test_rpc_client.py new file mode 100644 index 0000000..8f54fde --- /dev/null +++ b/tests/wallet/test_rpc_client.py @@ -0,0 +1,422 @@ +from __future__ import annotations + +import logging + +from time import monotonic, sleep # the polls of the tests are waited for with them +from typing import Any +from typing_extensions import override + +import pytest +from monero import ( + MoneroError, MoneroOutputWallet, MoneroRpcError, MoneroTxConfig, MoneroTxPriority, MoneroTxQuery, MoneroWalletConfig, + MoneroWalletListener, MoneroWalletRpc +) + +from utils import BaseTestClass, FakeWalletRpcServer +from utils.fake_method_rpc_server import FakeMethodRpcServer + +logger: logging.Logger = logging.getLogger("TestMoneroWalletRpcClient") + +ADDRESS: str = "4" + "A" * 94 + +# the codes of the errors of monero-wallet-rpc (wallet_rpc_server_error_codes.h) +CODE_UNKNOWN_ERROR: int = -1 +CODE_WATCH_ONLY: int = -29 +CODE_ATTRIBUTE_NOT_FOUND: int = -45 + + +def _accounts(*indices: int) -> dict[str, Any]: + """The result of `get_accounts` of a wallet that has the accounts with these indices.""" + return { + "subaddress_accounts": [ + {"account_index": index, "balance": 0, "unlocked_balance": 0, "base_address": ADDRESS, "label": f"account {index}", "tag": ""} + for index in indices + ], + "total_balance": 0, + "total_unlocked_balance": 0 + } + + +def _transfer(kind: str, tx_hash: str, amount: int) -> dict[str, Any]: + """A transfer of `get_transfers`, in or out, that is in a block and still locked.""" + transfer: dict[str, Any] = { + "address": ADDRESS, "amount": amount, "confirmations": 1, "double_spend_seen": False, "fee": 0 if kind == "in" else 1000, "height": 103, + "locked": True, "note": "", "payment_id": "0000000000000000", "subaddr_index": {"major": 0, "minor": 0}, + "subaddr_indices": [{"major": 0, "minor": 0}], "suggested_confirmations_threshold": 1, "timestamp": 1700000000, "txid": tx_hash, + "type": kind, "unlock_time": 0 + } + if kind == "out": + transfer["destinations"] = [{"address": ADDRESS, "amount": amount}] + return transfer + + +def _sweep_result(tx_hash: str) -> dict[str, Any]: + """The result of `sweep_all` that made one tx.""" + return { + "amount_list": [1000], "fee_list": [10], "multisig_txset": "", "unsigned_txset": "", "weight_list": [1500], + "spent_key_images_list": [{"key_images": ["e" * 64]}], "tx_hash_list": [tx_hash], "tx_key_list": ["f" * 64], + "tx_blob_list": ["00"], "tx_metadata_list": ["00"] + } + + +def _balance(*unlocked: int) -> dict[str, Any]: + """The result of `get_balance` of an account that has a subaddress for each of the unlocked balances.""" + return { + "balance": sum(unlocked), "unlocked_balance": sum(unlocked), "multisig_import_needed": False, + "per_subaddress": [ + { + "account_index": 0, "address_index": index, "address": ADDRESS, "balance": value, "unlocked_balance": value, "label": "", + "num_unspent_outputs": 1 + } + for index, value in enumerate(unlocked) + ] + } + + +class _RaisingListener(MoneroWalletListener): + """Listener that fails each time that it is notified.""" + + def __init__(self) -> None: + super().__init__() + self.blocks: int = 0 + self.balances: int = 0 + self.received: int = 0 + self.spent: int = 0 + + @override + def on_new_block(self, height: int) -> None: + self.blocks += 1 + raise RuntimeError("listener failed") + + @override + def on_balances_changed(self, new_balance: int, new_unlocked_balance: int) -> None: + self.balances += 1 + raise RuntimeError("listener failed") + + @override + def on_output_received(self, output: MoneroOutputWallet) -> None: + self.received += 1 + raise RuntimeError("listener failed") + + @override + def on_output_spent(self, output: MoneroOutputWallet) -> None: + self.spent += 1 + raise RuntimeError("listener failed") + + +@pytest.mark.unit +class TestMoneroWalletRpcClient(BaseTestClass): + """Wallet rpc client unit tests, on a local rpc server that answers with the responses that the tests set: the ones that a wallet rpc + server gives when it has nothing to report or something wrong, which the one of the integration tests does not.""" + + #region Tests + + # Can refuse to create a wallet from a seed and from keys at the same time + def test_create_wallet_with_seed_and_keys(self) -> None: + with FakeMethodRpcServer() as server: + config: MoneroWalletConfig = MoneroWalletConfig(path="wallet", password="password", seed="seed", primary_address=ADDRESS) + with pytest.raises(MoneroError) as exc_info: + MoneroWalletRpc(server.uri).create_wallet(config) + assert server.methods == [] + assert str(exc_info.value) == "Wallet can be initialized with a seed or keys but not both" + + # Can raise the error of a server that cannot create a wallet from keys, as the one of a wallet that exists + def test_create_wallet_from_keys_that_exists(self) -> None: + with FakeMethodRpcServer() as server: + server.set_method_error("generate_from_keys", CODE_UNKNOWN_ERROR, "Wallet already exists.") + config: MoneroWalletConfig = MoneroWalletConfig( + path="wallet", password="password", primary_address=ADDRESS, private_view_key="b" * 64, private_spend_key="c" * 64 + ) + with pytest.raises(MoneroRpcError) as exc_info: + MoneroWalletRpc(server.uri).create_wallet(config) + assert str(exc_info.value) == "Wallet already exists: wallet" + + # Can raise the error of a server that cannot create a wallet from keys for another reason, as it is + def test_create_wallet_from_keys_error(self) -> None: + with FakeMethodRpcServer() as server: + server.set_method_error("generate_from_keys", CODE_UNKNOWN_ERROR, "Failed to generate") + config: MoneroWalletConfig = MoneroWalletConfig( + path="wallet", password="password", primary_address=ADDRESS, private_view_key="b" * 64, private_spend_key="c" * 64 + ) + with pytest.raises(MoneroRpcError) as exc_info: + MoneroWalletRpc(server.uri).create_wallet(config) + assert str(exc_info.value) == "Failed to generate" + + # Can stop the wallet rpc server + def test_stop(self) -> None: + with FakeMethodRpcServer() as server: + server.set_method("stop_wallet", {}) + MoneroWalletRpc(server.uri).stop() + assert "stop_wallet" in server.methods + + # Can rescan the blockchain + def test_rescan_blockchain(self) -> None: + with FakeMethodRpcServer() as server: + server.set_method("rescan_blockchain", {}) + MoneroWalletRpc(server.uri).rescan_blockchain() + assert "rescan_blockchain" in server.methods + + # Can raise an error for an account that the wallet does not have + def test_get_account_that_does_not_exist(self) -> None: + with FakeMethodRpcServer() as server: + server.set_method("get_accounts", _accounts(0, 1)) + wallet: MoneroWalletRpc = MoneroWalletRpc(server.uri) + assert wallet.get_account(1).index == 1 + with pytest.raises(MoneroError) as exc_info: + wallet.get_account(5) + assert str(exc_info.value) == "Account with index 5 does not exist" + + # Can tell if a wallet is view only from the error of the server, and raise the other errors + def test_is_view_only(self) -> None: + with FakeMethodRpcServer() as server: + wallet: MoneroWalletRpc = MoneroWalletRpc(server.uri) + + server.set_method("query_key", {"key": "words"}) + assert wallet.is_view_only() is False + + server.set_method_error("query_key", CODE_WATCH_ONLY, "The wallet is watch-only. Cannot retrieve seed.") + assert wallet.is_view_only() is True + + server.set_method_error("query_key", CODE_UNKNOWN_ERROR, "The wallet is non-deterministic. Cannot display seed.") + assert wallet.is_view_only() is False + + server.set_method_error("query_key", -13, "No wallet file") + with pytest.raises(MoneroRpcError) as exc_info: + wallet.is_view_only() + assert exc_info.value.code == -13 + + # Can get an attribute that the wallet has, an empty one for one that it does not have, and raise the other errors + def test_get_attribute(self) -> None: + with FakeMethodRpcServer() as server: + wallet: MoneroWalletRpc = MoneroWalletRpc(server.uri) + + server.set_method("get_attribute", {"value": "stored"}) + assert wallet.get_attribute("key") == "stored" + + server.set_method_error("get_attribute", CODE_ATTRIBUTE_NOT_FOUND, "Attribute not found") + assert wallet.get_attribute("key") == "" + + server.set_method_error("get_attribute", CODE_UNKNOWN_ERROR, "Failed") + with pytest.raises(MoneroRpcError) as exc_info: + wallet.get_attribute("key") + assert exc_info.value.code == CODE_UNKNOWN_ERROR + + # Can refuse to fetch the txs that are in the pool and confirmed + def test_get_txs_in_the_pool_and_confirmed(self) -> None: + with FakeMethodRpcServer() as server: + with pytest.raises(MoneroError) as exc_info: + MoneroWalletRpc(server.uri).get_txs(MoneroTxQuery(is_confirmed=True, in_tx_pool=True)) + assert "get_transfers" not in server.methods + assert str(exc_info.value) == "Cannot fetch pool transactions because it contradicts configuration" + + # Can ask the txs from the height 0, with that height as the minimum + def test_get_txs_from_height_0(self) -> None: + with FakeMethodRpcServer() as server: + server.set_method("get_transfers", {}) + server.set_method("get_accounts", _accounts(0)) + MoneroWalletRpc(server.uri).get_txs(MoneroTxQuery(min_height=0)) + params: list[Any] = server.get_params("get_transfers") + assert len(params) > 0 + assert all(p["min_height"] == 0 for p in params) + + # Can get the default priority of the fees, from the number that the server gives + @pytest.mark.parametrize("number, priority", [ + (0, MoneroTxPriority.DEFAULT), (1, MoneroTxPriority.UNIMPORTANT), (2, MoneroTxPriority.NORMAL), (3, MoneroTxPriority.ELEVATED) + ]) + def test_get_default_fee_priority(self, number: int, priority: MoneroTxPriority) -> None: + with FakeMethodRpcServer() as server: + server.set_method("get_default_fee_priority", {"priority": number}) + assert MoneroWalletRpc(server.uri).get_default_fee_priority() == priority + + # Can raise an error for a priority of the fees that is not one of the wallet, or that is missing + @pytest.mark.parametrize("result", [{"priority": 4}, {"priority": -1}, {}]) + def test_get_default_fee_priority_not_valid(self, result: dict[str, Any]) -> None: + with FakeMethodRpcServer() as server: + server.set_method("get_default_fee_priority", result) + with pytest.raises(MoneroError) as exc_info: + MoneroWalletRpc(server.uri).get_default_fee_priority() + assert str(exc_info.value) == "Could not get default fee priority" + + # Can raise an error for a response to a request for the height that has no height + def test_get_height_without_height(self) -> None: + with FakeMethodRpcServer() as server: + server.set_method("get_height", {}) + with pytest.raises(MoneroError) as exc_info: + MoneroWalletRpc(server.uri).get_height() + assert str(exc_info.value) == "Invalid get_height response" + + # Can go on polling after a listener fails, and notify it again + def test_poller_survives_a_failing_listener(self) -> None: + listener: _RaisingListener = _RaisingListener() + with FakeWalletRpcServer() as server: + wallet: MoneroWalletRpc = MoneroWalletRpc(server.uri) + wallet.add_listener(listener) + wallet.start_syncing(20) + try: + deadline: float = monotonic() + 10 + while listener.blocks < 3 and monotonic() < deadline: + sleep(0.02) + finally: + wallet.remove_listener(listener) + wallet.stop_syncing() + assert listener.blocks >= 3, "The poller stopped after the first failure of the listener" + + # Can go on polling after a listener fails to be told of the balances that change, and tell it again + def test_poller_survives_a_failing_listener_of_balances(self) -> None: + listener: _RaisingListener = _RaisingListener() + with FakeMethodRpcServer() as server: + server.set_method("auto_refresh", {}) + server.set_method("get_height", {"height": 100}) + server.set_method("get_transfers", {}) + server.set_method("incoming_transfers", {}) + # a balance that is another at each request + results: list[dict[str, Any]] = [] + for balance in range(10, 40): + result: dict[str, Any] = _accounts(0) + result["total_balance"] = result["total_unlocked_balance"] = balance + result["subaddress_accounts"][0]["balance"] = result["subaddress_accounts"][0]["unlocked_balance"] = balance + results.append(result) + server.set_method_sequence("get_accounts", results) + wallet: MoneroWalletRpc = MoneroWalletRpc(server.uri) + wallet.add_listener(listener) + wallet.start_syncing(20) + try: + deadline: float = monotonic() + 10 + while listener.balances < 3 and monotonic() < deadline: + sleep(0.02) + finally: + wallet.remove_listener(listener) + wallet.stop_syncing() + assert listener.balances >= 3, "The poller stopped after the first failure of the listener" + + # Can go on polling after a listener fails to be told of the outputs that the wallet receives and spends + def test_poller_survives_a_failing_listener_of_outputs(self) -> None: + listener: _RaisingListener = _RaisingListener() + with FakeMethodRpcServer() as server: + server.set_method("auto_refresh", {}) + server.set_method("get_height", {"height": 103}) + server.set_method("get_accounts", _accounts(0)) + server.set_method("incoming_transfers", {}) + # nothing in the first requests, which the poller takes as what the wallet has, and then two txs that it did not have + appears: dict[str, Any] = {"in": [_transfer("in", "a" * 64, 1000)], "out": [_transfer("out", "b" * 64, 500)]} + nothing: dict[str, Any] = {} + server.set_method_sequence("get_transfers", [nothing] * 8 + [appears]) + wallet: MoneroWalletRpc = MoneroWalletRpc(server.uri) + wallet.add_listener(listener) + wallet.start_syncing(20) + try: + deadline: float = monotonic() + 10 + while (listener.received < 1 or listener.spent < 1) and monotonic() < deadline: + sleep(0.02) + finally: + wallet.remove_listener(listener) + wallet.stop_syncing() + assert listener.received >= 1, "The wallet did not tell of the output that it received" + assert listener.spent >= 1, "The wallet did not tell of the output that it spent" + + # Can raise an error for a response to a request for a payment uri that has no uri + def test_get_payment_uri_without_uri(self) -> None: + with FakeMethodRpcServer() as server: + server.set_method("make_uri", {}) + with pytest.raises(MoneroError) as exc_info: + MoneroWalletRpc(server.uri).get_payment_uri(MoneroTxConfig(address=ADDRESS, amount=1)) + assert str(exc_info.value) == "Could not deserialize payment uri" + + # Can add an entry to the address book, and raise an error for a response that has no index for it + def test_add_address_book_entry(self) -> None: + with FakeMethodRpcServer() as server: + wallet: MoneroWalletRpc = MoneroWalletRpc(server.uri) + server.set_method("add_address_book", {"index": 3}) + assert wallet.add_address_book_entry(ADDRESS, "description") == 3 + server.set_method("add_address_book", {}) + with pytest.raises(MoneroError) as exc_info: + wallet.add_address_book_entry(ADDRESS, "description") + assert str(exc_info.value) == "Could not deserialize address book entry index" + + # Can get the entries of the address book, with their payment ids + def test_get_address_book_entries(self) -> None: + with FakeMethodRpcServer() as server: + book: dict[str, Any] = {"entries": [ + {"index": 0, "address": ADDRESS, "description": "first", "payment_id": "0123456789abcdef"}, + {"index": 1, "address": ADDRESS, "description": "second"} + ]} + server.set_method("get_address_book", book) + entries = MoneroWalletRpc(server.uri).get_address_book_entries() + assert [(e.index, e.description) for e in entries] == [(0, "first"), (1, "second")] + assert entries[0].payment_id == "0123456789abcdef" + + # Can raise an error for a response to a request for a reserve proof that has no signature + def test_get_reserve_proof_without_signature(self) -> None: + with FakeMethodRpcServer() as server: + server.set_method("get_reserve_proof", {}) + with pytest.raises(MoneroError) as exc_info: + MoneroWalletRpc(server.uri).get_reserve_proof_wallet("message") + assert str(exc_info.value) == "Invalid reserve proof response" + + # Can ask for a tx with each priority of the fees + @pytest.mark.parametrize("priority, number", [ + (MoneroTxPriority.DEFAULT, 0), (MoneroTxPriority.UNIMPORTANT, 1), (MoneroTxPriority.NORMAL, 2), (MoneroTxPriority.ELEVATED, 3) + ]) + def test_create_tx_priority(self, priority: MoneroTxPriority, number: int) -> None: + with FakeMethodRpcServer() as server: + wallet: MoneroWalletRpc = MoneroWalletRpc(server.uri) + with pytest.raises(MoneroError): + wallet.create_tx(MoneroTxConfig(account_index=0, address=ADDRESS, amount=1, priority=priority)) + params: list[Any] = server.get_params("transfer") + assert len(params) == 1 + assert params[0]["priority"] == number + + # Can get the txs that failed + def test_get_failed_txs(self) -> None: + with FakeMethodRpcServer() as server: + server.set_method("get_accounts", _accounts(0)) + server.set_method("get_transfers", {"failed": [_transfer("failed", "c" * 64, 700)]}) + txs = MoneroWalletRpc(server.uri).get_txs(MoneroTxQuery(is_failed=True)) + assert [tx.hash for tx in txs] == ["c" * 64] + assert txs[0].is_failed is True + assert txs[0].is_confirmed is False + + # Can raise an error for a transfer of a type that the wallet does not have + def test_get_txs_of_a_type_that_is_not_known(self) -> None: + with FakeMethodRpcServer() as server: + server.set_method("get_accounts", _accounts(0)) + server.set_method("get_transfers", {"in": [_transfer("other", "d" * 64, 700)]}) + with pytest.raises(MoneroError) as exc_info: + MoneroWalletRpc(server.uri).get_txs() + assert str(exc_info.value) == "Unrecognized transfer type: other" + + @staticmethod + def _sweep(server: FakeMethodRpcServer, each_subaddress: bool) -> tuple[int, list[Any]]: + """Sweep an account whose subaddresses 0 and 2 have an unlocked balance, and the 1 has none, and give the txs that the wallet made + and the parameters of the requests that it sent.""" + accounts: dict[str, Any] = _accounts(0) + accounts["subaddress_accounts"][0]["balance"] = accounts["subaddress_accounts"][0]["unlocked_balance"] = 30 + server.set_method("get_accounts", accounts) + server.set_method("get_balance", _balance(10, 0, 20)) + addresses: dict[str, Any] = {"address": ADDRESS, "addresses": [ + {"address": ADDRESS, "address_index": index, "label": "", "used": True} for index in range(3) + ]} + server.set_method("get_address", addresses) + server.set_method("sweep_all", _sweep_result("a" * 64)) + txs = MoneroWalletRpc(server.uri).sweep_unlocked(MoneroTxConfig(address=ADDRESS, sweep_each_subaddress=each_subaddress, relay=False)) + return len(txs), server.get_params("sweep_all") + + # Can sweep the subaddresses of an account that have an unlocked balance, in a request for all of them + def test_sweep_unlocked(self) -> None: + with FakeMethodRpcServer() as server: + count, params = self._sweep(server, False) + assert [p["subaddr_indices"] for p in params] == [[0, 2]] + assert count == 1 + + # Can sweep each subaddress that has an unlocked balance, in a request of its own + @pytest.mark.xfail( + reason="TODO monero-cpp: sweep_unlocked() sets sweep_each_subaddress to false in the copy of the config, and then looks at the " + "copy and not at the config, so it never sweeps each subaddress (monero_wallet_rpc.cpp, and monero_wallet_full.cpp)", strict=True + ) + def test_sweep_each_subaddress(self) -> None: + with FakeMethodRpcServer() as server: + count, params = self._sweep(server, True) + assert [p["subaddr_indices"] for p in params] == [[0], [2]] + assert count == 2 + + #endregion From 5cf1d705050226dec1a1be90422813c112e7285c Mon Sep 17 00:00:00 2001 From: everoddandeven Date: Wed, 2 Dec 2026 01:16:40 +0100 Subject: [PATCH 4/8] tests: test what the daemon rpc client makes of its responses --- tests/daemon/test_rpc_responses.py | 211 +++++++++++++++++++++++++++++ 1 file changed, 211 insertions(+) create mode 100644 tests/daemon/test_rpc_responses.py diff --git a/tests/daemon/test_rpc_responses.py b/tests/daemon/test_rpc_responses.py new file mode 100644 index 0000000..3cc7c9c --- /dev/null +++ b/tests/daemon/test_rpc_responses.py @@ -0,0 +1,211 @@ +from __future__ import annotations + +import json +import logging + +from typing import Any + +import pytest +from monero import ( + MoneroConnectionType, MoneroDaemonRpc, MoneroError, MoneroKeyImageSpentStatus, MoneroNetworkType +) + +from utils import BaseTestClass, FakeRawRpcServer + +logger: logging.Logger = logging.getLogger("TestMoneroDaemonRpcResponses") + +HASH: str = "a" * 64 +NO_HASH: str = "0" * 64 + + +def _json_rpc(result: object) -> dict[str, Any]: + """The JSON-RPC response of a daemon with a result.""" + return {"jsonrpc": "2.0", "id": "0", "result": result} + + +def _peer(address_type: int, port: str = "18080") -> dict[str, Any]: + """A peer, as a daemon gives it.""" + return { + "address": f"1.2.3.4:{port}", "address_type": address_type, "avg_download": 1, "avg_upload": 2, "connection_id": "c" * 32, + "current_download": 3, "current_upload": 4, "height": 100, "host": "1.2.3.4", "incoming": False, "ip": "1.2.3.4", "live_time": 5, + "local_ip": False, "localhost": False, "peer_id": "d" * 16, "port": port, "pruning_seed": 0, "recv_count": 6, "recv_idle_time": 7, + "rpc_credits_per_hash": 0, "rpc_port": 0, "send_count": 8, "send_idle_time": 9, "state": "normal", "support_flags": 1 + } + + +def _pool_tx(**fields: Any) -> dict[str, Any]: + """A tx of the pool, as a daemon gives it, with the fields of its failure as the test sets them.""" + tx_json: dict[str, Any] = { + "version": 2, "unlock_time": 0, + "vin": [{"key": {"amount": 0, "key_offsets": [1, 2], "k_image": "b" * 64}}], + "vout": [{"amount": 0, "target": {"tagged_key": {"key": "c" * 64, "view_tag": "dd"}}}], + "extra": [1, 2, 3], "rct_signatures": {"type": 6, "txnFee": 100} + } + tx_json.update(fields.pop("tx_json", {})) + tx: dict[str, Any] = { + "id_hash": HASH, "blob_size": 100, "weight": 100, "fee": 100, "max_used_block_height": 0, "max_used_block_id_hash": NO_HASH, + "last_failed_height": 0, "last_failed_id_hash": NO_HASH, "receive_time": 1700000000, "relayed": True, "kept_by_block": False, + "do_not_relay": False, "double_spend_seen": False, "tx_blob": "00", "tx_json": json.dumps(tx_json) + } + tx.update(fields) + return tx + + +@pytest.mark.unit +class TestMoneroDaemonRpcResponses(BaseTestClass): + """Daemon rpc client unit tests of what it makes of the responses that a daemon gives, with the ones that the daemon of the integration + tests rarely does: failed txs, peers of every kind, connections that are syncing, and a network that is not the main one.""" + + #region Tests + + # Can get the status of the key images + def test_get_key_image_spent_statuses(self) -> None: + with FakeRawRpcServer() as server: + server.set_response("/is_key_image_spent", {"status": "OK", "spent_status": [0, 1, 2]}) + statuses = MoneroDaemonRpc(server.uri).get_key_image_spent_statuses([HASH, HASH, HASH]) + assert list(statuses) == [MoneroKeyImageSpentStatus.NOT_SPENT, MoneroKeyImageSpentStatus.CONFIRMED, MoneroKeyImageSpentStatus.TX_POOL] + + # Can raise an error for a status of a key image that the daemon does not have + def test_get_key_image_spent_statuses_not_valid(self) -> None: + with FakeRawRpcServer() as server: + server.set_response("/is_key_image_spent", {"status": "OK", "spent_status": [3]}) + with pytest.raises(MoneroError) as exc_info: + MoneroDaemonRpc(server.uri).get_key_image_spent_statuses([HASH]) + assert str(exc_info.value) == "Invalid key image spent status, expected 0-2:3" + + # Can get the miner data, with the txs that the pool has for the next block + def test_get_miner_data(self) -> None: + with FakeRawRpcServer() as server: + result: dict[str, Any] = { + "status": "OK", "major_version": 16, "height": 10, "prev_id": HASH, "seed_hash": "b" * 64, "difficulty": "0x5", + "median_weight": 300000, "already_generated_coins": 12345, + "tx_backlog": [{"id": "c" * 64, "weight": 1500, "fee": 30000}, {"id": "d" * 64, "weight": 2500, "fee": 40000}] + } + server.set_response("/json_rpc", _json_rpc(result)) + data = MoneroDaemonRpc(server.uri).get_miner_data() + assert data.height == 10 + assert [(tx.hash, tx.weight, tx.fee) for tx in data.tx_pool_backlog] == [("c" * 64, 1500, 30000), ("d" * 64, 2500, 40000)] + assert all(tx.in_tx_pool is True and tx.is_confirmed is False and tx.num_confirmations == 0 for tx in data.tx_pool_backlog) + + # Can get the sync info of a daemon that is syncing, with the spans of blocks that it is downloading + def test_get_sync_info_with_spans(self) -> None: + with FakeRawRpcServer() as server: + result: dict[str, Any] = { + "status": "OK", "height": 10, "target_height": 20, "next_needed_pruning_seed": 0, "overview": "[]", + "peers": [{"info": _peer(1)}], + "spans": [{"connection_id": "e" * 32, "nblocks": 5, "rate": 6, "remote_address": "1.2.3.4:18080", "size": 7, "speed": 8, + "start_block_height": 9}] + } + server.set_response("/json_rpc", _json_rpc(result)) + info = MoneroDaemonRpc(server.uri).get_sync_info() + assert (info.height, info.target_height) == (10, 20) + assert len(info.peers) == 1 + assert len(info.spans) == 1 + span = info.spans[0] + assert (span.connection_id, span.num_blocks, span.remote_address) == ("e" * 32, 5, "1.2.3.4:18080") + assert (span.rate, span.speed, span.size, span.start_height) == (6, 8, 7, 9) + + # Can get the connections of a daemon with each type of address + # TODO monero-cpp: the code has Tor as 3 and I2P as 4, and its own comment says that epee has them the other way + @pytest.mark.parametrize("number, expected", [ + (0, MoneroConnectionType.INVALID), (1, MoneroConnectionType.IPV4), (2, MoneroConnectionType.IPV6), (3, MoneroConnectionType.TOR), + (4, MoneroConnectionType.I2P) + ]) + def test_get_peers_address_type(self, number: int, expected: MoneroConnectionType) -> None: + with FakeRawRpcServer() as server: + server.set_response("/json_rpc", _json_rpc({"status": "OK", "connections": [_peer(number)]})) + peers = MoneroDaemonRpc(server.uri).get_peers() + assert len(peers) == 1 + assert peers[0].connection_type == expected + assert peers[0].address == "1.2.3.4:18080" + assert peers[0].is_online is True + + # Can raise an error for a type of address that the daemon does not have + def test_get_peers_address_type_not_valid(self) -> None: + with FakeRawRpcServer() as server: + server.set_response("/json_rpc", _json_rpc({"status": "OK", "connections": [_peer(5)]})) + with pytest.raises(MoneroError) as exc_info: + MoneroDaemonRpc(server.uri).get_peers() + assert str(exc_info.value) == "Invalid RPC peer type, expected 0-4: 5" + + # Can get the peers that a daemon knows, and the ones that it saw but are offline + def test_get_known_peers(self) -> None: + with FakeRawRpcServer() as server: + server.set_response("/get_peer_list", {"status": "OK", "white_list": [_peer(1, "1")], "gray_list": [_peer(2, "2")]}) + peers = MoneroDaemonRpc(server.uri).get_known_peers() + assert [(p.port, p.is_online) for p in peers] == [(1, True), (2, False)] + + # Can get the public nodes, and which ones are offline + def test_get_public_peers(self) -> None: + with FakeRawRpcServer() as server: + server.set_response("/get_public_nodes", {"status": "OK", "white": [_peer(1, "1")], "gray": [_peer(2, "2")]}) + peers = MoneroDaemonRpc(server.uri).get_public_peers() + assert [(p.port, p.is_online) for p in peers] == [(1, True), (2, False)] + + # Can get the stats of a pool that has no tx, with no value for the ones that do not apply + def test_get_tx_pool_stats_with_no_txs(self) -> None: + with FakeRawRpcServer() as server: + server.set_response("/get_transaction_pool_stats", {"status": "OK", "pool_stats": { + "bytes_max": 0, "bytes_med": 0, "bytes_min": 0, "bytes_total": 0, "fee_total": 0, "histo_98pc": 0, "num_10m": 0, + "num_double_spends": 0, "num_failing": 0, "num_not_relayed": 0, "oldest": 0, "txs_total": 0 + }}) + stats = MoneroDaemonRpc(server.uri).get_tx_pool_stats() + assert stats.num_txs == 0 + assert stats.bytes_min is None + assert stats.bytes_max is None + assert stats.bytes_med is None + assert stats.histo98pc is None + assert stats.oldest_timestamp is None + + # Can get the network of a daemon + @pytest.mark.parametrize("nettype, expected", [ + ("mainnet", MoneroNetworkType.MAINNET), ("testnet", MoneroNetworkType.TESTNET), ("stagenet", MoneroNetworkType.STAGENET), + ("fakechain", MoneroNetworkType.MAINNET) + ]) + def test_get_info_network_type(self, nettype: str, expected: MoneroNetworkType) -> None: + with FakeRawRpcServer() as server: + server.set_response("/json_rpc", _json_rpc({"status": "OK", "nettype": nettype, "height": 10})) + info = MoneroDaemonRpc(server.uri).get_info() + assert info.network_type == expected + + # Can tell which txs of the pool failed: the ones that have a height or a hash of a block where they failed + def test_get_tx_pool_failed_txs(self) -> None: + with FakeRawRpcServer() as server: + server.set_response("/get_transaction_pool", {"status": "OK", "transactions": [ + _pool_tx(id_hash="1" * 64), + _pool_tx(id_hash="2" * 64, last_failed_height=5, last_failed_id_hash="e" * 64), + _pool_tx(id_hash="3" * 64, last_failed_id_hash="f" * 64) + ]}) + txs = {tx.hash: tx for tx in MoneroDaemonRpc(server.uri).get_tx_pool()} + assert txs["1" * 64].is_failed is False + assert txs["2" * 64].is_failed is True + assert txs["2" * 64].last_failed_height == 5 + assert txs["2" * 64].last_failed_hash == "e" * 64 + assert txs["3" * 64].is_failed is True + assert txs["3" * 64].last_failed_hash == "f" * 64 + assert all(tx.in_tx_pool is True and tx.is_confirmed is False for tx in txs.values()) + + # Can get the signatures of a tx of the first version + def test_get_tx_pool_tx_signatures(self) -> None: + with FakeRawRpcServer() as server: + server.set_response("/get_transaction_pool", {"status": "OK", "transactions": [ + _pool_tx(tx_json={"version": 1, "signatures": ["s" * 128, "t" * 128]}) + ]}) + txs = MoneroDaemonRpc(server.uri).get_tx_pool() + assert [list(tx.signatures) for tx in txs] == [["s" * 128, "t" * 128]] + + # Can tell that a tx is not confirmed when the daemon gives its time as its height, as it does for the ones of the pool + def test_get_tx_in_the_pool_with_a_height_that_is_a_time(self) -> None: + with FakeRawRpcServer() as server: + tx: dict[str, Any] = { + "tx_hash": HASH, "in_pool": True, "block_height": 1700000000, "block_timestamp": 1700000000, "as_hex": "00", + "as_json": _pool_tx()["tx_json"], "double_spend_seen": False, "relayed": True + } + server.set_response("/get_transactions", {"status": "OK", "txs": [tx]}) + result = MoneroDaemonRpc(server.uri).get_tx(HASH) + assert result is not None + assert result.is_confirmed is False + assert result.in_tx_pool is True + assert result.block is None + + #endregion From 99b1b07a825a712f6ad173d2827304af9f92527a Mon Sep 17 00:00:00 2001 From: everoddandeven Date: Wed, 2 Dec 2026 01:16:40 +0100 Subject: [PATCH 5/8] tests: test binary blocks and signatures that are not valid --- .../monero_utils/test_binary_blocks_errors.py | 61 +++++++++++++++++++ tests/wallet/test_keys_wallet_signatures.py | 33 ++++++++++ 2 files changed, 94 insertions(+) create mode 100644 tests/common/monero_utils/test_binary_blocks_errors.py create mode 100644 tests/wallet/test_keys_wallet_signatures.py diff --git a/tests/common/monero_utils/test_binary_blocks_errors.py b/tests/common/monero_utils/test_binary_blocks_errors.py new file mode 100644 index 0000000..c9baedd --- /dev/null +++ b/tests/common/monero_utils/test_binary_blocks_errors.py @@ -0,0 +1,61 @@ +from __future__ import annotations + +import json +import logging + +from typing import Optional + +import pytest +from monero import MoneroError, MoneroUtils + +from utils import BaseTestClass + +logger: logging.Logger = logging.getLogger("TestMoneroUtilsBinaryBlocksErrors") + +# the miner tx of the genesis block, which is the one block that has no hash to compute: the header of a block is the +# major version, the minor version, the timestamp, the hash of the previous block, and the nonce, then the miner tx and the hashes of the txs +GENESIS_TX: bytes = bytes.fromhex( + "013c01ff0001ffffffffffff03029b2e4c0281c0b02e7c53291a94d1d0cbff8883f8024f5142ee494ffbbd08807121017767aafcde9be00dcfd098715ebcf7f410dae" + "bc582fda69d24a28e9d0bc890d1" +) +GENESIS_BLOCK: bytes = bytes.fromhex("010000") + bytes(32) + bytes.fromhex("10270000") + GENESIS_TX + b"\x00" + + +def _binary_blocks(block: bytes, tx: Optional[bytes] = None, pruned: bool = False) -> bytes: + """The binary response of a daemon with one block and, if given, one tx of it. The blobs go through a placeholder of their size: the + conversion from JSON to binary cannot take bytes that are not text.""" + entry: dict[str, object] = {"block": "X" * len(block), "pruned": pruned, "txs": []} + if tx is not None: + entry["txs"] = [{"blob": "Y" * len(tx), "prunable_hash": "P" * 32}] + data: bytes = MoneroUtils.json_to_binary(json.dumps({"status": "OK", "untrusted": False, "blocks": [entry]})) + data = data.replace(b"X" * len(block), block) + if tx is not None: + data = data.replace(b"Y" * len(tx), tx).replace(b"P" * 32, bytes(32)) + return data + + +@pytest.mark.unit +class TestMoneroUtilsBinaryBlocksErrors(BaseTestClass): + """Conversion of binary blocks to JSON unit tests, with blobs that the daemon would never send.""" + + #region Tests + + # Can convert a block that is valid + def test_binary_blocks_to_json(self) -> None: + blocks: dict[str, list[str]] = json.loads(MoneroUtils.binary_blocks_to_json(_binary_blocks(GENESIS_BLOCK))) + assert len(blocks["blocks"]) == 1 + assert json.loads(blocks["blocks"][0])["major_version"] == 1 + + # Can raise an error for a block that is not one + def test_binary_blocks_to_json_with_a_block_that_is_not_valid(self) -> None: + with pytest.raises(MoneroError) as exc_info: + MoneroUtils.binary_blocks_to_json(_binary_blocks(b"not a block blob")) + assert str(exc_info.value) == "failed to parse block blob at index 0" + + # Can raise an error for a tx that is not one + def test_binary_blocks_to_json_with_a_tx_that_is_not_valid(self) -> None: + with pytest.raises(MoneroError) as exc_info: + MoneroUtils.binary_blocks_to_json(_binary_blocks(GENESIS_BLOCK, b"not a tx blob at all", pruned=True)) + assert str(exc_info.value) == "failed to parse tx blob at index 0" + + #endregion diff --git a/tests/wallet/test_keys_wallet_signatures.py b/tests/wallet/test_keys_wallet_signatures.py new file mode 100644 index 0000000..5396a8a --- /dev/null +++ b/tests/wallet/test_keys_wallet_signatures.py @@ -0,0 +1,33 @@ +from __future__ import annotations + +import logging + +import pytest +from monero import MoneroNetworkType, MoneroWalletConfig, MoneroWalletKeys + +from utils import BaseTestClass + +logger: logging.Logger = logging.getLogger("TestMoneroWalletKeysSignatures") + + +@pytest.mark.unit +class TestMoneroWalletKeysSignatures(BaseTestClass): + """Keys wallet unit tests of the verification of a message with signatures that cannot be one.""" + + #region Tests + + # Can say that a message is not signed when the signature is not one that was made by a wallet + @pytest.mark.parametrize("signature", [ + "", # no header + "garbage", # no header + "SigV2", # nothing after the header + "SigV2" + "0OIl", # letters that are not of base 58 + "SigV2" + "1", # a number of bytes that a signature does not have + "SigV1" + "1" + ]) + def test_verify_message_with_a_signature_that_is_not_valid(self, signature: str) -> None: + wallet: MoneroWalletKeys = MoneroWalletKeys.create_wallet_random(MoneroWalletConfig(network_type=MoneroNetworkType.MAINNET, language="English")) + result = wallet.verify_message("message", wallet.get_primary_address(), signature) + assert result.is_good is False + + #endregion From 7e96e50478dc33133c0cddff1b4ab8c1bb2cd39c Mon Sep 17 00:00:00 2001 From: everoddandeven Date: Wed, 2 Dec 2026 01:16:40 +0100 Subject: [PATCH 6/8] tests: give the balances poller test enough responses --- tests/wallet/test_rpc_client.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/wallet/test_rpc_client.py b/tests/wallet/test_rpc_client.py index 8f54fde..7558383 100644 --- a/tests/wallet/test_rpc_client.py +++ b/tests/wallet/test_rpc_client.py @@ -269,9 +269,9 @@ def test_poller_survives_a_failing_listener_of_balances(self) -> None: server.set_method("get_height", {"height": 100}) server.set_method("get_transfers", {}) server.set_method("incoming_transfers", {}) - # a balance that is another at each request + # a balance that is another at each request, and enough of them for all the requests that the poller makes while the test waits results: list[dict[str, Any]] = [] - for balance in range(10, 40): + for balance in range(10, 6010): result: dict[str, Any] = _accounts(0) result["total_balance"] = result["total_unlocked_balance"] = balance result["subaddress_accounts"][0]["balance"] = result["subaddress_accounts"][0]["unlocked_balance"] = balance From 30e34a30535e13551c35acc0d532935ce76c9b3c Mon Sep 17 00:00:00 2001 From: everoddandeven Date: Wed, 2 Dec 2026 01:17:17 +0100 Subject: [PATCH 7/8] vscode: add additional cspell words --- .vscode/settings.json | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index 8e4786e..a56d80a 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -85,6 +85,7 @@ "armhf", "armv", "autoremove", + "autouse", "backlink", "badpassword", "banhammer", @@ -92,10 +93,13 @@ "behaviour", "bitmonero", "blobdata", + "blockhashing", + "blocktemplate", "buildflags", "buildopts", "buildpackage", "CFLAGS", + "CLSAGs", "conftest", "cpus", "Cryptonote", @@ -150,12 +154,14 @@ "OBJCXXFLAGS", "ohhai", "OMZG", + "peerlist", "posonlyargs", "pubkeys", "pybind", "pytest", "qttools", "rapidjson", + "rctsig", "REGTEST", "repointed", "repoints", @@ -164,9 +170,11 @@ "rescan", "rescans", "ringdb", + "RLIMIT", "rockstar", "RUSAGE", "scikit", + "setrlimit", "shlibdeps", "stagenet", "stubgen", @@ -182,11 +190,14 @@ "unfound", "unmixable", "unrelayed", + "varint", "vout", "wijqwnn", "wipeable", "woodser", "wrongpass", - "wronguser" + "wronguser", + "xfail", + "xfails" ] } From 99c16e26f14afae2e7363b49e8a937357034034b Mon Sep 17 00:00:00 2001 From: everoddandeven Date: Wed, 2 Dec 2026 01:35:16 +0100 Subject: [PATCH 8/8] tests: update test_get_attribute to handle None for missing attributes --- tests/wallet/test_rpc_client.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/wallet/test_rpc_client.py b/tests/wallet/test_rpc_client.py index 7558383..6e0c241 100644 --- a/tests/wallet/test_rpc_client.py +++ b/tests/wallet/test_rpc_client.py @@ -185,7 +185,7 @@ def test_is_view_only(self) -> None: wallet.is_view_only() assert exc_info.value.code == -13 - # Can get an attribute that the wallet has, an empty one for one that it does not have, and raise the other errors + # Can get an attribute that the wallet has, none for one that it does not have, and raise the other errors def test_get_attribute(self) -> None: with FakeMethodRpcServer() as server: wallet: MoneroWalletRpc = MoneroWalletRpc(server.uri) @@ -194,7 +194,7 @@ def test_get_attribute(self) -> None: assert wallet.get_attribute("key") == "stored" server.set_method_error("get_attribute", CODE_ATTRIBUTE_NOT_FOUND, "Attribute not found") - assert wallet.get_attribute("key") == "" + assert wallet.get_attribute("key") is None server.set_method_error("get_attribute", CODE_UNKNOWN_ERROR, "Failed") with pytest.raises(MoneroRpcError) as exc_info: