Skip to content
13 changes: 12 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -85,17 +85,21 @@
"armhf",
"armv",
"autoremove",
"autouse",
"backlink",
"badpassword",
"banhammer",
"beefdead",
"behaviour",
"bitmonero",
"blobdata",
"blockhashing",
"blocktemplate",
"buildflags",
"buildopts",
"buildpackage",
"CFLAGS",
"CLSAGs",
"conftest",
"cpus",
"Cryptonote",
Expand Down Expand Up @@ -150,12 +154,14 @@
"OBJCXXFLAGS",
"ohhai",
"OMZG",
"peerlist",
"posonlyargs",
"pubkeys",
"pybind",
"pytest",
"qttools",
"rapidjson",
"rctsig",
"REGTEST",
"repointed",
"repoints",
Expand All @@ -164,9 +170,11 @@
"rescan",
"rescans",
"ringdb",
"RLIMIT",
"rockstar",
"RUSAGE",
"scikit",
"setrlimit",
"shlibdeps",
"stagenet",
"stubgen",
Expand All @@ -182,11 +190,14 @@
"unfound",
"unmixable",
"unrelayed",
"varint",
"vout",
"wijqwnn",
"wipeable",
"woodser",
"wrongpass",
"wronguser"
"wronguser",
"xfail",
"xfails"
]
}
61 changes: 61 additions & 0 deletions tests/common/monero_utils/test_binary_blocks_errors.py
Original file line number Diff line number Diff line change
@@ -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
191 changes: 191 additions & 0 deletions tests/daemon/test_rpc_client.py
Original file line number Diff line number Diff line change
@@ -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"

Check warning on line 162 in tests/daemon/test_rpc_client.py

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

tests/daemon/test_rpc_client.py#L162

Probable insecure usage of temp file/directory.
})
result = MoneroDaemonRpc(server.uri).download_update("/tmp")

Check warning on line 164 in tests/daemon/test_rpc_client.py

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

tests/daemon/test_rpc_client.py#L164

Probable insecure usage of temp file/directory.
assert result.is_update_available is True
assert result.version == "1.2.3"
assert result.download_path == "/tmp/monero-1.2.3.tar.bz2"

Check warning on line 167 in tests/daemon/test_rpc_client.py

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

tests/daemon/test_rpc_client.py#L167

Probable insecure usage of temp file/directory.

# 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
Loading
Loading