diff --git a/CMakeLists.txt b/CMakeLists.txt index 62275815..55d58305 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -234,6 +234,11 @@ if (Boost_VERSION_STRING VERSION_LESS 1.69.0) list(APPEND BOOST_COMPONENTS system) endif() +# Boost Regex is header-only since 1.84. monero-project uses it, and before that it is a library that the module has to link +if (Boost_VERSION_STRING VERSION_LESS 1.84.0) + list(APPEND BOOST_COMPONENTS regex) +endif() + find_package(Boost ${BOOST_MIN_VER} QUIET REQUIRED COMPONENTS ${BOOST_COMPONENTS}) message(STATUS "Boost components: ${BOOST_COMPONENTS}") message(STATUS "Using Boost include dir at ${Boost_INCLUDE_DIR}") diff --git a/README.md b/README.md index 3714c76b..0e64875c 100644 --- a/README.md +++ b/README.md @@ -271,6 +271,16 @@ For example: `export LD_PRELOAD=/path/to/libjemalloc.so.2` then run your app. It ```bash pytest -m unit ``` + + The wallet tests are in [tests/wallet](tests/wallet), a file for each topic (`test_sweep.py`, `test_txs.py`, `test_outputs.py`...). Each file has a base class with the tests that every wallet should pass, and a class for each wallet type (`TestMoneroWalletFullSweep`, `TestMoneroWalletRpcSweep`, `TestMoneroWalletKeysSweep`) with what that type does differently. To run one topic, or one wallet type: + ```bash + pytest tests/wallet/test_sweep.py + pytest tests/wallet -k Rpc + ``` + + The daemon tests are split in the same way: [tests/daemon/rpc](tests/daemon/rpc) has the integration tests of the rpc daemon (a file for each topic, such as `test_blocks.py`, `test_tx_pool.py` and `test_peers.py`), [tests/daemon/model](tests/daemon/model) the unit tests of the daemon models, grouped by model, and [tests/daemon/test_interface.py](tests/daemon/test_interface.py) the ones of the daemon interface. + + The wallet models are tested in [tests/wallet/model](tests/wallet/model) (a file for each kind of model: queries, transfers, outputs, accounts...), the calls of the wallet interface in [tests/wallet/test_interface.py](tests/wallet/test_interface.py), and the tests of what is not about a wallet or a daemon, such as the rpc connection, in [tests/common](tests/common), where the tests of `MoneroUtils` are split by topic in [tests/common/monero_utils](tests/common/monero_utils). 7. Cleanup docker test environment ```bash docker compose -f tests/docker-compose.yml down -v diff --git a/src/cpp/daemon/py_monero_daemon_bindings.cpp b/src/cpp/daemon/py_monero_daemon_bindings.cpp index 2648e6fe..d988794c 100644 --- a/src/cpp/daemon/py_monero_daemon_bindings.cpp +++ b/src/cpp/daemon/py_monero_daemon_bindings.cpp @@ -595,7 +595,7 @@ void py_monero_bind_daemon(py::module_& m, PyMoneroTypes& t) { .def(py::init<>()) .def("add_listener", [](monero_daemon& self, monero_daemon_listener& listener) { MONERO_CATCH_AND_RETHROW(self.add_listener(listener)); - }, py::arg("listener"), py::call_guard()) + }, py::arg("listener"), py::keep_alive<1, 2>(), py::call_guard()) .def("remove_listener", [](monero_daemon& self, monero_daemon_listener& listener) { MONERO_CATCH_AND_RETHROW(self.remove_listener(listener)); }, py::arg("listener"), py::call_guard()) @@ -851,8 +851,12 @@ void py_monero_bind_daemon(py::module_& m, PyMoneroTypes& t) { // monero_daemon_rpc t.py_monero_daemon_rpc - .def(py::init&>(), py::arg("rpc"), py::call_guard()) - .def(py::init&>(), py::arg("uri"), py::arg("username") = "", py::arg("password") = "", py::arg("proxy_uri") = "", py::arg("zmq_uri") = "", py::arg("timeout_ms") = py::none(), py::call_guard()) + .def(py::init([](const std::shared_ptr& rpc) { + return make_gil_free_holder(new monero_daemon_rpc(rpc)); + }), py::arg("rpc"), py::call_guard()) + .def(py::init([](const std::string& uri, const std::string& username, const std::string& password, const std::string& proxy_uri, const std::string& zmq_uri, const boost::optional& timeout) { + return make_gil_free_holder(new monero_daemon_rpc(uri, username, password, proxy_uri, zmq_uri, timeout)); + }), py::arg("uri"), py::arg("username") = "", py::arg("password") = "", py::arg("proxy_uri") = "", py::arg("zmq_uri") = "", py::arg("timeout_ms") = py::none(), py::call_guard()) .def("get_rpc_connection", [](const monero_daemon_rpc& self) { MONERO_CATCH_AND_RETHROW(self.get_rpc_connection()); }) diff --git a/src/cpp/py_monero_types.h b/src/cpp/py_monero_types.h index 458871b9..507e3809 100644 --- a/src/cpp/py_monero_types.h +++ b/src/cpp/py_monero_types.h @@ -79,6 +79,27 @@ PYBIND11_MAKE_OPAQUE(VectorUint64); #include "wallet/monero_wallet_full.h" #include "utils/py_monero_utils.h" +// The destructor of a daemon or of a wallet waits for the thread of its poller to finish, and that thread can be calling a listener of +// python, which needs the GIL. A python object is destroyed with the GIL, so the destructor and the thread waited for each wait for the other +// one and the process stays stuck. The holders of these objects release the GIL to delete them. +struct gil_free_delete { + template + void operator()(T* ptr) const { + // the GIL is not held when the last reference is dropped by a thread of c++ + if (PyGILState_Check()) { + py::gil_scoped_release release; + delete ptr; + } else { + delete ptr; + } + } +}; + +template +std::shared_ptr make_gil_free_holder(T* ptr) { + return std::shared_ptr(ptr, gil_free_delete()); +} + #define MONERO_CATCH_AND_RETHROW(expr) \ try { \ return expr; \ diff --git a/src/cpp/wallet/py_monero_wallet_bindings.cpp b/src/cpp/wallet/py_monero_wallet_bindings.cpp index 75bf629d..63be0d16 100644 --- a/src/cpp/wallet/py_monero_wallet_bindings.cpp +++ b/src/cpp/wallet/py_monero_wallet_bindings.cpp @@ -695,7 +695,7 @@ void py_monero_bind_wallet(py::module_& m, PyMoneroTypes& t) { }, py::arg("year"), py::arg("month"), py::arg("day"), py::call_guard()) .def("add_listener", [](PyMoneroWallet& self, monero_wallet_listener& listener) { MONERO_CATCH_AND_RETHROW(self.add_listener(listener)); - }, py::arg("listener"), py::call_guard()) + }, py::arg("listener"), py::keep_alive<1, 2>(), py::call_guard()) .def("remove_listener", [](PyMoneroWallet& self, monero_wallet_listener& listener) { MONERO_CATCH_AND_RETHROW(self.remove_listener(listener)); }, py::arg("listener"), py::call_guard()) @@ -1064,13 +1064,13 @@ void py_monero_bind_wallet(py::module_& m, PyMoneroTypes& t) { // monero_wallet_keys t.py_monero_wallet_keys .def_static("create_wallet_random", [](const monero_wallet_config& config) { - MONERO_CATCH_AND_RETHROW(monero_wallet_keys::create_wallet_random(config)); + MONERO_CATCH_AND_RETHROW(make_gil_free_holder(monero_wallet_keys::create_wallet_random(config))); }, py::arg("config"), py::call_guard()) .def_static("create_wallet_from_seed", [](const monero_wallet_config& config) { - MONERO_CATCH_AND_RETHROW(monero_wallet_keys::create_wallet_from_seed(config)); + MONERO_CATCH_AND_RETHROW(make_gil_free_holder(monero_wallet_keys::create_wallet_from_seed(config))); }, py::arg("config"), py::call_guard()) .def_static("create_wallet_from_keys", [](const monero_wallet_config& config) { - MONERO_CATCH_AND_RETHROW(monero_wallet_keys::create_wallet_from_keys(config)); + MONERO_CATCH_AND_RETHROW(make_gil_free_holder(monero_wallet_keys::create_wallet_from_keys(config))); }, py::arg("config"), py::call_guard()) .def_static("get_seed_languages", []() { MONERO_CATCH_AND_RETHROW(monero_wallet_keys::get_seed_languages()); @@ -1082,13 +1082,13 @@ void py_monero_bind_wallet(py::module_& m, PyMoneroTypes& t) { MONERO_CATCH_AND_RETHROW(monero_wallet_full::wallet_exists(path)); }, py::arg("path"), py::call_guard()) .def_static("open_wallet", [](const std::string& path, const std::string& password, monero_network_type nettype, bool regtest) { - MONERO_CATCH_AND_RETHROW(monero_wallet_full::open_wallet(path, password, nettype, regtest)); + MONERO_CATCH_AND_RETHROW(make_gil_free_holder(monero_wallet_full::open_wallet(path, password, nettype, regtest))); }, py::arg("path"), py::arg("password"), py::arg("nettype"), py::arg("regtest") = false, py::call_guard()) .def_static("open_wallet_data", [](const std::string& password, monero_network_type nettype, const std::string& keys_data, const std::string& cache_data, const std::shared_ptr& daemon_connection, bool regtest) { - MONERO_CATCH_AND_RETHROW(monero_wallet_full::open_wallet_data(password, nettype, keys_data, cache_data, daemon_connection, nullptr, regtest)); + MONERO_CATCH_AND_RETHROW(make_gil_free_holder(monero_wallet_full::open_wallet_data(password, nettype, keys_data, cache_data, daemon_connection, nullptr, regtest))); }, py::arg("password"), py::arg("nettype"), py::arg("keys_data"), py::arg("cache_data"), py::arg("daemon_connection") = py::none(), py::arg("regtest") = false, py::call_guard()) .def_static("create_wallet", [](const monero_wallet_config& config) { - MONERO_CATCH_AND_RETHROW(monero_wallet_full::create_wallet(config)); + MONERO_CATCH_AND_RETHROW(make_gil_free_holder(monero_wallet_full::create_wallet(config))); }, py::arg("config"), py::call_guard()) .def_static("get_seed_languages", []() { MONERO_CATCH_AND_RETHROW(monero_wallet_full::get_seed_languages()); @@ -1105,8 +1105,12 @@ void py_monero_bind_wallet(py::module_& m, PyMoneroTypes& t) { // monero_wallet_rpc t.py_monero_wallet_rpc - .def(py::init&>(), py::arg("rpc_connection"), py::call_guard()) - .def(py::init&>(), py::arg("uri") = "", py::arg("username") = "", py::arg("password") = "", py::arg("proxy_uri") = "", py::arg("zmq_uri") = "", py::arg("timeout_ms") = py::none(), py::call_guard()) + .def(py::init([](const std::shared_ptr& rpc_connection) { + return make_gil_free_holder(new monero_wallet_rpc(rpc_connection)); + }), py::arg("rpc_connection"), py::call_guard()) + .def(py::init([](const std::string& uri, const std::string& username, const std::string& password, const std::string& proxy_uri, const std::string& zmq_uri, const boost::optional& timeout) { + return make_gil_free_holder(new monero_wallet_rpc(uri, username, password, proxy_uri, zmq_uri, timeout)); + }), py::arg("uri") = "", py::arg("username") = "", py::arg("password") = "", py::arg("proxy_uri") = "", py::arg("zmq_uri") = "", py::arg("timeout_ms") = py::none(), py::call_guard()) .def("create_wallet", [](monero_wallet_rpc& self, const std::shared_ptr& config) { MONERO_CATCH_AND_RETHROW(self.create_wallet(config)); }, py::arg("config"), py::call_guard()) diff --git a/tests/common/__init__.py b/tests/common/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/common/monero_utils/__init__.py b/tests/common/monero_utils/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/common/monero_utils/base_test_monero_utils.py b/tests/common/monero_utils/base_test_monero_utils.py new file mode 100644 index 00000000..82454139 --- /dev/null +++ b/tests/common/monero_utils/base_test_monero_utils.py @@ -0,0 +1,53 @@ +from __future__ import annotations + +import logging +from configparser import ConfigParser + +import pytest + +from utils import AddressBook, BaseTestClass, KeysBook + +logger: logging.Logger = logging.getLogger("TestMoneroUtils") + + +class BaseTestMoneroUtils(BaseTestClass): + """Monero utilities unit tests.""" + + class Config: + """Utils tests configuration.""" + mainnet: AddressBook = AddressBook() + """Mainnet address book.""" + testnet: AddressBook = AddressBook() + """Testnet address book.""" + stagenet: AddressBook = AddressBook() + """Stagenet address book.""" + keys: KeysBook = KeysBook() + """Wallet keys book.""" + serialization_msg: str = '' + """Message to serialize.""" + + @classmethod + def parse(cls, parser: ConfigParser) -> BaseTestMoneroUtils.Config: + """Parse utils tests configuration. + + :param ConfigParser parser: configuration parser. + :returns BaseTestMoneroUtils.Config: parsed test utils configuration. + """ + config: BaseTestMoneroUtils.Config = cls() + # check section + assert parser.has_section("serialization"), "Section [serialization] not found in test config" + # load address books + config.mainnet = AddressBook.parse(parser, "mainnet") + config.testnet = AddressBook.parse(parser, "testnet") + config.stagenet = AddressBook.parse(parser, "stagenet") + # load keys book + config.keys = KeysBook.parse(parser) + config.serialization_msg = parser.get("serialization", "msg") + return config + + @pytest.fixture(scope="class") + @classmethod + def config(cls) -> BaseTestMoneroUtils.Config: + parser: ConfigParser = ConfigParser() + parser.read('tests/config/test_monero_utils.ini') + return BaseTestMoneroUtils.Config.parse(parser) diff --git a/tests/common/monero_utils/test_amounts.py b/tests/common/monero_utils/test_amounts.py new file mode 100644 index 00000000..de55f776 --- /dev/null +++ b/tests/common/monero_utils/test_amounts.py @@ -0,0 +1,100 @@ +from __future__ import annotations + +import logging + +import pytest +from monero import MoneroUtils + +from utils import BaseTestClass + +logger: logging.Logger = logging.getLogger("TestMoneroUtilsAmounts") + + +@pytest.mark.unit +class TestMoneroUtilsAmounts(BaseTestClass): + """Monero utilities amounts unit tests.""" + + # Can convert between XMR and atomic units + def test_atomic_unit_conversion(self) -> None: + assert 1000000000000 == MoneroUtils.xmr_to_atomic_units(1) + assert 1 == MoneroUtils.atomic_units_to_xmr(1000000000000) + assert 1000000000 == MoneroUtils.xmr_to_atomic_units(0.001) + assert 0.001 == MoneroUtils.atomic_units_to_xmr(1000000000) + assert 250000000000 == MoneroUtils.xmr_to_atomic_units(0.25) + assert 0.25 == MoneroUtils.atomic_units_to_xmr(250000000000) + assert 1250000000000 == MoneroUtils.xmr_to_atomic_units(1.25) + assert 1.25 == MoneroUtils.atomic_units_to_xmr(1250000000000) + assert 2796726190000 == MoneroUtils.xmr_to_atomic_units(2.79672619) + assert 2.79672619 == MoneroUtils.atomic_units_to_xmr(2796726190000) + assert 2796726190001 == MoneroUtils.xmr_to_atomic_units(2.796726190001) + assert 2.796726190001 == MoneroUtils.atomic_units_to_xmr(2796726190001) + assert 2796726189999 == MoneroUtils.xmr_to_atomic_units(2.796726189999) + assert 2.796726189999 == MoneroUtils.atomic_units_to_xmr(2796726189999) + assert 2796726180000 == MoneroUtils.xmr_to_atomic_units(2.79672618) + assert 2.79672618 == MoneroUtils.atomic_units_to_xmr(2796726180000) + + # xmr_to_atomic_units(0.0) and negative zero are valid, not errors + def test_xmr_to_atomic_units_zero(self) -> None: + assert 0 == MoneroUtils.xmr_to_atomic_units(0.0) + # -0.0 < 0 is False in IEEE 754, so it must not be rejected by the + # "amount must be non-negative" check + assert 0 == MoneroUtils.xmr_to_atomic_units(-0.0) + + # Amounts smaller than half an atomic unit (1e-12 XMR) round down to 0 + def test_xmr_to_atomic_units_rounds_down_to_zero(self) -> None: + assert 0 == MoneroUtils.xmr_to_atomic_units(1e-13) + assert 0 == MoneroUtils.xmr_to_atomic_units(4e-13) + + # xmr_to_atomic_units() rounds the underlying long double * 1e12 product to + # the nearest atomic unit (away from zero on an exact .5). Decimal literals + # ending in .5e-12 are not necessarily exact halves once represented as a + # double, so which way they round depends on whether the closest double is + # a hair above or below the nominal decimal value, and that itself can + # depend on the platform's "long double" precision (80-bit extended on + # x86_64 Linux/glibc, but identical to a plain 64-bit double on Apple + # Silicon/macOS), so the same literal can round differently on different + # platforms. This is inherent to IEEE 754, not an inconsistency in + # xmr_to_atomic_units() itself, assert the result lands on one of the + # two atomic units the value sits between, not a specific platform's tie-break. + def test_xmr_to_atomic_units_half_atomic_unit_rounding(self) -> None: + cases: list[tuple[float, int, int]] = [ + (0.5e-12, 0, 1), + (1.5e-12, 1, 2), + (2.5e-12, 2, 3), + (3.5e-12, 3, 4), + ] + for amount_xmr, floor_atomic, ceil_atomic in cases: + actual: int = MoneroUtils.xmr_to_atomic_units(amount_xmr) + logger.debug(f"xmr_to_atomic_units({amount_xmr!r}) = {actual} (expected {floor_atomic} or {ceil_atomic})") + assert actual in (floor_atomic, ceil_atomic), f"xmr_to_atomic_units({amount_xmr!r}) == {actual}, expected {floor_atomic} or {ceil_atomic}" + + # amount_xmr must be finite and non-negative + @pytest.mark.parametrize("amount_xmr", [-1.0, -0.0000000001, float("nan"), float("inf"), float("-inf")]) + def test_xmr_to_atomic_units_invalid_amount(self, amount_xmr: float) -> None: + with pytest.raises(RuntimeError, match="amount must be a finite, non-negative number"): + MoneroUtils.xmr_to_atomic_units(amount_xmr) + + # amounts whose rounded atomic-unit value would overflow uint64_t are rejected + # rather than silently wrapping or invoking undefined behavior on the cast + def test_xmr_to_atomic_units_overflow(self) -> None: + # UINT64_MAX atomic units is ~18446744.0737... XMR; comfortably over that + # (with margin for float imprecision) must raise + with pytest.raises(RuntimeError, match="amount exceeds maximum representable atomic units"): + MoneroUtils.xmr_to_atomic_units(18446745.0) + with pytest.raises(RuntimeError, match="amount exceeds maximum representable atomic units"): + MoneroUtils.xmr_to_atomic_units(2e22) + + # values comfortably below the uint64_t boundary succeed + def test_xmr_to_atomic_units_near_uint64_max_boundary(self) -> None: + uint64_max: int = 2 ** 64 - 1 + boundary_xmr: float = uint64_max / 1e12 # ~18446744.073709551615 XMR + margin_xmr: float = 1.0 + + safely_below: float = boundary_xmr - margin_xmr + below: int = MoneroUtils.xmr_to_atomic_units(safely_below) + logger.debug(f"xmr_to_atomic_units({safely_below!r}) = {below} (uint64_max = {uint64_max})") + assert below <= uint64_max + + safely_above: float = boundary_xmr + margin_xmr + with pytest.raises(RuntimeError, match="amount exceeds maximum representable atomic units"): + MoneroUtils.xmr_to_atomic_units(safely_above) diff --git a/tests/common/monero_utils/test_blocks.py b/tests/common/monero_utils/test_blocks.py new file mode 100644 index 00000000..d5861b89 --- /dev/null +++ b/tests/common/monero_utils/test_blocks.py @@ -0,0 +1,239 @@ +from __future__ import annotations + +import logging + +import pytest +from monero import MoneroBlock, MoneroIncomingTransfer, MoneroOutputWallet, MoneroTxWallet, MoneroUtils + +from utils import BaseTestClass + +logger: logging.Logger = logging.getLogger("TestMoneroUtilsBlocks") + + +@pytest.mark.unit +class TestMoneroUtilsBlocks(BaseTestClass): + """Monero utilities blocks unit tests.""" + + def test_get_blocks_from_txs_dedup_and_order(self) -> None: + block1: MoneroBlock = MoneroBlock() + block1.height = 100 + block2: MoneroBlock = MoneroBlock() + block2.height = 200 + + tx1: MoneroTxWallet = MoneroTxWallet() + tx1.hash = "a" * 64 + tx1.block = block1 + + tx2: MoneroTxWallet = MoneroTxWallet() + tx2.hash = "b" * 64 + tx2.block = block2 + + tx3: MoneroTxWallet = MoneroTxWallet() # shares block1 with tx1 + tx3.hash = "c" * 64 + tx3.block = block1 + + blocks: list[MoneroBlock] = MoneroUtils.get_blocks_from_txs([tx1, tx2, tx3]) + assert len(blocks) == 2 # block1 deduplicated despite appearing twice + assert blocks[0] is block1 # blocks are returned in first-seen order + assert blocks[1] is block2 + + def test_get_blocks_from_txs_unconfirmed_placeholder(self) -> None: + tx1: MoneroTxWallet = MoneroTxWallet() + tx1.hash = "a" * 64 + tx2: MoneroTxWallet = MoneroTxWallet() + tx2.hash = "b" * 64 + assert tx1.block is None and tx2.block is None + + blocks: list[MoneroBlock] = MoneroUtils.get_blocks_from_txs([tx1, tx2]) + + # unconfirmed (blockless) txs are grouped under one shared placeholder block + assert len(blocks) == 1 + placeholder: MoneroBlock = blocks[0] + assert placeholder.height is None + assert len(placeholder.txs) == 2 + + # side effect: get_blocks_from_txs() mutates its inputs, attaching each + # unconfirmed tx to the placeholder block it creates + assert tx1.block is placeholder + assert tx2.block is placeholder + + def test_get_blocks_from_txs_mixed_confirmed_and_unconfirmed(self) -> None: + block: MoneroBlock = MoneroBlock() + block.height = 100 + confirmed: MoneroTxWallet = MoneroTxWallet() + confirmed.hash = "a" * 64 + confirmed.block = block + + unconfirmed1: MoneroTxWallet = MoneroTxWallet() + unconfirmed1.hash = "b" * 64 + unconfirmed2: MoneroTxWallet = MoneroTxWallet() + unconfirmed2.hash = "c" * 64 + + blocks: list[MoneroBlock] = MoneroUtils.get_blocks_from_txs([confirmed, unconfirmed1, unconfirmed2]) + assert len(blocks) == 2 # the real block, plus one shared unconfirmed placeholder + assert blocks[0] is block + assert blocks[1].height is None + assert unconfirmed1.block is unconfirmed2.block is blocks[1] + + def test_get_blocks_from_txs_empty(self) -> None: + assert MoneroUtils.get_blocks_from_txs([]) == [] + + def test_get_blocks_from_transfers_dedup_and_order(self) -> None: + block1: MoneroBlock = MoneroBlock() + block1.height = 100 + block2: MoneroBlock = MoneroBlock() + block2.height = 200 + + t1: MoneroIncomingTransfer = MoneroIncomingTransfer() + t1.tx = MoneroTxWallet() + t1.tx.hash = "a" * 64 + t1.tx.block = block1 + + t2: MoneroIncomingTransfer = MoneroIncomingTransfer() + t2.tx = MoneroTxWallet() + t2.tx.hash = "b" * 64 + t2.tx.block = block2 + + t3: MoneroIncomingTransfer = MoneroIncomingTransfer() # tx shares block1 with t1 + t3.tx = MoneroTxWallet() + t3.tx.hash = "c" * 64 + t3.tx.block = block1 + + blocks: list[MoneroBlock] = MoneroUtils.get_blocks_from_transfers([t1, t2, t3]) + assert len(blocks) == 2 + assert blocks[0] is block1 + assert blocks[1] is block2 + + def test_get_blocks_from_transfers_unconfirmed_placeholder(self) -> None: + t1: MoneroIncomingTransfer = MoneroIncomingTransfer() + t1.tx = MoneroTxWallet() + t1.tx.hash = "a" * 64 + t2: MoneroIncomingTransfer = MoneroIncomingTransfer() + t2.tx = MoneroTxWallet() + t2.tx.hash = "b" * 64 + assert t1.tx.block is None and t2.tx.block is None + + blocks: list[MoneroBlock] = MoneroUtils.get_blocks_from_transfers([t1, t2]) + assert len(blocks) == 1 + placeholder: MoneroBlock = blocks[0] + assert placeholder.height is None + + # side effect: mutates transfer.tx.block, same as get_blocks_from_txs() + assert t1.tx.block is placeholder + assert t2.tx.block is placeholder + + def test_get_blocks_from_transfers_mixed_confirmed_and_unconfirmed(self) -> None: + block: MoneroBlock = MoneroBlock() + block.height = 100 + confirmed: MoneroIncomingTransfer = MoneroIncomingTransfer() + confirmed.tx = MoneroTxWallet() + confirmed.tx.hash = "a" * 64 + confirmed.tx.block = block + + unconfirmed1: MoneroIncomingTransfer = MoneroIncomingTransfer() + unconfirmed1.tx = MoneroTxWallet() + unconfirmed1.tx.hash = "b" * 64 + unconfirmed2: MoneroIncomingTransfer = MoneroIncomingTransfer() + unconfirmed2.tx = MoneroTxWallet() + unconfirmed2.tx.hash = "c" * 64 + + blocks: list[MoneroBlock] = MoneroUtils.get_blocks_from_transfers([confirmed, unconfirmed1, unconfirmed2]) + assert len(blocks) == 2 # the real block, plus one shared unconfirmed placeholder + assert blocks[0] is block + assert blocks[1].height is None + assert unconfirmed1.tx.block is unconfirmed2.tx.block is blocks[1] + + def test_get_blocks_from_transfers_missing_tx_raises(self) -> None: + # a transfer with no tx set is a legitimate, reachable state (it's just + # never assigned); get_blocks_from_transfers() must raise a catchable + # exception, not dereference transfer.tx and segfault + transfer: MoneroIncomingTransfer = MoneroIncomingTransfer() + transfer.amount = 500000 + with pytest.raises(RuntimeError) as exc_info: + MoneroUtils.get_blocks_from_transfers([transfer]) + assert str(exc_info.value) == "Transfer has no tx" + + def test_get_blocks_from_transfers_missing_tx_raises_after_partial_mutation(self) -> None: + # get_blocks_from_transfers() is not transactional: a transfer earlier + # in the list is already mutated (attached to a placeholder block) + # before a later, invalid transfer aborts the whole call + good: MoneroIncomingTransfer = MoneroIncomingTransfer() + good.tx = MoneroTxWallet() + good.tx.hash = "a" * 64 + assert good.tx.block is None + + bad: MoneroIncomingTransfer = MoneroIncomingTransfer() # no tx + with pytest.raises(RuntimeError): + MoneroUtils.get_blocks_from_transfers([good, bad]) + + assert good.tx.block is not None + assert good.tx.block.height is None + + def test_get_blocks_from_transfers_empty(self) -> None: + assert MoneroUtils.get_blocks_from_transfers([]) == [] + + def test_get_blocks_from_outputs_dedup_and_order(self) -> None: + block1: MoneroBlock = MoneroBlock() + block1.height = 100 + block2: MoneroBlock = MoneroBlock() + block2.height = 200 + + tx1: MoneroTxWallet = MoneroTxWallet() + tx1.hash = "a" * 64 + tx1.block = block1 + tx2: MoneroTxWallet = MoneroTxWallet() + tx2.hash = "b" * 64 + tx2.block = block2 + + o1: MoneroOutputWallet = MoneroOutputWallet() + o1.tx = tx1 + o2: MoneroOutputWallet = MoneroOutputWallet() + o2.tx = tx2 + o3: MoneroOutputWallet = MoneroOutputWallet() # tx shares block1 with o1 + o3.tx = tx1 + + blocks: list[MoneroBlock] = MoneroUtils.get_blocks_from_outputs([o1, o2, o3]) + assert len(blocks) == 2 + assert blocks[0] is block1 + assert blocks[1] is block2 + + def test_get_blocks_from_outputs_unconfirmed_raises(self) -> None: + # unlike get_blocks_from_txs()/get_blocks_from_transfers(), an + # unconfirmed (blockless) output's tx does not get a placeholder + # block -- it raises instead + output: MoneroOutputWallet = MoneroOutputWallet() + output.tx = MoneroTxWallet() + output.tx.hash = "a" * 64 + assert output.tx.block is None + + with pytest.raises(RuntimeError, match="Need to handle unconfirmed output"): + MoneroUtils.get_blocks_from_outputs([output]) + + def test_get_blocks_from_outputs_unconfirmed_raises_after_earlier_match(self) -> None: + # unlike get_blocks_from_transfers(), get_blocks_from_outputs() never mutates its inputs + block: MoneroBlock = MoneroBlock() + block.height = 100 + confirmed_tx: MoneroTxWallet = MoneroTxWallet() + confirmed_tx.hash = "a" * 64 + confirmed_tx.block = block + good: MoneroOutputWallet = MoneroOutputWallet() + good.tx = confirmed_tx + + bad: MoneroOutputWallet = MoneroOutputWallet() + bad.tx = MoneroTxWallet() + bad.tx.hash = "b" * 64 # unconfirmed + + with pytest.raises(RuntimeError, match="Need to handle unconfirmed output"): + MoneroUtils.get_blocks_from_outputs([good, bad]) + + def test_get_blocks_from_outputs_missing_tx_raises(self) -> None: + # same as get_blocks_from_transfers(): output.tx is a legitimate but + # unchecked null; must raise rather than dereference and segfault + output: MoneroOutputWallet = MoneroOutputWallet() + output.amount = 1000000 + with pytest.raises(RuntimeError) as exc_info: + MoneroUtils.get_blocks_from_outputs([output]) + assert str(exc_info.value) == "Output has no tx" + + def test_get_blocks_from_outputs_empty(self) -> None: + assert MoneroUtils.get_blocks_from_outputs([]) == [] diff --git a/tests/common/monero_utils/test_general.py b/tests/common/monero_utils/test_general.py new file mode 100644 index 00000000..be950337 --- /dev/null +++ b/tests/common/monero_utils/test_general.py @@ -0,0 +1,66 @@ +from __future__ import annotations + +import logging +import re + +import pytest +from monero import MoneroIntegratedAddress, MoneroNetworkType, MoneroUtils +from pathlib import Path + +from .base_test_monero_utils import BaseTestMoneroUtils + +logger: logging.Logger = logging.getLogger("TestMoneroUtilsGeneral") + + +@pytest.mark.unit +class TestMoneroUtilsGeneral(BaseTestMoneroUtils): + """Monero utilities general unit tests.""" + + # Can get integrated addresses + def test_get_integrated_address(self, config: BaseTestMoneroUtils.Config) -> None: + primary_address: str = config.stagenet.primary_address_4 + subaddress: str = config.stagenet.subaddress_4 + payment_id: str = "03284e41c342f036" + network_type: MoneroNetworkType = MoneroNetworkType.STAGENET + + # get integrated address with randomly generated payment id + integrated_address: MoneroIntegratedAddress = MoneroUtils.get_integrated_address(network_type, primary_address, "") + assert primary_address == integrated_address.standard_address + assert 16 == len(integrated_address.payment_id) + assert 106 == len(integrated_address.integrated_address) + + # get integrated address with specific payment id + integrated_address = MoneroUtils.get_integrated_address(network_type, primary_address, payment_id) + assert primary_address == integrated_address.standard_address + assert payment_id == integrated_address.payment_id + assert 106 == len(integrated_address.integrated_address) + + # get integrated address with subaddress + integrated_address = MoneroUtils.get_integrated_address(network_type, subaddress, payment_id) + assert subaddress == integrated_address.standard_address + assert payment_id == integrated_address.payment_id + assert 106 == len(integrated_address.integrated_address) + + # get integrated address with invalid payment id + try: + MoneroUtils.get_integrated_address(network_type, primary_address, "123") + raise Exception("Getting integrated address with invalid payment id should have failed") + except Exception as err: + assert "Invalid payment id" == str(err) + + # Can get version, which is the one declared in pyproject.toml + def test_get_version(self) -> None: + version: str = MoneroUtils.get_version() + logger.debug(f"Testing monero-python version: {version}") + assert version != "", "Version is empty" + # the repository root, two folders above tests/ and three above this file: the tests are not in tests/ itself anymore + root: Path = next(p for p in Path(__file__).resolve().parents if (p / "pyproject.toml").is_file()) + pyproject: str = (root / "pyproject.toml").read_text(encoding="utf-8") + declared = re.search(r'^version = "(\d+\.\d+\.\d+)"$', pyproject, re.MULTILINE) + assert declared is not None, "Version not found in pyproject.toml" + assert version == declared.group(1) + + # Can get ring size + def test_get_ring_size(self) -> None: + size: int = MoneroUtils.get_ring_size() + assert size == 16 diff --git a/tests/common/monero_utils/test_memory.py b/tests/common/monero_utils/test_memory.py new file mode 100644 index 00000000..9fc772a2 --- /dev/null +++ b/tests/common/monero_utils/test_memory.py @@ -0,0 +1,190 @@ +from __future__ import annotations + +import gc +import logging +import subprocess +import sys + +import pytest +from monero import ( + MoneroBlock, + MoneroIncomingTransfer, + MoneroOutputWallet, + MoneroTx, + MoneroTxWallet, + MoneroUtils, +) + +from utils import BaseTestClass + +if sys.platform != "win32": + import resource + +logger: logging.Logger = logging.getLogger("TestMoneroUtilsMemory") + + +@pytest.mark.unit +class TestMoneroUtilsMemory(BaseTestClass): + """Monero utilities memory unit tests.""" + + def test_free_block_breaks_tx_backlink(self) -> None: + block: MoneroBlock = MoneroBlock() + block.height = 100 + tx: MoneroTxWallet = MoneroTxWallet() + tx.hash = "a" * 64 + tx.block = block + block.txs = [tx] + + MoneroUtils.free(block) + assert tx.block is None + + def test_free_blocks_list(self) -> None: + block1: MoneroBlock = MoneroBlock() + block1.height = 1 + tx1: MoneroTxWallet = MoneroTxWallet() + tx1.hash = "a" * 64 + tx1.block = block1 + block1.txs = [tx1] + + block2: MoneroBlock = MoneroBlock() + block2.height = 2 + tx2: MoneroTxWallet = MoneroTxWallet() + tx2.hash = "b" * 64 + tx2.block = block2 + block2.txs = [tx2] + + MoneroUtils.free([block1, block2]) + assert tx1.block is None + assert tx2.block is None + + def test_free_tx_without_block_does_not_crash(self) -> None: + # free(tx) creates a throwaway placeholder block for an unconfirmed + # tx, then immediately frees it. Net no-op on tx.block, but exercises + # that code path safely + tx: MoneroTxWallet = MoneroTxWallet() + tx.hash = "a" * 64 + assert tx.block is None + MoneroUtils.free(tx) + assert tx.block is None + + def test_free_tx_with_block(self) -> None: + block: MoneroBlock = MoneroBlock() + block.height = 100 + tx: MoneroTxWallet = MoneroTxWallet() + tx.hash = "a" * 64 + tx.block = block + block.txs = [tx] + + MoneroUtils.free(tx) + assert tx.block is None + + def test_free_txs_list_confirmed_and_unconfirmed(self) -> None: + block: MoneroBlock = MoneroBlock() + block.height = 100 + confirmed: MoneroTxWallet = MoneroTxWallet() + confirmed.hash = "a" * 64 + confirmed.block = block + block.txs = [confirmed] + + unconfirmed: MoneroTxWallet = MoneroTxWallet() + unconfirmed.hash = "b" * 64 + + MoneroUtils.free([confirmed, unconfirmed]) + assert confirmed.block is None + assert unconfirmed.block is None + + def test_free_transfers_list(self) -> None: + block: MoneroBlock = MoneroBlock() + block.height = 100 + tx: MoneroTxWallet = MoneroTxWallet() + tx.hash = "a" * 64 + tx.block = block + block.txs = [tx] + + transfer: MoneroIncomingTransfer = MoneroIncomingTransfer() + transfer.tx = tx + + MoneroUtils.free([transfer]) + assert transfer.tx.block is None + + def test_free_outputs_list(self) -> None: + block: MoneroBlock = MoneroBlock() + block.height = 100 + tx: MoneroTxWallet = MoneroTxWallet() + tx.hash = "a" * 64 + tx.block = block + block.txs = [tx] + + output: MoneroOutputWallet = MoneroOutputWallet() + output.tx = tx + + MoneroUtils.free([output]) + assert output.tx.block is None + + @pytest.mark.skipif(sys.platform == "win32", reason="resource module (RSS measurement) is not available on Windows") + def test_free_breaks_reference_cycle_avoids_leak(self) -> None: + # regression guard for the leak demonstrated manually: building + # block<->tx cycles and dropping every Python reference without + # calling free() leaves the C++ shared_ptr cycle permanently + # unreachable-but-alive (confirmed: 2,000,000 such tx objects grew + # RSS by ~2.4GB with gc.collect() unable to reclaim any of it). This + # test builds a much smaller-but-still-telling batch, always calling + # free() before dropping references, and asserts memory stays roughly flat. + def rss_mb() -> float: + return resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024 + + def run_batch(rounds: int) -> None: + for _ in range(rounds): + for _ in range(50): + block: MoneroBlock = MoneroBlock() + block.height = 100 + txs: list[MoneroTx] = [] + for i in range(20): + tx: MoneroTxWallet = MoneroTxWallet() + tx.hash = "a" * 63 + str(i % 10) + tx.block = block + txs.append(tx) + block.txs = txs + MoneroUtils.free(block) + + gc.disable() + try: + run_batch(20) # unmeasured warmup: absorb one-time allocator growth + baseline: float = rss_mb() + run_batch(200) # measured: 200 * 50 * 20 = 200,000 tx objects + after: float = rss_mb() + finally: + gc.enable() + + growth_mb: float = after - baseline + logger.debug(f"RSS growth after freeing 200,000 tx objects (post-warmup): {growth_mb:.1f} MB") + # generous bound: a real leak of this shape grows ~1.2KB/tx (~240MB for + # 200,000 tx); this only needs to rule out that magnitude of leak, not + # pin down normal allocator noise + assert growth_mb < 100, f"RSS grew {growth_mb:.1f} MB after freeing 200,000 tx objects -- possible leak" + + def test_free_none_does_not_crash(self) -> None: + script: str = "import monero\nmonero.MoneroUtils.free(None)\n" + result: subprocess.CompletedProcess[str] = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, timeout=30) + logger.debug(f"subprocess exit code: {result.returncode}, stderr: {result.stderr.strip()}") + assert result.returncode == 0, ( + f"free(None) crashed the interpreter (exit code {result.returncode}) " + "instead of raising a Python exception (or being a documented no-op)" + ) + + def test_free_transfers_missing_tx_raises(self) -> None: + # free([transfers]) delegates to get_blocks_from_transfers(): a transfer + # with no tx must surface a catchable exception, not segfault + transfer: MoneroIncomingTransfer = MoneroIncomingTransfer() + transfer.amount = 500000 + with pytest.raises(RuntimeError) as exc_info: + MoneroUtils.free([transfer]) + assert str(exc_info.value) == "Transfer has no tx" + + def test_free_outputs_missing_tx_raises(self) -> None: + # free([outputs]) delegates to get_blocks_from_outputs(): same guarantee + output: MoneroOutputWallet = MoneroOutputWallet() + output.amount = 1000000 + with pytest.raises(RuntimeError) as exc_info: + MoneroUtils.free([output]) + assert str(exc_info.value) == "Output has no tx" diff --git a/tests/common/monero_utils/test_payment_uri.py b/tests/common/monero_utils/test_payment_uri.py new file mode 100644 index 00000000..92af5206 --- /dev/null +++ b/tests/common/monero_utils/test_payment_uri.py @@ -0,0 +1,146 @@ +from __future__ import annotations + +import logging + +import pytest +from monero import MoneroNetworkType, MoneroTxConfig, MoneroUtils + +from utils import WalletUtils +from .base_test_monero_utils import BaseTestMoneroUtils + +logger: logging.Logger = logging.getLogger("TestMoneroUtilsPaymentUri") + + +@pytest.mark.unit +class TestMoneroUtilsPaymentUri(BaseTestMoneroUtils): + """Monero utilities payment uri unit tests.""" + + # Can get payment uri + def test_get_payment_uri(self, config: BaseTestMoneroUtils.Config) -> None: + address: str = config.mainnet.primary_address_1 + tx_config: MoneroTxConfig = WalletUtils.build_payment_uri_config(address) + payment_uri: str = MoneroUtils.get_payment_uri(tx_config) + query: str = "tx_amount=0.250000000000&recipient_name=John%20Doe&tx_description=My%20transfer%20to%20wallet" + logger.debug(f"Testing payment uri: {payment_uri}") + assert payment_uri == f"monero:{address}?{query}" + + # Test invalid payment uri address network type + def test_payment_uri_invalid_network_type(self, config: BaseTestMoneroUtils.Config) -> None: + address: str = config.testnet.primary_address_1 + tx_config: MoneroTxConfig = WalletUtils.build_payment_uri_config(address) + with pytest.raises(Exception) as exc_info: + MoneroUtils.get_payment_uri(tx_config) + + # get_payment_uri() wraps make_uri()'s error with context, unlike e.g. validate_address() + assert str(exc_info.value) == f"Cannot make URI from supplied parameters: wrong address: {address}" + + # Test deprecated standalone payment id + def test_payment_uri_deprecated_payment_uri(self, config: BaseTestMoneroUtils.Config) -> None: + address: str = config.testnet.primary_address_1 + tx_config: MoneroTxConfig = WalletUtils.build_payment_uri_config(address) + tx_config.payment_id = "03284e41c342f03603284e41c342f03603284e41c342f03603284e41c342f036" + with pytest.raises(Exception) as exc_info: + MoneroUtils.get_payment_uri(tx_config, MoneroNetworkType.TESTNET) + + # get_payment_uri() wraps make_uri()'s error with context, unlike e.g. validate_address() + assert str(exc_info.value) == "Cannot make URI from supplied parameters: Standalone payment id deprecated, use integrated address instead" + + # Test single payment id given with an integrated address + def test_payment_uri_single_payment_id_with_integrated_address(self, config: BaseTestMoneroUtils.Config) -> None: + address: str = config.mainnet.integrated_1 + tx_config: MoneroTxConfig = WalletUtils.build_payment_uri_config(address) + tx_config.payment_id = "03284e41c342f03603284e41c342f03603284e41c342f03603284e41c342f036" + with pytest.raises(Exception) as exc_info: + MoneroUtils.get_payment_uri(tx_config) + + # get_payment_uri() wraps make_uri()'s error with context, unlike e.g. validate_address() + assert str(exc_info.value) == "Cannot make URI from supplied parameters: A single payment id is allowed" + + # Can parse a payment uri without any query string + def test_parse_payment_uri_no_query(self, config: BaseTestMoneroUtils.Config) -> None: + address: str = config.mainnet.primary_address_1 + parsed: MoneroTxConfig = MoneroUtils.parse_payment_uri(f"monero:{address}") + assert parsed.destinations[0].address == address + assert parsed.destinations[0].amount == 0 + assert parsed.recipient_name is None + assert parsed.note is None + assert parsed.payment_id is None + + # Can parse a payment uri with an empty query string + def test_parse_payment_uri_empty_query(self, config: BaseTestMoneroUtils.Config) -> None: + address: str = config.mainnet.primary_address_1 + parsed: MoneroTxConfig = MoneroUtils.parse_payment_uri(f"monero:{address}?") + assert parsed.destinations[0].address == address + + # Can parse a payment uri round trip built by get_payment_uri() + def test_parse_payment_uri_round_trip(self, config: BaseTestMoneroUtils.Config) -> None: + address: str = config.mainnet.primary_address_1 + tx_config: MoneroTxConfig = WalletUtils.build_payment_uri_config(address) + uri: str = MoneroUtils.get_payment_uri(tx_config) + parsed: MoneroTxConfig = MoneroUtils.parse_payment_uri(uri) + assert parsed.destinations[0].address == address + assert parsed.destinations[0].amount == tx_config.amount + assert parsed.recipient_name == tx_config.recipient_name + assert parsed.note == tx_config.note + + # Payment uri must use the "monero:" scheme + def test_parse_payment_uri_wrong_scheme(self, config: BaseTestMoneroUtils.Config) -> None: + address: str = config.mainnet.primary_address_1 + with pytest.raises(RuntimeError) as exc_info: + MoneroUtils.parse_payment_uri(f"bitcoin:{address}") + assert str(exc_info.value) == f'Error parsing URI: URI has wrong scheme (expected "monero:"): bitcoin:{address}' + + # Payment uri address must be valid + def test_parse_payment_uri_wrong_address(self, config: BaseTestMoneroUtils.Config) -> None: + address: str = config.mainnet.invalid_1 + with pytest.raises(RuntimeError) as exc_info: + MoneroUtils.parse_payment_uri(f"monero:{address}") + assert str(exc_info.value) == f"Error parsing URI: URI has wrong address: {address}" + + # Payment uri parameters must be "key=value" pairs + def test_parse_payment_uri_malformed_parameter(self, config: BaseTestMoneroUtils.Config) -> None: + address: str = config.mainnet.primary_address_1 + with pytest.raises(RuntimeError) as exc_info: + MoneroUtils.parse_payment_uri(f"monero:{address}?tx_amount") + assert str(exc_info.value) == "Error parsing URI: URI has wrong parameter: tx_amount" + + # Payment uri parameters must not repeat + def test_parse_payment_uri_duplicate_parameter(self, config: BaseTestMoneroUtils.Config) -> None: + address: str = config.mainnet.primary_address_1 + with pytest.raises(RuntimeError) as exc_info: + MoneroUtils.parse_payment_uri(f"monero:{address}?tx_amount=1&tx_amount=2") + assert str(exc_info.value) == "Error parsing URI: URI has more than one instance of tx_amount" + + # Payment uri tx_amount must be a valid amount + def test_parse_payment_uri_invalid_amount(self, config: BaseTestMoneroUtils.Config) -> None: + address: str = config.mainnet.primary_address_1 + with pytest.raises(RuntimeError) as exc_info: + MoneroUtils.parse_payment_uri(f"monero:{address}?tx_amount=abc") + assert str(exc_info.value) == "Error parsing URI: URI has invalid amount: abc" + + # Payment uri tx_payment_id must be a valid long payment id + def test_parse_payment_uri_invalid_payment_id(self, config: BaseTestMoneroUtils.Config) -> None: + address: str = config.mainnet.primary_address_1 + with pytest.raises(RuntimeError) as exc_info: + MoneroUtils.parse_payment_uri(f"monero:{address}?tx_payment_id=nothex") + assert str(exc_info.value) == "Error parsing URI: Invalid payment id: nothex" + + # Payment uri can carry a separate, valid tx_payment_id for a non-integrated address + def test_parse_payment_uri_valid_payment_id(self, config: BaseTestMoneroUtils.Config) -> None: + address: str = config.mainnet.primary_address_1 + payment_id: str = "a" * 64 + parsed: MoneroTxConfig = MoneroUtils.parse_payment_uri(f"monero:{address}?tx_payment_id={payment_id}") + assert parsed.payment_id == payment_id + + # Payment uri must not combine a separate tx_payment_id with an integrated address + def test_parse_payment_uri_separate_payment_id_with_integrated_address(self, config: BaseTestMoneroUtils.Config) -> None: + address: str = config.mainnet.integrated_1 + with pytest.raises(RuntimeError) as exc_info: + MoneroUtils.parse_payment_uri(f"monero:{address}?tx_payment_id={'a' * 64}") + assert str(exc_info.value) == "Error parsing URI: Separate payment id given with an integrated address" + + # Unknown payment uri parameters are silently discarded + def test_parse_payment_uri_unknown_parameter(self, config: BaseTestMoneroUtils.Config) -> None: + address: str = config.mainnet.primary_address_1 + parsed: MoneroTxConfig = MoneroUtils.parse_payment_uri(f"monero:{address}?foo=bar") + assert parsed.destinations[0].address == address diff --git a/tests/common/monero_utils/test_serialization.py b/tests/common/monero_utils/test_serialization.py new file mode 100644 index 00000000..782109b7 --- /dev/null +++ b/tests/common/monero_utils/test_serialization.py @@ -0,0 +1,92 @@ +from __future__ import annotations + +import logging +from typing import Any + +import pytest +from monero import MoneroUtils + +from .base_test_monero_utils import BaseTestMoneroUtils + +logger: logging.Logger = logging.getLogger("TestMoneroUtilsSerialization") + + +@pytest.mark.unit +class TestMoneroUtilsSerialization(BaseTestMoneroUtils): + """Monero utilities serialization unit tests.""" + + # Can serialize heights with small numbers + def test_serialize_heights_small(self) -> None: + json_map: dict[Any, Any] = { + "heights": [111, 222, 333] + } + + binary: bytes = MoneroUtils.dict_to_binary(json_map) + assert len(binary) > 0 + + json_map2: dict[Any, Any] = MoneroUtils.binary_to_dict(binary) + assert json_map == json_map2 + + # Can serialize heights with big numbers + def test_serialize_heights_big(self) -> None: + json_map: dict[Any, Any] = { + "heights": [123456, 1234567, 870987] + } + + binary: bytes = MoneroUtils.dict_to_binary(json_map) + assert len(binary) > 0 + + json_map2: dict[Any, Any] = MoneroUtils.binary_to_dict(binary) + assert json_map == json_map2 + + # can serialize height with large unsigned values + def test_serialize_large_unsigned_values(self) -> None: + big_value: int = 18446744073709551615 # UINT64_MAX + json_map: dict[Any, Any] = { + "heights": [big_value] + } + binary: bytes = MoneroUtils.dict_to_binary(json_map) + assert len(binary) > 0 + + json_map2: dict[Any, Any] = MoneroUtils.binary_to_dict(binary) + assert json_map == json_map2 + assert json_map2["heights"][0] > 0, "uint64 > INT64_MAX must not serialize as negative" + + # Can serialize jsonMap with text + def test_serialize_text_short(self, config: BaseTestMoneroUtils.Config) -> None: + assert config.serialization_msg is not None and config.serialization_msg != "" + json_map: dict[Any, Any] = { + "msg": config.serialization_msg + } + + binary: bytes = MoneroUtils.dict_to_binary(json_map) + assert len(binary) > 0 + + json_map2: dict[Any, Any] = MoneroUtils.binary_to_dict(binary) + assert json_map == json_map2 + + # Can serialize json with long text + def test_serialize_text_long(self, config: BaseTestMoneroUtils.Config) -> None: + msg: str = config.serialization_msg + json_map: dict[str, str] = { + "msg": f"{msg}\n" + + f"{msg}\n" + + f"{msg}\n" + + f"{msg}\n" + + f"{msg}\n" + + f"{msg}\n" + + f"{msg}\n" + + f"{msg}\n" + + f"{msg}\n" + + f"{msg}\n" + + f"{msg}\n" + + f"{msg}\n" + + f"{msg}\n" + + f"{msg}\n" + } + + binary: bytes = MoneroUtils.dict_to_binary(json_map) + assert len(binary) > 0 + + json_map2: dict[Any, Any] = MoneroUtils.binary_to_dict(binary) + assert json_map == json_map2 diff --git a/tests/common/monero_utils/test_validation.py b/tests/common/monero_utils/test_validation.py new file mode 100644 index 00000000..a133c7f6 --- /dev/null +++ b/tests/common/monero_utils/test_validation.py @@ -0,0 +1,228 @@ +from __future__ import annotations + +import logging + +import pytest +from monero import MoneroNetworkType, MoneroUtils + +from utils import WalletUtils +from .base_test_monero_utils import BaseTestMoneroUtils + +logger: logging.Logger = logging.getLogger("TestMoneroUtilsValidation") + + +@pytest.mark.unit +class TestMoneroUtilsValidation(BaseTestMoneroUtils): + """Monero utilities validation unit tests.""" + + # Can validate addresses + def test_address_validation(self, config: BaseTestMoneroUtils.Config) -> None: + + # test mainnet primary address validation + assert (MoneroUtils.is_valid_address(config.mainnet.primary_address_1, MoneroNetworkType.MAINNET)) is True + assert (MoneroUtils.is_valid_address(config.mainnet.primary_address_2, MoneroNetworkType.MAINNET)) is True + assert (MoneroUtils.is_valid_address(config.mainnet.primary_address_3, MoneroNetworkType.MAINNET)) is True + + # test mainnet integrated address validation + MoneroUtils.validate_address(config.mainnet.integrated_1, MoneroNetworkType.MAINNET) + MoneroUtils.validate_address(config.mainnet.integrated_2, MoneroNetworkType.MAINNET) + MoneroUtils.validate_address(config.mainnet.integrated_3, MoneroNetworkType.MAINNET) + + # test mainnet subaddress validation + MoneroUtils.validate_address(config.mainnet.subaddress_1, MoneroNetworkType.MAINNET) + MoneroUtils.validate_address(config.mainnet.subaddress_2, MoneroNetworkType.MAINNET) + MoneroUtils.validate_address(config.mainnet.subaddress_3, MoneroNetworkType.MAINNET) + + # test testnet primary address validation + assert (MoneroUtils.is_valid_address(config.testnet.primary_address_1, MoneroNetworkType.TESTNET)) is True + assert (MoneroUtils.is_valid_address(config.testnet.primary_address_2, MoneroNetworkType.TESTNET)) is True + assert (MoneroUtils.is_valid_address(config.testnet.primary_address_3, MoneroNetworkType.TESTNET)) is True + + # test testnet integrated address validation + assert (MoneroUtils.is_valid_address(config.testnet.integrated_1, MoneroNetworkType.TESTNET)) is True + assert (MoneroUtils.is_valid_address(config.testnet.integrated_2, MoneroNetworkType.TESTNET)) is True + assert (MoneroUtils.is_valid_address(config.testnet.integrated_3, MoneroNetworkType.TESTNET)) is True + + # test testnet subaddress validation + assert (MoneroUtils.is_valid_address(config.testnet.subaddress_1, MoneroNetworkType.TESTNET)) is True + assert (MoneroUtils.is_valid_address(config.testnet.subaddress_2, MoneroNetworkType.TESTNET)) is True + assert (MoneroUtils.is_valid_address(config.testnet.subaddress_3, MoneroNetworkType.TESTNET)) is True + + # test stagenet primary address validation + assert (MoneroUtils.is_valid_address(config.stagenet.primary_address_1, MoneroNetworkType.STAGENET)) is True + assert (MoneroUtils.is_valid_address(config.stagenet.primary_address_2, MoneroNetworkType.STAGENET)) is True + assert (MoneroUtils.is_valid_address(config.stagenet.primary_address_3, MoneroNetworkType.STAGENET)) is True + + # test stagenet integrated address validation + assert (MoneroUtils.is_valid_address(config.stagenet.integrated_1, MoneroNetworkType.STAGENET)) is True + assert (MoneroUtils.is_valid_address(config.stagenet.integrated_2, MoneroNetworkType.STAGENET)) is True + assert (MoneroUtils.is_valid_address(config.stagenet.integrated_3, MoneroNetworkType.STAGENET)) is True + + # test stagenet subaddress validation + assert (MoneroUtils.is_valid_address(config.stagenet.subaddress_1, MoneroNetworkType.STAGENET)) is True + assert (MoneroUtils.is_valid_address(config.stagenet.subaddress_2, MoneroNetworkType.STAGENET)) is True + assert (MoneroUtils.is_valid_address(config.stagenet.subaddress_3, MoneroNetworkType.STAGENET)) is True + + # test invalid addresses on mainnet + WalletUtils.test_invalid_address(None, MoneroNetworkType.MAINNET) + WalletUtils.test_invalid_address("", MoneroNetworkType.MAINNET) + WalletUtils.test_invalid_address(config.mainnet.invalid_1, MoneroNetworkType.MAINNET) + WalletUtils.test_invalid_address(config.mainnet.invalid_2, MoneroNetworkType.MAINNET) + WalletUtils.test_invalid_address(config.mainnet.invalid_3, MoneroNetworkType.MAINNET) + + # test invalid addresses on testnet + WalletUtils.test_invalid_address(None, MoneroNetworkType.TESTNET) + WalletUtils.test_invalid_address("", MoneroNetworkType.TESTNET) + WalletUtils.test_invalid_address(config.testnet.invalid_1, MoneroNetworkType.TESTNET) + WalletUtils.test_invalid_address(config.testnet.invalid_2, MoneroNetworkType.TESTNET) + WalletUtils.test_invalid_address(config.testnet.invalid_3, MoneroNetworkType.TESTNET) + + # test invalid addresses on stagenet + WalletUtils.test_invalid_address(None, MoneroNetworkType.STAGENET) + WalletUtils.test_invalid_address("", MoneroNetworkType.STAGENET) + WalletUtils.test_invalid_address(config.stagenet.invalid_1, MoneroNetworkType.STAGENET) + WalletUtils.test_invalid_address(config.stagenet.invalid_2, MoneroNetworkType.STAGENET) + WalletUtils.test_invalid_address(config.stagenet.invalid_3, MoneroNetworkType.STAGENET) + + # Can validate keys + def test_key_validation(self, config: BaseTestMoneroUtils.Config) -> None: + invalid_hex_64: str = "z" * 64 # right length but not hex + + # test private view key validation + assert MoneroUtils.is_valid_private_view_key(config.keys.private_view_key) + MoneroUtils.validate_private_view_key(config.keys.private_view_key) + WalletUtils.test_invalid_private_view_key("") + WalletUtils.test_invalid_private_view_key(None) + WalletUtils.test_invalid_private_view_key(config.keys.invalid_private_view_key) + WalletUtils.test_invalid_private_view_key(invalid_hex_64) + + # test public view key validation + assert MoneroUtils.is_valid_public_view_key(config.keys.public_view_key) + MoneroUtils.validate_public_view_key(config.keys.public_view_key) + WalletUtils.test_invalid_public_view_key("") + WalletUtils.test_invalid_public_view_key(None) + WalletUtils.test_invalid_public_view_key(config.keys.invalid_public_view_key) + WalletUtils.test_invalid_public_view_key(invalid_hex_64) + + # test private spend key validation + assert MoneroUtils.is_valid_private_spend_key(config.keys.private_spend_key) + WalletUtils.test_invalid_private_spend_key("") + WalletUtils.test_invalid_private_spend_key(None) + WalletUtils.test_invalid_private_spend_key(config.keys.invalid_private_spend_key) + WalletUtils.test_invalid_private_spend_key(invalid_hex_64) + + # test public spend key validation + assert MoneroUtils.is_valid_public_spend_key(config.keys.public_spend_key) + MoneroUtils.validate_public_spend_key(config.keys.public_spend_key) + WalletUtils.test_invalid_public_spend_key("") + WalletUtils.test_invalid_public_spend_key(None) + WalletUtils.test_invalid_public_spend_key(config.keys.invalid_public_spend_key) + WalletUtils.test_invalid_public_spend_key(invalid_hex_64) + + # Can validate seed + def test_mnemonic_validation(self, config: BaseTestMoneroUtils.Config) -> None: + + # test valid seed + MoneroUtils.validate_mnemonic(config.keys.seed) + assert MoneroUtils.is_valid_mnemonic(config.keys.seed), f"Invalid seed: {config.keys.seed}" + assert MoneroUtils.is_valid_mnemonic(config.keys.seed, "English"), f"Expected valid English seed: {config.keys.seed}" + + # test invalid seed language + assert not MoneroUtils.is_valid_mnemonic(config.keys.seed, "Spanish"), f"Expected invalid Spanish seed: {config.keys.seed}" + + # test invalid seed + assert not MoneroUtils.is_valid_mnemonic("invalid monero wallet seed") + + # test empty seed + assert not MoneroUtils.is_valid_mnemonic("") + + # Can validate language + def test_seed_language_validation(self) -> None: + languages: list[str] = ["Italian", "English", "German"] + + for language in languages: + assert MoneroUtils.is_valid_language(language), f"Expected valid language: {language}" + + invalid_languages: list[str] = ["", "english", "italian"] + + for language in invalid_languages: + assert not MoneroUtils.is_valid_language(language), f"Expected invalid language: {language}" + + # Can validate payment id + def test_payment_id_validation(self) -> None: + payment_ids: list[str] = [ + "43e04076e176b768", "ef35647e9842991c", + "8434d5452ad1b0ab", "3b5ac230d2666177", + "87fdf837b5e6a390", "304e0fa65b9c9e14" + ] + + for payment_id in payment_ids: + assert MoneroUtils.is_valid_payment_id(payment_id), f"Expected valid payment id: {payment_id}" + MoneroUtils.validate_payment_id(payment_id) + + # validate long payment id + assert MoneroUtils.is_valid_payment_id("87fdf837b5e6a390ef35647e9842991c8434d5452ad1b0ab304e0fa65b9c9e14") + + invalid_payment_ids: list[str] = [ + "", "wijqwnn38y", + "87fdf837b5e6a39", "3b5ac230d26661778", + "304e0fa65b9c9e14304e0fa65b9c9e14", + "z" * 16, "z" * 64 + ] + + for payment_id in invalid_payment_ids: + assert not MoneroUtils.is_valid_payment_id(payment_id), f"Expected invalid payment id: {payment_id}" + try: + MoneroUtils.validate_payment_id(payment_id) + except Exception as e: + expected: str = "payment id expected to be 64 or 16 hex characters" + e_str: str = str(e) + assert expected == e_str, f"Expected error '{expected}', got {e_str}" + + # Can validate a long payment id specifically + def test_payment_id_long_validation(self) -> None: + long_payment_id: str = "87fdf837b5e6a390ef35647e9842991c8434d5452ad1b0ab304e0fa65b9c9e14" + assert MoneroUtils.is_valid_payment_id_long(long_payment_id) + + short_payment_id: str = "87fdf837b5e6a390" + assert not MoneroUtils.is_valid_payment_id_long(short_payment_id) + + invalid_payment_ids: list[str] = ["", "wijqwnn38y", long_payment_id[:-1]] + + for payment_id in invalid_payment_ids: + assert not MoneroUtils.is_valid_payment_id_long(payment_id), f"Expected invalid long payment id: {payment_id}" + + # Can validate a short payment id specifically + def test_payment_id_short_validation(self) -> None: + short_payment_id: str = "87fdf837b5e6a390" + assert MoneroUtils.is_valid_payment_id_short(short_payment_id) + + long_payment_id: str = "87fdf837b5e6a390ef35647e9842991c8434d5452ad1b0ab304e0fa65b9c9e14" + assert not MoneroUtils.is_valid_payment_id_short(long_payment_id) + + invalid_payment_ids: list[str] = ["", "wijqwnn38y", short_payment_id[:-1]] + + for payment_id in invalid_payment_ids: + assert not MoneroUtils.is_valid_payment_id_short(payment_id), f"Expected invalid short payment id: {payment_id}" + + # Can validate a long payment id, raising on failure + def test_validate_payment_id_long(self) -> None: + long_payment_id: str = "87fdf837b5e6a390ef35647e9842991c8434d5452ad1b0ab304e0fa65b9c9e14" + MoneroUtils.validate_payment_id_long(long_payment_id) + + with pytest.raises(RuntimeError, match="Invalid long payment id"): + MoneroUtils.validate_payment_id_long("87fdf837b5e6a390") # too short + + with pytest.raises(RuntimeError, match="Invalid long payment id"): + MoneroUtils.validate_payment_id_long("wijqwnn38y") # not hex + + # Can validate a short payment id, raising on failure + def test_validate_payment_id_short(self) -> None: + short_payment_id: str = "87fdf837b5e6a390" + MoneroUtils.validate_payment_id_short(short_payment_id) + + with pytest.raises(RuntimeError, match="Invalid short payment id"): + MoneroUtils.validate_payment_id_short("87fdf837b5e6a390ef35647e9842991c8434d5452ad1b0ab304e0fa65b9c9e14") # too long + + with pytest.raises(RuntimeError, match="Invalid short payment id"): + MoneroUtils.validate_payment_id_short("wijqwnn38y") # not hex diff --git a/tests/common/test_block_generation.py b/tests/common/test_block_generation.py new file mode 100644 index 00000000..c17e9c82 --- /dev/null +++ b/tests/common/test_block_generation.py @@ -0,0 +1,47 @@ +from __future__ import annotations + +from typing import Any + +import pytest +from monero import MoneroDaemonInfo + +from utils import BaseTestClass +from utils.block_generation import MAX_GENERATE_DIFFICULTY, is_generation_fast + + +class _Daemon: + """Daemon that answers get_info with a given difficulty.""" + + def __init__(self, difficulty: int, is_regtest: bool | None = True, fails: bool = False) -> None: + self._difficulty: int = difficulty + self._is_regtest: bool | None = is_regtest + self._fails: bool = fails + + def get_info(self) -> MoneroDaemonInfo: + if self._fails: + raise RuntimeError("no node") + info: MoneroDaemonInfo = MoneroDaemonInfo() + info.difficulty_low = self._difficulty & ((1 << 64) - 1) + info.difficulty_high = self._difficulty >> 64 + info.is_regtest = self._is_regtest + return info + + +@pytest.mark.unit +class TestBlockGeneration(BaseTestClass): + """Choice between generating and mining blocks, unit tests.""" + + # Blocks are generated at a low difficulty, where the miner makes too many + @pytest.mark.parametrize("difficulty", [1, 5, MAX_GENERATE_DIFFICULTY]) + def test_generates_at_low_difficulty(self, difficulty: int) -> None: + assert is_generation_fast(_Daemon(difficulty)) is True # type: ignore[arg-type] + + # Blocks are mined at a high difficulty, where the miner is faster than generating + @pytest.mark.parametrize("difficulty", [MAX_GENERATE_DIFFICULTY + 1, 500, 1 << 70]) + def test_mines_at_high_difficulty(self, difficulty: int) -> None: + assert is_generation_fast(_Daemon(difficulty)) is False # type: ignore[arg-type] + + # Blocks are not generated outside regtest, or when the daemon does not answer + @pytest.mark.parametrize("daemon", [_Daemon(5, is_regtest=False), _Daemon(5, fails=True), _Daemon(0)]) + def test_does_not_generate_otherwise(self, daemon: Any) -> None: + assert is_generation_fast(daemon) is False diff --git a/tests/test_monero_common.py b/tests/common/test_common.py similarity index 100% rename from tests/test_monero_common.py rename to tests/common/test_common.py diff --git a/tests/test_gen_utils.py b/tests/common/test_gen_utils.py similarity index 100% rename from tests/test_gen_utils.py rename to tests/common/test_gen_utils.py diff --git a/tests/test_monero_rpc_connection.py b/tests/common/test_rpc_connection.py similarity index 100% rename from tests/test_monero_rpc_connection.py rename to tests/common/test_rpc_connection.py diff --git a/tests/daemon/__init__.py b/tests/daemon/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/daemon/model/__init__.py b/tests/daemon/model/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/daemon/model/test_blocks.py b/tests/daemon/model/test_blocks.py new file mode 100644 index 00000000..b2a3b8f8 --- /dev/null +++ b/tests/daemon/model/test_blocks.py @@ -0,0 +1,273 @@ +from __future__ import annotations + +import logging +import subprocess +import sys +from typing import LiteralString + +import pytest +from monero import ( + MoneroBlock, + MoneroBlockHeader, + MoneroBlockTemplate, + MoneroGetBlockHashesResult, + MoneroGetBlocksByHashResult, + MoneroTx, +) + +from utils import AssertUtils, BaseTestClass + +logger: logging.Logger = logging.getLogger("TestMoneroDaemonModelBlocks") + + +@pytest.mark.unit +class TestMoneroDaemonModelBlocks(BaseTestClass): + """Daemon blocks model unit tests.""" + + def test_block_template_deserialize(self) -> None: + template: MoneroBlockTemplate = MoneroBlockTemplate() + template.block_template_blob = "abcd" + template.block_hashing_blob = "ef01" + template.prev_hash = "a" * 64 + template.seed_hash = "b" * 64 + template.next_seed_hash = "c" * 64 + template.difficulty_low = 5000 + template.difficulty_high = 0 + template.expected_reward = 600000000000 + template.height = 12345 + template.reserved_offset = 130 + template.seed_height = 0 + AssertUtils.assert_serialization_integrity(template) + + def test_block_header_deserialize(self) -> None: + header: MoneroBlockHeader = MoneroBlockHeader() + header.hash = "a" * 64 + header.height = 12345 + header.timestamp = 1600000000 + header.size = 2048 + header.weight = 2048 + header.long_term_weight = 2048 + header.depth = 10 + header.difficulty_low = 5000 + header.difficulty_high = 0 + header.cumulative_difficulty_low = 900000 + header.cumulative_difficulty_high = 0 + header.major_version = 16 + header.minor_version = 16 + header.nonce = 42 + header.miner_tx_hash = "b" * 64 + header.num_txs = 3 + header.orphan_status = False + header.prev_hash = "c" * 64 + header.reward = 600000000000 + header.pow_hash = "d" * 64 + AssertUtils.assert_serialization_integrity(header) + + def test_block_deserialize(self) -> None: + block: MoneroBlock = MoneroBlock() + block.hash = "a" * 64 + block.height = 12345 + block.hex = "deadbeef" + block.tx_hashes = ["b" * 64, "c" * 64] + + miner_tx: MoneroTx = MoneroTx() + miner_tx.hash = "d" * 64 + miner_tx.is_miner_tx = True + block.miner_tx = miner_tx + + tx: MoneroTx = MoneroTx() + tx.hash = "e" * 64 + block.txs = [tx] + + restored: MoneroBlock = AssertUtils.assert_serialization_integrity(block) + + # nested txs are parsed and back-linked to the block + assert restored.miner_tx is not None + assert restored.miner_tx.hash == "d" * 64 + assert restored.miner_tx.is_miner_tx is True + assert restored.miner_tx.block is not None and restored.miner_tx.block.height == 12345 + assert len(restored.txs) == 1 + assert restored.txs[0].hash == "e" * 64 + assert restored.txs[0].block is not None and restored.txs[0].block.height == 12345 + + def test_get_block_hashes_result_deserialize(self) -> None: + result: MoneroGetBlockHashesResult = MoneroGetBlockHashesResult() + result.hashes = ["a" * 64, "b" * 64] + result.start_height = 100 + result.current_height = 3000000 + AssertUtils.assert_serialization_integrity(result) + + def test_get_blocks_by_hash_result_deserialize(self) -> None: + result: MoneroGetBlocksByHashResult = MoneroGetBlocksByHashResult() + result.current_height = 3000000 + # blocks are serialized but from_property_tree() never reads them back + # (monero_block has no from_property_tree of its own); see test below + AssertUtils.assert_serialization_integrity(result) + + def test_get_blocks_by_hash_result_blocks_deserialize(self) -> None: + result: MoneroGetBlocksByHashResult = MoneroGetBlocksByHashResult() + block: MoneroBlock = MoneroBlock() + block.hash = "a" * 64 + block.height = 100 + result.blocks = [block] + json_str: str = result.serialize() + logger.debug(f"Serialized get blocks by hash result: {json_str}") + assert '"blocks"' in json_str + restored: MoneroGetBlocksByHashResult = MoneroGetBlocksByHashResult.deserialize(json_str) + assert len(restored.blocks) == 0 + + def test_block_header_copy(self) -> None: + header: MoneroBlockHeader = MoneroBlockHeader() + header.hash = "a" * 64 + header.height = 100 + header.timestamp = 1700000000 + header.size = 1000 + header.weight = 1000 + header.major_version = 16 + header.minor_version = 16 + header.nonce = 12345 + header.reward = 600000000000 + + copy: MoneroBlockHeader = header.copy() + assert copy is not header + assert copy.serialize() == header.serialize() + + # copy is independent of the original + copy.height = 999 + assert header.height == 100 + + def test_block_header_merge(self) -> None: + a: MoneroBlockHeader = MoneroBlockHeader() + a.hash = "a" * 64 + a.height = 100 + a.timestamp = 1700000000 + + b: MoneroBlockHeader = a.copy() + b.height = 200 # height can increase -> resolves to the higher value + b.timestamp = 1800000000 # timestamp can increase -> resolves to the higher value + b.size = 2000 # a.size is unset -> merge fills the gap + + a.merge(b) + assert a.height == 200 + assert a.timestamp == 1800000000 + assert a.size == 2000 + assert a.hash == "a" * 64 + + def test_block_header_merge_conflict_raises(self) -> None: + # fields without special reconciliation (e.g. hash) must match on both + # sides, or merge() raises rather than silently picking one + a: MoneroBlockHeader = MoneroBlockHeader() + a.hash = "a" * 64 + b: MoneroBlockHeader = MoneroBlockHeader() + b.hash = "b" * 64 + with pytest.raises(Exception, match="[Cc]annot reconcile"): + a.merge(b) + + def test_block_copy(self) -> None: + block: MoneroBlock = MoneroBlock() + block.hash = "a" * 64 + block.height = 100 + block.hex = "deadbeef" + block.tx_hashes = ["b" * 64, "c" * 64] + + miner_tx: MoneroTx = MoneroTx() + miner_tx.hash = "d" * 64 + miner_tx.is_miner_tx = True + block.miner_tx = miner_tx + + tx: MoneroTx = MoneroTx() + tx.hash = "e" * 64 + block.txs = [tx] + + copy: MoneroBlock = block.copy() + assert copy is not block + assert copy.serialize() == block.serialize() + + # miner tx and non-wallet txs are deep copied and back-linked to the copy + assert copy.miner_tx is not None and copy.miner_tx is not block.miner_tx + assert copy.miner_tx.hash == "d" * 64 + assert copy.miner_tx.block is copy + assert len(copy.txs) == 1 + assert copy.txs[0] is not block.txs[0] + assert copy.txs[0].hash == "e" * 64 + assert copy.txs[0].block is copy + + def test_block_merge(self) -> None: + a: MoneroBlock = MoneroBlock() + a.hash = "a" * 64 + a.height = 100 + b: MoneroBlock = a.copy() + b.hex = "deadbeef" # a.hex is unset -> merge fills the gap + a.merge(b) + assert a.hex == "deadbeef" + + def test_block_header_merge_dispatches_to_block_merge(self) -> None: + a: MoneroBlock = MoneroBlock() + a.height = 100 + b: MoneroBlock = MoneroBlock() + b.height = 100 + b.hex = "deadbeef" # a.hex is unset -> merge fills the gap + + MoneroBlockHeader.merge(a, b) + assert a.hex == "deadbeef" + + def test_block_merge_adopts_other_miner_tx(self) -> None: + a: MoneroBlock = MoneroBlock() + a.height = 100 + # a.miner_tx is unset -> merge adopts other's miner tx and repoints its block at a + + b: MoneroBlock = MoneroBlock() + b.height = 100 + miner_tx: MoneroTx = MoneroTx() + miner_tx.hash = "a" * 64 + miner_tx.is_miner_tx = True + b.miner_tx = miner_tx + + a.merge(b) + assert a.miner_tx is not None + assert a.miner_tx is b.miner_tx + assert a.miner_tx.hash == "a" * 64 + assert a.miner_tx.block is a + + def test_block_merge_merges_distinct_miner_txs(self) -> None: + a: MoneroBlock = MoneroBlock() + a.height = 100 + miner_a: MoneroTx = MoneroTx() + miner_a.hash = "a" * 64 + miner_a.is_confirmed = True # required: tx merge() dereferences is_confirmed directly + a.miner_tx = miner_a + + b: MoneroBlock = MoneroBlock() + b.height = 100 + miner_b: MoneroTx = MoneroTx() + miner_b.hash = "a" * 64 + miner_b.is_confirmed = True + miner_b.num_confirmations = 5 # miner_a's num_confirmations is unset -> merge fills the gap + b.miner_tx = miner_b + + a.merge(b) + assert a.miner_tx is miner_a # kept in place, fields merged into it + assert a.miner_tx.num_confirmations == 5 + assert a.miner_tx.block is a + + def test_block_merge_txs_with_unset_hash_are_kept_distinct(self) -> None: + script: LiteralString = ( + "import monero, sys\n" + "a = monero.MoneroBlock()\n" + "a.height = 100\n" + "tx_a = monero.MoneroTx()\n" # hash intentionally left unset + "a.txs = [tx_a]\n" + "b = monero.MoneroBlock()\n" + "b.height = 100\n" + "tx_b = monero.MoneroTx()\n" # hash intentionally left unset + "b.txs = [tx_b]\n" + "a.merge(b)\n" + "n = len(a.txs) if a.txs else 0\n" + "sys.exit(0 if n == 2 else f'txs not kept distinct: len={n}')\n" + ) + result: subprocess.CompletedProcess[str] = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, timeout=30) + logger.debug(f"subprocess exit code: {result.returncode}, stderr: {result.stderr.strip()}") + assert result.returncode == 0, ( + f"Block.merge() did not keep unset-hash txs distinct (exit code {result.returncode}): " + f"{result.stderr.strip()[-300:]}" + ) diff --git a/tests/daemon/model/test_info.py b/tests/daemon/model/test_info.py new file mode 100644 index 00000000..3d4cb616 --- /dev/null +++ b/tests/daemon/model/test_info.py @@ -0,0 +1,175 @@ +from __future__ import annotations + +import logging + +import pytest +from monero import ( + MoneroAltChain, + MoneroConnectionSpan, + MoneroDaemonInfo, + MoneroDaemonNetworkStats, + MoneroDaemonSyncInfo, + MoneroDaemonUpdateCheckResult, + MoneroDaemonUpdateDownloadResult, + MoneroFeeEstimate, + MoneroHardForkInfo, + MoneroNetworkType, + MoneroPeer, + MoneroPruneResult, +) + +from utils import AssertUtils, BaseTestClass + +logger: logging.Logger = logging.getLogger("TestMoneroDaemonModelInfo") + + +@pytest.mark.unit +class TestMoneroDaemonModelInfo(BaseTestClass): + """Daemon info model unit tests.""" + + def test_alt_chain_deserialize(self) -> None: + alt_chain: MoneroAltChain = MoneroAltChain() + alt_chain.block_hashes = ["a" * 64, "b" * 64] + alt_chain.difficulty_low = 100 + alt_chain.difficulty_high = 0 + alt_chain.height = 12345 + alt_chain.length = 3 + alt_chain.main_chain_parent_block_hash = "c" * 64 + AssertUtils.assert_serialization_integrity(alt_chain) + + def test_prune_result_deserialize(self) -> None: + result: MoneroPruneResult = MoneroPruneResult() + result.pruning_seed = 387 + # is_pruned is deliberately not set here: to_rapidjson_val() serializes it + # under "isPruned" but from_property_tree() looks for "pruned" instead, so + # it never round trips (see test below) + AssertUtils.assert_serialization_integrity(result) + + def test_prune_result_is_pruned_deserialize(self) -> None: + result: MoneroPruneResult = MoneroPruneResult() + result.is_pruned = True + json_str: str = result.serialize() + logger.debug(f"Serialized prune result: {json_str}") + assert '"isPruned"' in json_str + restored: MoneroPruneResult = MoneroPruneResult.deserialize(json_str) + logger.debug(f"Deserialized prune result re-serialized: {restored.serialize()}") + assert restored.is_pruned == result.is_pruned + + def test_fee_estimate_deserialize(self) -> None: + estimate: MoneroFeeEstimate = MoneroFeeEstimate() + estimate.fee = 20000 + estimate.quantization_mask = 10000 + estimate.fees = [10000, 20000, 30000, 40000] + AssertUtils.assert_serialization_integrity(estimate) + + def test_daemon_info_deserialize(self) -> None: + info: MoneroDaemonInfo = MoneroDaemonInfo() + info.credits = 0 + info.top_block_hash = "a" * 64 + info.version = "0.18.5.1" + info.num_alt_blocks = 1 + info.block_size_limit = 600000 + info.block_size_median = 300000 + info.block_weight_limit = 600000 + info.block_weight_median = 300000 + info.bootstrap_daemon_address = "node.example.com" + info.difficulty_low = 123456 + info.difficulty_high = 0 + info.cumulative_difficulty_low = 987654 + info.cumulative_difficulty_high = 0 + info.free_space = 1000000000 + info.num_offline_peers = 1 + info.num_online_peers = 10 + info.height = 3000000 + info.height_without_bootstrap = 3000000 + info.network_type = MoneroNetworkType.TESTNET + info.is_offline = False + info.num_incoming_connections = 5 + info.num_outgoing_connections = 8 + info.num_rpc_connections = 2 + info.start_timestamp = 1600000000 + info.adjusted_timestamp = 1700000000 + info.target = 120 + info.target_height = 0 + info.num_txs = 100 + info.num_txs_pool = 3 + info.was_bootstrap_ever_used = False + info.database_size = 100000000 + info.update_available = False + info.is_busy_syncing = False + info.is_synchronized = True + info.is_restricted = False + info.is_regtest = True + AssertUtils.assert_serialization_integrity(info) + + def test_daemon_info_invalid_network_type(self) -> None: + with pytest.raises(RuntimeError, match="invalid network type"): + MoneroDaemonInfo.deserialize('{"networkType":9}') + + def test_daemon_sync_info_deserialize(self) -> None: + info: MoneroDaemonSyncInfo = MoneroDaemonSyncInfo() + info.credits = 0 + info.top_block_hash = "a" * 64 + info.height = 3000000 + info.target_height = 3000010 + info.next_needed_pruning_seed = 0 + info.overview = "syncing" + # peers/spans are serialized as sub-arrays but from_property_tree() never + # reads them back (see test below) + AssertUtils.assert_serialization_integrity(info) + + def test_daemon_sync_info_peers_and_spans_deserialize(self) -> None: + info: MoneroDaemonSyncInfo = MoneroDaemonSyncInfo() + info.peers = [MoneroPeer()] + info.spans = [MoneroConnectionSpan()] + json_str: str = info.serialize() + logger.debug(f"Serialized daemon sync info: {json_str}") + assert "peers" in json_str and "spans" in json_str + restored: MoneroDaemonSyncInfo = MoneroDaemonSyncInfo.deserialize(json_str) + logger.debug(f"Deserialized daemon sync info re-serialized: {restored.serialize()}") + assert len(restored.peers) == len(info.peers) + assert len(restored.spans) == len(info.spans) + + def test_hard_fork_info_deserialize(self) -> None: + info: MoneroHardForkInfo = MoneroHardForkInfo() + info.credits = 0 + info.top_block_hash = "a" * 64 + info.earliest_height = 100000 + info.is_enabled = True + info.state = 0 + info.threshold = 0 + info.version = 16 + info.num_votes = 5000 + info.window = 10080 + info.voting = 16 + AssertUtils.assert_serialization_integrity(info) + + def test_daemon_network_stats_deserialize(self) -> None: + stats: MoneroDaemonNetworkStats = MoneroDaemonNetworkStats() + stats.credits = 0 + stats.top_block_hash = "a" * 64 + stats.start_time = 1700000000 + stats.total_packets_in = 1234 + stats.total_bytes_in = 567890 + stats.total_packets_out = 4321 + stats.total_bytes_out = 98765 + AssertUtils.assert_serialization_integrity(stats) + + def test_daemon_update_check_result_deserialize(self) -> None: + result: MoneroDaemonUpdateCheckResult = MoneroDaemonUpdateCheckResult() + result.is_update_available = True + result.version = "0.18.5.1" + result.hash = "a" * 64 + result.auto_uri = "https://example.com/auto" + result.user_uri = "https://example.com/user" + AssertUtils.assert_serialization_integrity(result) + + def test_daemon_update_download_result_deserialize(self) -> None: + result: MoneroDaemonUpdateDownloadResult = MoneroDaemonUpdateDownloadResult() + result.is_update_available = True + result.version = "0.18.5.1" + result.hash = "a" * 64 + result.auto_uri = "https://example.com/auto" + result.user_uri = "https://example.com/user" + result.download_path = "/tmp/update.bin" + AssertUtils.assert_serialization_integrity(result) diff --git a/tests/daemon/model/test_mining.py b/tests/daemon/model/test_mining.py new file mode 100644 index 00000000..364c73f8 --- /dev/null +++ b/tests/daemon/model/test_mining.py @@ -0,0 +1,94 @@ +from __future__ import annotations + +import logging + +import pytest +from monero import ( + MoneroAddAuxiliaryPowResult, + MoneroAuxiliaryPow, + MoneroGenerateBlocksResult, + MoneroMinerData, + MoneroMinerTxSum, + MoneroMiningStatus, + MoneroTx, +) + +from utils import AssertUtils, BaseTestClass + +logger: logging.Logger = logging.getLogger("TestMoneroDaemonModelMining") + + +@pytest.mark.unit +class TestMoneroDaemonModelMining(BaseTestClass): + """Daemon mining model unit tests.""" + + def test_mining_status_deserialize(self) -> None: + status: MoneroMiningStatus = MoneroMiningStatus() + status.is_active = True + status.is_background = False + status.address = "9" + "a" * 94 + status.speed = 500 + status.num_threads = 4 + AssertUtils.assert_serialization_integrity(status) + + def test_mining_status_inactive_clears_background_and_address_deserialize(self) -> None: + # when isActive is false from_property_tree drops isBackground and address + # even if present in the json + json_str: str = ( + '{"isActive": false, "isBackground": true, ' + '"address": "' + "9" + "a" * 94 + '", "speed": 500, "numThreads": 4}' + ) + status: MoneroMiningStatus = MoneroMiningStatus.deserialize(json_str) + assert status.is_active is False + assert status.is_background is None + assert status.address is None + assert status.speed == 500 + assert status.num_threads == 4 + + def test_miner_tx_sum_deserialize(self) -> None: + summ: MoneroMinerTxSum = MoneroMinerTxSum() + summ.emission_sum_low = 1000 + summ.emission_sum_high = 0 + summ.fee_sum_low = 10 + summ.fee_sum_high = 0 + AssertUtils.assert_serialization_integrity(summ) + + def test_generate_blocks_result_deserialize(self) -> None: + result: MoneroGenerateBlocksResult = MoneroGenerateBlocksResult() + result.block_hashes = ["a" * 64, "b" * 64] + result.height = 12345 + AssertUtils.assert_serialization_integrity(result) + + def test_miner_data_deserialize(self) -> None: + data: MoneroMinerData = MoneroMinerData() + data.credits = 0 + data.top_block_hash = "a" * 64 + data.major_version = 16 + data.height = 3000000 + data.prev_hash = "b" * 64 + data.seed_hash = "c" * 64 + data.difficulty = "0x1f4" # daemon reports difficulty as a hex string + data.median_weight = 300000 + data.already_generated_coins = 5646232813355588 + tx: MoneroTx = MoneroTx() + tx.hash = "d" * 64 + tx.fee = 10000 + data.tx_pool_backlog = [tx] + AssertUtils.assert_serialization_integrity(data) + + def test_auxiliary_pow_deserialize(self) -> None: + aux_pow: MoneroAuxiliaryPow = MoneroAuxiliaryPow("a" * 64, "b" * 64) + assert aux_pow.id == "a" * 64 + assert aux_pow.hash == "b" * 64 + AssertUtils.assert_serialization_integrity(aux_pow) + + def test_add_auxiliary_pow_result_deserialize(self) -> None: + result: MoneroAddAuxiliaryPowResult = MoneroAddAuxiliaryPowResult() + result.credits = 0 + result.top_block_hash = "a" * 64 + result.block_template_blob = "abcd" + result.block_hashing_blob = "ef01" + result.merkle_root = "b" * 64 + result.merkle_tree_depth = 2 + result.aux_pow = [MoneroAuxiliaryPow("c" * 64, "d" * 64)] + AssertUtils.assert_serialization_integrity(result) diff --git a/tests/daemon/model/test_outputs.py b/tests/daemon/model/test_outputs.py new file mode 100644 index 00000000..fdbef300 --- /dev/null +++ b/tests/daemon/model/test_outputs.py @@ -0,0 +1,162 @@ +from __future__ import annotations + +import logging + +import pytest +from monero import ( + MoneroKeyImage, + MoneroOutput, + MoneroOutputDistributionEntry, + MoneroOutputHistogramEntry, + MoneroTx, +) + +from utils import AssertUtils, BaseTestClass + +logger: logging.Logger = logging.getLogger("TestMoneroDaemonModelOutputs") + + +@pytest.mark.unit +class TestMoneroDaemonModelOutputs(BaseTestClass): + """Daemon outputs model unit tests.""" + + def test_key_image_deserialize(self) -> None: + key_image: MoneroKeyImage = MoneroKeyImage() + key_image.hex = "a" * 64 + key_image.signature = "b" * 128 + AssertUtils.assert_serialization_integrity(key_image) + + def test_key_image_deserialize_key_images(self) -> None: + json_str: str = ( + '{"keyImages": [' + '{"hex": "' + "a" * 64 + '", "signature": "' + "b" * 128 + '"}, ' + '{"hex": "' + "c" * 64 + '"}' + ']}' + ) + key_images: list[MoneroKeyImage] = MoneroKeyImage.deserialize_key_images(json_str) + assert len(key_images) == 2 + assert key_images[0].hex == "a" * 64 + assert key_images[0].signature == "b" * 128 + assert key_images[1].hex == "c" * 64 + assert key_images[1].signature is None + + # a missing or empty keyImages array yields no key images + assert MoneroKeyImage.deserialize_key_images("{}") == [] + assert MoneroKeyImage.deserialize_key_images('{"keyImages": []}') == [] + + # an empty string is not valid json + with pytest.raises(Exception): + MoneroKeyImage.deserialize_key_images("") + + def test_output_deserialize(self) -> None: + output: MoneroOutput = MoneroOutput() + output.amount = 1000000 + output.index = 5 + key_image: MoneroKeyImage = MoneroKeyImage() + key_image.hex = "a" * 64 + key_image.signature = "b" * 128 + output.key_image = key_image + AssertUtils.assert_serialization_integrity(output) + + def test_output_ring_output_indices_and_stealth_public_key_deserialize(self) -> None: + output: MoneroOutput = MoneroOutput() + output.amount = 1000000 + output.index = 5 + output.ring_output_indices = [10, 20, 30] + output.stealth_public_key = "a" * 64 + output.mask = "b" * 64 + AssertUtils.assert_serialization_integrity(output) + + def test_output_distribution_entry_deserialize(self) -> None: + entry: MoneroOutputDistributionEntry = MoneroOutputDistributionEntry() + entry.amount = 0 + entry.base = 100 + entry.distribution = [1, 2, 3, 4] + entry.start_height = 0 + AssertUtils.assert_serialization_integrity(entry) + + def test_output_histogram_entry_deserialize(self) -> None: + entry: MoneroOutputHistogramEntry = MoneroOutputHistogramEntry() + entry.amount = 0 + entry.num_instances = 10 + entry.unlocked_instances = 8 + entry.recent_instances = 2 + AssertUtils.assert_serialization_integrity(entry) + + def test_key_image_copy(self) -> None: + key_image: MoneroKeyImage = MoneroKeyImage() + key_image.hex = "a" * 64 + key_image.signature = "b" * 128 + + copy: MoneroKeyImage = key_image.copy() + assert copy is not key_image + assert copy.serialize() == key_image.serialize() + + def test_key_image_merge(self) -> None: + a: MoneroKeyImage = MoneroKeyImage() + a.hex = "a" * 64 + b: MoneroKeyImage = a.copy() + b.signature = "b" * 128 # a.signature is unset -> merge fills the gap + a.merge(b) + assert a.signature == "b" * 128 + + def test_output_copy(self) -> None: + output: MoneroOutput = MoneroOutput() + output.amount = 1000000 + output.index = 5 + key_image: MoneroKeyImage = MoneroKeyImage() + key_image.hex = "a" * 64 + output.key_image = key_image + + copy: MoneroOutput = output.copy() + assert copy is not output + assert copy.key_image is not output.key_image # key_image is deep copied + assert copy.serialize() == output.serialize() + + def test_output_merge(self) -> None: + a: MoneroOutput = MoneroOutput() + a.amount = 1000000 + a.index = 5 + b: MoneroOutput = a.copy() # preserves the (unset) tx reference, so merge won't recurse into tx merge + b.key_image = MoneroKeyImage() + b.key_image.hex = "a" * 64 + a.merge(b) # a.key_image is unset -> merge adopts b's key_image + assert a.key_image is not None + assert a.key_image.hex == "a" * 64 + + def test_output_merge_recurses_into_tx_merge(self) -> None: + tx_a: MoneroTx = MoneroTx() + tx_a.hash = "a" * 64 + tx_a.is_confirmed = True + + tx_b: MoneroTx = MoneroTx() + tx_b.hash = "a" * 64 + tx_b.is_confirmed = True + tx_b.num_confirmations = 9 # only tx merge reconciles this + + out_a: MoneroOutput = MoneroOutput() + out_a.tx = tx_a + out_a.stealth_public_key = "s" * 64 + tx_a.outputs = [out_a] + + out_b: MoneroOutput = MoneroOutput() + out_b.tx = tx_b + out_b.stealth_public_key = "s" * 64 + tx_b.outputs = [out_b] + + # outputs on different txs -> merge delegates to tx merge (which comes back to merging outputs) + out_a.merge(out_b) + assert tx_a.num_confirmations == 9 + + def test_output_merge_ring_output_indices_and_stealth_public_key(self) -> None: + a: MoneroOutput = MoneroOutput() + a.amount = 1000000 + a.index = 5 + b: MoneroOutput = a.copy() # preserves the (unset) tx reference, so merge won't recurse into tx merge + b.ring_output_indices = [10, 20, 30] + b.stealth_public_key = "a" * 64 + b.mask = "b" * 64 + a.merge(b) # a's fields are unset -> merge should adopt b's + assert a.ring_output_indices == [10, 20, 30] + assert a.stealth_public_key == "a" * 64 + assert a.mask == "b" * 64 diff --git a/tests/daemon/model/test_peers.py b/tests/daemon/model/test_peers.py new file mode 100644 index 00000000..bafeb988 --- /dev/null +++ b/tests/daemon/model/test_peers.py @@ -0,0 +1,103 @@ +from __future__ import annotations + +import logging + +import pytest +from monero import MoneroBan, MoneroConnectionSpan, MoneroConnectionType, MoneroPeer + +from utils import AssertUtils, BaseTestClass + +logger: logging.Logger = logging.getLogger("TestMoneroDaemonModelPeers") + + +@pytest.mark.unit +class TestMoneroDaemonModelPeers(BaseTestClass): + """Daemon peers model unit tests.""" + + def test_ban_deserialize(self) -> None: + ban: MoneroBan = MoneroBan() + ban.host = "127.0.0.1" + ban.ip = 2130706433 + ban.is_banned = True + ban.seconds = 3600 + AssertUtils.assert_serialization_integrity(ban) + + def test_connection_span_deserialize(self) -> None: + span: MoneroConnectionSpan = MoneroConnectionSpan() + span.connection_id = "deadbeef" + span.remote_address = "127.0.0.1:18080" + span.num_blocks = 10 + span.rate = 100 + span.speed = 200 + span.size = 1024 + span.start_height = 1000 + AssertUtils.assert_serialization_integrity(span) + + def test_peer_deserialize(self) -> None: + peer: MoneroPeer = MoneroPeer() + peer.id = "1122334455667788" + peer.address = "127.0.0.1:18080" + peer.host = "127.0.0.1" + peer.port = 18080 + peer.last_seen_timestamp = 1700000000 + peer.pruning_seed = 0 + peer.rpc_port = 18081 + peer.rpc_credits_per_hash = 0 + peer.hash = "a" * 64 + peer.avg_download = 10 + peer.avg_upload = 20 + peer.current_download = 30 + peer.current_upload = 40 + peer.height = 12345 + peer.is_incoming = True + peer.live_time = 3600 + peer.is_local_ip = False + peer.is_local_host = False + peer.num_receives = 5 + peer.num_sends = 6 + peer.receive_idle_time = 7 + peer.send_idle_time = 8 + peer.state = "normal" + peer.num_support_flags = 1 + # is_online and connection_type are serialized (isOnline/addressType) but + # monero_peer::from_property_tree() never reads them back, so they are + # deliberately excluded from this round trip (see test below). + AssertUtils.assert_serialization_integrity(peer) + + def test_peer_is_online_deserialize(self) -> None: + peer: MoneroPeer = MoneroPeer() + peer.is_online = True + json_str: str = peer.serialize() + logger.debug(f"Serialized peer: {json_str}") + assert "isOnline" in json_str + restored: MoneroPeer = MoneroPeer.deserialize(json_str) + logger.debug(f"Deserialized peer re-serialized: {restored.serialize()}") + assert restored.is_online == peer.is_online + + def test_peer_connection_serialization_integrity(self) -> None: + peer: MoneroPeer = MoneroPeer() + peer.connection_type = MoneroConnectionType.IPV6 + json_str: str = peer.serialize() + logger.debug(f"Serialized peer: {json_str}") + assert "addressType" in json_str + restored: MoneroPeer = MoneroPeer.deserialize(json_str) + logger.debug(f"Deserialized peer re-serialized: {restored.serialize()}") + assert restored.connection_type == peer.connection_type + + def test_peer_connection_type_deserialize(self) -> None: + # connection_type is likewise never serialized by to_rapidjson_val(), so it + # can only be exercised by handing from_property_tree a raw "addressType" field + for value, expected in [ + (0, MoneroConnectionType.INVALID), + (1, MoneroConnectionType.IPV4), + (2, MoneroConnectionType.IPV6), + (3, MoneroConnectionType.TOR), + (4, MoneroConnectionType.I2P), + ]: + peer: MoneroPeer = MoneroPeer.deserialize(f'{{"addressType":{value}}}') + assert peer.connection_type == expected + + def test_peer_connection_type_invalid(self) -> None: + # TODO throws RuntimeError rather than MoneroError + with pytest.raises(RuntimeError, match="Invalid RPC peer type"): + MoneroPeer.deserialize('{"addressType":5}') diff --git a/tests/daemon/model/test_rpc.py b/tests/daemon/model/test_rpc.py new file mode 100644 index 00000000..7ab6648a --- /dev/null +++ b/tests/daemon/model/test_rpc.py @@ -0,0 +1,50 @@ +from __future__ import annotations + +import logging + +import pytest +from monero import MoneroRpcConnection, MoneroRpcPaymentInfo, MoneroVersion + +from utils import AssertUtils, BaseTestClass + +logger: logging.Logger = logging.getLogger("TestMoneroDaemonModelRpc") + + +@pytest.mark.unit +class TestMoneroDaemonModelRpc(BaseTestClass): + """Daemon rpc model unit tests.""" + + def test_version_deserialize(self) -> None: + version: MoneroVersion = MoneroVersion() + version.number = 65552 + version.is_release = True + AssertUtils.assert_serialization_integrity(version) + + def test_rpc_payment_info_deserialize(self) -> None: + info: MoneroRpcPaymentInfo = MoneroRpcPaymentInfo() + info.credits = 42 + info.top_block_hash = "a" * 64 + AssertUtils.assert_serialization_integrity(info) + + def test_rpc_connection_deserialize(self) -> None: + connection: MoneroRpcConnection = MoneroRpcConnection("http://127.0.0.1:18081", "user", "pass", "127.0.0.1:9050", "tcp://127.0.0.1:18083", 2, 5000) + json_str: str = connection.serialize() + logger.debug(f"Serialized rpc connection: {json_str}") + restored: MoneroRpcConnection = MoneroRpcConnection.deserialize(json_str) + assert restored.uri == connection.uri + assert restored.username == connection.username + assert restored.password == connection.password + assert restored.proxy_uri == connection.proxy_uri + assert restored.zmq_uri == connection.zmq_uri + + def test_rpc_connection_priority_and_timeout_deserialize(self) -> None: + # to_rapidjson_val() emits "priority" and "timeoutMs" but + # from_property_tree() never read either back + connection: MoneroRpcConnection = MoneroRpcConnection("http://127.0.0.1:18081", priority=2, timeout_ms=5000) + json_str: str = connection.serialize() + logger.debug(f"Serialized rpc connection: {json_str}") + assert '"priority"' in json_str and '"timeoutMs"' in json_str + restored: MoneroRpcConnection = MoneroRpcConnection.deserialize(json_str) + logger.debug(f"Deserialized rpc connection re-serialized: {restored.serialize()}") + assert restored.priority == connection.priority + assert restored.timeout_ms == connection.timeout_ms diff --git a/tests/daemon/model/test_txs.py b/tests/daemon/model/test_txs.py new file mode 100644 index 00000000..95198c55 --- /dev/null +++ b/tests/daemon/model/test_txs.py @@ -0,0 +1,315 @@ +from __future__ import annotations + +import logging + +import pytest +from monero import ( + MoneroBlock, + MoneroKeyImage, + MoneroOutput, + MoneroSubmitTxResult, + MoneroTx, + MoneroTxPoolStats, + TxHeightComparator, +) + +from utils import AssertUtils, BaseTestClass + +logger: logging.Logger = logging.getLogger("TestMoneroDaemonModelTxs") + + +@pytest.mark.unit +class TestMoneroDaemonModelTxs(BaseTestClass): + """Daemon txs model unit tests.""" + + def test_tx_deserialize(self) -> None: + tx: MoneroTx = MoneroTx() + tx.hash = "a" * 64 + tx.is_miner_tx = False + tx.payment_id = "b" * 16 + tx.fee = 7500000 + tx.relay = True + tx.is_relayed = True + tx.is_confirmed = True + tx.in_tx_pool = False + tx.is_locked = False + tx.num_confirmations = 10 + tx.unlock_time = 0 + tx.last_relayed_timestamp = 1700000000 + tx.received_timestamp = 1700000000 + tx.is_double_spend_seen = False + tx.key = "c" * 64 + tx.full_hex = "deadbeef" + tx.pruned_hex = "deadbeef" + tx.prunable_hex = "deadbeef" + tx.prunable_hash = "d" * 64 + tx.size = 1500 + tx.weight = 1500 + tx.metadata = "meta" + tx.is_kept_by_block = False + tx.is_failed = False + tx.last_failed_hash = "e" * 64 + tx.max_used_block_hash = "f" * 64 + # mixin, rctSignatures, rctSigPrunable and signatures are still left + # unimplemented in from_property_tree() (see below) + AssertUtils.assert_serialization_integrity(tx) + + @pytest.mark.parametrize("json_fragment", [ + '{"mixin":5}', + '{"rctSignatures":"x"}', + '{"rctSigPrunable":"x"}', + '{"signatures":["x"]}', + ]) + def test_tx_unimplemented_fields(self, json_fragment: str) -> None: + with pytest.raises(Exception, match="not implemented"): + MoneroTx.deserialize(json_fragment) + + def test_tx_version_common_tx_sets_last_failed_and_max_used_block_height_deserialize(self) -> None: + tx: MoneroTx = MoneroTx() + tx.version = 2 + tx.common_tx_sets = "sets" + tx.last_failed_height = 100 + tx.max_used_block_height = 200 + AssertUtils.assert_serialization_integrity(tx) + + def test_tx_ring_size_deserialize(self) -> None: + tx: MoneroTx = MoneroTx() + tx.ring_size = 16 + AssertUtils.assert_serialization_integrity(tx) + + def test_tx_extra_deserialize(self) -> None: + tx: MoneroTx = MoneroTx() + tx.extra = [1, 2, 3, 255] + AssertUtils.assert_serialization_integrity(tx) + + def test_tx_inputs_outputs_and_output_indices_deserialize(self) -> None: + tx: MoneroTx = MoneroTx() + tx.output_indices = [100, 101] + vin: MoneroOutput = MoneroOutput() + vin.amount = 1 + vin.key_image = MoneroKeyImage() + vin.key_image.hex = "a" * 64 + tx.inputs = [vin] + vout: MoneroOutput = MoneroOutput() + vout.amount = 2 + vout.index = 0 + tx.outputs = [vout] + AssertUtils.assert_serialization_integrity(tx) + + def test_submit_tx_result_deserialize(self) -> None: + result: MoneroSubmitTxResult = MoneroSubmitTxResult() + result.credits = 1 + result.top_block_hash = "a" * 64 + result.is_relayed = True + result.is_double_spend = False + result.is_fee_too_low = False + result.has_invalid_input = False + result.has_invalid_output = False + result.has_too_few_outputs = False + result.is_mixin_too_low = False + result.is_overspend = False + result.reason = "ok" + result.is_too_big = False + result.sanity_check_failed = False + result.is_tx_extra_too_big = False + result.is_nonzero_unlock_time = False + # is_good is serialized but never read back by from_property_tree() + AssertUtils.assert_serialization_integrity(result) + + def test_submit_tx_result_is_good_deserialize(self) -> None: + result: MoneroSubmitTxResult = MoneroSubmitTxResult() + result.is_good = True + json_str: str = result.serialize() + logger.debug(f"Serialized submit tx result: {json_str}") + assert "isGood" in json_str + restored: MoneroSubmitTxResult = MoneroSubmitTxResult.deserialize(json_str) + logger.debug(f"Deserialized submit tx result re-serialized: {restored.serialize()}") + assert restored.is_good == result.is_good + + def test_tx_pool_stats_deserialize(self) -> None: + stats: MoneroTxPoolStats = MoneroTxPoolStats() + stats.num_txs = 5 + stats.num_not_relayed = 1 + stats.num_failing = 0 + stats.num_double_spends = 0 + stats.num10m = 2 + stats.fee_total = 1000 + stats.bytes_max = 2000 + stats.bytes_med = 1500 + stats.bytes_min = 1000 + stats.bytes_total = 5000 + stats.histo98pc = 1800 + stats.oldest_timestamp = 1700000000 + # histo is serialized as an object but from_property_tree() has a TODO + # and never reads it back into the map + AssertUtils.assert_serialization_integrity(stats) + + def test_tx_pool_stats_histo_deserialize(self) -> None: + stats: MoneroTxPoolStats = MoneroTxPoolStats() + stats.histo = {100: 1, 200: 2} + json_str: str = stats.serialize() + logger.debug(f"Serialized tx pool stats: {json_str}") + assert "histo" in json_str + restored: MoneroTxPoolStats = MoneroTxPoolStats.deserialize(json_str) + logger.debug(f"Deserialized tx pool stats re-serialized: {restored.serialize()}") + assert dict(restored.histo) == dict(stats.histo) + + def test_tx_copy(self) -> None: + tx: MoneroTx = MoneroTx() + tx.hash = "a" * 64 + tx.is_confirmed = True + tx.fee = 7500000 + + copy: MoneroTx = tx.copy() + assert copy is not tx + assert copy.serialize() == tx.serialize() + + def test_tx_copy_deep_copies_inputs(self) -> None: + tx: MoneroTx = MoneroTx() + tx.hash = "a" * 64 + + key_image: MoneroKeyImage = MoneroKeyImage() + key_image.hex = "1" * 64 + tx_input: MoneroOutput = MoneroOutput() + tx_input.tx = tx + tx_input.key_image = key_image + tx_input.amount = 1234 + tx.inputs = [tx_input] + + copy: MoneroTx = tx.copy() + assert len(copy.inputs) == 1 + assert copy.inputs[0] is not tx_input + assert copy.inputs[0].key_image.hex == "1" * 64 # type: ignore + assert copy.inputs[0].amount == 1234 + assert copy.inputs[0].tx is copy + + def test_tx_merge(self) -> None: + a: MoneroTx = MoneroTx() + a.hash = "a" * 64 + a.is_confirmed = True # required: merge() dereferences is_confirmed directly + a.fee = 7500000 + + b: MoneroTx = a.copy() + b.num_confirmations = 5 # a.num_confirmations is unset -> merge fills the gap + a.merge(b) + assert a.num_confirmations == 5 + + def test_tx_merge_adopts_other_block(self) -> None: + block: MoneroBlock = MoneroBlock() + block.height = 200 + + other: MoneroTx = MoneroTx() + other.hash = "a" * 64 + other.is_confirmed = True + other.block = block + block.txs = [other] + + tx: MoneroTx = MoneroTx() + tx.hash = "a" * 64 + tx.is_confirmed = True + # tx.block is unset -> merge adopts other's block and repoints the block at tx + tx.merge(other) + assert tx.block is block + assert block.txs[0] is tx + + def test_tx_merge_is_confirmed_can_become_true(self) -> None: + a: MoneroTx = MoneroTx() + a.hash = "a" * 64 + a.is_confirmed = False + b: MoneroTx = a.copy() + b.is_confirmed = True + a.merge(b) + assert a.is_confirmed is True + + def test_tx_merge_is_double_spend_seen_can_become_true(self) -> None: + a: MoneroTx = MoneroTx() + a.hash = "a" * 64 + a.is_confirmed = True + a.is_double_spend_seen = False + b: MoneroTx = a.copy() + b.is_double_spend_seen = True + a.merge(b) + assert a.is_double_spend_seen is True + + def test_tx_merge_in_tx_pool_can_become_true(self) -> None: + a: MoneroTx = MoneroTx() + a.hash = "a" * 64 + a.is_confirmed = False + a.in_tx_pool = False + b: MoneroTx = a.copy() + b.in_tx_pool = True + a.merge(b) + assert a.in_tx_pool is True + + def test_tx_merge_is_locked_can_become_false(self) -> None: + a: MoneroTx = MoneroTx() + a.hash = "a" * 64 + a.is_confirmed = True + a.is_locked = False # self: already unlocked + b: MoneroTx = a.copy() + b.is_locked = True # other: still locked + a.merge(b) + assert a.is_locked is False + + def test_tx_merge_extra_and_output_indices(self) -> None: + a: MoneroTx = MoneroTx() + a.hash = "a" * 64 + a.is_confirmed = True # required: merge() dereferences is_confirmed directly + b: MoneroTx = a.copy() + b.extra = [1, 2, 3, 255] + b.output_indices = [100, 101] + a.merge(b) # a.extra/output_indices are unset -> merge should adopt b's + assert a.extra == [1, 2, 3, 255] + assert a.output_indices == [100, 101] + + def test_tx_merge_inputs(self) -> None: + def make_input(tx: MoneroTx, key_image_hex: str) -> MoneroOutput: + key_image: MoneroKeyImage = MoneroKeyImage() + key_image.hex = key_image_hex + tx_input: MoneroOutput = MoneroOutput() + tx_input.tx = tx + tx_input.key_image = key_image + return tx_input + + a: MoneroTx = MoneroTx() + a.hash = "a" * 64 + a.is_confirmed = True # required: merge() dereferences is_confirmed directly + a.inputs = [make_input(a, "1" * 64)] + + b: MoneroTx = MoneroTx() + b.hash = "a" * 64 + b.is_confirmed = True + shared_input: MoneroOutput = make_input(b, "1" * 64) # same key image -> merged into a's input + shared_input.amount = 5000 + b.inputs = [shared_input, make_input(b, "2" * 64)] # new key image -> appended + + a.merge(b) + assert len(a.inputs) == 2 + assert a.inputs[0].key_image.hex == "1" * 64 # type: ignore + assert a.inputs[0].amount == 5000 # filled from b's matching input + assert a.inputs[1].key_image.hex == "2" * 64 # type: ignore + assert a.inputs[1].tx is a # appended input is repointed at a + + def test_tx_lt_height_comparator(self) -> None: + tx_a: MoneroTx = MoneroTx() + tx_a.block = MoneroBlock() + tx_a.block.height = 100 + + tx_b: MoneroTx = MoneroTx() + tx_b.block = MoneroBlock() + tx_b.block.height = 200 + + assert tx_a < tx_b + assert not (tx_b < tx_a) + assert TxHeightComparator.compare(tx_a, tx_b) + assert not TxHeightComparator.compare(tx_b, tx_a) + + txs: list[MoneroTx] = [tx_b, tx_a] + txs.sort() + assert txs[0] is tx_a + assert txs[1] is tx_b + + # unconfirmed (no block) transactions sort after confirmed ones + tx_unconfirmed: MoneroTx = MoneroTx() + assert tx_a < tx_unconfirmed + assert not (tx_unconfirmed < tx_a) diff --git a/tests/daemon/rpc/__init__.py b/tests/daemon/rpc/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/daemon/rpc/base_test_monero_daemon_rpc.py b/tests/daemon/rpc/base_test_monero_daemon_rpc.py new file mode 100644 index 00000000..5c30d59d --- /dev/null +++ b/tests/daemon/rpc/base_test_monero_daemon_rpc.py @@ -0,0 +1,39 @@ +from __future__ import annotations + +import logging + +import pytest +from monero import MoneroDaemonRpc, MoneroWalletRpc +from typing_extensions import override + +from utils import BaseTestClass, BinaryBlockContext, IntegrationTestUtils, TestUtils as Utils, WalletType + +logger: logging.Logger = logging.getLogger("TestMoneroDaemonRpc") + + +class BaseTestMoneroDaemonRpc(BaseTestClass): + """Rpc daemon integration tests.""" + + BINARY_BLOCK_CTX: BinaryBlockContext = BinaryBlockContext() + + _test_wallet: MoneroWalletRpc | None = None + + @override + def before_all(self) -> None: + # setup wallet rpc for tests + IntegrationTestUtils.setup(WalletType.RPC) + + @pytest.fixture(scope="class") + @classmethod + def daemon(cls) -> MoneroDaemonRpc: + """Test rpc daemon instance""" + return Utils.get_daemon_rpc() + + @pytest.fixture(scope="class") + @classmethod + def wallet(cls) -> MoneroWalletRpc: + """Test rpc wallet instance""" + if cls._test_wallet is None: + cls._test_wallet = Utils.get_wallet_rpc() + + return cls._test_wallet diff --git a/tests/daemon/rpc/test_admin.py b/tests/daemon/rpc/test_admin.py new file mode 100644 index 00000000..7cb3ce97 --- /dev/null +++ b/tests/daemon/rpc/test_admin.py @@ -0,0 +1,137 @@ +from __future__ import annotations + +import logging +import time + +import pytest +from monero import ( + MoneroDaemonRpc, + MoneroDaemonUpdateCheckResult, + MoneroDaemonUpdateDownloadResult, + MoneroPruneResult, + MoneroRpcError, +) + +from utils import DaemonUtils, TestUtils as Utils +from .base_test_monero_daemon_rpc import BaseTestMoneroDaemonRpc + +logger: logging.Logger = logging.getLogger("TestMoneroDaemonRpcAdmin") + + +@pytest.mark.integration +class TestMoneroDaemonRpcAdmin(BaseTestMoneroDaemonRpc): + """Rpc daemon admin integration tests.""" + + # Can prune the blockchain + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_prune_blockchain(self, daemon: MoneroDaemonRpc) -> None: + result: MoneroPruneResult = daemon.prune_blockchain(True) + logger.debug(f"Testing prune result: {result.serialize()}") + + if result.is_pruned: + assert result.pruning_seed is not None + assert result.pruning_seed > 0 + else: + assert 0 == result.pruning_seed + + # Can check for an update + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + @pytest.mark.xfail(reason="the update check needs DNSSEC validated TXT records, which the daemon in docker does not get", raises=MoneroRpcError, strict=False) + def test_check_for_update(self, daemon: MoneroDaemonRpc) -> None: + result: MoneroDaemonUpdateCheckResult = daemon.check_for_update() + DaemonUtils.test_update_check_result(result) + + # Can download an update + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + @pytest.mark.xfail(reason="the update check needs DNSSEC validated TXT records, which the daemon in docker does not get", raises=MoneroRpcError, strict=False) + def test_download_update(self, daemon: MoneroDaemonRpc) -> None: + # download to default path + result: MoneroDaemonUpdateDownloadResult = daemon.download_update() + DaemonUtils.test_update_download_result(result, None) + + # download to defined path + path: str = "test_download_" + str(time.time()) + ".tar.bz2" + result = daemon.download_update(path) + DaemonUtils.test_update_download_result(result, path) + + # test invalid path + # TODO monerod: an invalid path causes a 500 in daemon rpc rather than a clean error + if result.is_update_available: + try: + daemon.download_update("./ohhai/there") + except Exception as e: + logger.warning(str(e)) + + # Can be stopped + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + @pytest.mark.skip(reason="test is disabled to not interfere with other tests") + def test_stop(self, daemon: MoneroDaemonRpc) -> None: + # stop the daemon + daemon.stop() + + # give the daemon time to shut down + time.sleep(Utils.SYNC_PERIOD_IN_MS / 1000) + + # try to interact with the stopped daemon + with pytest.raises(Exception): + daemon.get_height() + + # Can flush the blockchain to disk + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_save_blockchain(self, daemon: MoneroDaemonRpc) -> None: + daemon.save_blockchain() + + # Can flush the daemon's invalid block and tx caches + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_flush_cache(self, daemon: MoneroDaemonRpc) -> None: + daemon.flush_cache() + daemon.flush_cache(True) + + # Can disable the bootstrap daemon + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_remove_bootstrap_daemon(self, daemon: MoneroDaemonRpc) -> None: + daemon.remove_bootstrap_daemon() + + # Can set the poll period for block notifications + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_set_poll_period_in_ms(self, daemon: MoneroDaemonRpc) -> None: + try: + daemon.set_poll_period_in_ms(1000) + finally: + # restore the configured period so later tests poll at the expected rate + daemon.set_poll_period_in_ms(Utils.DAEMON_POLL_PERIOD_IN_MS) + + # Can set the daemon's log level + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_set_log_level(self, daemon: MoneroDaemonRpc) -> None: + try: + for i in range(0, 5): + daemon.set_log_level(i) + + for level in (-1, 5): + with pytest.raises(Exception) as exc_info: + daemon.set_log_level(level) + assert str(exc_info.value) == "Log level must be an integer between 0 and 4" + finally: + # restore the level from docker-compose so later tests keep full logs + daemon.set_log_level(Utils.DAEMON_LOG_LEVEL) + + # Can set the daemon's log categories + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_set_log_categories(self, daemon: MoneroDaemonRpc) -> None: + try: + categories: str = daemon.set_log_categories("*:WARNING") + assert isinstance(categories, str) + finally: + # re-applying the configured level also resets categories to its mapping + daemon.set_log_level(Utils.DAEMON_LOG_LEVEL) + + # Can toggle the mining hash rate in the daemon log + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_set_log_hash_rate(self, daemon: MoneroDaemonRpc) -> None: + try: + daemon.set_log_hash_rate(True) + daemon.set_log_hash_rate(False) + except Exception as e: + # daemon rejects the call while not mining + logger.warning(f"set_log_hash_rate: {e}") diff --git a/tests/daemon/rpc/test_blocks.py b/tests/daemon/rpc/test_blocks.py new file mode 100644 index 00000000..0a20f100 --- /dev/null +++ b/tests/daemon/rpc/test_blocks.py @@ -0,0 +1,338 @@ +from __future__ import annotations + +import logging + +import pytest +from monero import ( + MoneroAltChain, + MoneroBlock, + MoneroBlockHeader, + MoneroBlockTemplate, + MoneroDaemonRpc, + MoneroGetBlockHashesResult, + MoneroGetBlocksByHashResult, + MoneroMinerTxSum, +) + +from utils import AssertUtils, BlockUtils, DaemonUtils, MiningUtils, TestContext, TestUtils as Utils +from .base_test_monero_daemon_rpc import BaseTestMoneroDaemonRpc + +logger: logging.Logger = logging.getLogger("TestMoneroDaemonRpcBlocks") + + +@pytest.mark.integration +class TestMoneroDaemonRpcBlocks(BaseTestMoneroDaemonRpc): + """Rpc daemon blocks integration tests.""" + + # Can get the blockchain height + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_height(self, daemon: MoneroDaemonRpc) -> None: + height: int = daemon.get_height() + logger.debug(f"Daemon height: {height}") + assert height > 0, "Height must be greater than 0" + + # Can get a block hash by height + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_block_id_by_height(self, daemon: MoneroDaemonRpc) -> None: + last_header: MoneroBlockHeader = daemon.get_last_block_header() + logger.debug(f"Last block header height: {last_header.height}") + assert last_header.height is not None + hash_str: str = daemon.get_block_hash(last_header.height) + logger.debug(f"Got block hash: {hash_str}") + assert hash_str is not None + assert 64 == len(hash_str), f"Invalid block hash '{hash_str}'" + + # Can get a block template + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_block_template(self, daemon: MoneroDaemonRpc) -> None: + template: MoneroBlockTemplate = daemon.get_block_template(Utils.ADDRESS, 2) + BlockUtils.test_block_template(template) + + # Can get the last block's header + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_last_block_header(self, daemon: MoneroDaemonRpc) -> None: + last_header: MoneroBlockHeader = daemon.get_last_block_header() + BlockUtils.test_block_header(last_header, True) + + # Can get a block header by hash + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_block_header_by_hash(self, daemon: MoneroDaemonRpc) -> None: + # retrieve last block by hash + last_header: MoneroBlockHeader = daemon.get_last_block_header() + assert last_header.height is not None + hash_str: str = daemon.get_block_hash(last_header.height) + header: MoneroBlockHeader = daemon.get_block_header_by_hash(hash_str) + BlockUtils.test_block_header(header, True) + AssertUtils.assert_equals(last_header, header) + + # retrieve by hash of previous to last block + hash_str = daemon.get_block_hash(last_header.height - 1) + header = daemon.get_block_header_by_hash(hash_str) + BlockUtils.test_block_header(header, True) + assert last_header.height - 1 == header.height + + # Can get a block header by height + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_block_header_by_height(self, daemon: MoneroDaemonRpc) -> None: + # retrieve by height of last block + last_header: MoneroBlockHeader = daemon.get_last_block_header() + assert last_header.height is not None + header: MoneroBlockHeader = daemon.get_block_header_by_height(last_header.height) + BlockUtils.test_block_header(header, True) + AssertUtils.assert_equals(last_header, header) + + # retrieve by height of previous to last block + header = daemon.get_block_header_by_height(last_header.height - 1) + BlockUtils.test_block_header(header, True) + assert last_header.height - 1 == header.height + + # Can get block headers by range + # TODO: test start with no end, vice versa, inclusivity + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_block_headers_by_range(self, daemon: MoneroDaemonRpc) -> None: + # determine start and end height based on number of blocks and how many blocks ago + num_blocks: int = 100 + num_blocks_ago: int = 100 + current_height: int = daemon.get_height() + start_height: int = current_height - num_blocks_ago + end_height: int = current_height - (num_blocks_ago - num_blocks) - 1 + + # fetch headers + headers: list[MoneroBlockHeader] = daemon.get_block_headers_by_range(start_height, end_height) + + # test headers + assert num_blocks == len(headers) + + for i in range(num_blocks): + header: MoneroBlockHeader = headers[i] + assert start_height + i == header.height + BlockUtils.test_block_header(header, True) + + # Can get a block by hash + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_block_by_hash(self, daemon: MoneroDaemonRpc) -> None: + # test config + ctx: TestContext = TestContext() + ctx.has_hex = True + ctx.has_txs = False + ctx.header_is_full = True + + # retrieve by hash of last block + last_header: MoneroBlockHeader = daemon.get_last_block_header() + assert last_header.height is not None + hash_str: str = daemon.get_block_hash(last_header.height) + block: MoneroBlock = daemon.get_block_by_hash(hash_str) + assert block.height is not None + BlockUtils.test_block(block, ctx) + AssertUtils.assert_equals(daemon.get_block_by_height(block.height), block) + assert len(block.txs) == 0, f"No block tx expected, found: {len(block.txs)}" + + # retrieve by hash of previous to last block + hash_str = daemon.get_block_hash(last_header.height - 1) + block = daemon.get_block_by_hash(hash_str) + BlockUtils.test_block(block, ctx) + AssertUtils.assert_equals(daemon.get_block_by_height(last_header.height - 1), block) + assert len(block.txs) == 0, f"No block tx expected, found: {len(block.txs)}" + + # Can get blocks by hash which includes transactions (binary) + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_blocks_by_hash_binary(self, daemon: MoneroDaemonRpc) -> None: + chain_height: int = daemon.get_height() + genesis_hash: str = daemon.get_block_hash(0) + + # a non-zero start height resumes from there and ignores the hash list + resume_height: int = chain_height - 5 + result: MoneroGetBlocksByHashResult = daemon.get_blocks_by_hash([genesis_hash], resume_height, False, 0) + assert result.current_height is not None and result.current_height >= chain_height + assert len(result.blocks) > 0 + for i, block in enumerate(result.blocks): + assert block.height == resume_height + i + BlockUtils.test_block(block, self.BINARY_BLOCK_CTX) + + # a genesis-terminated history resumes from height 0, capped by max_block_count + result = daemon.get_blocks_by_hash([genesis_hash], 0, False, 10) + assert 0 < len(result.blocks) <= 10 + assert result.blocks[0].height == 0 + + # noop when the first hash is already the tip + tip: MoneroBlockHeader = daemon.get_last_block_header() + assert tip.hash is not None + result = daemon.get_blocks_by_hash([tip.hash, genesis_hash], 0, False, 0) + assert len(result.blocks) == 0 + + # Can get a block by height + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_block_by_height(self, daemon: MoneroDaemonRpc) -> None: + # config for testing blocks + ctx: TestContext = TestContext() + ctx.has_hex = True + ctx.header_is_full = True + ctx.has_txs = False + + # retrieve by height of last block + last_header: MoneroBlockHeader = daemon.get_last_block_header() + assert last_header.height is not None + block: MoneroBlock = daemon.get_block_by_height(last_header.height) + assert block.height is not None + BlockUtils.test_block(block, ctx) + AssertUtils.assert_equals(daemon.get_block_by_height(block.height), block) + + # retrieve by height of previous to last block + block = daemon.get_block_by_height(last_header.height - 1) + BlockUtils.test_block(block, ctx) + assert last_header.height - 1 == block.height + + # Can get blocks by height which includes transactions (binary) + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_blocks_by_height_binary(self, daemon: MoneroDaemonRpc) -> None: + # set number of blocks to test + num_blocks: int = 100 + + # select random heights # TODO: this is horribly inefficient way of computing last 100 blocks if not shuffling + current_height: int = daemon.get_height() + all_heights: list[int] = list(range(current_height - 1)) + start_height: int = len(all_heights) - num_blocks + heights: list[int] = list(range(start_height, len(all_heights))) + + # fetch blocks + blocks: list[MoneroBlock] = daemon.get_blocks_by_height(heights) + + # test blocks + tx_found: bool = False + assert num_blocks == len(blocks) + + for i, height in enumerate(heights): + block: MoneroBlock = blocks[i] + if len(block.txs) > 0: + tx_found = True + + BlockUtils.test_block(block, self.BINARY_BLOCK_CTX) + assert block.height == height + + assert tx_found, "No transactions found to test" + + # Can get blocks by range in a single request + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_blocks_by_range(self, daemon: MoneroDaemonRpc) -> None: + # get height range + num_blocks: int = 100 + num_blocks_ago: int = 102 + assert num_blocks > 0 + assert num_blocks_ago >= num_blocks + height: int = daemon.get_height() + assert height - num_blocks_ago + num_blocks - 1 < height + start_height: int = height - num_blocks_ago + end_height: int = height - num_blocks_ago + num_blocks - 1 + + # test known start and end heights + BlockUtils.test_get_blocks_range(daemon, start_height, end_height, height, False, self.BINARY_BLOCK_CTX) + + # test unspecified start + BlockUtils.test_get_blocks_range(daemon, None, num_blocks - 1, height, False, self.BINARY_BLOCK_CTX) + + # test unspecified end + BlockUtils.test_get_blocks_range(daemon, height - num_blocks - 1, None, height, False, self.BINARY_BLOCK_CTX) + + # Test invalid blocks range + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_blocks_by_range_invalid(self, daemon: MoneroDaemonRpc) -> None: + height: int = daemon.get_height() + blocks: list[MoneroBlock] = daemon.get_blocks_by_range_chunked(height, height - 10) + num_blocks: int = len(blocks) + assert num_blocks == 0, f"Expected empty blocks for invalid range request, got {num_blocks}" + + # Can get blocks by range using chunked requests + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_blocks_by_range_chunked(self, daemon: MoneroDaemonRpc) -> None: + # get long height range + num_blocks: int = min(daemon.get_height() - 2, 1440) # test up to ~2 days of blocks + assert num_blocks > 0 + height: int = daemon.get_height() + assert height - num_blocks - 1 < height + start_height: int = height - num_blocks + end_height: int = height - 1 + + # test known start and end heights + BlockUtils.test_get_blocks_range(daemon, start_height, end_height, height, True, self.BINARY_BLOCK_CTX) + + # test unspecified start + BlockUtils.test_get_blocks_range(daemon, None, num_blocks - 1, height, True, self.BINARY_BLOCK_CTX) + + # test unspecified end + BlockUtils.test_get_blocks_range(daemon, end_height - num_blocks - 1, None, height, True, self.BINARY_BLOCK_CTX) + + # Can get genesis block by range using chunked requests + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_genesis_block_by_range_chunked(self, daemon: MoneroDaemonRpc) -> None: + # get current chain height + chain_height: int = daemon.get_height() + + # test genesis + BlockUtils.test_get_blocks_range(daemon, 0, 0, chain_height, True, self.BINARY_BLOCK_CTX) + + # Can get block hashes (binary) + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_block_hashes_binary(self, daemon: MoneroDaemonRpc) -> None: + chain_height: int = daemon.get_height() + genesis_hash: str = daemon.get_block_hash(0) + + # a genesis-terminated history returns the whole chain from height 0 + result: MoneroGetBlockHashesResult = daemon.get_block_hashes([genesis_hash]) + assert result.start_height == 0 + assert result.current_height is not None and result.current_height >= chain_height + assert len(result.hashes) > 0 + assert result.hashes[0] == genesis_hash + for hash_str in result.hashes: + assert len(hash_str) == 64 + + # only the tip comes back when it is already the first hash + tip: MoneroBlockHeader = daemon.get_last_block_header() + assert tip.hash is not None + result = daemon.get_block_hashes([tip.hash, genesis_hash]) + assert result.hashes == [tip.hash] + + # Can get the miner tx sum + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_miner_tx_sum(self, daemon: MoneroDaemonRpc) -> None: + tx_sum: MoneroMinerTxSum = daemon.get_miner_tx_sum(0, min(5000, daemon.get_height())) + DaemonUtils.test_miner_tx_sum(tx_sum) + + # Can get alternative chains + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_alternative_chains(self, daemon: MoneroDaemonRpc) -> None: + alt_chains: list[MoneroAltChain] = daemon.get_alt_chains() + if len(alt_chains) == 0: + logger.warning("No alternative chain found!") + + for alt_chain in alt_chains: + BlockUtils.test_alt_chain(alt_chain) + + # Can get alternative block hashes + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_alternative_block_ids(self, daemon: MoneroDaemonRpc) -> None: + alt_block_ids: list[str] = daemon.get_alt_block_hashes() + if len(alt_block_ids) == 0: + logger.warning("No alternative block ids found!") + + for alt_block_id in alt_block_ids: + logger.debug(f"Testing alternarive block id: {alt_block_id}") + assert alt_block_id is not None + # TODO: common validation + assert 64, len(alt_block_id) + + # Can pop blocks from the top of the chain + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + @pytest.mark.skipif(Utils.REGTEST is False, reason="REGTEST disabled") + @pytest.mark.flaky(reruns=5, reruns_delay=5, only_rerun=[]) + def test_pop_blocks(self, daemon: MoneroDaemonRpc) -> None: + # stop mining so it doesn't race the pop, then restore the shared chain afterwards + MiningUtils.try_stop_mining(daemon) + height: int = daemon.get_height() + + assert daemon.pop_blocks(1) == height - 1 + MiningUtils.generate_blocks(Utils.MINING_ADDRESS, 1, daemon) + assert daemon.get_height() == height + + with pytest.raises(Exception) as exc_info: + daemon.pop_blocks(0) + assert str(exc_info.value) == "Must provide a number of blocks to pop greater than 0" diff --git a/tests/daemon/rpc/test_info.py b/tests/daemon/rpc/test_info.py new file mode 100644 index 00000000..30056f07 --- /dev/null +++ b/tests/daemon/rpc/test_info.py @@ -0,0 +1,86 @@ +from __future__ import annotations + +import logging + +import pytest +from monero import ( + MoneroDaemonInfo, + MoneroDaemonNetworkStats, + MoneroDaemonRpc, + MoneroDaemonSyncInfo, + MoneroHardForkInfo, + MoneroRpcConnection, + MoneroVersion, +) + +from utils import DaemonUtils, RpcConnectionUtils, TestUtils as Utils +from .base_test_monero_daemon_rpc import BaseTestMoneroDaemonRpc + +logger: logging.Logger = logging.getLogger("TestMoneroDaemonRpcInfo") + + +@pytest.mark.integration +class TestMoneroDaemonRpcInfo(BaseTestMoneroDaemonRpc): + """Rpc daemon info integration tests.""" + + # Test offline daemon connection + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_offline_daemon(self) -> None: + # create connection to offline uri + offline_connection: MoneroRpcConnection = MoneroRpcConnection(Utils.OFFLINE_SERVER_URI) + + assert offline_connection.check_connection() + assert not offline_connection.is_connected() + assert not offline_connection.is_online() + + # create daemon + daemon: MoneroDaemonRpc = MoneroDaemonRpc(offline_connection) + + # test daemon connection + assert daemon.get_rpc_connection() == offline_connection + assert not daemon.is_connected() + + # call to any daemon method should throw network error + with pytest.raises(Exception) as exc_info: + daemon.get_height() + assert str(exc_info.value) == RpcConnectionUtils.NETWORK_ERROR_MSG + + # Can get the daemon's version + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_version(self, daemon: MoneroDaemonRpc) -> None: + version: MoneroVersion = daemon.get_version() + logger.debug(f"Testing monero version: {version.serialize()}") + assert version.number is not None + assert version.number > 0 + assert version.is_release is not None + + # Can indicate if it's trusted + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_is_trusted(self, daemon: MoneroDaemonRpc) -> None: + is_trusted: bool = daemon.is_trusted() + logger.debug(f"Trusted daemon: {is_trusted}") + + # Can get general information + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_general_information(self, daemon: MoneroDaemonRpc) -> None: + info: MoneroDaemonInfo = daemon.get_info() + DaemonUtils.test_info(info) + assert info.is_regtest == Utils.REGTEST + + # Can get sync information + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_sync_information(self, daemon: MoneroDaemonRpc) -> None: + sync_info: MoneroDaemonSyncInfo = daemon.get_sync_info() + DaemonUtils.test_sync_info(sync_info) + + # Can get hard fork information + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_hard_fork_information(self, daemon: MoneroDaemonRpc) -> None: + hard_fork_info: MoneroHardForkInfo = daemon.get_hard_fork_info() + DaemonUtils.test_hard_fork_info(hard_fork_info) + + # Can get network (bandwidth) statistics + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_network_stats(self, daemon: MoneroDaemonRpc) -> None: + stats: MoneroDaemonNetworkStats = daemon.get_network_stats() + DaemonUtils.test_network_stats(stats) diff --git a/tests/daemon/rpc/test_listeners.py b/tests/daemon/rpc/test_listeners.py new file mode 100644 index 00000000..9e3f486d --- /dev/null +++ b/tests/daemon/rpc/test_listeners.py @@ -0,0 +1,88 @@ +from __future__ import annotations + +import logging + +import pytest +from monero import MoneroBlockHeader, MoneroDaemonListener, MoneroDaemonRpc, MoneroWalletRpc + +from utils import AssertUtils, BlockchainUtils, BlockUtils, DaemonNotificationCollector, TestUtils as Utils +from .base_test_monero_daemon_rpc import BaseTestMoneroDaemonRpc + +logger: logging.Logger = logging.getLogger("TestMoneroDaemonRpcListeners") + + +@pytest.mark.integration +class TestMoneroDaemonRpcListeners(BaseTestMoneroDaemonRpc): + """Rpc daemon listeners integration tests.""" + + # Can notify listeners when a new block is added to the chain + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + @pytest.mark.skipif(Utils.LITE_MODE is True or Utils.TEST_NOTIFICATIONS is False, reason="TEST_NOTIFICATIONS disabled") + def test_block_listener(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletRpc) -> None: + try: + # start mining if possible to help push the network along + address: str = wallet.get_primary_address() + try: + daemon.start_mining(address, 1, False, True) + except Exception as e: + logger.warning(f"[!]: {str(e)}") + + # register a listener + listener: MoneroDaemonListener = MoneroDaemonListener() + daemon.add_listener(listener) + + # wait for next block notification + header: MoneroBlockHeader = daemon.wait_for_next_block_header() + daemon.remove_listener(listener) # unregister listener so daemon does not keep polling + BlockUtils.test_block_header(header, True) + + # test that listener was called with equivalent header + AssertUtils.assert_equals(header, listener.last_header) + finally: + # stop mining + try : + daemon.stop_mining() + except Exception as e: + logger.warning(f"[!]: {str(e)}") + + # Can remove all listeners at once + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_remove_daemon_listeners(self, daemon: MoneroDaemonRpc) -> None: + listeners: list[DaemonNotificationCollector] = [DaemonNotificationCollector(daemon), DaemonNotificationCollector(daemon)] + for listener in listeners: + daemon.add_listener(listener) + try: + assert len(daemon.get_listeners()) == 2 + finally: + daemon.remove_listeners() + + assert len(daemon.get_listeners()) == 0 + + # Can start and stop listening + @pytest.mark.skipif(Utils.TEST_NOTIFICATIONS is False, reason="TEST_NOTIFICATIONS disabled") + def test_start_stop_listening(self, daemon: MoneroDaemonRpc) -> None: + # add listener + listener: DaemonNotificationCollector = DaemonNotificationCollector(daemon) + auto_remove_listener: DaemonNotificationCollector = DaemonNotificationCollector(daemon, True) + daemon.add_listener(listener) + daemon.add_listener(auto_remove_listener) + try: + assert len(daemon.get_listeners()) == 2 + + # mine blocks and collect notifications + BlockchainUtils.wait_for_blocks(10) + + # test notifications + assert listener.num_block_hashes > 0, "Daemon listener didn't collect any block hash" + assert listener.num_block_headers > 0, "Daemon listener didn't collect any block header" + assert listener.num_block_headers == listener.num_block_hashes, f"Count mismatch {listener.num_block_hashes} != {listener.num_block_headers}" + + # test autoremove listener + assert auto_remove_listener.num_block_headers == 1 + assert auto_remove_listener.num_block_hashes == 1 + assert len(daemon.get_listeners()) == 1 + finally: + # a listener that stays registered is called by the poller of the daemon for the rest of the session + daemon.remove_listeners() + + assert len(daemon.get_listeners()) == 0 diff --git a/tests/daemon/rpc/test_mining.py b/tests/daemon/rpc/test_mining.py new file mode 100644 index 00000000..e43bc8b9 --- /dev/null +++ b/tests/daemon/rpc/test_mining.py @@ -0,0 +1,130 @@ +from __future__ import annotations + +import logging + +import pytest +from monero import ( + MoneroAddAuxiliaryPowResult, + MoneroAuxiliaryPow, + MoneroBlockTemplate, + MoneroDaemonRpc, + MoneroMinerData, + MoneroMiningStatus, + MoneroWalletRpc, +) + +from utils import DaemonUtils, MiningUtils, TestUtils as Utils +from .base_test_monero_daemon_rpc import BaseTestMoneroDaemonRpc + +logger: logging.Logger = logging.getLogger("TestMoneroDaemonRpcMining") + + +@pytest.mark.integration +class TestMoneroDaemonRpcMining(BaseTestMoneroDaemonRpc): + """Rpc daemon mining integration tests.""" + + # Can start and stop mining + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_mining(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletRpc) -> None: + # stop mining at beginning of test + MiningUtils.try_stop_mining(daemon) + + # generate address to mine to + address: str = wallet.get_primary_address() + + # start mining + daemon.start_mining(address, 1, False, True) + + # stop mining + daemon.stop_mining() + + # Can get mining status + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_mining_status(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletRpc) -> None: + try: + # stop mining at beginning of test + MiningUtils.try_stop_mining(daemon) + + # test status without mining + status: MoneroMiningStatus = daemon.get_mining_status() + logger.debug(f"Testing mining status: {status.serialize()}") + assert status.is_active is False + assert status.address is None, f"Mining address is not None: {status.address}" + assert 0 == status.speed + assert 0 == status.num_threads + assert status.is_background is None + + # test status with mining + address: str = wallet.get_primary_address() + thread_count: int = 1 + is_background: bool = False + daemon.start_mining(address, thread_count, is_background, True) + status = daemon.get_mining_status() + logger.debug(f"Testing mining status: {status.serialize()}") + assert status.speed is not None + assert status.is_active is True + assert address == status.address + assert status.speed >= 0 + assert thread_count == status.num_threads + assert is_background == status.is_background + finally: + # stop mining at end of test + MiningUtils.try_stop_mining(daemon) + + # Can submit a mined block to the network + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + @pytest.mark.flaky(reruns=5, reruns_delay=5, only_rerun=[]) + def test_submit_mined_block(self, daemon: MoneroDaemonRpc) -> None: + # get template to mine on + template: MoneroBlockTemplate = daemon.get_block_template(Utils.ADDRESS) + assert template.block_template_blob is not None + + # TODO monero rpc: way to get mining nonce when found in order to submit? + + # try to submit block hashing blob without nonce + with pytest.raises(Exception) as exc_info: + daemon.submit_block(template.block_template_blob) + assert str(exc_info.value) == "Block not accepted" + + # Can get the data needed to mine a block + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_miner_data(self, daemon: MoneroDaemonRpc) -> None: + data: MoneroMinerData = daemon.get_miner_data() + DaemonUtils.test_miner_data(data) + + # Can calculate a block's proof-of-work hash + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_calculate_pow(self, daemon: MoneroDaemonRpc) -> None: + data: MoneroMinerData = daemon.get_miner_data() + template: MoneroBlockTemplate = daemon.get_block_template(Utils.ADDRESS) + assert data.major_version is not None + assert data.height is not None + assert data.seed_hash is not None + assert template.block_template_blob is not None + + pow_hash: str = daemon.calculate_pow(data.major_version, data.height, template.block_template_blob, data.seed_hash) + assert len(pow_hash) == 64 + + with pytest.raises(Exception) as exc_info: + daemon.calculate_pow(data.major_version, data.height, "", data.seed_hash) + assert str(exc_info.value) == "Must provide a block blob to hash" + + # Can add auxiliary proof-of-work to a block template + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_add_auxiliary_pow(self, daemon: MoneroDaemonRpc) -> None: + template: MoneroBlockTemplate = daemon.get_block_template(Utils.ADDRESS) + assert template.block_template_blob is not None + + aux_pow: MoneroAuxiliaryPow = MoneroAuxiliaryPow("11" * 32, "22" * 32) + result: MoneroAddAuxiliaryPowResult = daemon.add_auxiliary_pow(template.block_template_blob, [aux_pow]) + assert result.block_template_blob is not None and len(result.block_template_blob) > 0 + assert result.block_hashing_blob is not None and len(result.block_hashing_blob) > 0 + assert result.merkle_root is not None and len(result.merkle_root) == 64 + assert result.merkle_tree_depth is not None and result.merkle_tree_depth >= 0 + assert len(result.aux_pow) == 1 + assert result.aux_pow[0].id is not None and len(result.aux_pow[0].id) == 64 + assert result.aux_pow[0].hash is not None and len(result.aux_pow[0].hash) == 64 + + with pytest.raises(Exception) as exc_info: + daemon.add_auxiliary_pow(template.block_template_blob, []) + assert str(exc_info.value) == "Must provide auxiliary proof of work to add" diff --git a/tests/daemon/rpc/test_outputs.py b/tests/daemon/rpc/test_outputs.py new file mode 100644 index 00000000..a5043054 --- /dev/null +++ b/tests/daemon/rpc/test_outputs.py @@ -0,0 +1,143 @@ +from __future__ import annotations + +import logging + +import pytest +from monero import ( + MoneroDaemonRpc, + MoneroKeyImageSpentStatus, + MoneroOutput, + MoneroOutputDistributionEntry, + MoneroOutputHistogramEntry, + MoneroTx, + MoneroWalletRpc, +) + +from utils import DaemonUtils, OutputUtils, TestUtils as Utils, WalletTxsUtils +from .base_test_monero_daemon_rpc import BaseTestMoneroDaemonRpc + +logger: logging.Logger = logging.getLogger("TestMoneroDaemonRpcOutputs") + + +@pytest.mark.integration +class TestMoneroDaemonRpcOutputs(BaseTestMoneroDaemonRpc): + """Rpc daemon outputs integration tests.""" + + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_spent_status_of_key_images(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletRpc) -> None: + Utils.WALLET_TX_TRACKER.wait_for_txs_to_clear_pool(wallet) + + # submit txs to the pool to collect key images then flush them + txs: list[MoneroTx] = [] + + for i in range(1, 3): + tx: MoneroTx = WalletTxsUtils.get_unrelayed_tx(wallet, i) + assert tx.full_hex is not None + daemon.submit_tx_hex(tx.full_hex, True) + txs.append(tx) + + key_images: list[str] = [] + tx_hashes: list[str] = [] + for tx in txs: + assert tx.hash is not None + tx_hashes.append(tx.hash) + + for tx in daemon.get_txs(tx_hashes): + for tx_input in tx.inputs: + assert tx_input.key_image is not None + assert tx_input.key_image.hex is not None + key_images.append(tx_input.key_image.hex) + + daemon.flush_tx_pool(tx_hashes) + + # key images are not spent + DaemonUtils.test_spent_statuses(daemon, key_images, MoneroKeyImageSpentStatus.NOT_SPENT) + + # submit txs to the pool but don't relay + for tx in txs: + assert tx.full_hex is not None + daemon.submit_tx_hex(tx.full_hex, True) + + # key images are in the tx pool + DaemonUtils.test_spent_statuses(daemon, key_images, MoneroKeyImageSpentStatus.TX_POOL) + + # collect key images of confirmed txs + key_images = [] + txs = DaemonUtils.get_confirmed_txs(daemon, 10) + for tx in txs: + for tx_input in tx.inputs: + assert tx_input.key_image is not None + assert tx_input.key_image.hex is not None + key_images.append(tx_input.key_image.hex) + + # key images are all spent + DaemonUtils.test_spent_statuses(daemon, key_images, MoneroKeyImageSpentStatus.CONFIRMED) + + # flush this test's txs from pool + daemon.flush_tx_pool(tx_hashes) + + # Can get an output histogram (binary) + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_output_histogram_binary(self, daemon: MoneroDaemonRpc) -> None: + entries: list[MoneroOutputHistogramEntry] = daemon.get_output_histogram([], None, None, None, None) + assert len(entries) > 0 + for entry in entries: + OutputUtils.test_output_histogram_entry(entry) + + # Can get an output distribution + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_output_distribution(self, daemon: MoneroDaemonRpc) -> None: + amounts: list[int] = [0] + entries: list[MoneroOutputDistributionEntry] = daemon.get_output_distribution(amounts) + for entry in entries: + OutputUtils.test_output_distribution_entry(entry) + + # Can get the global output indices of a transaction + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_output_indices(self, daemon: MoneroDaemonRpc) -> None: + tx_hashes: list[str] = DaemonUtils.get_confirmed_tx_hashes(daemon) + assert len(tx_hashes) > 0, "No confirmed txs found" + + for tx_hash in tx_hashes: + indices: list[int] = daemon.get_output_indices(tx_hash) + assert len(indices) > 0 + for index in indices: + assert index >= 0 + + with pytest.raises(Exception) as exc_info: + daemon.get_output_indices("") + assert str(exc_info.value) == "Must provide a transaction hash" + + # Can get outputs given a list of output amounts and indices (binary) + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_outputs(self, daemon: MoneroDaemonRpc) -> None: + tx_hashes: list[str] = DaemonUtils.get_confirmed_tx_hashes(daemon) + assert len(tx_hashes) > 0, "No confirmed txs found" + + # identify each output by amount 0 (RingCT) and its global index + requested: list[MoneroOutput] = [] + for tx_hash in tx_hashes: + for index in daemon.get_output_indices(tx_hash): + output: MoneroOutput = MoneroOutput() + output.amount = 0 + output.index = index + requested.append(output) + + num_requested: int = len(requested) + assert num_requested > 0 + + fetched: list[MoneroOutput] = daemon.get_outputs(requested) + num_fetched: int = len(fetched) + assert num_fetched == num_requested + + for i, output in enumerate(fetched): + logger.debug(f"Testing fetched output: {output.serialize()}") + assert output.index == requested[i].index + assert output.stealth_public_key is not None and len(output.stealth_public_key) == 64 + assert output.mask is not None and len(output.mask) == 64 + assert output.tx is not None + assert output.tx.block is not None and output.tx.block.height is not None + + with pytest.raises(Exception) as exc_info: + daemon.get_outputs([]) + assert str(exc_info.value) == "Must provide outputs to fetch" diff --git a/tests/daemon/rpc/test_peers.py b/tests/daemon/rpc/test_peers.py new file mode 100644 index 00000000..07e4fd54 --- /dev/null +++ b/tests/daemon/rpc/test_peers.py @@ -0,0 +1,179 @@ +from __future__ import annotations + +import logging + +import pytest +from monero import MoneroBan, MoneroDaemonRpc, MoneroPeer + +from utils import DaemonUtils, TestUtils as Utils +from .base_test_monero_daemon_rpc import BaseTestMoneroDaemonRpc + +logger: logging.Logger = logging.getLogger("TestMoneroDaemonRpcPeers") + + +@pytest.mark.integration +class TestMoneroDaemonRpcPeers(BaseTestMoneroDaemonRpc): + """Rpc daemon peers integration tests.""" + + # Can get peers with active incoming or outgoing connections + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_peers(self, daemon: MoneroDaemonRpc) -> None: + peers: list[MoneroPeer] = daemon.get_peers() + assert len(peers) >= 0, "Daemon has no incoming or outgoing peers to test" + seen: set[tuple[str, int]] = set() + for peer in peers: + assert peer.host is not None + assert peer.port is not None + peer_key: tuple[str, int] = (peer.host, peer.port) + assert peer_key not in seen, f"Duplicate peer found: {peer_key}" + seen.add(peer_key) + assert peer.is_online, "Expected active peer connection to be online" + DaemonUtils.test_peer(peer) + + # Can get all known peers which may be online or offline + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_known_peers(self, daemon: MoneroDaemonRpc) -> None: + peers: list[MoneroPeer] = daemon.get_known_peers() + if Utils.REGTEST: + assert len(peers) == 0, "Regtest daemon should not have known peers to test" + logger.warning("Regtest daemon doesn't have known peers to test") + else: + assert len(peers) > 0, "Daemon has no known peers to test" + + for peer in peers: + DaemonUtils.test_known_peer(peer, False) + + # Can get public nodes known to the daemon + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_public_peers(self, daemon: MoneroDaemonRpc) -> None: + peers: list[MoneroPeer] = daemon.get_public_peers() + if Utils.REGTEST: + assert len(peers) == 0 + for peer in peers: + DaemonUtils.test_known_peer(peer, False) + + # Can limit the number of outgoing peers + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_set_outgoing_peer_limit(self, daemon: MoneroDaemonRpc) -> None: + daemon.set_outgoing_peer_limit(0) + daemon.set_outgoing_peer_limit(8) + daemon.set_outgoing_peer_limit(10) + + # Can limit the number of incoming peers + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_set_incoming_peer_limit(self, daemon: MoneroDaemonRpc) -> None: + daemon.set_incoming_peer_limit(0) + daemon.set_incoming_peer_limit(8) + daemon.set_incoming_peer_limit(10) + + # Can get, set, and reset a download bandwidth limit + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + @pytest.mark.flaky(reruns=5, reruns_delay=10, only_rerun=[]) + def test_set_download_bandwidth(self, daemon: MoneroDaemonRpc) -> None: + init_val: int = daemon.get_download_limit() + assert init_val > 0 + set_val: int = init_val * 2 + daemon.set_download_limit(set_val) + assert set_val == daemon.get_download_limit() + reset_val: int = daemon.reset_download_limit() + assert init_val == reset_val + + # test invalid limits + with pytest.raises(Exception) as exc_info: + daemon.set_download_limit(0) + assert str(exc_info.value) == "Download limit must be an integer greater than 0" + + assert daemon.get_download_limit() == init_val + + # Can get, set, and reset an upload bandwidth limit + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + @pytest.mark.flaky(reruns=5, reruns_delay=10, only_rerun=[]) + def test_set_upload_bandwidth(self, daemon: MoneroDaemonRpc) -> None: + init_val: int = daemon.get_upload_limit() + assert init_val > 0 + set_val: int = init_val * 2 + daemon.set_upload_limit(set_val) + assert set_val == daemon.get_upload_limit() + reset_val: int = daemon.reset_upload_limit() + assert init_val == reset_val + + # test invalid limits + with pytest.raises(Exception) as exc_info: + daemon.set_upload_limit(0) + assert str(exc_info.value) == "Upload limit must be an integer greater than 0" + + assert init_val == daemon.get_upload_limit() + + # Can ban a peer + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_ban_peer(self, daemon: MoneroDaemonRpc) -> None: + # set ban + host: str = "192.168.1.51" + ban: MoneroBan = MoneroBan() + ban.host = host + ban.is_banned = True + ban.seconds = 60 + daemon.set_peer_ban(ban) + + # test ban + bans: list[MoneroBan] = daemon.get_peer_bans() + found: bool = False + for peer_ban in bans: + DaemonUtils.test_ban(peer_ban) + if host == peer_ban.host: + found = True + + assert found, f"Could not find peer ban {host}" + + # Can ban peers + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_ban_peers(self, daemon: MoneroDaemonRpc) -> None: + # set bans + addr1: str = "192.168.1.52" + addr2: str = "192.168.1.53" + ban1: MoneroBan = MoneroBan() + ban1.host = addr1 + ban1.is_banned = True + ban1.seconds = 60 + ban2: MoneroBan = MoneroBan() + ban2.host = addr2 + ban2.is_banned = True + ban2.seconds = 60 + bans: list[MoneroBan] = [] + bans.append(ban1) + bans.append(ban2) + daemon.set_peer_bans(bans) + + # test bans + bans = daemon.get_peer_bans() + found1: bool = False + found2: bool = False + for a_ban in bans: + DaemonUtils.test_ban(a_ban) + if addr1 == a_ban.host: + found1 = True + if addr2 == a_ban.host: + found2 = True + + assert found1, f"Could not find peer ban1 {addr1}" + assert found2, f"Could not find peer ban2 {addr2}" + + # Can query the ban status of a single peer + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_peer_ban(self, daemon: MoneroDaemonRpc) -> None: + host: str = "192.168.1.60" + ban: MoneroBan = MoneroBan() + ban.host = host + ban.is_banned = True + ban.seconds = 60 + daemon.set_peer_ban(ban) + + banned: MoneroBan = daemon.get_peer_ban(host) + assert banned.is_banned is True + assert banned.seconds is not None and banned.seconds > 0 + + assert daemon.get_peer_ban("192.168.1.61").is_banned is False + + with pytest.raises(Exception) as exc_info: + daemon.get_peer_ban("") + assert str(exc_info.value) == "Must provide an address to check the ban status of" diff --git a/tests/daemon/rpc/test_tx_pool.py b/tests/daemon/rpc/test_tx_pool.py new file mode 100644 index 00000000..f3c8032c --- /dev/null +++ b/tests/daemon/rpc/test_tx_pool.py @@ -0,0 +1,274 @@ +from __future__ import annotations + +import logging + +import pytest +from monero import ( + MoneroDaemonRpc, + MoneroFeeEstimate, + MoneroSubmitTxResult, + MoneroTx, + MoneroTxPoolStats, + MoneroWalletRpc, +) + +from utils import ( + DaemonUtils, + GenUtils, + SubmitThenRelayTxTester, + TestContext, + TestUtils as Utils, + TxUtils, + WalletTxsUtils, +) +from .base_test_monero_daemon_rpc import BaseTestMoneroDaemonRpc + +logger: logging.Logger = logging.getLogger("TestMoneroDaemonRpcTxPool") + + +@pytest.mark.integration +class TestMoneroDaemonRpcTxPool(BaseTestMoneroDaemonRpc): + """Rpc daemon tx pool integration tests.""" + + # Can get fee estimate + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_fee_estimate(self, daemon: MoneroDaemonRpc) -> None: + fee_estimate: MoneroFeeEstimate = daemon.get_fee_estimate() + logger.debug(f"Testing fee estimate: {fee_estimate.serialize()}") + GenUtils.test_unsigned_big_integer(fee_estimate.fee, True) + assert len(fee_estimate.fees) == 4, "Exptected 4 fees" + for fee in fee_estimate.fees: + GenUtils.test_unsigned_big_integer(fee, True) + GenUtils.test_unsigned_big_integer(fee_estimate.quantization_mask, True) + + # Can get all transactions in the transaction pool + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_txs_in_pool(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletRpc) -> None: + Utils.WALLET_TX_TRACKER.wait_for_txs_to_clear_pool(wallet) + + # submit tx to pool but don't relay + tx: MoneroTx = WalletTxsUtils.get_unrelayed_tx(wallet, 1) + assert tx.hash is not None + assert tx.full_hex is not None + result: MoneroSubmitTxResult = daemon.submit_tx_hex(tx.full_hex, True) + DaemonUtils.test_submit_tx_result_good(result) + assert result.is_relayed is False + + # fetch txs in pool + txs: list[MoneroTx] = daemon.get_tx_pool() + num_txs: int = len(txs) + + # fetch tx hashes in pool + tx_hashes: list[str] = daemon.get_tx_pool_hashes() + num_tx_hashes: int = len(tx_hashes) + + # context for testing tx + ctx: TestContext = TestContext() + ctx.is_pruned = False + ctx.is_confirmed = False + ctx.from_get_tx_pool = True + + # test txs + assert num_txs > 0, "Test requires an unconfirmed tx in the tx pool" + assert num_txs == num_tx_hashes, f"Txs in pool {num_txs} != Txs hashes in pool {num_tx_hashes}" + for a_tx in txs: + TxUtils.test_tx(a_tx, ctx) + assert a_tx.hash in tx_hashes + + # flush the tx from the pool, gg + daemon.flush_tx_pool(tx.hash) + wallet.sync() + + # Can get transaction pool statistics + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_tx_pool_statistics(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletRpc) -> None: + Utils.WALLET_TX_TRACKER.wait_for_txs_to_clear_pool([wallet]) + tx_ids: list[str] = [] + try: + # submit txs to the pool but don't relay + for i in range(1, 3): + # submit tx hex + tx: MoneroTx = WalletTxsUtils.get_unrelayed_tx(wallet, i) + assert tx.full_hex is not None + result: MoneroSubmitTxResult = daemon.submit_tx_hex(tx.full_hex, True) + assert result.is_good, f"Expected True, got {result.is_good}" + assert tx.hash is not None + tx_ids.append(tx.hash) + + # get tx pool stats + stats: MoneroTxPoolStats = daemon.get_tx_pool_stats() + assert stats.num_txs is not None + assert stats.num_txs > i - 1 + DaemonUtils.test_tx_pool_stats(stats) + finally: + # flush txs + daemon.flush_tx_pool(tx_ids) + + # Can flush all transactions from the pool + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_flush_txs_from_pool(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletRpc) -> None: + Utils.WALLET_TX_TRACKER.wait_for_txs_to_clear_pool(wallet) + + # preserve original transactions in the pool + tx_pool_before: list[MoneroTx] = daemon.get_tx_pool() + + # submit txs to the pool but don't relay + for i in range(1, 3): + tx: MoneroTx = WalletTxsUtils.get_unrelayed_tx(wallet, i) + assert tx.full_hex is not None + result: MoneroSubmitTxResult = daemon.submit_tx_hex(tx.full_hex, True) + DaemonUtils.test_submit_tx_result_good(result) + + assert len(tx_pool_before) + 2 == len(daemon.get_tx_pool()) + + # flush tx pool + daemon.flush_tx_pool() + assert len(daemon.get_tx_pool()) == 0 + + # re-submit original transactions + for tx in tx_pool_before: + assert tx.full_hex is not None + assert tx.is_relayed is not None + result: MoneroSubmitTxResult = daemon.submit_tx_hex(tx.full_hex, tx.is_relayed) + + # pool is back to original state + assert len(tx_pool_before) == len(daemon.get_tx_pool()) + + # sync wallet for next test + wallet.sync() + + # Can flush a transaction from the pool by hash + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_flush_tx_from_pool_by_hash(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletRpc) -> None: + Utils.WALLET_TX_TRACKER.wait_for_txs_to_clear_pool(wallet) + + # preserve original transactions in the pool + tx_pool_before: list[MoneroTx] = daemon.get_tx_pool() + + # submit txs to the pool but don't relay + txs: list[MoneroTx] = [] + for i in range(1, 3): + tx: MoneroTx = WalletTxsUtils.get_unrelayed_tx(wallet, i) + assert tx.full_hex is not None + result: MoneroSubmitTxResult = daemon.submit_tx_hex(tx.full_hex, True) + DaemonUtils.test_submit_tx_result_good(result) + txs.append(tx) + + # remove each tx from the pool by hash and test + num_txs: int = len(txs) + for i, tx in enumerate(txs): + assert tx.hash is not None + # flush tx from pool + daemon.flush_tx_pool(tx.hash) + + # test tx pool + pool_txs: list[MoneroTx] = daemon.get_tx_pool() + assert num_txs - i - 1 == len(pool_txs) + + # pool is back to original state + assert len(tx_pool_before) == len(daemon.get_tx_pool()) + + # sync wallet for next test + wallet.sync() + + # Can flush transactions from the pool by hashes + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_flush_txs_from_pool_by_hashes(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletRpc) -> None: + Utils.WALLET_TX_TRACKER.wait_for_txs_to_clear_pool(wallet) + + # preserve original transactions in the pool + tx_pool_before: list[MoneroTx] = daemon.get_tx_pool() + + # submit txs to the pool but don't relay + tx_hashes: list[str] = [] + for i in range(1, 3): + tx: MoneroTx = WalletTxsUtils.get_unrelayed_tx(wallet, i) + assert tx.hash is not None + assert tx.full_hex is not None + result: MoneroSubmitTxResult = daemon.submit_tx_hex(tx.full_hex, True) + DaemonUtils.test_submit_tx_result_good(result) + tx_hashes.append(tx.hash) + + assert len(tx_pool_before) + len(tx_hashes) == len(daemon.get_tx_pool()) + + # remove all txs by hashes + daemon.flush_tx_pool(tx_hashes) + + # pool is back to original state + assert len(tx_pool_before) == len(daemon.get_tx_pool()) + wallet.sync() + + # Can submit a tx in hex format to the pool and relay in one call + @pytest.mark.skipif(Utils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") + @pytest.mark.skipif(Utils.LITE_MODE, reason="LITE_MODE enabled") + def test_submit_and_relay_tx_hex(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletRpc) -> None: + # wait one time for wallet txs in the pool to clear + # TODO monero-project: update from pool does not prevent creating double spend tx + Utils.WALLET_TX_TRACKER.wait_for_txs_to_clear_pool(wallet) + + # create 2 txs, the second will double spend outputs of first + # TODO: this test requires tx to be from/to different accounts else + # the occlusion issue (#4500) causes the tx to not be recognized by the wallet at all + tx1: MoneroTx = WalletTxsUtils.get_unrelayed_tx(wallet, 2) + tx2: MoneroTx = WalletTxsUtils.get_unrelayed_tx(wallet, 2) + + # submit and relay tx1 + assert tx1.hash is not None + assert tx1.full_hex is not None + result: MoneroSubmitTxResult = daemon.submit_tx_hex(tx1.full_hex) + assert result.is_relayed is True + DaemonUtils.test_submit_tx_result_good(result) + + # tx1 is in the pool + txs: list[MoneroTx] = daemon.get_tx_pool() + found: bool = False + for a_tx in txs: + assert a_tx.hash is not None + if a_tx.hash == tx1.hash: + assert a_tx.is_relayed is True + found = True + break + + assert found, "Tx1 was not found after being submitted to the daemon's tx pool" + + # tx1 is recognized by the wallet + wallet.sync() + wallet.get_tx(tx1.hash) + + # submit and relay tx2 hex which double spends tx1 + assert tx2.full_hex is not None + result = daemon.submit_tx_hex(tx2.full_hex) + assert result.is_relayed is True + DaemonUtils.test_submit_tx_result_double_spend(result) + + # tx2 is not in the pool + txs = daemon.get_tx_pool() + found = False + for a_tx in txs: + assert a_tx.hash is not None + if a_tx.hash == tx2.hash: + found = True + break + + assert not found, "Tx2 should not be in the pool because it double spends tx1 which is in the pool" + + # Can submit a tx in hex format to the pool then relay + @pytest.mark.skipif(Utils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") + @pytest.mark.skipif(Utils.LITE_MODE, reason="LITE_MODE enabled") + def test_submit_then_relay_tx_hex(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletRpc) -> None: + Utils.WALLET_TX_TRACKER.wait_for_txs_to_clear_pool(wallet) + tx: MoneroTx = WalletTxsUtils.get_unrelayed_tx(wallet, 1) + tester: SubmitThenRelayTxTester = SubmitThenRelayTxTester(daemon, [tx]) + tester.test() + + # Can submit txs in hex format to the pool then relay + @pytest.mark.skipif(Utils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") + @pytest.mark.skipif(Utils.LITE_MODE, reason="LITE_MODE enabled") + def test_submit_then_relay_tx_hexes(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletRpc) -> None: + Utils.WALLET_TX_TRACKER.wait_for_txs_to_clear_pool(wallet) + txs: list[MoneroTx] = [] + txs.append(WalletTxsUtils.get_unrelayed_tx(wallet, 1)) + # TODO: accounts cannot be re-used across send tests else isRelayed is true; wallet needs to update? + txs.append(WalletTxsUtils.get_unrelayed_tx(wallet, 2)) + tester: SubmitThenRelayTxTester = SubmitThenRelayTxTester(daemon, txs) + tester.test() diff --git a/tests/daemon/rpc/test_txs.py b/tests/daemon/rpc/test_txs.py new file mode 100644 index 00000000..aeb709c9 --- /dev/null +++ b/tests/daemon/rpc/test_txs.py @@ -0,0 +1,195 @@ +from __future__ import annotations + +import logging + +import pytest +from monero import ( + MoneroDaemonRpc, + MoneroDestination, + MoneroSubmitTxResult, + MoneroTx, + MoneroTxConfig, + MoneroWalletRpc, +) + +from utils import DaemonUtils, TestContext, TestUtils as Utils, TxUtils, TxWalletUtils, WalletTxsUtils +from .base_test_monero_daemon_rpc import BaseTestMoneroDaemonRpc + +logger: logging.Logger = logging.getLogger("TestMoneroDaemonRpcTxs") + + +@pytest.mark.integration +class TestMoneroDaemonRpcTxs(BaseTestMoneroDaemonRpc): + """Rpc daemon txs integration tests.""" + + # Can get a transaction by hash and without pruning + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_tx_by_hash(self, daemon: MoneroDaemonRpc) -> None: + # fetch tx hashses to test + tx_hashes: list[str] = DaemonUtils.get_confirmed_tx_hashes(daemon) + + # context for creating txs + ctx: TestContext = TestContext() + ctx.is_pruned = False + ctx.is_confirmed = True + ctx.from_get_tx_pool = False + + # fetch each tx by hash without pruning + for tx_hash in tx_hashes: + tx: MoneroTx | None = daemon.get_tx(tx_hash) + TxUtils.test_tx(tx, ctx) + + # fetch each tx by hash with pruning + for tx_hash in tx_hashes: + tx: MoneroTx | None = daemon.get_tx(tx_hash, True) + ctx.is_pruned = True + TxUtils.test_tx(tx, ctx) + + # fetch invalid hash + with pytest.raises(Exception) as exc_info: + daemon.get_tx("invalid tx hash") + assert str(exc_info.value) == "Invalid transaction hash" + + # Can get transactions by hashes with and without pruning + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + @pytest.mark.flaky(reruns=5, reruns_delay=5, only_rerun=[]) + def test_get_txs_by_hashes(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletRpc) -> None: + # fetch tx hashses to test + tx_hashes: list[str] = DaemonUtils.get_confirmed_tx_hashes(daemon) + assert len(tx_hashes) > 0, "No tx hashes found" + + # context for creating txs + ctx: TestContext = TestContext() + ctx.is_pruned = False + ctx.is_confirmed = True + ctx.from_get_tx_pool = False + + # fetch each tx by hash without pruning + txs: list[MoneroTx] = daemon.get_txs(tx_hashes) + assert len(txs) == len(tx_hashes), f"Expected len(txs) == len(tx_hashes), got {len(txs)} == {len(tx_hashes)}" + for tx in txs: + TxUtils.test_tx(tx, ctx) + + # fetch each tx by hash with pruning + txs = daemon.get_txs(tx_hashes, True) + ctx.is_pruned = True + assert len(txs) == len(tx_hashes), f"Expected len(txs) == len(tx_hashes), got {len(txs)} == {len(tx_hashes)}" + for tx in txs: + TxUtils.test_tx(tx, ctx) + + # fetch missing hash + dest: MoneroDestination = MoneroDestination() + dest.address = wallet.get_primary_address() + dest.amount = TxWalletUtils.MAX_FEE + config: MoneroTxConfig = MoneroTxConfig() + config.account_index = 0 + config.destinations.append(dest) + tx = wallet.create_tx(config) + assert tx.hash is not None + daemon_tx: MoneroTx | None = daemon.get_tx(tx.hash) + assert daemon_tx is None + tx_hashes.append(tx.hash) + num_txs: int = len(txs) + txs = daemon.get_txs(tx_hashes) + assert num_txs == len(txs) + + # fetch invalid hash + with pytest.raises(Exception) as exc_info: + daemon.get_txs(["invalid tx hash"]) + assert str(exc_info.value) == "Invalid transaction hash" + + # Can get transactions by hashes that are in the transaction pool + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_txs_by_hashes_in_pool(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletRpc) -> None: + # wait for wallet's txs in the pool to clear to ensure reliable sync + Utils.WALLET_TX_TRACKER.wait_for_txs_to_clear_pool(wallet) + + # submit txs to the pool but don't relay + tx_hashes: list[str] = [] + for i in range(1, 3): + tx: MoneroTx = WalletTxsUtils.get_unrelayed_tx(wallet, i) + assert tx.hash is not None + assert tx.full_hex is not None + assert len(tx.full_hex) > 0 + result: MoneroSubmitTxResult = daemon.submit_tx_hex(tx.full_hex, True) + DaemonUtils.test_submit_tx_result_good(result) + assert result.is_relayed is False + tx_hashes.append(tx.hash) + + # fetch txs by hash + logger.debug("Fetching txs...") + txs: list[MoneroTx] = daemon.get_txs(tx_hashes) + num_txs: int = len(txs) + logger.debug(f"Fetched {num_txs} tx(s)") + + # context for testing tx + ctx: TestContext = TestContext() + ctx.is_pruned = False + ctx.is_confirmed = False + ctx.from_get_tx_pool = False + + # test fetched txs + assert len(tx_hashes) == num_txs + for tx in txs: + TxUtils.test_tx(tx, ctx) + + # clear txs from pool + daemon.flush_tx_pool(tx_hashes) + wallet.sync() + + # Can get a transaction hex by hash with and without pruning + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_tx_hex_by_hash(self, daemon: MoneroDaemonRpc) -> None: + # fetch transaction hashes to test + tx_hashes: list[str] = DaemonUtils.get_confirmed_tx_hashes(daemon) + + # fetch each tx hex by hash with and without pruning + hexes: list[str | None] = [] + hexes_pruned: list[str | None] = [] + for tx_hash in tx_hashes: + hexes.append(daemon.get_tx_hex(tx_hash)) + hexes_pruned.append(daemon.get_tx_hex(tx_hash, True)) + + # test results + assert len(hexes) == len(tx_hashes) + assert len(hexes_pruned) == len(tx_hashes) + + for i, tx_hex in enumerate(hexes): + pruned_tx_hex: str | None = hexes_pruned[i] + assert tx_hex is not None + assert pruned_tx_hex is not None + assert len(pruned_tx_hex) > 0 + # pruned hex is shorter + assert len(tx_hex) >= len(pruned_tx_hex) + + # fetch invalid hash + with pytest.raises(Exception) as exc_info: + daemon.get_tx_hex("invalid tx hash") + assert str(exc_info.value) == "Invalid transaction hash" + + # Can get transaction hexes by hashes with and without pruning + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_tx_hexes_by_hashes(self, daemon: MoneroDaemonRpc) -> None: + # fetch transaction hashes to test + tx_hashes: list[str] = DaemonUtils.get_confirmed_tx_hashes(daemon) + + # fetch tx hexes by hash with and without pruning + hexes: list[str] = daemon.get_tx_hexes(tx_hashes) + hexes_pruned: list[str] = daemon.get_tx_hexes(tx_hashes, True) + + # test results + assert len(hexes) == len(tx_hashes) + assert len(hexes_pruned) == len(tx_hashes) + for i, tx_hex in enumerate(hexes): + pruned_tx_hex: str = hexes_pruned[i] + assert tx_hex is not None + assert pruned_tx_hex is not None + assert len(pruned_tx_hex) > 0 + # pruned hex is shorter + assert len(tx_hex) >= len(pruned_tx_hex) + + # fetch invalid hash + tx_hashes.append("invalid tx hash") + with pytest.raises(Exception) as exc_info: + daemon.get_tx_hexes(tx_hashes) + assert str(exc_info.value) == "Invalid transaction hash" diff --git a/tests/test_monero_daemon_interface.py b/tests/daemon/test_interface.py similarity index 100% rename from tests/test_monero_daemon_interface.py rename to tests/daemon/test_interface.py diff --git a/tests/daemon/test_listener_lifetime.py b/tests/daemon/test_listener_lifetime.py new file mode 100644 index 00000000..3247caf1 --- /dev/null +++ b/tests/daemon/test_listener_lifetime.py @@ -0,0 +1,111 @@ +from __future__ import annotations + +import gc +import logging +import weakref + +from time import monotonic, sleep +from typing import override + +import pytest +from monero import MoneroBlockHeader, MoneroDaemonListener, MoneroDaemonRpc + +from utils import BaseTestClass, FakeDaemonRpcServer + +logger: logging.Logger = logging.getLogger("TestMoneroDaemonListenerLifetime") + + +class _HeaderRecorder(MoneroDaemonListener): + """Listener that only records the heights it is notified of, in a list that the test keeps.""" + + def __init__(self, heights: list[int]) -> None: + super().__init__() + self._heights: list[int] = heights + + @override + def on_block_header(self, header: MoneroBlockHeader) -> None: + assert header.height is not None + self._heights.append(header.height) + + +@pytest.mark.unit +class TestMoneroDaemonListenerLifetime(BaseTestClass): + """A listener that Python does not reference any more must stay alive while the daemon has it. + + The poller of the daemon calls its listeners from a thread of its own. When the listener was freed by Python, the poller called a + deleted object, and the process died with a segmentation fault. + """ + + #region Tests + + # The poller notifies a listener that nothing but the daemon references + def test_listener_is_notified_after_python_drops_it(self) -> None: + heights: list[int] = [] + with FakeDaemonRpcServer() as server: + daemon: MoneroDaemonRpc = MoneroDaemonRpc(server.uri) + daemon.set_poll_period_in_ms(20) + listener: _HeaderRecorder = _HeaderRecorder(heights) + listener_ref: weakref.ref[_HeaderRecorder] = weakref.ref(listener) + daemon.add_listener(listener) + try: + # the only reference left is the one that add_listener keeps + del listener + gc.collect() + assert listener_ref() is not None, "The daemon does not keep alive its listener" + + # it is called many times, by the thread of the poller, while the objects around it are collected + deadline: float = monotonic() + 10 + while len(heights) < 10 and monotonic() < deadline: + gc.collect() + sleep(0.02) + assert len(heights) >= 10, f"The listener was notified {len(heights)} times" + assert heights == sorted(heights), f"Block headers out of order: {heights}" + finally: + daemon.remove_listeners() + + # The listener is released with the daemon that kept it + def test_listener_is_released_with_the_daemon(self) -> None: + heights: list[int] = [] + with FakeDaemonRpcServer() as server: + daemon: MoneroDaemonRpc = MoneroDaemonRpc(server.uri) + daemon.set_poll_period_in_ms(20) + listener: _HeaderRecorder = _HeaderRecorder(heights) + listener_ref: weakref.ref[_HeaderRecorder] = weakref.ref(listener) + daemon.add_listener(listener) + del listener + gc.collect() + assert listener_ref() is not None + + # removed once the poller has run: removing a listener right after adding it can make the destruction of the daemon wait forever + deadline: float = monotonic() + 10 + while len(heights) < 2 and monotonic() < deadline: + sleep(0.02) + assert len(heights) >= 2, f"The listener was notified {len(heights)} times" + + daemon.remove_listeners() + del daemon + gc.collect() + assert listener_ref() is None, "The listener is kept alive after its daemon is gone" + + # The daemon is destroyed while its poller waits for the node + def test_daemon_is_destroyed_with_a_request_in_flight(self) -> None: + # The server of this process answers from a thread of python, which needs the GIL. The destruction of the daemon waits for the + # request of the poller, and it used to do it with the GIL held: both waited for the other one until the request timed out. + heights: list[int] = [] + with FakeDaemonRpcServer(response_delay=0.5) as server: + daemon: MoneroDaemonRpc = MoneroDaemonRpc(server.uri, timeout_ms=20000) + daemon.set_poll_period_in_ms(20) + daemon.add_listener(_HeaderRecorder(heights)) + requests: int = server.num_requests + deadline: float = monotonic() + 10 + while server.num_requests == requests and monotonic() < deadline: + sleep(0.005) + assert server.num_requests > requests, "The poller did not ask the node" + + start: float = monotonic() + del daemon + gc.collect() + elapsed: float = monotonic() - start + assert elapsed < 10, f"The destruction of the daemon took {elapsed:.1f} s" + + #endregion diff --git a/tests/test_monero_daemon_model.py b/tests/test_monero_daemon_model.py deleted file mode 100644 index 02f7f7e9..00000000 --- a/tests/test_monero_daemon_model.py +++ /dev/null @@ -1,1065 +0,0 @@ -import pytest -import logging -import subprocess -import sys - -from typing import LiteralString - -from monero import ( - MoneroVersion, MoneroRpcPaymentInfo, MoneroRpcConnection, MoneroAltChain, - MoneroBan, MoneroPruneResult, MoneroMiningStatus, MoneroMinerTxSum, - MoneroBlockTemplate, MoneroConnectionSpan, MoneroPeer, MoneroConnectionType, - MoneroSubmitTxResult, MoneroOutputDistributionEntry, MoneroOutputHistogramEntry, - MoneroTxPoolStats, MoneroDaemonUpdateCheckResult, MoneroDaemonUpdateDownloadResult, - MoneroFeeEstimate, MoneroDaemonInfo, MoneroNetworkType, MoneroDaemonSyncInfo, - MoneroHardForkInfo, MoneroGenerateBlocksResult, MoneroTx, MoneroKeyImage, - MoneroOutput, MoneroBlockHeader, MoneroBlock, TxHeightComparator, - MoneroMinerData, MoneroDaemonNetworkStats, MoneroAuxiliaryPow, - MoneroAddAuxiliaryPowResult, MoneroGetBlocksByHashResult, MoneroGetBlockHashesResult -) -from utils import BaseTestClass, AssertUtils - -logger: logging.Logger = logging.getLogger("TestMoneroDaemonModel") - - -@pytest.mark.unit -class TestMoneroDaemonModel(BaseTestClass): - """Test monero daemon data models' deserialize() (from_property_tree) round trips.""" - - #region Common / rpc models - - def test_version_deserialize(self) -> None: - version: MoneroVersion = MoneroVersion() - version.number = 65552 - version.is_release = True - AssertUtils.assert_serialization_integrity(version) - - def test_rpc_payment_info_deserialize(self) -> None: - info: MoneroRpcPaymentInfo = MoneroRpcPaymentInfo() - info.credits = 42 - info.top_block_hash = "a" * 64 - AssertUtils.assert_serialization_integrity(info) - - def test_rpc_connection_deserialize(self) -> None: - connection: MoneroRpcConnection = MoneroRpcConnection("http://127.0.0.1:18081", "user", "pass", "127.0.0.1:9050", "tcp://127.0.0.1:18083", 2, 5000) - json_str: str = connection.serialize() - logger.debug(f"Serialized rpc connection: {json_str}") - restored: MoneroRpcConnection = MoneroRpcConnection.deserialize(json_str) - assert restored.uri == connection.uri - assert restored.username == connection.username - assert restored.password == connection.password - assert restored.proxy_uri == connection.proxy_uri - assert restored.zmq_uri == connection.zmq_uri - - def test_rpc_connection_priority_and_timeout_deserialize(self) -> None: - # to_rapidjson_val() emits "priority" and "timeoutMs" but - # from_property_tree() never read either back - connection: MoneroRpcConnection = MoneroRpcConnection("http://127.0.0.1:18081", priority=2, timeout_ms=5000) - json_str: str = connection.serialize() - logger.debug(f"Serialized rpc connection: {json_str}") - assert '"priority"' in json_str and '"timeoutMs"' in json_str - restored: MoneroRpcConnection = MoneroRpcConnection.deserialize(json_str) - logger.debug(f"Deserialized rpc connection re-serialized: {restored.serialize()}") - assert restored.priority == connection.priority - assert restored.timeout_ms == connection.timeout_ms - - #endregion - - #region Blockchain / mining models - - def test_alt_chain_deserialize(self) -> None: - alt_chain: MoneroAltChain = MoneroAltChain() - alt_chain.block_hashes = ["a" * 64, "b" * 64] - alt_chain.difficulty_low = 100 - alt_chain.difficulty_high = 0 - alt_chain.height = 12345 - alt_chain.length = 3 - alt_chain.main_chain_parent_block_hash = "c" * 64 - AssertUtils.assert_serialization_integrity(alt_chain) - - def test_ban_deserialize(self) -> None: - ban: MoneroBan = MoneroBan() - ban.host = "127.0.0.1" - ban.ip = 2130706433 - ban.is_banned = True - ban.seconds = 3600 - AssertUtils.assert_serialization_integrity(ban) - - def test_prune_result_deserialize(self) -> None: - result: MoneroPruneResult = MoneroPruneResult() - result.pruning_seed = 387 - # is_pruned is deliberately not set here: to_rapidjson_val() serializes it - # under "isPruned" but from_property_tree() looks for "pruned" instead, so - # it never round trips (see test below) - AssertUtils.assert_serialization_integrity(result) - - def test_prune_result_is_pruned_deserialize(self) -> None: - result: MoneroPruneResult = MoneroPruneResult() - result.is_pruned = True - json_str: str = result.serialize() - logger.debug(f"Serialized prune result: {json_str}") - assert '"isPruned"' in json_str - restored: MoneroPruneResult = MoneroPruneResult.deserialize(json_str) - logger.debug(f"Deserialized prune result re-serialized: {restored.serialize()}") - assert restored.is_pruned == result.is_pruned - - def test_mining_status_deserialize(self) -> None: - status: MoneroMiningStatus = MoneroMiningStatus() - status.is_active = True - status.is_background = False - status.address = "9" + "a" * 94 - status.speed = 500 - status.num_threads = 4 - AssertUtils.assert_serialization_integrity(status) - - def test_mining_status_inactive_clears_background_and_address_deserialize(self) -> None: - # when isActive is false from_property_tree drops isBackground and address - # even if present in the json - json_str: str = ( - '{"isActive": false, "isBackground": true, ' - '"address": "' + "9" + "a" * 94 + '", "speed": 500, "numThreads": 4}' - ) - status: MoneroMiningStatus = MoneroMiningStatus.deserialize(json_str) - assert status.is_active is False - assert status.is_background is None - assert status.address is None - assert status.speed == 500 - assert status.num_threads == 4 - - def test_miner_tx_sum_deserialize(self) -> None: - summ: MoneroMinerTxSum = MoneroMinerTxSum() - summ.emission_sum_low = 1000 - summ.emission_sum_high = 0 - summ.fee_sum_low = 10 - summ.fee_sum_high = 0 - AssertUtils.assert_serialization_integrity(summ) - - def test_block_template_deserialize(self) -> None: - template: MoneroBlockTemplate = MoneroBlockTemplate() - template.block_template_blob = "abcd" - template.block_hashing_blob = "ef01" - template.prev_hash = "a" * 64 - template.seed_hash = "b" * 64 - template.next_seed_hash = "c" * 64 - template.difficulty_low = 5000 - template.difficulty_high = 0 - template.expected_reward = 600000000000 - template.height = 12345 - template.reserved_offset = 130 - template.seed_height = 0 - AssertUtils.assert_serialization_integrity(template) - - def test_block_header_deserialize(self) -> None: - header: MoneroBlockHeader = MoneroBlockHeader() - header.hash = "a" * 64 - header.height = 12345 - header.timestamp = 1600000000 - header.size = 2048 - header.weight = 2048 - header.long_term_weight = 2048 - header.depth = 10 - header.difficulty_low = 5000 - header.difficulty_high = 0 - header.cumulative_difficulty_low = 900000 - header.cumulative_difficulty_high = 0 - header.major_version = 16 - header.minor_version = 16 - header.nonce = 42 - header.miner_tx_hash = "b" * 64 - header.num_txs = 3 - header.orphan_status = False - header.prev_hash = "c" * 64 - header.reward = 600000000000 - header.pow_hash = "d" * 64 - AssertUtils.assert_serialization_integrity(header) - - def test_block_deserialize(self) -> None: - block: MoneroBlock = MoneroBlock() - block.hash = "a" * 64 - block.height = 12345 - block.hex = "deadbeef" - block.tx_hashes = ["b" * 64, "c" * 64] - - miner_tx: MoneroTx = MoneroTx() - miner_tx.hash = "d" * 64 - miner_tx.is_miner_tx = True - block.miner_tx = miner_tx - - tx: MoneroTx = MoneroTx() - tx.hash = "e" * 64 - block.txs = [tx] - - restored: MoneroBlock = AssertUtils.assert_serialization_integrity(block) - - # nested txs are parsed and back-linked to the block - assert restored.miner_tx is not None - assert restored.miner_tx.hash == "d" * 64 - assert restored.miner_tx.is_miner_tx is True - assert restored.miner_tx.block is not None and restored.miner_tx.block.height == 12345 - assert len(restored.txs) == 1 - assert restored.txs[0].hash == "e" * 64 - assert restored.txs[0].block is not None and restored.txs[0].block.height == 12345 - - def test_connection_span_deserialize(self) -> None: - span: MoneroConnectionSpan = MoneroConnectionSpan() - span.connection_id = "deadbeef" - span.remote_address = "127.0.0.1:18080" - span.num_blocks = 10 - span.rate = 100 - span.speed = 200 - span.size = 1024 - span.start_height = 1000 - AssertUtils.assert_serialization_integrity(span) - - def test_peer_deserialize(self) -> None: - peer: MoneroPeer = MoneroPeer() - peer.id = "1122334455667788" - peer.address = "127.0.0.1:18080" - peer.host = "127.0.0.1" - peer.port = 18080 - peer.last_seen_timestamp = 1700000000 - peer.pruning_seed = 0 - peer.rpc_port = 18081 - peer.rpc_credits_per_hash = 0 - peer.hash = "a" * 64 - peer.avg_download = 10 - peer.avg_upload = 20 - peer.current_download = 30 - peer.current_upload = 40 - peer.height = 12345 - peer.is_incoming = True - peer.live_time = 3600 - peer.is_local_ip = False - peer.is_local_host = False - peer.num_receives = 5 - peer.num_sends = 6 - peer.receive_idle_time = 7 - peer.send_idle_time = 8 - peer.state = "normal" - peer.num_support_flags = 1 - # is_online and connection_type are serialized (isOnline/addressType) but - # monero_peer::from_property_tree() never reads them back, so they are - # deliberately excluded from this round trip (see test below). - AssertUtils.assert_serialization_integrity(peer) - - def test_peer_is_online_deserialize(self) -> None: - peer: MoneroPeer = MoneroPeer() - peer.is_online = True - json_str: str = peer.serialize() - logger.debug(f"Serialized peer: {json_str}") - assert "isOnline" in json_str - restored: MoneroPeer = MoneroPeer.deserialize(json_str) - logger.debug(f"Deserialized peer re-serialized: {restored.serialize()}") - assert restored.is_online == peer.is_online - - def test_peer_connection_serialization_integrity(self) -> None: - peer: MoneroPeer = MoneroPeer() - peer.connection_type = MoneroConnectionType.IPV6 - json_str: str = peer.serialize() - logger.debug(f"Serialized peer: {json_str}") - assert "addressType" in json_str - restored: MoneroPeer = MoneroPeer.deserialize(json_str) - logger.debug(f"Deserialized peer re-serialized: {restored.serialize()}") - assert restored.connection_type == peer.connection_type - - def test_peer_connection_type_deserialize(self) -> None: - # connection_type is likewise never serialized by to_rapidjson_val(), so it - # can only be exercised by handing from_property_tree a raw "addressType" field - for value, expected in [ - (0, MoneroConnectionType.INVALID), - (1, MoneroConnectionType.IPV4), - (2, MoneroConnectionType.IPV6), - (3, MoneroConnectionType.TOR), - (4, MoneroConnectionType.I2P), - ]: - peer: MoneroPeer = MoneroPeer.deserialize(f'{{"addressType":{value}}}') - assert peer.connection_type == expected - - def test_peer_connection_type_invalid(self) -> None: - # TODO throws RuntimeError rather than MoneroError - with pytest.raises(RuntimeError, match="Invalid RPC peer type"): - MoneroPeer.deserialize('{"addressType":5}') - - def test_submit_tx_result_deserialize(self) -> None: - result: MoneroSubmitTxResult = MoneroSubmitTxResult() - result.credits = 1 - result.top_block_hash = "a" * 64 - result.is_relayed = True - result.is_double_spend = False - result.is_fee_too_low = False - result.has_invalid_input = False - result.has_invalid_output = False - result.has_too_few_outputs = False - result.is_mixin_too_low = False - result.is_overspend = False - result.reason = "ok" - result.is_too_big = False - result.sanity_check_failed = False - result.is_tx_extra_too_big = False - result.is_nonzero_unlock_time = False - # is_good is serialized but never read back by from_property_tree() - AssertUtils.assert_serialization_integrity(result) - - def test_submit_tx_result_is_good_deserialize(self) -> None: - result: MoneroSubmitTxResult = MoneroSubmitTxResult() - result.is_good = True - json_str: str = result.serialize() - logger.debug(f"Serialized submit tx result: {json_str}") - assert "isGood" in json_str - restored: MoneroSubmitTxResult = MoneroSubmitTxResult.deserialize(json_str) - logger.debug(f"Deserialized submit tx result re-serialized: {restored.serialize()}") - assert restored.is_good == result.is_good - - def test_output_distribution_entry_deserialize(self) -> None: - entry: MoneroOutputDistributionEntry = MoneroOutputDistributionEntry() - entry.amount = 0 - entry.base = 100 - entry.distribution = [1, 2, 3, 4] - entry.start_height = 0 - AssertUtils.assert_serialization_integrity(entry) - - def test_output_histogram_entry_deserialize(self) -> None: - entry: MoneroOutputHistogramEntry = MoneroOutputHistogramEntry() - entry.amount = 0 - entry.num_instances = 10 - entry.unlocked_instances = 8 - entry.recent_instances = 2 - AssertUtils.assert_serialization_integrity(entry) - - def test_tx_pool_stats_deserialize(self) -> None: - stats: MoneroTxPoolStats = MoneroTxPoolStats() - stats.num_txs = 5 - stats.num_not_relayed = 1 - stats.num_failing = 0 - stats.num_double_spends = 0 - stats.num10m = 2 - stats.fee_total = 1000 - stats.bytes_max = 2000 - stats.bytes_med = 1500 - stats.bytes_min = 1000 - stats.bytes_total = 5000 - stats.histo98pc = 1800 - stats.oldest_timestamp = 1700000000 - # histo is serialized as an object but from_property_tree() has a TODO - # and never reads it back into the map - AssertUtils.assert_serialization_integrity(stats) - - def test_tx_pool_stats_histo_deserialize(self) -> None: - stats: MoneroTxPoolStats = MoneroTxPoolStats() - stats.histo = {100: 1, 200: 2} - json_str: str = stats.serialize() - logger.debug(f"Serialized tx pool stats: {json_str}") - assert "histo" in json_str - restored: MoneroTxPoolStats = MoneroTxPoolStats.deserialize(json_str) - logger.debug(f"Deserialized tx pool stats re-serialized: {restored.serialize()}") - assert dict(restored.histo) == dict(stats.histo) - - def test_daemon_update_check_result_deserialize(self) -> None: - result: MoneroDaemonUpdateCheckResult = MoneroDaemonUpdateCheckResult() - result.is_update_available = True - result.version = "0.18.5.1" - result.hash = "a" * 64 - result.auto_uri = "https://example.com/auto" - result.user_uri = "https://example.com/user" - AssertUtils.assert_serialization_integrity(result) - - def test_daemon_update_download_result_deserialize(self) -> None: - result: MoneroDaemonUpdateDownloadResult = MoneroDaemonUpdateDownloadResult() - result.is_update_available = True - result.version = "0.18.5.1" - result.hash = "a" * 64 - result.auto_uri = "https://example.com/auto" - result.user_uri = "https://example.com/user" - result.download_path = "/tmp/update.bin" - AssertUtils.assert_serialization_integrity(result) - - def test_fee_estimate_deserialize(self) -> None: - estimate: MoneroFeeEstimate = MoneroFeeEstimate() - estimate.fee = 20000 - estimate.quantization_mask = 10000 - estimate.fees = [10000, 20000, 30000, 40000] - AssertUtils.assert_serialization_integrity(estimate) - - def test_daemon_info_deserialize(self) -> None: - info: MoneroDaemonInfo = MoneroDaemonInfo() - info.credits = 0 - info.top_block_hash = "a" * 64 - info.version = "0.18.5.1" - info.num_alt_blocks = 1 - info.block_size_limit = 600000 - info.block_size_median = 300000 - info.block_weight_limit = 600000 - info.block_weight_median = 300000 - info.bootstrap_daemon_address = "node.example.com" - info.difficulty_low = 123456 - info.difficulty_high = 0 - info.cumulative_difficulty_low = 987654 - info.cumulative_difficulty_high = 0 - info.free_space = 1000000000 - info.num_offline_peers = 1 - info.num_online_peers = 10 - info.height = 3000000 - info.height_without_bootstrap = 3000000 - info.network_type = MoneroNetworkType.TESTNET - info.is_offline = False - info.num_incoming_connections = 5 - info.num_outgoing_connections = 8 - info.num_rpc_connections = 2 - info.start_timestamp = 1600000000 - info.adjusted_timestamp = 1700000000 - info.target = 120 - info.target_height = 0 - info.num_txs = 100 - info.num_txs_pool = 3 - info.was_bootstrap_ever_used = False - info.database_size = 100000000 - info.update_available = False - info.is_busy_syncing = False - info.is_synchronized = True - info.is_restricted = False - info.is_regtest = True - AssertUtils.assert_serialization_integrity(info) - - def test_daemon_info_invalid_network_type(self) -> None: - with pytest.raises(RuntimeError, match="invalid network type"): - MoneroDaemonInfo.deserialize('{"networkType":9}') - - def test_daemon_sync_info_deserialize(self) -> None: - info: MoneroDaemonSyncInfo = MoneroDaemonSyncInfo() - info.credits = 0 - info.top_block_hash = "a" * 64 - info.height = 3000000 - info.target_height = 3000010 - info.next_needed_pruning_seed = 0 - info.overview = "syncing" - # peers/spans are serialized as sub-arrays but from_property_tree() never - # reads them back (see test below) - AssertUtils.assert_serialization_integrity(info) - - def test_daemon_sync_info_peers_and_spans_deserialize(self) -> None: - info: MoneroDaemonSyncInfo = MoneroDaemonSyncInfo() - info.peers = [MoneroPeer()] - info.spans = [MoneroConnectionSpan()] - json_str: str = info.serialize() - logger.debug(f"Serialized daemon sync info: {json_str}") - assert "peers" in json_str and "spans" in json_str - restored: MoneroDaemonSyncInfo = MoneroDaemonSyncInfo.deserialize(json_str) - logger.debug(f"Deserialized daemon sync info re-serialized: {restored.serialize()}") - assert len(restored.peers) == len(info.peers) - assert len(restored.spans) == len(info.spans) - - def test_hard_fork_info_deserialize(self) -> None: - info: MoneroHardForkInfo = MoneroHardForkInfo() - info.credits = 0 - info.top_block_hash = "a" * 64 - info.earliest_height = 100000 - info.is_enabled = True - info.state = 0 - info.threshold = 0 - info.version = 16 - info.num_votes = 5000 - info.window = 10080 - info.voting = 16 - AssertUtils.assert_serialization_integrity(info) - - def test_generate_blocks_result_deserialize(self) -> None: - result: MoneroGenerateBlocksResult = MoneroGenerateBlocksResult() - result.block_hashes = ["a" * 64, "b" * 64] - result.height = 12345 - AssertUtils.assert_serialization_integrity(result) - - def test_miner_data_deserialize(self) -> None: - data: MoneroMinerData = MoneroMinerData() - data.credits = 0 - data.top_block_hash = "a" * 64 - data.major_version = 16 - data.height = 3000000 - data.prev_hash = "b" * 64 - data.seed_hash = "c" * 64 - data.difficulty = "0x1f4" # daemon reports difficulty as a hex string - data.median_weight = 300000 - data.already_generated_coins = 5646232813355588 - tx: MoneroTx = MoneroTx() - tx.hash = "d" * 64 - tx.fee = 10000 - data.tx_pool_backlog = [tx] - AssertUtils.assert_serialization_integrity(data) - - def test_daemon_network_stats_deserialize(self) -> None: - stats: MoneroDaemonNetworkStats = MoneroDaemonNetworkStats() - stats.credits = 0 - stats.top_block_hash = "a" * 64 - stats.start_time = 1700000000 - stats.total_packets_in = 1234 - stats.total_bytes_in = 567890 - stats.total_packets_out = 4321 - stats.total_bytes_out = 98765 - AssertUtils.assert_serialization_integrity(stats) - - def test_auxiliary_pow_deserialize(self) -> None: - aux_pow: MoneroAuxiliaryPow = MoneroAuxiliaryPow("a" * 64, "b" * 64) - assert aux_pow.id == "a" * 64 - assert aux_pow.hash == "b" * 64 - AssertUtils.assert_serialization_integrity(aux_pow) - - def test_add_auxiliary_pow_result_deserialize(self) -> None: - result: MoneroAddAuxiliaryPowResult = MoneroAddAuxiliaryPowResult() - result.credits = 0 - result.top_block_hash = "a" * 64 - result.block_template_blob = "abcd" - result.block_hashing_blob = "ef01" - result.merkle_root = "b" * 64 - result.merkle_tree_depth = 2 - result.aux_pow = [MoneroAuxiliaryPow("c" * 64, "d" * 64)] - AssertUtils.assert_serialization_integrity(result) - - def test_get_block_hashes_result_deserialize(self) -> None: - result: MoneroGetBlockHashesResult = MoneroGetBlockHashesResult() - result.hashes = ["a" * 64, "b" * 64] - result.start_height = 100 - result.current_height = 3000000 - AssertUtils.assert_serialization_integrity(result) - - def test_get_blocks_by_hash_result_deserialize(self) -> None: - result: MoneroGetBlocksByHashResult = MoneroGetBlocksByHashResult() - result.current_height = 3000000 - # blocks are serialized but from_property_tree() never reads them back - # (monero_block has no from_property_tree of its own); see test below - AssertUtils.assert_serialization_integrity(result) - - def test_get_blocks_by_hash_result_blocks_deserialize(self) -> None: - result: MoneroGetBlocksByHashResult = MoneroGetBlocksByHashResult() - block: MoneroBlock = MoneroBlock() - block.hash = "a" * 64 - block.height = 100 - result.blocks = [block] - json_str: str = result.serialize() - logger.debug(f"Serialized get blocks by hash result: {json_str}") - assert '"blocks"' in json_str - restored: MoneroGetBlocksByHashResult = MoneroGetBlocksByHashResult.deserialize(json_str) - assert len(restored.blocks) == 0 - - #endregion - - #region Tx / output / key image - - def test_key_image_deserialize(self) -> None: - key_image: MoneroKeyImage = MoneroKeyImage() - key_image.hex = "a" * 64 - key_image.signature = "b" * 128 - AssertUtils.assert_serialization_integrity(key_image) - - def test_key_image_deserialize_key_images(self) -> None: - json_str: str = ( - '{"keyImages": [' - '{"hex": "' + "a" * 64 + '", "signature": "' + "b" * 128 + '"}, ' - '{"hex": "' + "c" * 64 + '"}' - ']}' - ) - key_images: list[MoneroKeyImage] = MoneroKeyImage.deserialize_key_images(json_str) - assert len(key_images) == 2 - assert key_images[0].hex == "a" * 64 - assert key_images[0].signature == "b" * 128 - assert key_images[1].hex == "c" * 64 - assert key_images[1].signature is None - - # a missing or empty keyImages array yields no key images - assert MoneroKeyImage.deserialize_key_images("{}") == [] - assert MoneroKeyImage.deserialize_key_images('{"keyImages": []}') == [] - - # an empty string is not valid json - with pytest.raises(Exception): - MoneroKeyImage.deserialize_key_images("") - - def test_output_deserialize(self) -> None: - output: MoneroOutput = MoneroOutput() - output.amount = 1000000 - output.index = 5 - key_image: MoneroKeyImage = MoneroKeyImage() - key_image.hex = "a" * 64 - key_image.signature = "b" * 128 - output.key_image = key_image - AssertUtils.assert_serialization_integrity(output) - - def test_output_ring_output_indices_and_stealth_public_key_deserialize(self) -> None: - output: MoneroOutput = MoneroOutput() - output.amount = 1000000 - output.index = 5 - output.ring_output_indices = [10, 20, 30] - output.stealth_public_key = "a" * 64 - output.mask = "b" * 64 - AssertUtils.assert_serialization_integrity(output) - - def test_tx_deserialize(self) -> None: - tx: MoneroTx = MoneroTx() - tx.hash = "a" * 64 - tx.is_miner_tx = False - tx.payment_id = "b" * 16 - tx.fee = 7500000 - tx.relay = True - tx.is_relayed = True - tx.is_confirmed = True - tx.in_tx_pool = False - tx.is_locked = False - tx.num_confirmations = 10 - tx.unlock_time = 0 - tx.last_relayed_timestamp = 1700000000 - tx.received_timestamp = 1700000000 - tx.is_double_spend_seen = False - tx.key = "c" * 64 - tx.full_hex = "deadbeef" - tx.pruned_hex = "deadbeef" - tx.prunable_hex = "deadbeef" - tx.prunable_hash = "d" * 64 - tx.size = 1500 - tx.weight = 1500 - tx.metadata = "meta" - tx.is_kept_by_block = False - tx.is_failed = False - tx.last_failed_hash = "e" * 64 - tx.max_used_block_hash = "f" * 64 - # mixin, rctSignatures, rctSigPrunable and signatures are still left - # unimplemented in from_property_tree() (see below) - AssertUtils.assert_serialization_integrity(tx) - - @pytest.mark.parametrize("json_fragment", [ - '{"mixin":5}', - '{"rctSignatures":"x"}', - '{"rctSigPrunable":"x"}', - '{"signatures":["x"]}', - ]) - def test_tx_unimplemented_fields(self, json_fragment: str) -> None: - with pytest.raises(Exception, match="not implemented"): - MoneroTx.deserialize(json_fragment) - - def test_tx_version_common_tx_sets_last_failed_and_max_used_block_height_deserialize(self) -> None: - tx: MoneroTx = MoneroTx() - tx.version = 2 - tx.common_tx_sets = "sets" - tx.last_failed_height = 100 - tx.max_used_block_height = 200 - AssertUtils.assert_serialization_integrity(tx) - - def test_tx_ring_size_deserialize(self) -> None: - tx: MoneroTx = MoneroTx() - tx.ring_size = 16 - AssertUtils.assert_serialization_integrity(tx) - - def test_tx_extra_deserialize(self) -> None: - tx: MoneroTx = MoneroTx() - tx.extra = [1, 2, 3, 255] - AssertUtils.assert_serialization_integrity(tx) - - def test_tx_inputs_outputs_and_output_indices_deserialize(self) -> None: - tx: MoneroTx = MoneroTx() - tx.output_indices = [100, 101] - vin: MoneroOutput = MoneroOutput() - vin.amount = 1 - vin.key_image = MoneroKeyImage() - vin.key_image.hex = "a" * 64 - tx.inputs = [vin] - vout: MoneroOutput = MoneroOutput() - vout.amount = 2 - vout.index = 0 - tx.outputs = [vout] - AssertUtils.assert_serialization_integrity(tx) - - #endregion - - #region Copy / merge / comparators - - def test_block_header_copy(self) -> None: - header: MoneroBlockHeader = MoneroBlockHeader() - header.hash = "a" * 64 - header.height = 100 - header.timestamp = 1700000000 - header.size = 1000 - header.weight = 1000 - header.major_version = 16 - header.minor_version = 16 - header.nonce = 12345 - header.reward = 600000000000 - - copy: MoneroBlockHeader = header.copy() - assert copy is not header - assert copy.serialize() == header.serialize() - - # copy is independent of the original - copy.height = 999 - assert header.height == 100 - - def test_block_header_merge(self) -> None: - a: MoneroBlockHeader = MoneroBlockHeader() - a.hash = "a" * 64 - a.height = 100 - a.timestamp = 1700000000 - - b: MoneroBlockHeader = a.copy() - b.height = 200 # height can increase -> resolves to the higher value - b.timestamp = 1800000000 # timestamp can increase -> resolves to the higher value - b.size = 2000 # a.size is unset -> merge fills the gap - - a.merge(b) - assert a.height == 200 - assert a.timestamp == 1800000000 - assert a.size == 2000 - assert a.hash == "a" * 64 - - def test_block_header_merge_conflict_raises(self) -> None: - # fields without special reconciliation (e.g. hash) must match on both - # sides, or merge() raises rather than silently picking one - a: MoneroBlockHeader = MoneroBlockHeader() - a.hash = "a" * 64 - b: MoneroBlockHeader = MoneroBlockHeader() - b.hash = "b" * 64 - with pytest.raises(Exception, match="[Cc]annot reconcile"): - a.merge(b) - - def test_block_copy(self) -> None: - block: MoneroBlock = MoneroBlock() - block.hash = "a" * 64 - block.height = 100 - block.hex = "deadbeef" - block.tx_hashes = ["b" * 64, "c" * 64] - - miner_tx: MoneroTx = MoneroTx() - miner_tx.hash = "d" * 64 - miner_tx.is_miner_tx = True - block.miner_tx = miner_tx - - tx: MoneroTx = MoneroTx() - tx.hash = "e" * 64 - block.txs = [tx] - - copy: MoneroBlock = block.copy() - assert copy is not block - assert copy.serialize() == block.serialize() - - # miner tx and non-wallet txs are deep copied and back-linked to the copy - assert copy.miner_tx is not None and copy.miner_tx is not block.miner_tx - assert copy.miner_tx.hash == "d" * 64 - assert copy.miner_tx.block is copy - assert len(copy.txs) == 1 - assert copy.txs[0] is not block.txs[0] - assert copy.txs[0].hash == "e" * 64 - assert copy.txs[0].block is copy - - def test_block_merge(self) -> None: - a: MoneroBlock = MoneroBlock() - a.hash = "a" * 64 - a.height = 100 - b: MoneroBlock = a.copy() - b.hex = "deadbeef" # a.hex is unset -> merge fills the gap - a.merge(b) - assert a.hex == "deadbeef" - - def test_block_header_merge_dispatches_to_block_merge(self) -> None: - a: MoneroBlock = MoneroBlock() - a.height = 100 - b: MoneroBlock = MoneroBlock() - b.height = 100 - b.hex = "deadbeef" # a.hex is unset -> merge fills the gap - - MoneroBlockHeader.merge(a, b) - assert a.hex == "deadbeef" - - def test_block_merge_adopts_other_miner_tx(self) -> None: - a: MoneroBlock = MoneroBlock() - a.height = 100 - # a.miner_tx is unset -> merge adopts other's miner tx and repoints its block at a - - b: MoneroBlock = MoneroBlock() - b.height = 100 - miner_tx: MoneroTx = MoneroTx() - miner_tx.hash = "a" * 64 - miner_tx.is_miner_tx = True - b.miner_tx = miner_tx - - a.merge(b) - assert a.miner_tx is not None - assert a.miner_tx is b.miner_tx - assert a.miner_tx.hash == "a" * 64 - assert a.miner_tx.block is a - - def test_block_merge_merges_distinct_miner_txs(self) -> None: - a: MoneroBlock = MoneroBlock() - a.height = 100 - miner_a: MoneroTx = MoneroTx() - miner_a.hash = "a" * 64 - miner_a.is_confirmed = True # required: tx merge() dereferences is_confirmed directly - a.miner_tx = miner_a - - b: MoneroBlock = MoneroBlock() - b.height = 100 - miner_b: MoneroTx = MoneroTx() - miner_b.hash = "a" * 64 - miner_b.is_confirmed = True - miner_b.num_confirmations = 5 # miner_a's num_confirmations is unset -> merge fills the gap - b.miner_tx = miner_b - - a.merge(b) - assert a.miner_tx is miner_a # kept in place, fields merged into it - assert a.miner_tx.num_confirmations == 5 - assert a.miner_tx.block is a - - def test_block_merge_txs_with_unset_hash_are_kept_distinct(self) -> None: - script: LiteralString = ( - "import monero, sys\n" - "a = monero.MoneroBlock()\n" - "a.height = 100\n" - "tx_a = monero.MoneroTx()\n" # hash intentionally left unset - "a.txs = [tx_a]\n" - "b = monero.MoneroBlock()\n" - "b.height = 100\n" - "tx_b = monero.MoneroTx()\n" # hash intentionally left unset - "b.txs = [tx_b]\n" - "a.merge(b)\n" - "n = len(a.txs) if a.txs else 0\n" - "sys.exit(0 if n == 2 else f'txs not kept distinct: len={n}')\n" - ) - result: subprocess.CompletedProcess[str] = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, timeout=30) - logger.debug(f"subprocess exit code: {result.returncode}, stderr: {result.stderr.strip()}") - assert result.returncode == 0, ( - f"Block.merge() did not keep unset-hash txs distinct (exit code {result.returncode}): " - f"{result.stderr.strip()[-300:]}" - ) - - def test_tx_copy(self) -> None: - tx: MoneroTx = MoneroTx() - tx.hash = "a" * 64 - tx.is_confirmed = True - tx.fee = 7500000 - - copy: MoneroTx = tx.copy() - assert copy is not tx - assert copy.serialize() == tx.serialize() - - def test_tx_copy_deep_copies_inputs(self) -> None: - tx: MoneroTx = MoneroTx() - tx.hash = "a" * 64 - - key_image: MoneroKeyImage = MoneroKeyImage() - key_image.hex = "1" * 64 - tx_input: MoneroOutput = MoneroOutput() - tx_input.tx = tx - tx_input.key_image = key_image - tx_input.amount = 1234 - tx.inputs = [tx_input] - - copy: MoneroTx = tx.copy() - assert len(copy.inputs) == 1 - assert copy.inputs[0] is not tx_input - assert copy.inputs[0].key_image.hex == "1" * 64 # type: ignore - assert copy.inputs[0].amount == 1234 - assert copy.inputs[0].tx is copy - - def test_tx_merge(self) -> None: - a: MoneroTx = MoneroTx() - a.hash = "a" * 64 - a.is_confirmed = True # required: merge() dereferences is_confirmed directly - a.fee = 7500000 - - b: MoneroTx = a.copy() - b.num_confirmations = 5 # a.num_confirmations is unset -> merge fills the gap - a.merge(b) - assert a.num_confirmations == 5 - - def test_tx_merge_adopts_other_block(self) -> None: - block: MoneroBlock = MoneroBlock() - block.height = 200 - - other: MoneroTx = MoneroTx() - other.hash = "a" * 64 - other.is_confirmed = True - other.block = block - block.txs = [other] - - tx: MoneroTx = MoneroTx() - tx.hash = "a" * 64 - tx.is_confirmed = True - # tx.block is unset -> merge adopts other's block and repoints the block at tx - tx.merge(other) - assert tx.block is block - assert block.txs[0] is tx - - def test_tx_merge_is_confirmed_can_become_true(self) -> None: - a: MoneroTx = MoneroTx() - a.hash = "a" * 64 - a.is_confirmed = False - b: MoneroTx = a.copy() - b.is_confirmed = True - a.merge(b) - assert a.is_confirmed is True - - def test_tx_merge_is_double_spend_seen_can_become_true(self) -> None: - a: MoneroTx = MoneroTx() - a.hash = "a" * 64 - a.is_confirmed = True - a.is_double_spend_seen = False - b: MoneroTx = a.copy() - b.is_double_spend_seen = True - a.merge(b) - assert a.is_double_spend_seen is True - - def test_tx_merge_in_tx_pool_can_become_true(self) -> None: - a: MoneroTx = MoneroTx() - a.hash = "a" * 64 - a.is_confirmed = False - a.in_tx_pool = False - b: MoneroTx = a.copy() - b.in_tx_pool = True - a.merge(b) - assert a.in_tx_pool is True - - def test_tx_merge_is_locked_can_become_false(self) -> None: - a: MoneroTx = MoneroTx() - a.hash = "a" * 64 - a.is_confirmed = True - a.is_locked = False # self: already unlocked - b: MoneroTx = a.copy() - b.is_locked = True # other: still locked - a.merge(b) - assert a.is_locked is False - - def test_key_image_copy(self) -> None: - key_image: MoneroKeyImage = MoneroKeyImage() - key_image.hex = "a" * 64 - key_image.signature = "b" * 128 - - copy: MoneroKeyImage = key_image.copy() - assert copy is not key_image - assert copy.serialize() == key_image.serialize() - - def test_key_image_merge(self) -> None: - a: MoneroKeyImage = MoneroKeyImage() - a.hex = "a" * 64 - b: MoneroKeyImage = a.copy() - b.signature = "b" * 128 # a.signature is unset -> merge fills the gap - a.merge(b) - assert a.signature == "b" * 128 - - def test_output_copy(self) -> None: - output: MoneroOutput = MoneroOutput() - output.amount = 1000000 - output.index = 5 - key_image: MoneroKeyImage = MoneroKeyImage() - key_image.hex = "a" * 64 - output.key_image = key_image - - copy: MoneroOutput = output.copy() - assert copy is not output - assert copy.key_image is not output.key_image # key_image is deep copied - assert copy.serialize() == output.serialize() - - def test_output_merge(self) -> None: - a: MoneroOutput = MoneroOutput() - a.amount = 1000000 - a.index = 5 - b: MoneroOutput = a.copy() # preserves the (unset) tx reference, so merge won't recurse into tx merge - b.key_image = MoneroKeyImage() - b.key_image.hex = "a" * 64 - a.merge(b) # a.key_image is unset -> merge adopts b's key_image - assert a.key_image is not None - assert a.key_image.hex == "a" * 64 - - def test_output_merge_recurses_into_tx_merge(self) -> None: - tx_a: MoneroTx = MoneroTx() - tx_a.hash = "a" * 64 - tx_a.is_confirmed = True - - tx_b: MoneroTx = MoneroTx() - tx_b.hash = "a" * 64 - tx_b.is_confirmed = True - tx_b.num_confirmations = 9 # only tx merge reconciles this - - out_a: MoneroOutput = MoneroOutput() - out_a.tx = tx_a - out_a.stealth_public_key = "s" * 64 - tx_a.outputs = [out_a] - - out_b: MoneroOutput = MoneroOutput() - out_b.tx = tx_b - out_b.stealth_public_key = "s" * 64 - tx_b.outputs = [out_b] - - # outputs on different txs -> merge delegates to tx merge (which comes back to merging outputs) - out_a.merge(out_b) - assert tx_a.num_confirmations == 9 - - def test_tx_merge_extra_and_output_indices(self) -> None: - a: MoneroTx = MoneroTx() - a.hash = "a" * 64 - a.is_confirmed = True # required: merge() dereferences is_confirmed directly - b: MoneroTx = a.copy() - b.extra = [1, 2, 3, 255] - b.output_indices = [100, 101] - a.merge(b) # a.extra/output_indices are unset -> merge should adopt b's - assert a.extra == [1, 2, 3, 255] - assert a.output_indices == [100, 101] - - def test_tx_merge_inputs(self) -> None: - def make_input(tx: MoneroTx, key_image_hex: str) -> MoneroOutput: - key_image: MoneroKeyImage = MoneroKeyImage() - key_image.hex = key_image_hex - tx_input: MoneroOutput = MoneroOutput() - tx_input.tx = tx - tx_input.key_image = key_image - return tx_input - - a: MoneroTx = MoneroTx() - a.hash = "a" * 64 - a.is_confirmed = True # required: merge() dereferences is_confirmed directly - a.inputs = [make_input(a, "1" * 64)] - - b: MoneroTx = MoneroTx() - b.hash = "a" * 64 - b.is_confirmed = True - shared_input: MoneroOutput = make_input(b, "1" * 64) # same key image -> merged into a's input - shared_input.amount = 5000 - b.inputs = [shared_input, make_input(b, "2" * 64)] # new key image -> appended - - a.merge(b) - assert len(a.inputs) == 2 - assert a.inputs[0].key_image.hex == "1" * 64 # type: ignore - assert a.inputs[0].amount == 5000 # filled from b's matching input - assert a.inputs[1].key_image.hex == "2" * 64 # type: ignore - assert a.inputs[1].tx is a # appended input is repointed at a - - def test_output_merge_ring_output_indices_and_stealth_public_key(self) -> None: - a: MoneroOutput = MoneroOutput() - a.amount = 1000000 - a.index = 5 - b: MoneroOutput = a.copy() # preserves the (unset) tx reference, so merge won't recurse into tx merge - b.ring_output_indices = [10, 20, 30] - b.stealth_public_key = "a" * 64 - b.mask = "b" * 64 - a.merge(b) # a's fields are unset -> merge should adopt b's - assert a.ring_output_indices == [10, 20, 30] - assert a.stealth_public_key == "a" * 64 - assert a.mask == "b" * 64 - - def test_tx_lt_height_comparator(self) -> None: - tx_a: MoneroTx = MoneroTx() - tx_a.block = MoneroBlock() - tx_a.block.height = 100 - - tx_b: MoneroTx = MoneroTx() - tx_b.block = MoneroBlock() - tx_b.block.height = 200 - - assert tx_a < tx_b - assert not (tx_b < tx_a) - assert TxHeightComparator.compare(tx_a, tx_b) - assert not TxHeightComparator.compare(tx_b, tx_a) - - txs: list[MoneroTx] = [tx_b, tx_a] - txs.sort() - assert txs[0] is tx_a - assert txs[1] is tx_b - - # unconfirmed (no block) transactions sort after confirmed ones - tx_unconfirmed: MoneroTx = MoneroTx() - assert tx_a < tx_unconfirmed - assert not (tx_unconfirmed < tx_a) - - #endregion diff --git a/tests/test_monero_daemon_rpc.py b/tests/test_monero_daemon_rpc.py deleted file mode 100644 index 3bb96f2c..00000000 --- a/tests/test_monero_daemon_rpc.py +++ /dev/null @@ -1,1432 +0,0 @@ -import pytest -import time -import logging - -from typing import override - -from monero import ( - MoneroDaemonRpc, MoneroVersion, MoneroBlockHeader, MoneroBlockTemplate, - MoneroBlock, MoneroMiningStatus, MoneroPruneResult, MoneroMinerTxSum, - MoneroDaemonUpdateCheckResult, MoneroDaemonUpdateDownloadResult, MoneroRpcError, - MoneroDaemonListener, MoneroPeer, MoneroDaemonInfo, MoneroDaemonSyncInfo, - MoneroHardForkInfo, MoneroAltChain, MoneroTx, MoneroSubmitTxResult, - MoneroTxPoolStats, MoneroBan, MoneroTxConfig, MoneroDestination, - MoneroWalletRpc, MoneroKeyImageSpentStatus, MoneroRpcConnection, - MoneroOutputHistogramEntry, MoneroOutputDistributionEntry, MoneroFeeEstimate, - MoneroMinerData, MoneroDaemonNetworkStats, MoneroAuxiliaryPow, - MoneroAddAuxiliaryPowResult, MoneroGetBlocksByHashResult, MoneroGetBlockHashesResult, - MoneroOutput -) -from utils import ( - TestUtils as Utils, TestContext, BinaryBlockContext, RpcConnectionUtils, - AssertUtils, TxUtils, OutputUtils, BlockUtils, GenUtils, BlockchainUtils, - DaemonUtils, WalletType, IntegrationTestUtils, SubmitThenRelayTxTester, - BaseTestClass, TxWalletUtils, WalletTxsUtils, DaemonNotificationCollector, - MiningUtils -) - -logger: logging.Logger = logging.getLogger("TestMoneroDaemonRpc") - - -@pytest.mark.integration -class TestMoneroDaemonRpc(BaseTestClass): - """Rpc daemon integration tests.""" - - BINARY_BLOCK_CTX: BinaryBlockContext = BinaryBlockContext() - _test_wallet: MoneroWalletRpc | None = None - - #region Fixtures - - @override - def before_all(self) -> None: - # setup wallet rpc for tests - IntegrationTestUtils.setup(WalletType.RPC) - - @pytest.fixture(scope="class") - @classmethod - def daemon(cls) -> MoneroDaemonRpc: - """Test rpc daemon instance""" - return Utils.get_daemon_rpc() - - @pytest.fixture(scope="class") - @classmethod - def wallet(cls) -> MoneroWalletRpc: - """Test rpc wallet instance""" - if cls._test_wallet is None: - cls._test_wallet = Utils.get_wallet_rpc() - - return cls._test_wallet - - #endregion - - #region Non Relays Tests - - # Test offline daemon connection - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_offline_daemon(self) -> None: - # create connection to offline uri - offline_connection: MoneroRpcConnection = MoneroRpcConnection(Utils.OFFLINE_SERVER_URI) - - assert offline_connection.check_connection() - assert not offline_connection.is_connected() - assert not offline_connection.is_online() - - # create daemon - daemon: MoneroDaemonRpc = MoneroDaemonRpc(offline_connection) - - # test daemon connection - assert daemon.get_rpc_connection() == offline_connection - assert not daemon.is_connected() - - # call to any daemon method should throw network error - with pytest.raises(Exception) as exc_info: - daemon.get_height() - assert str(exc_info.value) == RpcConnectionUtils.NETWORK_ERROR_MSG - - # Can get the daemon's version - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_version(self, daemon: MoneroDaemonRpc) -> None: - version: MoneroVersion = daemon.get_version() - logger.debug(f"Testing monero version: {version.serialize()}") - assert version.number is not None - assert version.number > 0 - assert version.is_release is not None - - # Can indicate if it's trusted - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_is_trusted(self, daemon: MoneroDaemonRpc) -> None: - is_trusted: bool = daemon.is_trusted() - logger.debug(f"Trusted daemon: {is_trusted}") - - # Can get the blockchain height - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_height(self, daemon: MoneroDaemonRpc) -> None: - height: int = daemon.get_height() - logger.debug(f"Daemon height: {height}") - assert height > 0, "Height must be greater than 0" - - # Can get a block hash by height - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_block_id_by_height(self, daemon: MoneroDaemonRpc) -> None: - last_header: MoneroBlockHeader = daemon.get_last_block_header() - logger.debug(f"Last block header height: {last_header.height}") - assert last_header.height is not None - hash_str: str = daemon.get_block_hash(last_header.height) - logger.debug(f"Got block hash: {hash_str}") - assert hash_str is not None - assert 64 == len(hash_str), f"Invalid block hash '{hash_str}'" - - # Can get a block template - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_block_template(self, daemon: MoneroDaemonRpc) -> None: - template: MoneroBlockTemplate = daemon.get_block_template(Utils.ADDRESS, 2) - BlockUtils.test_block_template(template) - - # Can get the last block's header - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_last_block_header(self, daemon: MoneroDaemonRpc) -> None: - last_header: MoneroBlockHeader = daemon.get_last_block_header() - BlockUtils.test_block_header(last_header, True) - - # Can get a block header by hash - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_block_header_by_hash(self, daemon: MoneroDaemonRpc) -> None: - # retrieve last block by hash - last_header: MoneroBlockHeader = daemon.get_last_block_header() - assert last_header.height is not None - hash_str: str = daemon.get_block_hash(last_header.height) - header: MoneroBlockHeader = daemon.get_block_header_by_hash(hash_str) - BlockUtils.test_block_header(header, True) - AssertUtils.assert_equals(last_header, header) - - # retrieve by hash of previous to last block - hash_str = daemon.get_block_hash(last_header.height - 1) - header = daemon.get_block_header_by_hash(hash_str) - BlockUtils.test_block_header(header, True) - assert last_header.height - 1 == header.height - - # Can get a block header by height - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_block_header_by_height(self, daemon: MoneroDaemonRpc) -> None: - # retrieve by height of last block - last_header: MoneroBlockHeader = daemon.get_last_block_header() - assert last_header.height is not None - header: MoneroBlockHeader = daemon.get_block_header_by_height(last_header.height) - BlockUtils.test_block_header(header, True) - AssertUtils.assert_equals(last_header, header) - - # retrieve by height of previous to last block - header = daemon.get_block_header_by_height(last_header.height - 1) - BlockUtils.test_block_header(header, True) - assert last_header.height - 1 == header.height - - # Can get block headers by range - # TODO: test start with no end, vice versa, inclusivity - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_block_headers_by_range(self, daemon: MoneroDaemonRpc) -> None: - # determine start and end height based on number of blocks and how many blocks ago - num_blocks: int = 100 - num_blocks_ago: int = 100 - current_height: int = daemon.get_height() - start_height: int = current_height - num_blocks_ago - end_height: int = current_height - (num_blocks_ago - num_blocks) - 1 - - # fetch headers - headers: list[MoneroBlockHeader] = daemon.get_block_headers_by_range(start_height, end_height) - - # test headers - assert num_blocks == len(headers) - - for i in range(num_blocks): - header: MoneroBlockHeader = headers[i] - assert start_height + i == header.height - BlockUtils.test_block_header(header, True) - - # Can get a block by hash - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_block_by_hash(self, daemon: MoneroDaemonRpc) -> None: - # test config - ctx: TestContext = TestContext() - ctx.has_hex = True - ctx.has_txs = False - ctx.header_is_full = True - - # retrieve by hash of last block - last_header: MoneroBlockHeader = daemon.get_last_block_header() - assert last_header.height is not None - hash_str: str = daemon.get_block_hash(last_header.height) - block: MoneroBlock = daemon.get_block_by_hash(hash_str) - assert block.height is not None - BlockUtils.test_block(block, ctx) - AssertUtils.assert_equals(daemon.get_block_by_height(block.height), block) - assert len(block.txs) == 0, f"No block tx expected, found: {len(block.txs)}" - - # retrieve by hash of previous to last block - hash_str = daemon.get_block_hash(last_header.height - 1) - block = daemon.get_block_by_hash(hash_str) - BlockUtils.test_block(block, ctx) - AssertUtils.assert_equals(daemon.get_block_by_height(last_header.height - 1), block) - assert len(block.txs) == 0, f"No block tx expected, found: {len(block.txs)}" - - # Can get blocks by hash which includes transactions (binary) - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_blocks_by_hash_binary(self, daemon: MoneroDaemonRpc) -> None: - chain_height: int = daemon.get_height() - genesis_hash: str = daemon.get_block_hash(0) - - # a non-zero start height resumes from there and ignores the hash list - resume_height: int = chain_height - 5 - result: MoneroGetBlocksByHashResult = daemon.get_blocks_by_hash([genesis_hash], resume_height, False, 0) - assert result.current_height is not None and result.current_height >= chain_height - assert len(result.blocks) > 0 - for i, block in enumerate(result.blocks): - assert block.height == resume_height + i - BlockUtils.test_block(block, self.BINARY_BLOCK_CTX) - - # a genesis-terminated history resumes from height 0, capped by max_block_count - result = daemon.get_blocks_by_hash([genesis_hash], 0, False, 10) - assert 0 < len(result.blocks) <= 10 - assert result.blocks[0].height == 0 - - # noop when the first hash is already the tip - tip: MoneroBlockHeader = daemon.get_last_block_header() - assert tip.hash is not None - result = daemon.get_blocks_by_hash([tip.hash, genesis_hash], 0, False, 0) - assert len(result.blocks) == 0 - - # Can get a block by height - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_block_by_height(self, daemon: MoneroDaemonRpc) -> None: - # config for testing blocks - ctx: TestContext = TestContext() - ctx.has_hex = True - ctx.header_is_full = True - ctx.has_txs = False - - # retrieve by height of last block - last_header: MoneroBlockHeader = daemon.get_last_block_header() - assert last_header.height is not None - block: MoneroBlock = daemon.get_block_by_height(last_header.height) - assert block.height is not None - BlockUtils.test_block(block, ctx) - AssertUtils.assert_equals(daemon.get_block_by_height(block.height), block) - - # retrieve by height of previous to last block - block = daemon.get_block_by_height(last_header.height - 1) - BlockUtils.test_block(block, ctx) - assert last_header.height - 1 == block.height - - # Can get blocks by height which includes transactions (binary) - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_blocks_by_height_binary(self, daemon: MoneroDaemonRpc) -> None: - # set number of blocks to test - num_blocks: int = 100 - - # select random heights # TODO: this is horribly inefficient way of computing last 100 blocks if not shuffling - current_height: int = daemon.get_height() - all_heights: list[int] = list(range(current_height - 1)) - start_height: int = len(all_heights) - num_blocks - heights: list[int] = list(range(start_height, len(all_heights))) - - # fetch blocks - blocks: list[MoneroBlock] = daemon.get_blocks_by_height(heights) - - # test blocks - tx_found: bool = False - assert num_blocks == len(blocks) - - for i, height in enumerate(heights): - block: MoneroBlock = blocks[i] - if len(block.txs) > 0: - tx_found = True - - BlockUtils.test_block(block, self.BINARY_BLOCK_CTX) - assert block.height == height - - assert tx_found, "No transactions found to test" - - # Can get blocks by range in a single request - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_blocks_by_range(self, daemon: MoneroDaemonRpc) -> None: - # get height range - num_blocks: int = 100 - num_blocks_ago: int = 102 - assert num_blocks > 0 - assert num_blocks_ago >= num_blocks - height: int = daemon.get_height() - assert height - num_blocks_ago + num_blocks - 1 < height - start_height: int = height - num_blocks_ago - end_height: int = height - num_blocks_ago + num_blocks - 1 - - # test known start and end heights - BlockUtils.test_get_blocks_range(daemon, start_height, end_height, height, False, self.BINARY_BLOCK_CTX) - - # test unspecified start - BlockUtils.test_get_blocks_range(daemon, None, num_blocks - 1, height, False, self.BINARY_BLOCK_CTX) - - # test unspecified end - BlockUtils.test_get_blocks_range(daemon, height - num_blocks - 1, None, height, False, self.BINARY_BLOCK_CTX) - - # Test invalid blocks range - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_blocks_by_range_invalid(self, daemon: MoneroDaemonRpc) -> None: - height: int = daemon.get_height() - blocks: list[MoneroBlock] = daemon.get_blocks_by_range_chunked(height, height - 10) - num_blocks: int = len(blocks) - assert num_blocks == 0, f"Expected empty blocks for invalid range request, got {num_blocks}" - - # Can get blocks by range using chunked requests - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_blocks_by_range_chunked(self, daemon: MoneroDaemonRpc) -> None: - # get long height range - num_blocks: int = min(daemon.get_height() - 2, 1440) # test up to ~2 days of blocks - assert num_blocks > 0 - height: int = daemon.get_height() - assert height - num_blocks - 1 < height - start_height: int = height - num_blocks - end_height: int = height - 1 - - # test known start and end heights - BlockUtils.test_get_blocks_range(daemon, start_height, end_height, height, True, self.BINARY_BLOCK_CTX) - - # test unspecified start - BlockUtils.test_get_blocks_range(daemon, None, num_blocks - 1, height, True, self.BINARY_BLOCK_CTX) - - # test unspecified end - BlockUtils.test_get_blocks_range(daemon, end_height - num_blocks - 1, None, height, True, self.BINARY_BLOCK_CTX) - - # Can get genesis block by range using chunked requests - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_genesis_block_by_range_chunked(self, daemon: MoneroDaemonRpc) -> None: - # get current chain height - chain_height: int = daemon.get_height() - - # test genesis - BlockUtils.test_get_blocks_range(daemon, 0, 0, chain_height, True, self.BINARY_BLOCK_CTX) - - # Can get block hashes (binary) - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_block_hashes_binary(self, daemon: MoneroDaemonRpc) -> None: - chain_height: int = daemon.get_height() - genesis_hash: str = daemon.get_block_hash(0) - - # a genesis-terminated history returns the whole chain from height 0 - result: MoneroGetBlockHashesResult = daemon.get_block_hashes([genesis_hash]) - assert result.start_height == 0 - assert result.current_height is not None and result.current_height >= chain_height - assert len(result.hashes) > 0 - assert result.hashes[0] == genesis_hash - for hash_str in result.hashes: - assert len(hash_str) == 64 - - # only the tip comes back when it is already the first hash - tip: MoneroBlockHeader = daemon.get_last_block_header() - assert tip.hash is not None - result = daemon.get_block_hashes([tip.hash, genesis_hash]) - assert result.hashes == [tip.hash] - - # Can get a transaction by hash and without pruning - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_tx_by_hash(self, daemon: MoneroDaemonRpc) -> None: - # fetch tx hashses to test - tx_hashes: list[str] = DaemonUtils.get_confirmed_tx_hashes(daemon) - - # context for creating txs - ctx: TestContext = TestContext() - ctx.is_pruned = False - ctx.is_confirmed = True - ctx.from_get_tx_pool = False - - # fetch each tx by hash without pruning - for tx_hash in tx_hashes: - tx: MoneroTx | None = daemon.get_tx(tx_hash) - TxUtils.test_tx(tx, ctx) - - # fetch each tx by hash with pruning - for tx_hash in tx_hashes: - tx: MoneroTx | None = daemon.get_tx(tx_hash, True) - ctx.is_pruned = True - TxUtils.test_tx(tx, ctx) - - # fetch invalid hash - with pytest.raises(Exception) as exc_info: - daemon.get_tx("invalid tx hash") - assert str(exc_info.value) == "Invalid transaction hash" - - # Can get transactions by hashes with and without pruning - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - @pytest.mark.flaky(reruns=5, reruns_delay=5, only_rerun=[]) - def test_get_txs_by_hashes(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletRpc) -> None: - # fetch tx hashses to test - tx_hashes: list[str] = DaemonUtils.get_confirmed_tx_hashes(daemon) - assert len(tx_hashes) > 0, "No tx hashes found" - - # context for creating txs - ctx: TestContext = TestContext() - ctx.is_pruned = False - ctx.is_confirmed = True - ctx.from_get_tx_pool = False - - # fetch each tx by hash without pruning - txs: list[MoneroTx] = daemon.get_txs(tx_hashes) - assert len(txs) == len(tx_hashes), f"Expected len(txs) == len(tx_hashes), got {len(txs)} == {len(tx_hashes)}" - for tx in txs: - TxUtils.test_tx(tx, ctx) - - # fetch each tx by hash with pruning - txs = daemon.get_txs(tx_hashes, True) - ctx.is_pruned = True - assert len(txs) == len(tx_hashes), f"Expected len(txs) == len(tx_hashes), got {len(txs)} == {len(tx_hashes)}" - for tx in txs: - TxUtils.test_tx(tx, ctx) - - # fetch missing hash - dest: MoneroDestination = MoneroDestination() - dest.address = wallet.get_primary_address() - dest.amount = TxWalletUtils.MAX_FEE - config: MoneroTxConfig = MoneroTxConfig() - config.account_index = 0 - config.destinations.append(dest) - tx = wallet.create_tx(config) - assert tx.hash is not None - daemon_tx: MoneroTx | None = daemon.get_tx(tx.hash) - assert daemon_tx is None - tx_hashes.append(tx.hash) - num_txs: int = len(txs) - txs = daemon.get_txs(tx_hashes) - assert num_txs == len(txs) - - # fetch invalid hash - with pytest.raises(Exception) as exc_info: - daemon.get_txs(["invalid tx hash"]) - assert str(exc_info.value) == "Invalid transaction hash" - - # Can get transactions by hashes that are in the transaction pool - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_txs_by_hashes_in_pool(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletRpc) -> None: - # wait for wallet's txs in the pool to clear to ensure reliable sync - Utils.WALLET_TX_TRACKER.wait_for_txs_to_clear_pool(wallet) - - # submit txs to the pool but don't relay - tx_hashes: list[str] = [] - for i in range(1, 3): - tx: MoneroTx = WalletTxsUtils.get_unrelayed_tx(wallet, i) - assert tx.hash is not None - assert tx.full_hex is not None - assert len(tx.full_hex) > 0 - result: MoneroSubmitTxResult = daemon.submit_tx_hex(tx.full_hex, True) - DaemonUtils.test_submit_tx_result_good(result) - assert result.is_relayed is False - tx_hashes.append(tx.hash) - - # fetch txs by hash - logger.debug("Fetching txs...") - txs: list[MoneroTx] = daemon.get_txs(tx_hashes) - num_txs: int = len(txs) - logger.debug(f"Fetched {num_txs} tx(s)") - - # context for testing tx - ctx: TestContext = TestContext() - ctx.is_pruned = False - ctx.is_confirmed = False - ctx.from_get_tx_pool = False - - # test fetched txs - assert len(tx_hashes) == num_txs - for tx in txs: - TxUtils.test_tx(tx, ctx) - - # clear txs from pool - daemon.flush_tx_pool(tx_hashes) - wallet.sync() - - # Can get a transaction hex by hash with and without pruning - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_tx_hex_by_hash(self, daemon: MoneroDaemonRpc) -> None: - # fetch transaction hashes to test - tx_hashes: list[str] = DaemonUtils.get_confirmed_tx_hashes(daemon) - - # fetch each tx hex by hash with and without pruning - hexes: list[str | None] = [] - hexes_pruned: list[str | None] = [] - for tx_hash in tx_hashes: - hexes.append(daemon.get_tx_hex(tx_hash)) - hexes_pruned.append(daemon.get_tx_hex(tx_hash, True)) - - # test results - assert len(hexes) == len(tx_hashes) - assert len(hexes_pruned) == len(tx_hashes) - - for i, tx_hex in enumerate(hexes): - pruned_tx_hex: str | None = hexes_pruned[i] - assert tx_hex is not None - assert pruned_tx_hex is not None - assert len(pruned_tx_hex) > 0 - # pruned hex is shorter - assert len(tx_hex) >= len(pruned_tx_hex) - - # fetch invalid hash - with pytest.raises(Exception) as exc_info: - daemon.get_tx_hex("invalid tx hash") - assert str(exc_info.value) == "Invalid transaction hash" - - # Can get transaction hexes by hashes with and without pruning - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_tx_hexes_by_hashes(self, daemon: MoneroDaemonRpc) -> None: - # fetch transaction hashes to test - tx_hashes: list[str] = DaemonUtils.get_confirmed_tx_hashes(daemon) - - # fetch tx hexes by hash with and without pruning - hexes: list[str] = daemon.get_tx_hexes(tx_hashes) - hexes_pruned: list[str] = daemon.get_tx_hexes(tx_hashes, True) - - # test results - assert len(hexes) == len(tx_hashes) - assert len(hexes_pruned) == len(tx_hashes) - for i, tx_hex in enumerate(hexes): - pruned_tx_hex: str = hexes_pruned[i] - assert tx_hex is not None - assert pruned_tx_hex is not None - assert len(pruned_tx_hex) > 0 - # pruned hex is shorter - assert len(tx_hex) >= len(pruned_tx_hex) - - # fetch invalid hash - tx_hashes.append("invalid tx hash") - with pytest.raises(Exception) as exc_info: - daemon.get_tx_hexes(tx_hashes) - assert str(exc_info.value) == "Invalid transaction hash" - - # Can get the miner tx sum - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_miner_tx_sum(self, daemon: MoneroDaemonRpc) -> None: - tx_sum: MoneroMinerTxSum = daemon.get_miner_tx_sum(0, min(5000, daemon.get_height())) - DaemonUtils.test_miner_tx_sum(tx_sum) - - # Can get fee estimate - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_fee_estimate(self, daemon: MoneroDaemonRpc) -> None: - fee_estimate: MoneroFeeEstimate = daemon.get_fee_estimate() - logger.debug(f"Testing fee estimate: {fee_estimate.serialize()}") - GenUtils.test_unsigned_big_integer(fee_estimate.fee, True) - assert len(fee_estimate.fees) == 4, "Exptected 4 fees" - for fee in fee_estimate.fees: - GenUtils.test_unsigned_big_integer(fee, True) - GenUtils.test_unsigned_big_integer(fee_estimate.quantization_mask, True) - - # Can get all transactions in the transaction pool - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_txs_in_pool(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletRpc) -> None: - Utils.WALLET_TX_TRACKER.wait_for_txs_to_clear_pool(wallet) - - # submit tx to pool but don't relay - tx: MoneroTx = WalletTxsUtils.get_unrelayed_tx(wallet, 1) - assert tx.hash is not None - assert tx.full_hex is not None - result: MoneroSubmitTxResult = daemon.submit_tx_hex(tx.full_hex, True) - DaemonUtils.test_submit_tx_result_good(result) - assert result.is_relayed is False - - # fetch txs in pool - txs: list[MoneroTx] = daemon.get_tx_pool() - num_txs: int = len(txs) - - # fetch tx hashes in pool - tx_hashes: list[str] = daemon.get_tx_pool_hashes() - num_tx_hashes: int = len(tx_hashes) - - # context for testing tx - ctx: TestContext = TestContext() - ctx.is_pruned = False - ctx.is_confirmed = False - ctx.from_get_tx_pool = True - - # test txs - assert num_txs > 0, "Test requires an unconfirmed tx in the tx pool" - assert num_txs == num_tx_hashes, f"Txs in pool {num_txs} != Txs hashes in pool {num_tx_hashes}" - for a_tx in txs: - TxUtils.test_tx(a_tx, ctx) - assert a_tx.hash in tx_hashes - - # flush the tx from the pool, gg - daemon.flush_tx_pool(tx.hash) - wallet.sync() - - # Can get transaction pool statistics - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_tx_pool_statistics(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletRpc) -> None: - Utils.WALLET_TX_TRACKER.wait_for_txs_to_clear_pool([wallet]) - tx_ids: list[str] = [] - try: - # submit txs to the pool but don't relay - for i in range(1, 3): - # submit tx hex - tx: MoneroTx = WalletTxsUtils.get_unrelayed_tx(wallet, i) - assert tx.full_hex is not None - result: MoneroSubmitTxResult = daemon.submit_tx_hex(tx.full_hex, True) - assert result.is_good, f"Expected True, got {result.is_good}" - assert tx.hash is not None - tx_ids.append(tx.hash) - - # get tx pool stats - stats: MoneroTxPoolStats = daemon.get_tx_pool_stats() - assert stats.num_txs is not None - assert stats.num_txs > i - 1 - DaemonUtils.test_tx_pool_stats(stats) - finally: - # flush txs - daemon.flush_tx_pool(tx_ids) - - # Can flush all transactions from the pool - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_flush_txs_from_pool(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletRpc) -> None: - Utils.WALLET_TX_TRACKER.wait_for_txs_to_clear_pool(wallet) - - # preserve original transactions in the pool - tx_pool_before: list[MoneroTx] = daemon.get_tx_pool() - - # submit txs to the pool but don't relay - for i in range(1, 3): - tx: MoneroTx = WalletTxsUtils.get_unrelayed_tx(wallet, i) - assert tx.full_hex is not None - result: MoneroSubmitTxResult = daemon.submit_tx_hex(tx.full_hex, True) - DaemonUtils.test_submit_tx_result_good(result) - - assert len(tx_pool_before) + 2 == len(daemon.get_tx_pool()) - - # flush tx pool - daemon.flush_tx_pool() - assert len(daemon.get_tx_pool()) == 0 - - # re-submit original transactions - for tx in tx_pool_before: - assert tx.full_hex is not None - assert tx.is_relayed is not None - result: MoneroSubmitTxResult = daemon.submit_tx_hex(tx.full_hex, tx.is_relayed) - - # pool is back to original state - assert len(tx_pool_before) == len(daemon.get_tx_pool()) - - # sync wallet for next test - wallet.sync() - - # Can flush a transaction from the pool by hash - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_flush_tx_from_pool_by_hash(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletRpc) -> None: - Utils.WALLET_TX_TRACKER.wait_for_txs_to_clear_pool(wallet) - - # preserve original transactions in the pool - tx_pool_before: list[MoneroTx] = daemon.get_tx_pool() - - # submit txs to the pool but don't relay - txs: list[MoneroTx] = [] - for i in range(1, 3): - tx: MoneroTx = WalletTxsUtils.get_unrelayed_tx(wallet, i) - assert tx.full_hex is not None - result: MoneroSubmitTxResult = daemon.submit_tx_hex(tx.full_hex, True) - DaemonUtils.test_submit_tx_result_good(result) - txs.append(tx) - - # remove each tx from the pool by hash and test - num_txs: int = len(txs) - for i, tx in enumerate(txs): - assert tx.hash is not None - # flush tx from pool - daemon.flush_tx_pool(tx.hash) - - # test tx pool - pool_txs: list[MoneroTx] = daemon.get_tx_pool() - assert num_txs - i - 1 == len(pool_txs) - - # pool is back to original state - assert len(tx_pool_before) == len(daemon.get_tx_pool()) - - # sync wallet for next test - wallet.sync() - - # Can flush transactions from the pool by hashes - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_flush_txs_from_pool_by_hashes(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletRpc) -> None: - Utils.WALLET_TX_TRACKER.wait_for_txs_to_clear_pool(wallet) - - # preserve original transactions in the pool - tx_pool_before: list[MoneroTx] = daemon.get_tx_pool() - - # submit txs to the pool but don't relay - tx_hashes: list[str] = [] - for i in range(1, 3): - tx: MoneroTx = WalletTxsUtils.get_unrelayed_tx(wallet, i) - assert tx.hash is not None - assert tx.full_hex is not None - result: MoneroSubmitTxResult = daemon.submit_tx_hex(tx.full_hex, True) - DaemonUtils.test_submit_tx_result_good(result) - tx_hashes.append(tx.hash) - - assert len(tx_pool_before) + len(tx_hashes) == len(daemon.get_tx_pool()) - - # remove all txs by hashes - daemon.flush_tx_pool(tx_hashes) - - # pool is back to original state - assert len(tx_pool_before) == len(daemon.get_tx_pool()) - wallet.sync() - - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_spent_status_of_key_images(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletRpc) -> None: - Utils.WALLET_TX_TRACKER.wait_for_txs_to_clear_pool(wallet) - - # submit txs to the pool to collect key images then flush them - txs: list[MoneroTx] = [] - - for i in range(1, 3): - tx: MoneroTx = WalletTxsUtils.get_unrelayed_tx(wallet, i) - assert tx.full_hex is not None - daemon.submit_tx_hex(tx.full_hex, True) - txs.append(tx) - - key_images: list[str] = [] - tx_hashes: list[str] = [] - for tx in txs: - assert tx.hash is not None - tx_hashes.append(tx.hash) - - for tx in daemon.get_txs(tx_hashes): - for tx_input in tx.inputs: - assert tx_input.key_image is not None - assert tx_input.key_image.hex is not None - key_images.append(tx_input.key_image.hex) - - daemon.flush_tx_pool(tx_hashes) - - # key images are not spent - DaemonUtils.test_spent_statuses(daemon, key_images, MoneroKeyImageSpentStatus.NOT_SPENT) - - # submit txs to the pool but don't relay - for tx in txs: - assert tx.full_hex is not None - daemon.submit_tx_hex(tx.full_hex, True) - - # key images are in the tx pool - DaemonUtils.test_spent_statuses(daemon, key_images, MoneroKeyImageSpentStatus.TX_POOL) - - # collect key images of confirmed txs - key_images = [] - txs = DaemonUtils.get_confirmed_txs(daemon, 10) - for tx in txs: - for tx_input in tx.inputs: - assert tx_input.key_image is not None - assert tx_input.key_image.hex is not None - key_images.append(tx_input.key_image.hex) - - # key images are all spent - DaemonUtils.test_spent_statuses(daemon, key_images, MoneroKeyImageSpentStatus.CONFIRMED) - - # flush this test's txs from pool - daemon.flush_tx_pool(tx_hashes) - - # Can get an output histogram (binary) - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_output_histogram_binary(self, daemon: MoneroDaemonRpc) -> None: - entries: list[MoneroOutputHistogramEntry] = daemon.get_output_histogram([], None, None, None, None) - assert len(entries) > 0 - for entry in entries: - OutputUtils.test_output_histogram_entry(entry) - - # Can get an output distribution - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_output_distribution(self, daemon: MoneroDaemonRpc) -> None: - amounts: list[int] = [0] - entries: list[MoneroOutputDistributionEntry] = daemon.get_output_distribution(amounts) - for entry in entries: - OutputUtils.test_output_distribution_entry(entry) - - # Can get general information - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_general_information(self, daemon: MoneroDaemonRpc) -> None: - info: MoneroDaemonInfo = daemon.get_info() - DaemonUtils.test_info(info) - assert info.is_regtest == Utils.REGTEST - - # Can get sync information - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_sync_information(self, daemon: MoneroDaemonRpc) -> None: - sync_info: MoneroDaemonSyncInfo = daemon.get_sync_info() - DaemonUtils.test_sync_info(sync_info) - - # Can get hard fork information - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_hard_fork_information(self, daemon: MoneroDaemonRpc) -> None: - hard_fork_info: MoneroHardForkInfo = daemon.get_hard_fork_info() - DaemonUtils.test_hard_fork_info(hard_fork_info) - - # Can get alternative chains - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_alternative_chains(self, daemon: MoneroDaemonRpc) -> None: - alt_chains: list[MoneroAltChain] = daemon.get_alt_chains() - if len(alt_chains) == 0: - logger.warning("No alternative chain found!") - - for alt_chain in alt_chains: - BlockUtils.test_alt_chain(alt_chain) - - # Can get alternative block hashes - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_alternative_block_ids(self, daemon: MoneroDaemonRpc) -> None: - alt_block_ids: list[str] = daemon.get_alt_block_hashes() - if len(alt_block_ids) == 0: - logger.warning("No alternative block ids found!") - - for alt_block_id in alt_block_ids: - logger.debug(f"Testing alternarive block id: {alt_block_id}") - assert alt_block_id is not None - # TODO: common validation - assert 64, len(alt_block_id) - - # Can get, set, and reset a download bandwidth limit - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - @pytest.mark.flaky(reruns=5, reruns_delay=10, only_rerun=[]) - def test_set_download_bandwidth(self, daemon: MoneroDaemonRpc) -> None: - init_val: int = daemon.get_download_limit() - assert init_val > 0 - set_val: int = init_val * 2 - daemon.set_download_limit(set_val) - assert set_val == daemon.get_download_limit() - reset_val: int = daemon.reset_download_limit() - assert init_val == reset_val - - # test invalid limits - with pytest.raises(Exception) as exc_info: - daemon.set_download_limit(0) - assert str(exc_info.value) == "Download limit must be an integer greater than 0" - - assert daemon.get_download_limit() == init_val - - # Can get, set, and reset an upload bandwidth limit - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - @pytest.mark.flaky(reruns=5, reruns_delay=10, only_rerun=[]) - def test_set_upload_bandwidth(self, daemon: MoneroDaemonRpc) -> None: - init_val: int = daemon.get_upload_limit() - assert init_val > 0 - set_val: int = init_val * 2 - daemon.set_upload_limit(set_val) - assert set_val == daemon.get_upload_limit() - reset_val: int = daemon.reset_upload_limit() - assert init_val == reset_val - - # test invalid limits - with pytest.raises(Exception) as exc_info: - daemon.set_upload_limit(0) - assert str(exc_info.value) == "Upload limit must be an integer greater than 0" - - assert init_val == daemon.get_upload_limit() - - # Can get peers with active incoming or outgoing connections - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_peers(self, daemon: MoneroDaemonRpc) -> None: - peers: list[MoneroPeer] = daemon.get_peers() - assert len(peers) >= 0, "Daemon has no incoming or outgoing peers to test" - seen: set[tuple[str, int]] = set() - for peer in peers: - assert peer.host is not None - assert peer.port is not None - peer_key: tuple[str, int] = (peer.host, peer.port) - assert peer_key not in seen, f"Duplicate peer found: {peer_key}" - seen.add(peer_key) - assert peer.is_online, "Expected active peer connection to be online" - DaemonUtils.test_peer(peer) - - # Can get all known peers which may be online or offline - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_known_peers(self, daemon: MoneroDaemonRpc) -> None: - peers: list[MoneroPeer] = daemon.get_known_peers() - if Utils.REGTEST: - assert len(peers) == 0, "Regtest daemon should not have known peers to test" - logger.warning("Regtest daemon doesn't have known peers to test") - else: - assert len(peers) > 0, "Daemon has no known peers to test" - - for peer in peers: - DaemonUtils.test_known_peer(peer, False) - - # Can limit the number of outgoing peers - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_set_outgoing_peer_limit(self, daemon: MoneroDaemonRpc) -> None: - daemon.set_outgoing_peer_limit(0) - daemon.set_outgoing_peer_limit(8) - daemon.set_outgoing_peer_limit(10) - - # Can limit the number of incoming peers - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_set_incoming_peer_limit(self, daemon: MoneroDaemonRpc) -> None: - daemon.set_incoming_peer_limit(0) - daemon.set_incoming_peer_limit(8) - daemon.set_incoming_peer_limit(10) - - # Can notify listeners when a new block is added to the chain - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - @pytest.mark.skipif(Utils.LITE_MODE is True or Utils.TEST_NOTIFICATIONS is False, reason="TEST_NOTIFICATIONS disabled") - def test_block_listener(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletRpc) -> None: - try: - # start mining if possible to help push the network along - address: str = wallet.get_primary_address() - try: - daemon.start_mining(address, 1, False, True) - except Exception as e: - logger.warning(f"[!]: {str(e)}") - - # register a listener - listener: MoneroDaemonListener = MoneroDaemonListener() - daemon.add_listener(listener) - - # wait for next block notification - header: MoneroBlockHeader = daemon.wait_for_next_block_header() - daemon.remove_listener(listener) # unregister listener so daemon does not keep polling - BlockUtils.test_block_header(header, True) - - # test that listener was called with equivalent header - AssertUtils.assert_equals(header, listener.last_header) - finally: - # stop mining - try : - daemon.stop_mining() - except Exception as e: - logger.warning(f"[!]: {str(e)}") - - # Can ban a peer - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_ban_peer(self, daemon: MoneroDaemonRpc) -> None: - # set ban - host: str = "192.168.1.51" - ban: MoneroBan = MoneroBan() - ban.host = host - ban.is_banned = True - ban.seconds = 60 - daemon.set_peer_ban(ban) - - # test ban - bans: list[MoneroBan] = daemon.get_peer_bans() - found: bool = False - for peer_ban in bans: - DaemonUtils.test_ban(peer_ban) - if host == peer_ban.host: - found = True - - assert found, f"Could not find peer ban {host}" - - # Can ban peers - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_ban_peers(self, daemon: MoneroDaemonRpc) -> None: - # set bans - addr1: str = "192.168.1.52" - addr2: str = "192.168.1.53" - ban1: MoneroBan = MoneroBan() - ban1.host = addr1 - ban1.is_banned = True - ban1.seconds = 60 - ban2: MoneroBan = MoneroBan() - ban2.host = addr2 - ban2.is_banned = True - ban2.seconds = 60 - bans: list[MoneroBan] = [] - bans.append(ban1) - bans.append(ban2) - daemon.set_peer_bans(bans) - - # test bans - bans = daemon.get_peer_bans() - found1: bool = False - found2: bool = False - for a_ban in bans: - DaemonUtils.test_ban(a_ban) - if addr1 == a_ban.host: - found1 = True - if addr2 == a_ban.host: - found2 = True - - assert found1, f"Could not find peer ban1 {addr1}" - assert found2, f"Could not find peer ban2 {addr2}" - - # Can start and stop mining - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_mining(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletRpc) -> None: - # stop mining at beginning of test - MiningUtils.try_stop_mining(daemon) - - # generate address to mine to - address: str = wallet.get_primary_address() - - # start mining - daemon.start_mining(address, 1, False, True) - - # stop mining - daemon.stop_mining() - - # Can get mining status - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_mining_status(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletRpc) -> None: - try: - # stop mining at beginning of test - MiningUtils.try_stop_mining(daemon) - - # test status without mining - status: MoneroMiningStatus = daemon.get_mining_status() - logger.debug(f"Testing mining status: {status.serialize()}") - assert status.is_active is False - assert status.address is None, f"Mining address is not None: {status.address}" - assert 0 == status.speed - assert 0 == status.num_threads - assert status.is_background is None - - # test status with mining - address: str = wallet.get_primary_address() - thread_count: int = 1 - is_background: bool = False - daemon.start_mining(address, thread_count, is_background, True) - status = daemon.get_mining_status() - logger.debug(f"Testing mining status: {status.serialize()}") - assert status.speed is not None - assert status.is_active is True - assert address == status.address - assert status.speed >= 0 - assert thread_count == status.num_threads - assert is_background == status.is_background - finally: - # stop mining at end of test - MiningUtils.try_stop_mining(daemon) - - # Can submit a mined block to the network - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - @pytest.mark.flaky(reruns=5, reruns_delay=5, only_rerun=[]) - def test_submit_mined_block(self, daemon: MoneroDaemonRpc) -> None: - # get template to mine on - template: MoneroBlockTemplate = daemon.get_block_template(Utils.ADDRESS) - assert template.block_template_blob is not None - - # TODO monero rpc: way to get mining nonce when found in order to submit? - - # try to submit block hashing blob without nonce - with pytest.raises(Exception) as exc_info: - daemon.submit_block(template.block_template_blob) - assert str(exc_info.value) == "Block not accepted" - - # Can prune the blockchain - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_prune_blockchain(self, daemon: MoneroDaemonRpc) -> None: - result: MoneroPruneResult = daemon.prune_blockchain(True) - logger.debug(f"Testing prune result: {result.serialize()}") - - if result.is_pruned: - assert result.pruning_seed is not None - assert result.pruning_seed > 0 - else: - assert 0 == result.pruning_seed - - # Can check for an update - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - @pytest.mark.xfail(reason="the update check needs DNSSEC validated TXT records, which the daemon in docker does not get", raises=MoneroRpcError, strict=False) - def test_check_for_update(self, daemon: MoneroDaemonRpc) -> None: - result: MoneroDaemonUpdateCheckResult = daemon.check_for_update() - DaemonUtils.test_update_check_result(result) - - # Can download an update - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - @pytest.mark.xfail(reason="the update check needs DNSSEC validated TXT records, which the daemon in docker does not get", raises=MoneroRpcError, strict=False) - def test_download_update(self, daemon: MoneroDaemonRpc) -> None: - # download to default path - result: MoneroDaemonUpdateDownloadResult = daemon.download_update() - DaemonUtils.test_update_download_result(result, None) - - # download to defined path - path: str = "test_download_" + str(time.time()) + ".tar.bz2" - result = daemon.download_update(path) - DaemonUtils.test_update_download_result(result, path) - - # test invalid path - # TODO monerod: an invalid path causes a 500 in daemon rpc rather than a clean error - if result.is_update_available: - try: - daemon.download_update("./ohhai/there") - except Exception as e: - logger.warning(str(e)) - - # Can be stopped - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - @pytest.mark.skip(reason="test is disabled to not interfere with other tests") - def test_stop(self, daemon: MoneroDaemonRpc) -> None: - # stop the daemon - daemon.stop() - - # give the daemon time to shut down - time.sleep(Utils.SYNC_PERIOD_IN_MS / 1000) - - # try to interact with the stopped daemon - with pytest.raises(Exception): - daemon.get_height() - - # Can get the data needed to mine a block - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_miner_data(self, daemon: MoneroDaemonRpc) -> None: - data: MoneroMinerData = daemon.get_miner_data() - DaemonUtils.test_miner_data(data) - - # Can calculate a block's proof-of-work hash - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_calculate_pow(self, daemon: MoneroDaemonRpc) -> None: - data: MoneroMinerData = daemon.get_miner_data() - template: MoneroBlockTemplate = daemon.get_block_template(Utils.ADDRESS) - assert data.major_version is not None - assert data.height is not None - assert data.seed_hash is not None - assert template.block_template_blob is not None - - pow_hash: str = daemon.calculate_pow(data.major_version, data.height, template.block_template_blob, data.seed_hash) - assert len(pow_hash) == 64 - - with pytest.raises(Exception) as exc_info: - daemon.calculate_pow(data.major_version, data.height, "", data.seed_hash) - assert str(exc_info.value) == "Must provide a block blob to hash" - - # Can add auxiliary proof-of-work to a block template - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_add_auxiliary_pow(self, daemon: MoneroDaemonRpc) -> None: - template: MoneroBlockTemplate = daemon.get_block_template(Utils.ADDRESS) - assert template.block_template_blob is not None - - aux_pow: MoneroAuxiliaryPow = MoneroAuxiliaryPow("11" * 32, "22" * 32) - result: MoneroAddAuxiliaryPowResult = daemon.add_auxiliary_pow(template.block_template_blob, [aux_pow]) - assert result.block_template_blob is not None and len(result.block_template_blob) > 0 - assert result.block_hashing_blob is not None and len(result.block_hashing_blob) > 0 - assert result.merkle_root is not None and len(result.merkle_root) == 64 - assert result.merkle_tree_depth is not None and result.merkle_tree_depth >= 0 - assert len(result.aux_pow) == 1 - assert result.aux_pow[0].id is not None and len(result.aux_pow[0].id) == 64 - assert result.aux_pow[0].hash is not None and len(result.aux_pow[0].hash) == 64 - - with pytest.raises(Exception) as exc_info: - daemon.add_auxiliary_pow(template.block_template_blob, []) - assert str(exc_info.value) == "Must provide auxiliary proof of work to add" - - # Can get the global output indices of a transaction - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_output_indices(self, daemon: MoneroDaemonRpc) -> None: - tx_hashes: list[str] = DaemonUtils.get_confirmed_tx_hashes(daemon) - assert len(tx_hashes) > 0, "No confirmed txs found" - - for tx_hash in tx_hashes: - indices: list[int] = daemon.get_output_indices(tx_hash) - assert len(indices) > 0 - for index in indices: - assert index >= 0 - - with pytest.raises(Exception) as exc_info: - daemon.get_output_indices("") - assert str(exc_info.value) == "Must provide a transaction hash" - - # Can get outputs given a list of output amounts and indices (binary) - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_outputs(self, daemon: MoneroDaemonRpc) -> None: - tx_hashes: list[str] = DaemonUtils.get_confirmed_tx_hashes(daemon) - assert len(tx_hashes) > 0, "No confirmed txs found" - - # identify each output by amount 0 (RingCT) and its global index - requested: list[MoneroOutput] = [] - for tx_hash in tx_hashes: - for index in daemon.get_output_indices(tx_hash): - output: MoneroOutput = MoneroOutput() - output.amount = 0 - output.index = index - requested.append(output) - - num_requested: int = len(requested) - assert num_requested > 0 - - fetched: list[MoneroOutput] = daemon.get_outputs(requested) - num_fetched: int = len(fetched) - assert num_fetched == num_requested - - for i, output in enumerate(fetched): - logger.debug(f"Testing fetched output: {output.serialize()}") - assert output.index == requested[i].index - assert output.stealth_public_key is not None and len(output.stealth_public_key) == 64 - assert output.mask is not None and len(output.mask) == 64 - assert output.tx is not None - assert output.tx.block is not None and output.tx.block.height is not None - - with pytest.raises(Exception) as exc_info: - daemon.get_outputs([]) - assert str(exc_info.value) == "Must provide outputs to fetch" - - # Can get network (bandwidth) statistics - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_network_stats(self, daemon: MoneroDaemonRpc) -> None: - stats: MoneroDaemonNetworkStats = daemon.get_network_stats() - DaemonUtils.test_network_stats(stats) - - # Can get public nodes known to the daemon - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_public_peers(self, daemon: MoneroDaemonRpc) -> None: - peers: list[MoneroPeer] = daemon.get_public_peers() - if Utils.REGTEST: - assert len(peers) == 0 - for peer in peers: - DaemonUtils.test_known_peer(peer, False) - - # Can query the ban status of a single peer - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_peer_ban(self, daemon: MoneroDaemonRpc) -> None: - host: str = "192.168.1.60" - ban: MoneroBan = MoneroBan() - ban.host = host - ban.is_banned = True - ban.seconds = 60 - daemon.set_peer_ban(ban) - - banned: MoneroBan = daemon.get_peer_ban(host) - assert banned.is_banned is True - assert banned.seconds is not None and banned.seconds > 0 - - assert daemon.get_peer_ban("192.168.1.61").is_banned is False - - with pytest.raises(Exception) as exc_info: - daemon.get_peer_ban("") - assert str(exc_info.value) == "Must provide an address to check the ban status of" - - # Can remove all listeners at once - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_remove_daemon_listeners(self, daemon: MoneroDaemonRpc) -> None: - listeners: list[DaemonNotificationCollector] = [DaemonNotificationCollector(daemon), DaemonNotificationCollector(daemon)] - for listener in listeners: - daemon.add_listener(listener) - assert len(daemon.get_listeners()) == 2 - - daemon.remove_listeners() - assert len(daemon.get_listeners()) == 0 - - # Can flush the blockchain to disk - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_save_blockchain(self, daemon: MoneroDaemonRpc) -> None: - daemon.save_blockchain() - - # Can flush the daemon's invalid block and tx caches - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_flush_cache(self, daemon: MoneroDaemonRpc) -> None: - daemon.flush_cache() - daemon.flush_cache(True) - - # Can disable the bootstrap daemon - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_remove_bootstrap_daemon(self, daemon: MoneroDaemonRpc) -> None: - daemon.remove_bootstrap_daemon() - - # Can set the poll period for block notifications - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_set_poll_period_in_ms(self, daemon: MoneroDaemonRpc) -> None: - try: - daemon.set_poll_period_in_ms(1000) - finally: - # restore the configured period so later tests poll at the expected rate - daemon.set_poll_period_in_ms(Utils.DAEMON_POLL_PERIOD_IN_MS) - - # Can set the daemon's log level - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_set_log_level(self, daemon: MoneroDaemonRpc) -> None: - try: - for i in range(0, 5): - daemon.set_log_level(i) - - for level in (-1, 5): - with pytest.raises(Exception) as exc_info: - daemon.set_log_level(level) - assert str(exc_info.value) == "Log level must be an integer between 0 and 4" - finally: - # restore the level from docker-compose so later tests keep full logs - daemon.set_log_level(Utils.DAEMON_LOG_LEVEL) - - # Can set the daemon's log categories - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_set_log_categories(self, daemon: MoneroDaemonRpc) -> None: - try: - categories: str = daemon.set_log_categories("*:WARNING") - assert isinstance(categories, str) - finally: - # re-applying the configured level also resets categories to its mapping - daemon.set_log_level(Utils.DAEMON_LOG_LEVEL) - - # Can toggle the mining hash rate in the daemon log - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_set_log_hash_rate(self, daemon: MoneroDaemonRpc) -> None: - try: - daemon.set_log_hash_rate(True) - daemon.set_log_hash_rate(False) - except Exception as e: - # daemon rejects the call while not mining - logger.warning(f"set_log_hash_rate: {e}") - - # Can pop blocks from the top of the chain - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - @pytest.mark.skipif(Utils.REGTEST is False, reason="REGTEST disabled") - @pytest.mark.flaky(reruns=5, reruns_delay=5, only_rerun=[]) - def test_pop_blocks(self, daemon: MoneroDaemonRpc) -> None: - # stop mining so it doesn't race the pop, then restore the shared chain afterwards - MiningUtils.try_stop_mining(daemon) - height: int = daemon.get_height() - - assert daemon.pop_blocks(1) == height - 1 - MiningUtils.generate_blocks(Utils.MINING_ADDRESS, 1, daemon) - assert daemon.get_height() == height - - with pytest.raises(Exception) as exc_info: - daemon.pop_blocks(0) - assert str(exc_info.value) == "Must provide a number of blocks to pop greater than 0" - - #endregion - - #region Relays Tests - - # Can submit a tx in hex format to the pool and relay in one call - @pytest.mark.skipif(Utils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") - @pytest.mark.skipif(Utils.LITE_MODE, reason="LITE_MODE enabled") - def test_submit_and_relay_tx_hex(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletRpc) -> None: - # wait one time for wallet txs in the pool to clear - # TODO monero-project: update from pool does not prevent creating double spend tx - Utils.WALLET_TX_TRACKER.wait_for_txs_to_clear_pool(wallet) - - # create 2 txs, the second will double spend outputs of first - # TODO: this test requires tx to be from/to different accounts else - # the occlusion issue (#4500) causes the tx to not be recognized by the wallet at all - tx1: MoneroTx = WalletTxsUtils.get_unrelayed_tx(wallet, 2) - tx2: MoneroTx = WalletTxsUtils.get_unrelayed_tx(wallet, 2) - - # submit and relay tx1 - assert tx1.hash is not None - assert tx1.full_hex is not None - result: MoneroSubmitTxResult = daemon.submit_tx_hex(tx1.full_hex) - assert result.is_relayed is True - DaemonUtils.test_submit_tx_result_good(result) - - # tx1 is in the pool - txs: list[MoneroTx] = daemon.get_tx_pool() - found: bool = False - for a_tx in txs: - assert a_tx.hash is not None - if a_tx.hash == tx1.hash: - assert a_tx.is_relayed is True - found = True - break - - assert found, "Tx1 was not found after being submitted to the daemon's tx pool" - - # tx1 is recognized by the wallet - wallet.sync() - wallet.get_tx(tx1.hash) - - # submit and relay tx2 hex which double spends tx1 - assert tx2.full_hex is not None - result = daemon.submit_tx_hex(tx2.full_hex) - assert result.is_relayed is True - DaemonUtils.test_submit_tx_result_double_spend(result) - - # tx2 is not in the pool - txs = daemon.get_tx_pool() - found = False - for a_tx in txs: - assert a_tx.hash is not None - if a_tx.hash == tx2.hash: - found = True - break - - assert not found, "Tx2 should not be in the pool because it double spends tx1 which is in the pool" - - # Can submit a tx in hex format to the pool then relay - @pytest.mark.skipif(Utils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") - @pytest.mark.skipif(Utils.LITE_MODE, reason="LITE_MODE enabled") - def test_submit_then_relay_tx_hex(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletRpc) -> None: - Utils.WALLET_TX_TRACKER.wait_for_txs_to_clear_pool(wallet) - tx: MoneroTx = WalletTxsUtils.get_unrelayed_tx(wallet, 1) - tester: SubmitThenRelayTxTester = SubmitThenRelayTxTester(daemon, [tx]) - tester.test() - - # Can submit txs in hex format to the pool then relay - @pytest.mark.skipif(Utils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") - @pytest.mark.skipif(Utils.LITE_MODE, reason="LITE_MODE enabled") - def test_submit_then_relay_tx_hexes(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletRpc) -> None: - Utils.WALLET_TX_TRACKER.wait_for_txs_to_clear_pool(wallet) - txs: list[MoneroTx] = [] - txs.append(WalletTxsUtils.get_unrelayed_tx(wallet, 1)) - # TODO: accounts cannot be re-used across send tests else isRelayed is true; wallet needs to update? - txs.append(WalletTxsUtils.get_unrelayed_tx(wallet, 2)) - tester: SubmitThenRelayTxTester = SubmitThenRelayTxTester(daemon, txs) - tester.test() - - #endregion - - #region Test Notifications - - # Can start and stop listening - @pytest.mark.skipif(Utils.TEST_NOTIFICATIONS is False, reason="TEST_NOTIFICATIONS disabled") - def test_start_stop_listening(self, daemon: MoneroDaemonRpc) -> None: - # add listener - listener: DaemonNotificationCollector = DaemonNotificationCollector(daemon) - auto_remove_listener: DaemonNotificationCollector = DaemonNotificationCollector(daemon, True) - daemon.add_listener(listener) - daemon.add_listener(auto_remove_listener) - assert len(daemon.get_listeners()) == 2 - - # mine blocks and collect notifications - BlockchainUtils.wait_for_blocks(10) - - # test notifications - assert listener.num_block_hashes > 0, "Daemon listener didn't collect any block hash" - assert listener.num_block_headers > 0, "Daemon listener didn't collect any block header" - assert listener.num_block_headers == listener.num_block_hashes, f"Count mismatch {listener.num_block_hashes} != {listener.num_block_headers}" - - # test autoremove listener - assert auto_remove_listener.num_block_headers == 1 - assert auto_remove_listener.num_block_hashes == 1 - assert len(daemon.get_listeners()) == 1 - - # remove listener - daemon.remove_listener(listener) - assert len(daemon.get_listeners()) == 0 - - #endregion diff --git a/tests/test_monero_utils.py b/tests/test_monero_utils.py deleted file mode 100644 index 1d704e6f..00000000 --- a/tests/test_monero_utils.py +++ /dev/null @@ -1,1019 +0,0 @@ -from __future__ import annotations - -import pytest -import logging -import subprocess -import sys -import gc -import re - -if sys.platform != "win32": - import resource - -from typing import Any -from pathlib import Path -from configparser import ConfigParser -from monero import ( - MoneroNetworkType, MoneroIntegratedAddress, MoneroUtils, MoneroTxConfig, - MoneroBlock, MoneroTxWallet, MoneroIncomingTransfer, MoneroOutputWallet, - MoneroTx -) -from utils import AddressBook, KeysBook, WalletUtils, BaseTestClass - -logger: logging.Logger = logging.getLogger("TestMoneroUtils") - - -@pytest.mark.unit -class TestMoneroUtils(BaseTestClass): - """Monero utilities unit tests.""" - - class Config: - """Utils tests configuration.""" - mainnet: AddressBook = AddressBook() - """Mainnet address book.""" - testnet: AddressBook = AddressBook() - """Testnet address book.""" - stagenet: AddressBook = AddressBook() - """Stagenet address book.""" - keys: KeysBook = KeysBook() - """Wallet keys book.""" - serialization_msg: str = '' - """Message to serialize.""" - - @classmethod - def parse(cls, parser: ConfigParser) -> TestMoneroUtils.Config: - """Parse utils tests configuration. - - :param ConfigParser parser: configuration parser. - :returns TestMoneroUtils.Config: parsed test utils configuration. - """ - config: TestMoneroUtils.Config = cls() - # check section - assert parser.has_section("serialization"), "Section [serialization] not found in test config" - # load address books - config.mainnet = AddressBook.parse(parser, "mainnet") - config.testnet = AddressBook.parse(parser, "testnet") - config.stagenet = AddressBook.parse(parser, "stagenet") - # load keys book - config.keys = KeysBook.parse(parser) - config.serialization_msg = parser.get("serialization", "msg") - return config - - #region Fixtures - - @pytest.fixture(scope="class") - @classmethod - def config(cls) -> TestMoneroUtils.Config: - parser: ConfigParser = ConfigParser() - parser.read('tests/config/test_monero_utils.ini') - return TestMoneroUtils.Config.parse(parser) - - #endregion - - #region Tests - - # Can get integrated addresses - def test_get_integrated_address(self, config: TestMoneroUtils.Config) -> None: - primary_address: str = config.stagenet.primary_address_4 - subaddress: str = config.stagenet.subaddress_4 - payment_id: str = "03284e41c342f036" - network_type: MoneroNetworkType = MoneroNetworkType.STAGENET - - # get integrated address with randomly generated payment id - integrated_address: MoneroIntegratedAddress = MoneroUtils.get_integrated_address(network_type, primary_address, "") - assert primary_address == integrated_address.standard_address - assert 16 == len(integrated_address.payment_id) - assert 106 == len(integrated_address.integrated_address) - - # get integrated address with specific payment id - integrated_address = MoneroUtils.get_integrated_address(network_type, primary_address, payment_id) - assert primary_address == integrated_address.standard_address - assert payment_id == integrated_address.payment_id - assert 106 == len(integrated_address.integrated_address) - - # get integrated address with subaddress - integrated_address = MoneroUtils.get_integrated_address(network_type, subaddress, payment_id) - assert subaddress == integrated_address.standard_address - assert payment_id == integrated_address.payment_id - assert 106 == len(integrated_address.integrated_address) - - # get integrated address with invalid payment id - try: - MoneroUtils.get_integrated_address(network_type, primary_address, "123") - raise Exception("Getting integrated address with invalid payment id should have failed") - except Exception as err: - assert "Invalid payment id" == str(err) - - # Can serialize heights with small numbers - def test_serialize_heights_small(self) -> None: - json_map: dict[Any, Any] = { - "heights": [111, 222, 333] - } - - binary: bytes = MoneroUtils.dict_to_binary(json_map) - assert len(binary) > 0 - - json_map2: dict[Any, Any] = MoneroUtils.binary_to_dict(binary) - assert json_map == json_map2 - - # Can serialize heights with big numbers - def test_serialize_heights_big(self) -> None: - json_map: dict[Any, Any] = { - "heights": [123456, 1234567, 870987] - } - - binary: bytes = MoneroUtils.dict_to_binary(json_map) - assert len(binary) > 0 - - json_map2: dict[Any, Any] = MoneroUtils.binary_to_dict(binary) - assert json_map == json_map2 - - # can serialize height with large unsigned values - def test_serialize_large_unsigned_values(self) -> None: - big_value: int = 18446744073709551615 # UINT64_MAX - json_map: dict[Any, Any] = { - "heights": [big_value] - } - binary: bytes = MoneroUtils.dict_to_binary(json_map) - assert len(binary) > 0 - - json_map2: dict[Any, Any] = MoneroUtils.binary_to_dict(binary) - assert json_map == json_map2 - assert json_map2["heights"][0] > 0, "uint64 > INT64_MAX must not serialize as negative" - - # Can serialize jsonMap with text - def test_serialize_text_short(self, config: TestMoneroUtils.Config) -> None: - assert config.serialization_msg is not None and config.serialization_msg != "" - json_map: dict[Any, Any] = { - "msg": config.serialization_msg - } - - binary: bytes = MoneroUtils.dict_to_binary(json_map) - assert len(binary) > 0 - - json_map2: dict[Any, Any] = MoneroUtils.binary_to_dict(binary) - assert json_map == json_map2 - - # Can serialize json with long text - def test_serialize_text_long(self, config: TestMoneroUtils.Config) -> None: - msg: str = config.serialization_msg - json_map: dict[str, str] = { - "msg": f"{msg}\n" + - f"{msg}\n" + - f"{msg}\n" + - f"{msg}\n" + - f"{msg}\n" + - f"{msg}\n" + - f"{msg}\n" + - f"{msg}\n" + - f"{msg}\n" + - f"{msg}\n" + - f"{msg}\n" + - f"{msg}\n" + - f"{msg}\n" + - f"{msg}\n" - } - - binary: bytes = MoneroUtils.dict_to_binary(json_map) - assert len(binary) > 0 - - json_map2: dict[Any, Any] = MoneroUtils.binary_to_dict(binary) - assert json_map == json_map2 - - # Can validate addresses - def test_address_validation(self, config: TestMoneroUtils.Config) -> None: - - # test mainnet primary address validation - assert (MoneroUtils.is_valid_address(config.mainnet.primary_address_1, MoneroNetworkType.MAINNET)) is True - assert (MoneroUtils.is_valid_address(config.mainnet.primary_address_2, MoneroNetworkType.MAINNET)) is True - assert (MoneroUtils.is_valid_address(config.mainnet.primary_address_3, MoneroNetworkType.MAINNET)) is True - - # test mainnet integrated address validation - MoneroUtils.validate_address(config.mainnet.integrated_1, MoneroNetworkType.MAINNET) - MoneroUtils.validate_address(config.mainnet.integrated_2, MoneroNetworkType.MAINNET) - MoneroUtils.validate_address(config.mainnet.integrated_3, MoneroNetworkType.MAINNET) - - # test mainnet subaddress validation - MoneroUtils.validate_address(config.mainnet.subaddress_1, MoneroNetworkType.MAINNET) - MoneroUtils.validate_address(config.mainnet.subaddress_2, MoneroNetworkType.MAINNET) - MoneroUtils.validate_address(config.mainnet.subaddress_3, MoneroNetworkType.MAINNET) - - # test testnet primary address validation - assert (MoneroUtils.is_valid_address(config.testnet.primary_address_1, MoneroNetworkType.TESTNET)) is True - assert (MoneroUtils.is_valid_address(config.testnet.primary_address_2, MoneroNetworkType.TESTNET)) is True - assert (MoneroUtils.is_valid_address(config.testnet.primary_address_3, MoneroNetworkType.TESTNET)) is True - - # test testnet integrated address validation - assert (MoneroUtils.is_valid_address(config.testnet.integrated_1, MoneroNetworkType.TESTNET)) is True - assert (MoneroUtils.is_valid_address(config.testnet.integrated_2, MoneroNetworkType.TESTNET)) is True - assert (MoneroUtils.is_valid_address(config.testnet.integrated_3, MoneroNetworkType.TESTNET)) is True - - # test testnet subaddress validation - assert (MoneroUtils.is_valid_address(config.testnet.subaddress_1, MoneroNetworkType.TESTNET)) is True - assert (MoneroUtils.is_valid_address(config.testnet.subaddress_2, MoneroNetworkType.TESTNET)) is True - assert (MoneroUtils.is_valid_address(config.testnet.subaddress_3, MoneroNetworkType.TESTNET)) is True - - # test stagenet primary address validation - assert (MoneroUtils.is_valid_address(config.stagenet.primary_address_1, MoneroNetworkType.STAGENET)) is True - assert (MoneroUtils.is_valid_address(config.stagenet.primary_address_2, MoneroNetworkType.STAGENET)) is True - assert (MoneroUtils.is_valid_address(config.stagenet.primary_address_3, MoneroNetworkType.STAGENET)) is True - - # test stagenet integrated address validation - assert (MoneroUtils.is_valid_address(config.stagenet.integrated_1, MoneroNetworkType.STAGENET)) is True - assert (MoneroUtils.is_valid_address(config.stagenet.integrated_2, MoneroNetworkType.STAGENET)) is True - assert (MoneroUtils.is_valid_address(config.stagenet.integrated_3, MoneroNetworkType.STAGENET)) is True - - # test stagenet subaddress validation - assert (MoneroUtils.is_valid_address(config.stagenet.subaddress_1, MoneroNetworkType.STAGENET)) is True - assert (MoneroUtils.is_valid_address(config.stagenet.subaddress_2, MoneroNetworkType.STAGENET)) is True - assert (MoneroUtils.is_valid_address(config.stagenet.subaddress_3, MoneroNetworkType.STAGENET)) is True - - # test invalid addresses on mainnet - WalletUtils.test_invalid_address(None, MoneroNetworkType.MAINNET) - WalletUtils.test_invalid_address("", MoneroNetworkType.MAINNET) - WalletUtils.test_invalid_address(config.mainnet.invalid_1, MoneroNetworkType.MAINNET) - WalletUtils.test_invalid_address(config.mainnet.invalid_2, MoneroNetworkType.MAINNET) - WalletUtils.test_invalid_address(config.mainnet.invalid_3, MoneroNetworkType.MAINNET) - - # test invalid addresses on testnet - WalletUtils.test_invalid_address(None, MoneroNetworkType.TESTNET) - WalletUtils.test_invalid_address("", MoneroNetworkType.TESTNET) - WalletUtils.test_invalid_address(config.testnet.invalid_1, MoneroNetworkType.TESTNET) - WalletUtils.test_invalid_address(config.testnet.invalid_2, MoneroNetworkType.TESTNET) - WalletUtils.test_invalid_address(config.testnet.invalid_3, MoneroNetworkType.TESTNET) - - # test invalid addresses on stagenet - WalletUtils.test_invalid_address(None, MoneroNetworkType.STAGENET) - WalletUtils.test_invalid_address("", MoneroNetworkType.STAGENET) - WalletUtils.test_invalid_address(config.stagenet.invalid_1, MoneroNetworkType.STAGENET) - WalletUtils.test_invalid_address(config.stagenet.invalid_2, MoneroNetworkType.STAGENET) - WalletUtils.test_invalid_address(config.stagenet.invalid_3, MoneroNetworkType.STAGENET) - - # Can validate keys - def test_key_validation(self, config: TestMoneroUtils.Config) -> None: - invalid_hex_64: str = "z" * 64 # right length but not hex - - # test private view key validation - assert MoneroUtils.is_valid_private_view_key(config.keys.private_view_key) - MoneroUtils.validate_private_view_key(config.keys.private_view_key) - WalletUtils.test_invalid_private_view_key("") - WalletUtils.test_invalid_private_view_key(None) - WalletUtils.test_invalid_private_view_key(config.keys.invalid_private_view_key) - WalletUtils.test_invalid_private_view_key(invalid_hex_64) - - # test public view key validation - assert MoneroUtils.is_valid_public_view_key(config.keys.public_view_key) - MoneroUtils.validate_public_view_key(config.keys.public_view_key) - WalletUtils.test_invalid_public_view_key("") - WalletUtils.test_invalid_public_view_key(None) - WalletUtils.test_invalid_public_view_key(config.keys.invalid_public_view_key) - WalletUtils.test_invalid_public_view_key(invalid_hex_64) - - # test private spend key validation - assert MoneroUtils.is_valid_private_spend_key(config.keys.private_spend_key) - WalletUtils.test_invalid_private_spend_key("") - WalletUtils.test_invalid_private_spend_key(None) - WalletUtils.test_invalid_private_spend_key(config.keys.invalid_private_spend_key) - WalletUtils.test_invalid_private_spend_key(invalid_hex_64) - - # test public spend key validation - assert MoneroUtils.is_valid_public_spend_key(config.keys.public_spend_key) - MoneroUtils.validate_public_spend_key(config.keys.public_spend_key) - WalletUtils.test_invalid_public_spend_key("") - WalletUtils.test_invalid_public_spend_key(None) - WalletUtils.test_invalid_public_spend_key(config.keys.invalid_public_spend_key) - WalletUtils.test_invalid_public_spend_key(invalid_hex_64) - - # Can validate seed - def test_mnemonic_validation(self, config: TestMoneroUtils.Config) -> None: - - # test valid seed - MoneroUtils.validate_mnemonic(config.keys.seed) - assert MoneroUtils.is_valid_mnemonic(config.keys.seed), f"Invalid seed: {config.keys.seed}" - assert MoneroUtils.is_valid_mnemonic(config.keys.seed, "English"), f"Expected valid English seed: {config.keys.seed}" - - # test invalid seed language - assert not MoneroUtils.is_valid_mnemonic(config.keys.seed, "Spanish"), f"Expected invalid Spanish seed: {config.keys.seed}" - - # test invalid seed - assert not MoneroUtils.is_valid_mnemonic("invalid monero wallet seed") - - # test empty seed - assert not MoneroUtils.is_valid_mnemonic("") - - # Can validate language - def test_seed_language_validation(self) -> None: - languages: list[str] = ["Italian", "English", "German"] - - for language in languages: - assert MoneroUtils.is_valid_language(language), f"Expected valid language: {language}" - - invalid_languages: list[str] = ["", "english", "italian"] - - for language in invalid_languages: - assert not MoneroUtils.is_valid_language(language), f"Expected invalid language: {language}" - - # Can validate payment id - def test_payment_id_validation(self) -> None: - payment_ids: list[str] = [ - "43e04076e176b768", "ef35647e9842991c", - "8434d5452ad1b0ab", "3b5ac230d2666177", - "87fdf837b5e6a390", "304e0fa65b9c9e14" - ] - - for payment_id in payment_ids: - assert MoneroUtils.is_valid_payment_id(payment_id), f"Expected valid payment id: {payment_id}" - MoneroUtils.validate_payment_id(payment_id) - - # validate long payment id - assert MoneroUtils.is_valid_payment_id("87fdf837b5e6a390ef35647e9842991c8434d5452ad1b0ab304e0fa65b9c9e14") - - invalid_payment_ids: list[str] = [ - "", "wijqwnn38y", - "87fdf837b5e6a39", "3b5ac230d26661778", - "304e0fa65b9c9e14304e0fa65b9c9e14", - "z" * 16, "z" * 64 - ] - - for payment_id in invalid_payment_ids: - assert not MoneroUtils.is_valid_payment_id(payment_id), f"Expected invalid payment id: {payment_id}" - try: - MoneroUtils.validate_payment_id(payment_id) - except Exception as e: - expected: str = "payment id expected to be 64 or 16 hex characters" - e_str: str = str(e) - assert expected == e_str, f"Expected error '{expected}', got {e_str}" - - # Can validate a long payment id specifically - def test_payment_id_long_validation(self) -> None: - long_payment_id: str = "87fdf837b5e6a390ef35647e9842991c8434d5452ad1b0ab304e0fa65b9c9e14" - assert MoneroUtils.is_valid_payment_id_long(long_payment_id) - - short_payment_id: str = "87fdf837b5e6a390" - assert not MoneroUtils.is_valid_payment_id_long(short_payment_id) - - invalid_payment_ids: list[str] = ["", "wijqwnn38y", long_payment_id[:-1]] - - for payment_id in invalid_payment_ids: - assert not MoneroUtils.is_valid_payment_id_long(payment_id), f"Expected invalid long payment id: {payment_id}" - - # Can validate a short payment id specifically - def test_payment_id_short_validation(self) -> None: - short_payment_id: str = "87fdf837b5e6a390" - assert MoneroUtils.is_valid_payment_id_short(short_payment_id) - - long_payment_id: str = "87fdf837b5e6a390ef35647e9842991c8434d5452ad1b0ab304e0fa65b9c9e14" - assert not MoneroUtils.is_valid_payment_id_short(long_payment_id) - - invalid_payment_ids: list[str] = ["", "wijqwnn38y", short_payment_id[:-1]] - - for payment_id in invalid_payment_ids: - assert not MoneroUtils.is_valid_payment_id_short(payment_id), f"Expected invalid short payment id: {payment_id}" - - # Can validate a long payment id, raising on failure - def test_validate_payment_id_long(self) -> None: - long_payment_id: str = "87fdf837b5e6a390ef35647e9842991c8434d5452ad1b0ab304e0fa65b9c9e14" - MoneroUtils.validate_payment_id_long(long_payment_id) - - with pytest.raises(RuntimeError, match="Invalid long payment id"): - MoneroUtils.validate_payment_id_long("87fdf837b5e6a390") # too short - - with pytest.raises(RuntimeError, match="Invalid long payment id"): - MoneroUtils.validate_payment_id_long("wijqwnn38y") # not hex - - # Can validate a short payment id, raising on failure - def test_validate_payment_id_short(self) -> None: - short_payment_id: str = "87fdf837b5e6a390" - MoneroUtils.validate_payment_id_short(short_payment_id) - - with pytest.raises(RuntimeError, match="Invalid short payment id"): - MoneroUtils.validate_payment_id_short("87fdf837b5e6a390ef35647e9842991c8434d5452ad1b0ab304e0fa65b9c9e14") # too long - - with pytest.raises(RuntimeError, match="Invalid short payment id"): - MoneroUtils.validate_payment_id_short("wijqwnn38y") # not hex - - # Can convert between XMR and atomic units - def test_atomic_unit_conversion(self) -> None: - assert 1000000000000 == MoneroUtils.xmr_to_atomic_units(1) - assert 1 == MoneroUtils.atomic_units_to_xmr(1000000000000) - assert 1000000000 == MoneroUtils.xmr_to_atomic_units(0.001) - assert 0.001 == MoneroUtils.atomic_units_to_xmr(1000000000) - assert 250000000000 == MoneroUtils.xmr_to_atomic_units(0.25) - assert 0.25 == MoneroUtils.atomic_units_to_xmr(250000000000) - assert 1250000000000 == MoneroUtils.xmr_to_atomic_units(1.25) - assert 1.25 == MoneroUtils.atomic_units_to_xmr(1250000000000) - assert 2796726190000 == MoneroUtils.xmr_to_atomic_units(2.79672619) - assert 2.79672619 == MoneroUtils.atomic_units_to_xmr(2796726190000) - assert 2796726190001 == MoneroUtils.xmr_to_atomic_units(2.796726190001) - assert 2.796726190001 == MoneroUtils.atomic_units_to_xmr(2796726190001) - assert 2796726189999 == MoneroUtils.xmr_to_atomic_units(2.796726189999) - assert 2.796726189999 == MoneroUtils.atomic_units_to_xmr(2796726189999) - assert 2796726180000 == MoneroUtils.xmr_to_atomic_units(2.79672618) - assert 2.79672618 == MoneroUtils.atomic_units_to_xmr(2796726180000) - - # xmr_to_atomic_units(0.0) and negative zero are valid, not errors - def test_xmr_to_atomic_units_zero(self) -> None: - assert 0 == MoneroUtils.xmr_to_atomic_units(0.0) - # -0.0 < 0 is False in IEEE 754, so it must not be rejected by the - # "amount must be non-negative" check - assert 0 == MoneroUtils.xmr_to_atomic_units(-0.0) - - # Amounts smaller than half an atomic unit (1e-12 XMR) round down to 0 - def test_xmr_to_atomic_units_rounds_down_to_zero(self) -> None: - assert 0 == MoneroUtils.xmr_to_atomic_units(1e-13) - assert 0 == MoneroUtils.xmr_to_atomic_units(4e-13) - - # xmr_to_atomic_units() rounds the underlying long double * 1e12 product to - # the nearest atomic unit (away from zero on an exact .5). Decimal literals - # ending in .5e-12 are not necessarily exact halves once represented as a - # double, so which way they round depends on whether the closest double is - # a hair above or below the nominal decimal value, and that itself can - # depend on the platform's "long double" precision (80-bit extended on - # x86_64 Linux/glibc, but identical to a plain 64-bit double on Apple - # Silicon/macOS), so the same literal can round differently on different - # platforms. This is inherent to IEEE 754, not an inconsistency in - # xmr_to_atomic_units() itself, assert the result lands on one of the - # two atomic units the value sits between, not a specific platform's tie-break. - def test_xmr_to_atomic_units_half_atomic_unit_rounding(self) -> None: - cases: list[tuple[float, int, int]] = [ - (0.5e-12, 0, 1), - (1.5e-12, 1, 2), - (2.5e-12, 2, 3), - (3.5e-12, 3, 4), - ] - for amount_xmr, floor_atomic, ceil_atomic in cases: - actual: int = MoneroUtils.xmr_to_atomic_units(amount_xmr) - logger.debug(f"xmr_to_atomic_units({amount_xmr!r}) = {actual} (expected {floor_atomic} or {ceil_atomic})") - assert actual in (floor_atomic, ceil_atomic), f"xmr_to_atomic_units({amount_xmr!r}) == {actual}, expected {floor_atomic} or {ceil_atomic}" - - # amount_xmr must be finite and non-negative - @pytest.mark.parametrize("amount_xmr", [-1.0, -0.0000000001, float("nan"), float("inf"), float("-inf")]) - def test_xmr_to_atomic_units_invalid_amount(self, amount_xmr: float) -> None: - with pytest.raises(RuntimeError, match="amount must be a finite, non-negative number"): - MoneroUtils.xmr_to_atomic_units(amount_xmr) - - # amounts whose rounded atomic-unit value would overflow uint64_t are rejected - # rather than silently wrapping or invoking undefined behavior on the cast - def test_xmr_to_atomic_units_overflow(self) -> None: - # UINT64_MAX atomic units is ~18446744.0737... XMR; comfortably over that - # (with margin for float imprecision) must raise - with pytest.raises(RuntimeError, match="amount exceeds maximum representable atomic units"): - MoneroUtils.xmr_to_atomic_units(18446745.0) - with pytest.raises(RuntimeError, match="amount exceeds maximum representable atomic units"): - MoneroUtils.xmr_to_atomic_units(2e22) - - # values comfortably below the uint64_t boundary succeed - def test_xmr_to_atomic_units_near_uint64_max_boundary(self) -> None: - uint64_max: int = 2 ** 64 - 1 - boundary_xmr: float = uint64_max / 1e12 # ~18446744.073709551615 XMR - margin_xmr: float = 1.0 - - safely_below: float = boundary_xmr - margin_xmr - below: int = MoneroUtils.xmr_to_atomic_units(safely_below) - logger.debug(f"xmr_to_atomic_units({safely_below!r}) = {below} (uint64_max = {uint64_max})") - assert below <= uint64_max - - safely_above: float = boundary_xmr + margin_xmr - with pytest.raises(RuntimeError, match="amount exceeds maximum representable atomic units"): - MoneroUtils.xmr_to_atomic_units(safely_above) - - # Can get payment uri - def test_get_payment_uri(self, config: TestMoneroUtils.Config) -> None: - address: str = config.mainnet.primary_address_1 - tx_config: MoneroTxConfig = WalletUtils.build_payment_uri_config(address) - payment_uri: str = MoneroUtils.get_payment_uri(tx_config) - query: str = "tx_amount=0.250000000000&recipient_name=John%20Doe&tx_description=My%20transfer%20to%20wallet" - logger.debug(f"Testing payment uri: {payment_uri}") - assert payment_uri == f"monero:{address}?{query}" - - # Test invalid payment uri address network type - def test_payment_uri_invalid_network_type(self, config: TestMoneroUtils.Config) -> None: - address: str = config.testnet.primary_address_1 - tx_config: MoneroTxConfig = WalletUtils.build_payment_uri_config(address) - with pytest.raises(Exception) as exc_info: - MoneroUtils.get_payment_uri(tx_config) - - # get_payment_uri() wraps make_uri()'s error with context, unlike e.g. validate_address() - assert str(exc_info.value) == f"Cannot make URI from supplied parameters: wrong address: {address}" - - # Test deprecated standalone payment id - def test_payment_uri_deprecated_payment_uri(self, config: TestMoneroUtils.Config) -> None: - address: str = config.testnet.primary_address_1 - tx_config: MoneroTxConfig = WalletUtils.build_payment_uri_config(address) - tx_config.payment_id = "03284e41c342f03603284e41c342f03603284e41c342f03603284e41c342f036" - with pytest.raises(Exception) as exc_info: - MoneroUtils.get_payment_uri(tx_config, MoneroNetworkType.TESTNET) - - # get_payment_uri() wraps make_uri()'s error with context, unlike e.g. validate_address() - assert str(exc_info.value) == "Cannot make URI from supplied parameters: Standalone payment id deprecated, use integrated address instead" - - # Test single payment id given with an integrated address - def test_payment_uri_single_payment_id_with_integrated_address(self, config: TestMoneroUtils.Config) -> None: - address: str = config.mainnet.integrated_1 - tx_config: MoneroTxConfig = WalletUtils.build_payment_uri_config(address) - tx_config.payment_id = "03284e41c342f03603284e41c342f03603284e41c342f03603284e41c342f036" - with pytest.raises(Exception) as exc_info: - MoneroUtils.get_payment_uri(tx_config) - - # get_payment_uri() wraps make_uri()'s error with context, unlike e.g. validate_address() - assert str(exc_info.value) == "Cannot make URI from supplied parameters: A single payment id is allowed" - - # Can parse a payment uri without any query string - def test_parse_payment_uri_no_query(self, config: TestMoneroUtils.Config) -> None: - address: str = config.mainnet.primary_address_1 - parsed: MoneroTxConfig = MoneroUtils.parse_payment_uri(f"monero:{address}") - assert parsed.destinations[0].address == address - assert parsed.destinations[0].amount == 0 - assert parsed.recipient_name is None - assert parsed.note is None - assert parsed.payment_id is None - - # Can parse a payment uri with an empty query string - def test_parse_payment_uri_empty_query(self, config: TestMoneroUtils.Config) -> None: - address: str = config.mainnet.primary_address_1 - parsed: MoneroTxConfig = MoneroUtils.parse_payment_uri(f"monero:{address}?") - assert parsed.destinations[0].address == address - - # Can parse a payment uri round trip built by get_payment_uri() - def test_parse_payment_uri_round_trip(self, config: TestMoneroUtils.Config) -> None: - address: str = config.mainnet.primary_address_1 - tx_config: MoneroTxConfig = WalletUtils.build_payment_uri_config(address) - uri: str = MoneroUtils.get_payment_uri(tx_config) - parsed: MoneroTxConfig = MoneroUtils.parse_payment_uri(uri) - assert parsed.destinations[0].address == address - assert parsed.destinations[0].amount == tx_config.amount - assert parsed.recipient_name == tx_config.recipient_name - assert parsed.note == tx_config.note - - # Payment uri must use the "monero:" scheme - def test_parse_payment_uri_wrong_scheme(self, config: TestMoneroUtils.Config) -> None: - address: str = config.mainnet.primary_address_1 - with pytest.raises(RuntimeError) as exc_info: - MoneroUtils.parse_payment_uri(f"bitcoin:{address}") - assert str(exc_info.value) == f'Error parsing URI: URI has wrong scheme (expected "monero:"): bitcoin:{address}' - - # Payment uri address must be valid - def test_parse_payment_uri_wrong_address(self, config: TestMoneroUtils.Config) -> None: - address: str = config.mainnet.invalid_1 - with pytest.raises(RuntimeError) as exc_info: - MoneroUtils.parse_payment_uri(f"monero:{address}") - assert str(exc_info.value) == f"Error parsing URI: URI has wrong address: {address}" - - # Payment uri parameters must be "key=value" pairs - def test_parse_payment_uri_malformed_parameter(self, config: TestMoneroUtils.Config) -> None: - address: str = config.mainnet.primary_address_1 - with pytest.raises(RuntimeError) as exc_info: - MoneroUtils.parse_payment_uri(f"monero:{address}?tx_amount") - assert str(exc_info.value) == "Error parsing URI: URI has wrong parameter: tx_amount" - - # Payment uri parameters must not repeat - def test_parse_payment_uri_duplicate_parameter(self, config: TestMoneroUtils.Config) -> None: - address: str = config.mainnet.primary_address_1 - with pytest.raises(RuntimeError) as exc_info: - MoneroUtils.parse_payment_uri(f"monero:{address}?tx_amount=1&tx_amount=2") - assert str(exc_info.value) == "Error parsing URI: URI has more than one instance of tx_amount" - - # Payment uri tx_amount must be a valid amount - def test_parse_payment_uri_invalid_amount(self, config: TestMoneroUtils.Config) -> None: - address: str = config.mainnet.primary_address_1 - with pytest.raises(RuntimeError) as exc_info: - MoneroUtils.parse_payment_uri(f"monero:{address}?tx_amount=abc") - assert str(exc_info.value) == "Error parsing URI: URI has invalid amount: abc" - - # Payment uri tx_payment_id must be a valid long payment id - def test_parse_payment_uri_invalid_payment_id(self, config: TestMoneroUtils.Config) -> None: - address: str = config.mainnet.primary_address_1 - with pytest.raises(RuntimeError) as exc_info: - MoneroUtils.parse_payment_uri(f"monero:{address}?tx_payment_id=nothex") - assert str(exc_info.value) == "Error parsing URI: Invalid payment id: nothex" - - # Payment uri can carry a separate, valid tx_payment_id for a non-integrated address - def test_parse_payment_uri_valid_payment_id(self, config: TestMoneroUtils.Config) -> None: - address: str = config.mainnet.primary_address_1 - payment_id: str = "a" * 64 - parsed: MoneroTxConfig = MoneroUtils.parse_payment_uri(f"monero:{address}?tx_payment_id={payment_id}") - assert parsed.payment_id == payment_id - - # Payment uri must not combine a separate tx_payment_id with an integrated address - def test_parse_payment_uri_separate_payment_id_with_integrated_address(self, config: TestMoneroUtils.Config) -> None: - address: str = config.mainnet.integrated_1 - with pytest.raises(RuntimeError) as exc_info: - MoneroUtils.parse_payment_uri(f"monero:{address}?tx_payment_id={'a' * 64}") - assert str(exc_info.value) == "Error parsing URI: Separate payment id given with an integrated address" - - # Unknown payment uri parameters are silently discarded - def test_parse_payment_uri_unknown_parameter(self, config: TestMoneroUtils.Config) -> None: - address: str = config.mainnet.primary_address_1 - parsed: MoneroTxConfig = MoneroUtils.parse_payment_uri(f"monero:{address}?foo=bar") - assert parsed.destinations[0].address == address - - # Can get version, which is the one declared in pyproject.toml - def test_get_version(self) -> None: - version: str = MoneroUtils.get_version() - logger.debug(f"Testing monero-python version: {version}") - assert version != "", "Version is empty" - pyproject: str = (Path(__file__).resolve().parent.parent / "pyproject.toml").read_text(encoding="utf-8") - declared = re.search(r'^version = "(\d+\.\d+\.\d+)"$', pyproject, re.MULTILINE) - assert declared is not None, "Version not found in pyproject.toml" - assert version == declared.group(1) - - # Can get ring size - def test_get_ring_size(self) -> None: - size: int = MoneroUtils.get_ring_size() - assert size == 16 - - #endregion - - #region Gather blocks - - def test_get_blocks_from_txs_dedup_and_order(self) -> None: - block1: MoneroBlock = MoneroBlock() - block1.height = 100 - block2: MoneroBlock = MoneroBlock() - block2.height = 200 - - tx1: MoneroTxWallet = MoneroTxWallet() - tx1.hash = "a" * 64 - tx1.block = block1 - - tx2: MoneroTxWallet = MoneroTxWallet() - tx2.hash = "b" * 64 - tx2.block = block2 - - tx3: MoneroTxWallet = MoneroTxWallet() # shares block1 with tx1 - tx3.hash = "c" * 64 - tx3.block = block1 - - blocks: list[MoneroBlock] = MoneroUtils.get_blocks_from_txs([tx1, tx2, tx3]) - assert len(blocks) == 2 # block1 deduplicated despite appearing twice - assert blocks[0] is block1 # blocks are returned in first-seen order - assert blocks[1] is block2 - - def test_get_blocks_from_txs_unconfirmed_placeholder(self) -> None: - tx1: MoneroTxWallet = MoneroTxWallet() - tx1.hash = "a" * 64 - tx2: MoneroTxWallet = MoneroTxWallet() - tx2.hash = "b" * 64 - assert tx1.block is None and tx2.block is None - - blocks: list[MoneroBlock] = MoneroUtils.get_blocks_from_txs([tx1, tx2]) - - # unconfirmed (blockless) txs are grouped under one shared placeholder block - assert len(blocks) == 1 - placeholder: MoneroBlock = blocks[0] - assert placeholder.height is None - assert len(placeholder.txs) == 2 - - # side effect: get_blocks_from_txs() mutates its inputs, attaching each - # unconfirmed tx to the placeholder block it creates - assert tx1.block is placeholder - assert tx2.block is placeholder - - def test_get_blocks_from_txs_mixed_confirmed_and_unconfirmed(self) -> None: - block: MoneroBlock = MoneroBlock() - block.height = 100 - confirmed: MoneroTxWallet = MoneroTxWallet() - confirmed.hash = "a" * 64 - confirmed.block = block - - unconfirmed1: MoneroTxWallet = MoneroTxWallet() - unconfirmed1.hash = "b" * 64 - unconfirmed2: MoneroTxWallet = MoneroTxWallet() - unconfirmed2.hash = "c" * 64 - - blocks: list[MoneroBlock] = MoneroUtils.get_blocks_from_txs([confirmed, unconfirmed1, unconfirmed2]) - assert len(blocks) == 2 # the real block, plus one shared unconfirmed placeholder - assert blocks[0] is block - assert blocks[1].height is None - assert unconfirmed1.block is unconfirmed2.block is blocks[1] - - def test_get_blocks_from_txs_empty(self) -> None: - assert MoneroUtils.get_blocks_from_txs([]) == [] - - def test_get_blocks_from_transfers_dedup_and_order(self) -> None: - block1: MoneroBlock = MoneroBlock() - block1.height = 100 - block2: MoneroBlock = MoneroBlock() - block2.height = 200 - - t1: MoneroIncomingTransfer = MoneroIncomingTransfer() - t1.tx = MoneroTxWallet() - t1.tx.hash = "a" * 64 - t1.tx.block = block1 - - t2: MoneroIncomingTransfer = MoneroIncomingTransfer() - t2.tx = MoneroTxWallet() - t2.tx.hash = "b" * 64 - t2.tx.block = block2 - - t3: MoneroIncomingTransfer = MoneroIncomingTransfer() # tx shares block1 with t1 - t3.tx = MoneroTxWallet() - t3.tx.hash = "c" * 64 - t3.tx.block = block1 - - blocks: list[MoneroBlock] = MoneroUtils.get_blocks_from_transfers([t1, t2, t3]) - assert len(blocks) == 2 - assert blocks[0] is block1 - assert blocks[1] is block2 - - def test_get_blocks_from_transfers_unconfirmed_placeholder(self) -> None: - t1: MoneroIncomingTransfer = MoneroIncomingTransfer() - t1.tx = MoneroTxWallet() - t1.tx.hash = "a" * 64 - t2: MoneroIncomingTransfer = MoneroIncomingTransfer() - t2.tx = MoneroTxWallet() - t2.tx.hash = "b" * 64 - assert t1.tx.block is None and t2.tx.block is None - - blocks: list[MoneroBlock] = MoneroUtils.get_blocks_from_transfers([t1, t2]) - assert len(blocks) == 1 - placeholder: MoneroBlock = blocks[0] - assert placeholder.height is None - - # side effect: mutates transfer.tx.block, same as get_blocks_from_txs() - assert t1.tx.block is placeholder - assert t2.tx.block is placeholder - - def test_get_blocks_from_transfers_mixed_confirmed_and_unconfirmed(self) -> None: - block: MoneroBlock = MoneroBlock() - block.height = 100 - confirmed: MoneroIncomingTransfer = MoneroIncomingTransfer() - confirmed.tx = MoneroTxWallet() - confirmed.tx.hash = "a" * 64 - confirmed.tx.block = block - - unconfirmed1: MoneroIncomingTransfer = MoneroIncomingTransfer() - unconfirmed1.tx = MoneroTxWallet() - unconfirmed1.tx.hash = "b" * 64 - unconfirmed2: MoneroIncomingTransfer = MoneroIncomingTransfer() - unconfirmed2.tx = MoneroTxWallet() - unconfirmed2.tx.hash = "c" * 64 - - blocks: list[MoneroBlock] = MoneroUtils.get_blocks_from_transfers([confirmed, unconfirmed1, unconfirmed2]) - assert len(blocks) == 2 # the real block, plus one shared unconfirmed placeholder - assert blocks[0] is block - assert blocks[1].height is None - assert unconfirmed1.tx.block is unconfirmed2.tx.block is blocks[1] - - def test_get_blocks_from_transfers_missing_tx_raises(self) -> None: - # a transfer with no tx set is a legitimate, reachable state (it's just - # never assigned); get_blocks_from_transfers() must raise a catchable - # exception, not dereference transfer.tx and segfault - transfer: MoneroIncomingTransfer = MoneroIncomingTransfer() - transfer.amount = 500000 - with pytest.raises(RuntimeError) as exc_info: - MoneroUtils.get_blocks_from_transfers([transfer]) - assert str(exc_info.value) == "Transfer has no tx" - - def test_get_blocks_from_transfers_missing_tx_raises_after_partial_mutation(self) -> None: - # get_blocks_from_transfers() is not transactional: a transfer earlier - # in the list is already mutated (attached to a placeholder block) - # before a later, invalid transfer aborts the whole call - good: MoneroIncomingTransfer = MoneroIncomingTransfer() - good.tx = MoneroTxWallet() - good.tx.hash = "a" * 64 - assert good.tx.block is None - - bad: MoneroIncomingTransfer = MoneroIncomingTransfer() # no tx - with pytest.raises(RuntimeError): - MoneroUtils.get_blocks_from_transfers([good, bad]) - - assert good.tx.block is not None - assert good.tx.block.height is None - - def test_get_blocks_from_transfers_empty(self) -> None: - assert MoneroUtils.get_blocks_from_transfers([]) == [] - - def test_get_blocks_from_outputs_dedup_and_order(self) -> None: - block1: MoneroBlock = MoneroBlock() - block1.height = 100 - block2: MoneroBlock = MoneroBlock() - block2.height = 200 - - tx1: MoneroTxWallet = MoneroTxWallet() - tx1.hash = "a" * 64 - tx1.block = block1 - tx2: MoneroTxWallet = MoneroTxWallet() - tx2.hash = "b" * 64 - tx2.block = block2 - - o1: MoneroOutputWallet = MoneroOutputWallet() - o1.tx = tx1 - o2: MoneroOutputWallet = MoneroOutputWallet() - o2.tx = tx2 - o3: MoneroOutputWallet = MoneroOutputWallet() # tx shares block1 with o1 - o3.tx = tx1 - - blocks: list[MoneroBlock] = MoneroUtils.get_blocks_from_outputs([o1, o2, o3]) - assert len(blocks) == 2 - assert blocks[0] is block1 - assert blocks[1] is block2 - - def test_get_blocks_from_outputs_unconfirmed_raises(self) -> None: - # unlike get_blocks_from_txs()/get_blocks_from_transfers(), an - # unconfirmed (blockless) output's tx does not get a placeholder - # block -- it raises instead - output: MoneroOutputWallet = MoneroOutputWallet() - output.tx = MoneroTxWallet() - output.tx.hash = "a" * 64 - assert output.tx.block is None - - with pytest.raises(RuntimeError, match="Need to handle unconfirmed output"): - MoneroUtils.get_blocks_from_outputs([output]) - - def test_get_blocks_from_outputs_unconfirmed_raises_after_earlier_match(self) -> None: - # unlike get_blocks_from_transfers(), get_blocks_from_outputs() never mutates its inputs - block: MoneroBlock = MoneroBlock() - block.height = 100 - confirmed_tx: MoneroTxWallet = MoneroTxWallet() - confirmed_tx.hash = "a" * 64 - confirmed_tx.block = block - good: MoneroOutputWallet = MoneroOutputWallet() - good.tx = confirmed_tx - - bad: MoneroOutputWallet = MoneroOutputWallet() - bad.tx = MoneroTxWallet() - bad.tx.hash = "b" * 64 # unconfirmed - - with pytest.raises(RuntimeError, match="Need to handle unconfirmed output"): - MoneroUtils.get_blocks_from_outputs([good, bad]) - - def test_get_blocks_from_outputs_missing_tx_raises(self) -> None: - # same as get_blocks_from_transfers(): output.tx is a legitimate but - # unchecked null; must raise rather than dereference and segfault - output: MoneroOutputWallet = MoneroOutputWallet() - output.amount = 1000000 - with pytest.raises(RuntimeError) as exc_info: - MoneroUtils.get_blocks_from_outputs([output]) - assert str(exc_info.value) == "Output has no tx" - - def test_get_blocks_from_outputs_empty(self) -> None: - assert MoneroUtils.get_blocks_from_outputs([]) == [] - - #endregion - - #region Free memory - - def test_free_block_breaks_tx_backlink(self) -> None: - block: MoneroBlock = MoneroBlock() - block.height = 100 - tx: MoneroTxWallet = MoneroTxWallet() - tx.hash = "a" * 64 - tx.block = block - block.txs = [tx] - - MoneroUtils.free(block) - assert tx.block is None - - def test_free_blocks_list(self) -> None: - block1: MoneroBlock = MoneroBlock() - block1.height = 1 - tx1: MoneroTxWallet = MoneroTxWallet() - tx1.hash = "a" * 64 - tx1.block = block1 - block1.txs = [tx1] - - block2: MoneroBlock = MoneroBlock() - block2.height = 2 - tx2: MoneroTxWallet = MoneroTxWallet() - tx2.hash = "b" * 64 - tx2.block = block2 - block2.txs = [tx2] - - MoneroUtils.free([block1, block2]) - assert tx1.block is None - assert tx2.block is None - - def test_free_tx_without_block_does_not_crash(self) -> None: - # free(tx) creates a throwaway placeholder block for an unconfirmed - # tx, then immediately frees it. Net no-op on tx.block, but exercises - # that code path safely - tx: MoneroTxWallet = MoneroTxWallet() - tx.hash = "a" * 64 - assert tx.block is None - MoneroUtils.free(tx) - assert tx.block is None - - def test_free_tx_with_block(self) -> None: - block: MoneroBlock = MoneroBlock() - block.height = 100 - tx: MoneroTxWallet = MoneroTxWallet() - tx.hash = "a" * 64 - tx.block = block - block.txs = [tx] - - MoneroUtils.free(tx) - assert tx.block is None - - def test_free_txs_list_confirmed_and_unconfirmed(self) -> None: - block: MoneroBlock = MoneroBlock() - block.height = 100 - confirmed: MoneroTxWallet = MoneroTxWallet() - confirmed.hash = "a" * 64 - confirmed.block = block - block.txs = [confirmed] - - unconfirmed: MoneroTxWallet = MoneroTxWallet() - unconfirmed.hash = "b" * 64 - - MoneroUtils.free([confirmed, unconfirmed]) - assert confirmed.block is None - assert unconfirmed.block is None - - def test_free_transfers_list(self) -> None: - block: MoneroBlock = MoneroBlock() - block.height = 100 - tx: MoneroTxWallet = MoneroTxWallet() - tx.hash = "a" * 64 - tx.block = block - block.txs = [tx] - - transfer: MoneroIncomingTransfer = MoneroIncomingTransfer() - transfer.tx = tx - - MoneroUtils.free([transfer]) - assert transfer.tx.block is None - - def test_free_outputs_list(self) -> None: - block: MoneroBlock = MoneroBlock() - block.height = 100 - tx: MoneroTxWallet = MoneroTxWallet() - tx.hash = "a" * 64 - tx.block = block - block.txs = [tx] - - output: MoneroOutputWallet = MoneroOutputWallet() - output.tx = tx - - MoneroUtils.free([output]) - assert output.tx.block is None - - @pytest.mark.skipif(sys.platform == "win32", reason="resource module (RSS measurement) is not available on Windows") - def test_free_breaks_reference_cycle_avoids_leak(self) -> None: - # regression guard for the leak demonstrated manually: building - # block<->tx cycles and dropping every Python reference without - # calling free() leaves the C++ shared_ptr cycle permanently - # unreachable-but-alive (confirmed: 2,000,000 such tx objects grew - # RSS by ~2.4GB with gc.collect() unable to reclaim any of it). This - # test builds a much smaller-but-still-telling batch, always calling - # free() before dropping references, and asserts memory stays roughly flat. - def rss_mb() -> float: - return resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024 - - def run_batch(rounds: int) -> None: - for _ in range(rounds): - for _ in range(50): - block: MoneroBlock = MoneroBlock() - block.height = 100 - txs: list[MoneroTx] = [] - for i in range(20): - tx: MoneroTxWallet = MoneroTxWallet() - tx.hash = "a" * 63 + str(i % 10) - tx.block = block - txs.append(tx) - block.txs = txs - MoneroUtils.free(block) - - gc.disable() - try: - run_batch(20) # unmeasured warmup: absorb one-time allocator growth - baseline: float = rss_mb() - run_batch(200) # measured: 200 * 50 * 20 = 200,000 tx objects - after: float = rss_mb() - finally: - gc.enable() - - growth_mb: float = after - baseline - logger.debug(f"RSS growth after freeing 200,000 tx objects (post-warmup): {growth_mb:.1f} MB") - # generous bound: a real leak of this shape grows ~1.2KB/tx (~240MB for - # 200,000 tx); this only needs to rule out that magnitude of leak, not - # pin down normal allocator noise - assert growth_mb < 100, f"RSS grew {growth_mb:.1f} MB after freeing 200,000 tx objects -- possible leak" - - def test_free_none_does_not_crash(self) -> None: - script: str = "import monero\nmonero.MoneroUtils.free(None)\n" - result: subprocess.CompletedProcess[str] = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, timeout=30) - logger.debug(f"subprocess exit code: {result.returncode}, stderr: {result.stderr.strip()}") - assert result.returncode == 0, ( - f"free(None) crashed the interpreter (exit code {result.returncode}) " - "instead of raising a Python exception (or being a documented no-op)" - ) - - def test_free_transfers_missing_tx_raises(self) -> None: - # free([transfers]) delegates to get_blocks_from_transfers(): a transfer - # with no tx must surface a catchable exception, not segfault - transfer: MoneroIncomingTransfer = MoneroIncomingTransfer() - transfer.amount = 500000 - with pytest.raises(RuntimeError) as exc_info: - MoneroUtils.free([transfer]) - assert str(exc_info.value) == "Transfer has no tx" - - def test_free_outputs_missing_tx_raises(self) -> None: - # free([outputs]) delegates to get_blocks_from_outputs(): same guarantee - output: MoneroOutputWallet = MoneroOutputWallet() - output.amount = 1000000 - with pytest.raises(RuntimeError) as exc_info: - MoneroUtils.free([output]) - assert str(exc_info.value) == "Output has no tx" - - #endregion diff --git a/tests/test_monero_wallet_common.py b/tests/test_monero_wallet_common.py deleted file mode 100644 index e8b406f8..00000000 --- a/tests/test_monero_wallet_common.py +++ /dev/null @@ -1,3888 +0,0 @@ -from __future__ import annotations - -import pytest -import logging - -from typing import override -from time import sleep, monotonic -from random import shuffle -from configparser import ConfigParser -from abc import abstractmethod -from typing import Optional -from datetime import datetime - -from monero import ( - MoneroWallet, MoneroWalletRpc, MoneroDaemonRpc, MoneroWalletConfig, - MoneroTxConfig, MoneroDestination, MoneroRpcConnection, MoneroError, - MoneroKeyImage, MoneroTxQuery, MoneroUtils, MoneroBlock, MoneroTransferQuery, - MoneroOutputQuery, MoneroTransfer, MoneroIncomingTransfer, MoneroOutgoingTransfer, - MoneroTxWallet, MoneroOutputWallet, MoneroTx, MoneroAccount, MoneroSubaddress, - MoneroMessageSignatureType, MoneroTxPriority, MoneroFeeEstimate, - MoneroIntegratedAddress, MoneroCheckTx, MoneroCheckReserve, MoneroAddressBookEntry, - MoneroSubmitTxResult, MoneroAccountTag, MoneroKeyImageExportResult, MoneroWalletFull, - MoneroKeyImageImportResult, MoneroMessageSignatureResult, - MoneroMiningStatus, MoneroVersion, MoneroSyncResult, -) -from utils import ( - MultisigSampleCodeTester, TestUtils, WalletEqualityUtils, - StringUtils, AssertUtils, TxContext, GenUtils, WalletUtils, - WalletType, IntegrationTestUtils, ViewOnlyAndOfflineWalletTester, - WalletNotificationCollector, MiningUtils, BaseTestClass, - OutputUtils, TxWalletUtils, TransferUtils, WalletTxsUtils, - WalletTransfersUtils, WalletErrorUtils, WalletSendUtils, WalletTestUtils -) - -logger: logging.Logger = logging.getLogger("TestMoneroWalletCommon") - - -# Base class for common wallet tests -class BaseTestMoneroWallet(BaseTestClass): - """Common wallet tests that every Monero wallet implementation should support.""" - - _test_wallet: Optional[MoneroWallet] = None - """Private reference to test wallet instance.""" - - @classmethod - def get_wallet_type(cls) -> WalletType: - """Wallet type to test.""" - return WalletType.UNDEFINED - - @classmethod - def supports_save(cls) -> bool: - wallet_type: WalletType = cls.get_wallet_type() - return wallet_type == WalletType.FULL or wallet_type == WalletType.RPC - - class Config: - """Wallet test configuration.""" - - seed: str = "" - """Test wallet seed.""" - - @classmethod - def parse(cls, parser: ConfigParser) -> BaseTestMoneroWallet.Config: - """Parse wallet test configuration. - - :param ConfigParser parser: configuration parser. - :returns BaseTestMoneroWallet.Config: wallet test configuration. - """ - section: str = "test_create_wallet_from_seed" - if not parser.has_section(section): - # raise exception if section not found - raise Exception(f"Cannot find section '{section}' in test_monero_wallet_common.ini") - config: BaseTestMoneroWallet.Config = cls() - # parse configuration - config.seed = parser.get(section, "seed") - return config - - #region Private Methods - - @classmethod - def _get_test_daemon(cls) -> MoneroDaemonRpc: - """Get the daemon to test. - - :returns MoneroDaemonRpc: the daemon to test. - """ - return TestUtils.get_daemon_rpc() - - @classmethod - def get_test_wallet(cls) -> MoneroWallet: - """Get the main wallet to test. - - :returns MoneroWallet: the wallet to test. - """ - if cls._test_wallet is None: - wallet_type: WalletType = cls.get_wallet_type() - if wallet_type == WalletType.FULL: - cls._test_wallet = TestUtils.get_wallet_full() - elif wallet_type == WalletType.RPC: - cls._test_wallet = TestUtils.get_wallet_rpc() - elif wallet_type == WalletType.KEYS: - cls._test_wallet = TestUtils.get_wallet_keys() - else: - raise Exception("Cannot get test wallet: No wallet type setup for tests") - - return cls._test_wallet - - @abstractmethod - def _open_wallet(self, config: Optional[MoneroWalletConfig]) -> MoneroWallet: - """Open a test wallet with default configuration for each wallet type. - - :param MoneroWalletConfig | None config: configures the wallet to open. - :returns MoneroWallet: is the opened wallet. - """ - ... - - @abstractmethod - def _create_wallet(self, config: MoneroWalletConfig) -> MoneroWallet: - """Create a test wallet with default configuration for each wallet type. - - :param MoneroWalletConfig config: configures the wallet to create. - :returns MoneroWallet: is the created wallet. - """ - ... - - @abstractmethod - def _close_wallet(self, wallet: MoneroWallet, save: bool = False) -> None: - """Close a test wallet with customization for each wallet type. - - :param MoneroWallet wallet: the wallet to close. - :param bool save: whether or not to save the wallet. - """ - ... - - @abstractmethod - def _get_seed_languages(self) -> list[str]: - """Get the wallet's supported languages for the seed. This is an - instance method for wallet rpc and a static utility for other wallets. - - :returns list[str]: the wallet's supported languages. - """ - ... - - def _open_wallet_from_path(self, path: str, password: str | None) -> MoneroWallet: - """Open a wallet from path. - - :param str path: wallet path to open. - :param str | None password: wallet password. - :returns MoneroWallet: opened wallet. - """ - config: MoneroWalletConfig = MoneroWalletConfig() - config.path = path - config.password = password - - return self._open_wallet(config) - - def get_daemon_rpc_uri(self) -> str: - return TestUtils.DAEMON_RPC_URI - - @classmethod - def is_random_wallet_config(cls, config: Optional[MoneroWalletConfig]) -> bool: - """Check if config is valid to create a random wallet. - - :param MoneroWalletConfig | None config: config to check. - :returns bool: `True` if config is valid to create a random wallet, `False` otherwise. - """ - assert config is not None - return config.seed is None and config.primary_address is None - - #endregion - - #region Fixtures - - # Test wallet configuration - @pytest.fixture(scope="class") - @classmethod - def test_config(cls) -> BaseTestMoneroWallet.Config: - """Test configuration.""" - parser: ConfigParser = ConfigParser() - parser.read('tests/config/test_monero_wallet_common.ini') - return BaseTestMoneroWallet.Config.parse(parser) - - # Test daemon fixture - @pytest.fixture(scope="class") - @classmethod - def daemon(cls) -> MoneroDaemonRpc: - """Test rpc daemon instance.""" - return TestUtils.get_daemon_rpc() - - # Test wallet fixture - @pytest.fixture(scope="class") - @classmethod - def wallet(cls) -> MoneroWallet: - """Test wallet instance.""" - pytest.skip("No wallet test instance setup") - - # Before all tests - @override - def before_all(self) -> None: - super().before_all() - IntegrationTestUtils.setup(self.get_wallet_type()) - - # After all tests - @override - def after_all(self) -> None: - super().after_all() - daemon: MoneroDaemonRpc = self._get_test_daemon() - MiningUtils.try_stop_mining(daemon) - - # close wallet - wallet: MoneroWallet = self.get_test_wallet() - wallet.close(self.supports_save()) - - # Before each test - @override - def before_each(self, request: pytest.FixtureRequest) -> None: - super().before_each(request) - daemon: MoneroDaemonRpc = self._get_test_daemon() - wallet: MoneroWallet = self.get_test_wallet() - status: MoneroMiningStatus = daemon.get_mining_status() - - if status.is_active is True: - wallet.stop_mining() - - # After each test - @override - def after_each(self, request: pytest.FixtureRequest) -> None: - super().after_each(request) - daemon: MoneroDaemonRpc = self._get_test_daemon() - status: MoneroMiningStatus = daemon.get_mining_status() - - if status.is_active is True: - logger.warning(f"Mining is active after test {request.node.name}") # type: ignore - - #endregion - - #region Tests - - #region Relays Tests - - # Validates inputs when sending funds - @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") - @pytest.mark.flaky(reruns=5, reruns_delay=5, only_rerun=[]) - def test_validate_inputs_sending_funds(self, wallet: MoneroWallet) -> None: - # try sending with invalid address - tx_config: MoneroTxConfig = MoneroTxConfig() - tx_config.address = "my invalid address" - tx_config.account_index = 0 - tx_config.amount = TxWalletUtils.MAX_FEE - with pytest.raises(Exception) as exc_info: - wallet.create_tx(tx_config) - assert str(exc_info.value) == "Invalid destination address" - - # Can sync with txs in the pool sent from/to the same account - # TODO this test fails because wallet does not recognize pool tx sent from/to same account - @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") - def test_sync_with_pool_same_accounts(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: - config: MoneroTxConfig = MoneroTxConfig() - config.account_index = 0 - config.address = wallet.get_primary_address() - config.amount = TxWalletUtils.MAX_FEE * 5 - config.relay = True - WalletSendUtils.test_sync_with_pool_submit(daemon, wallet, config) - - # Can sync with txs submitted and flushed from the pool - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_RELAYS disabled") - @pytest.mark.skipif(TestUtils.LITE_MODE, reason="LITE_MODE enabled") - @pytest.mark.skipif(TestUtils.CI, reason="CI is too slow to catchup failed txs (see wallet2::process_unconfirmed_transfer)") - def test_sync_with_pool_submit_and_flush(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: - logger.warning("This test takes at least 500 seconds (~8 minutes) to catchup failed txs (see wallet2::process_unconfirmed_transfer).") - config: MoneroTxConfig = MoneroTxConfig() - config.account_index = 2 - config.address = wallet.get_primary_address() - config.amount = TxWalletUtils.MAX_FEE * 5 - config.relay = False - WalletSendUtils.test_sync_with_pool_submit(daemon, wallet, config) - - # Can sync with txs submitted and relayed from the pool - @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") - @pytest.mark.skipif(TestUtils.LITE_MODE, reason="LITE_MODE enabled") - def test_sync_with_pool_submit_and_relay(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: - config: MoneroTxConfig = MoneroTxConfig() - config.account_index = 2 - config.address = wallet.get_primary_address() - config.amount = TxWalletUtils.MAX_FEE * 5 - config.relay = True - WalletSendUtils.test_sync_with_pool_submit(daemon, wallet, config) - - # can sync with txs relayed to the pool - @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") - @pytest.mark.skipif(TestUtils.LITE_MODE, reason="LITE_MODE enabled") - def test_sync_with_pool_relay(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: - # wait one time for wallet txs in the pool to clear - TestUtils.WALLET_TX_TRACKER.wait_for_txs_to_clear_pool(wallet) - - # record wallet balances before submitting tx to pool - balance_before: int = wallet.get_balance() - unlocked_balance_before: int = wallet.get_unlocked_balance() - - # create config - config: MoneroTxConfig = MoneroTxConfig() - config.account_index = 2 - config.address = wallet.get_primary_address() - config.amount = TxWalletUtils.MAX_FEE * 5 - - # create tx to relay - tx: MoneroTxWallet = wallet.create_tx(config) - assert tx.hash is not None - assert tx.full_hex is not None - assert tx.fee is not None - - # create another tx using same config which would be double spend - tx_double_spend: MoneroTxWallet = wallet.create_tx(config) - assert tx_double_spend.hash is not None - assert tx_double_spend.full_hex is not None - - # relay first tx directly to daemon - result: MoneroSubmitTxResult = daemon.submit_tx_hex(tx.full_hex) - assert result.is_good, "Transaction could not be submitted to the pool" - - # sync wallet which updates from pool - wallet.sync() - - # collect issues to report at end of test - issues: list[str] = [] - - # wallet should be aware of tx - fetched: MoneroTxWallet | None = wallet.get_tx(tx.hash) - assert fetched is not None, "Wallet should be aware of its tx in pool after syncing" - - # test wallet balances - if unlocked_balance_before == wallet.get_unlocked_balance(): - issues.append("unlocked balance should have decreased after relaying tx directly to the daemon") - - if balance_before == wallet.get_balance(): - issues.append("balance should have decreased after relaying tx directly to the daemon") - - expected_balance: int = balance_before - tx.fee - if expected_balance != wallet.get_balance(): - issues.append(f"expected balance after relaying tx directly to the daemon to be {expected_balance} but was {wallet.get_balance()}") - - # submit double spend tx - result_double_spend: MoneroSubmitTxResult = daemon.submit_tx_hex(tx_double_spend.full_hex) - if result_double_spend.is_good: - daemon.flush_tx_pool(tx_double_spend.hash) - issues.append("Tx submit result should have been double spend") - - # sync wallet which updates from pool - wallet.sync() - - # create tx using same config which is no longer double spend - tx2: MoneroTxWallet | None = None - try: - config_copy: MoneroTxConfig = config.copy() - config_copy.relay = True - tx2 = wallet.create_tx(config_copy) - except Exception as e: - logger.warning(e) - # TODO monero-project: this fails meaning wallet did not recognize tx relayed directly to pool - issues.append("creating and sending tx through wallet should succeed after syncing wallet with pool but creates a double spend") - - # submit the transaction to the pool and test - if tx2 is not None: - assert tx2.hash is not None - assert tx2.full_hex is not None - result2: MoneroSubmitTxResult = daemon.submit_tx_hex(tx2.full_hex, True) - if result2.is_double_spend: - issues.append("creating and submitting tx to daemon should succeed after syncing wallet with pool but was a double spend") - else: - assert result2.is_good - - wallet.sync() - if wallet.get_tx(tx2.hash) is None: - issues.append("wallet should be aware of tx created and relayed through it after syncing with pool") - - daemon.flush_tx_pool(tx2.hash) - - # should be no issues - for issue in issues: - logger.warning(issue) - - assert len(issues) == 0, f"test_sync_with_pool_relay has {len(issues)} issues" - - # Can send to self - @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") - def test_send_to_self(self, wallet: MoneroWallet) -> None: - # wait for txs to confirm and for sufficient unlocked balance - TestUtils.WALLET_TX_TRACKER.wait_for_txs_to_clear_pool(wallet) - amount: int = TxWalletUtils.MAX_FEE * 3 - TestUtils.WALLET_TX_TRACKER.wait_for_unlocked_balance(wallet, 0, None, amount) - - # collect sender balances before - balance1: int = wallet.get_balance() - unlocked_balance1: int = wallet.get_unlocked_balance() - - # test error sending funds to self with integrated subaddress - # TODO (monero-project): sending funds to self - # with integrated subaddress throws error: https://github.com/monero-project/monero/issues/8380 - - tx_config: MoneroTxConfig = MoneroTxConfig() - tx_config.account_index = 0 - subaddress: MoneroSubaddress = wallet.get_subaddress(0, 1) - assert subaddress.address is not None - address: str = subaddress.address - tx_config.address = MoneroUtils.get_integrated_address(TestUtils.NETWORK_TYPE, address, '').integrated_address - tx_config.amount = amount - tx_config.relay = True - with pytest.raises(Exception, match="Total received by"): - wallet.create_tx(tx_config) - - # send funds to self - tx_config = MoneroTxConfig() - tx_config.account_index = 0 - tx_config.address = wallet.get_integrated_address().integrated_address - tx_config.amount = amount - tx_config.relay = True - - tx: MoneroTxWallet = wallet.create_tx(tx_config) - - # test balances after - balance2: int = wallet.get_balance() - unlocked_balance2: int = wallet.get_unlocked_balance() - - # unlocked balance should decrease - assert unlocked_balance2 < unlocked_balance1 - assert tx.fee is not None - expected_balance: int = balance1 - tx.fee - assert expected_balance == balance2, "Balance after send was not balance before - fee" - - # Can send to external address - @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") - def test_send_to_external(self, wallet: MoneroWallet) -> None: - recipient: Optional[MoneroWallet] = None - try: - # wait for txs to confirm and for sufficient unlocked balance - TestUtils.WALLET_TX_TRACKER.wait_for_txs_to_clear_pool(wallet) - amount: int = TxWalletUtils.MAX_FEE * 3 - TestUtils.WALLET_TX_TRACKER.wait_for_unlocked_balance(wallet, 0, None, amount) - - # create recipient wallet - recipient = self._create_wallet(MoneroWalletConfig()) - - balance1: int = wallet.get_balance() - unlocked_balance1: int = wallet.get_unlocked_balance() - - # send funds to recipient - tx_config: MoneroTxConfig = MoneroTxConfig() - tx_config.account_index = 0 - tx_config.address = wallet.get_integrated_address(recipient.get_primary_address(), "54491f3bb3572a37").integrated_address - tx_config.amount = amount - tx_config.relay = True - tx: MoneroTxWallet = wallet.create_tx(tx_config) - - # test sender balances after - balance2: int = wallet.get_balance() - unlocked_balance2: int = wallet.get_unlocked_balance() - - # unlocked balance should decrease - assert unlocked_balance2 < unlocked_balance1 - assert tx.fee is not None - expected_balance: int = balance1 - tx.get_outgoing_amount() - tx.fee - assert expected_balance == balance2, "Balance after send was not balance before - net tx amount - fee (5 - 1 != 4 test)" - - tx_query: MoneroTxQuery = MoneroTxQuery() - tx_query.is_confirmed = False - txs: list[MoneroTxWallet] = wallet.get_txs(tx_query) - assert len(txs) > 0 - - # test recipient balance after - recipient.sync() - assert amount == recipient.get_balance() - - finally: - if recipient is not None: - self._close_wallet(recipient) - - # Can send to multiple subaddresses in a single transaction - @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") - def test_send_to_multiple(self, wallet: MoneroWallet) -> None: - WalletSendUtils.test_send_to_multiple(wallet, 5, 3, False) - - # Can send to multiple addresses in split transactions - @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") - def test_send_to_multiple_split(self, wallet: MoneroWallet) -> None: - WalletSendUtils.test_send_to_multiple(wallet, 3, 15, True) - - # Can send dust to multiple addresses in split transactions - @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") - def test_send_dust_to_multiple_split(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: - estimate: MoneroFeeEstimate = daemon.get_fee_estimate() - assert estimate.fee is not None - dust_amount: int = int(estimate.fee / 2) - WalletSendUtils.test_send_to_multiple(wallet, 5, 3, True, dust_amount) - - # Can subtract fees from destinations - @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") - def test_subtract_fee_from(self, wallet: MoneroWallet) -> None: - WalletSendUtils.test_send_to_multiple(wallet, 5, 3, False, None, True) - - # Cannot subtract fees from destinations in split transactions - @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") - def test_subtract_fee_from_split(self, wallet: MoneroWallet) -> None: - WalletSendUtils.test_send_to_multiple(wallet, 3, 15, True, None, True) - - # Can send from multiple subaddresses in a single transaction - @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") - def test_send_from_subaddresses(self, wallet: MoneroWallet) -> None: - WalletSendUtils.test_send_from_multiple(wallet, None) - - # Can send from multiple subaddresses in split transactions - @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") - def test_send_from_subaddresses_split(self, wallet: MoneroWallet) -> None: - WalletSendUtils.test_send_from_multiple(wallet, True) - - # Can send to an address in a single transaction - @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") - def test_send(self, wallet: MoneroWallet) -> None: - WalletSendUtils.test_send_to_single(wallet, False) - - # Can send to an address in a single transaction with a payment id - # NOTE this test will be invalid when payment hashes are fully removed - @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") - def test_send_with_payment_id(self, wallet: MoneroWallet) -> None: - integrated_address: MoneroIntegratedAddress = wallet.get_integrated_address() - assert integrated_address.payment_id is not None - payment_id: str = integrated_address.payment_id - msg = "Standalone payment IDs are obsolete. Use subaddresses or integrated addresses instead" - with pytest.raises(Exception) as exc_info: - WalletSendUtils.test_send_to_single(wallet, False, None, f"{payment_id}{payment_id}{payment_id}") - assert str(exc_info.value) == msg - - # Can send to an address with split transactions - @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") - def test_send_split(self, wallet: MoneroWallet) -> None: - WalletSendUtils.test_send_to_single(wallet, True) - - # Can create then relay a transaction to send to a single address - @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") - def test_create_then_relay(self, wallet: MoneroWallet) -> None: - WalletSendUtils.test_send_to_single(wallet, False, False) - - # Can create then relay split transactions to send to a single address - @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") - def test_create_then_relay_split(self, wallet: MoneroWallet) -> None: - WalletSendUtils.test_send_to_single(wallet, True, False) - - # Can sweep individual outputs identified by their key images - @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") - def test_sweep_outputs(self, wallet: MoneroWallet) -> None: - TestUtils.WALLET_TX_TRACKER.wait_for_txs_to_clear_pool(wallet) - - # test config - num_outputs: int = 3 - - # get outputs to sweep (not spent, unlocked, and amount >= fee) - query: MoneroOutputQuery = MoneroOutputQuery() - query.is_spent = False - tx_query: MoneroTxQuery = MoneroTxQuery() - tx_query.is_locked = False - query.set_tx_query(tx_query, True) - spendable_unlocked_outputs: list[MoneroOutputWallet] = wallet.get_outputs(query) - outputs_to_sweep: list[MoneroOutputWallet] = [] - for spendable_output in spendable_unlocked_outputs: - if len(outputs_to_sweep) >= num_outputs: - break - assert spendable_output.amount is not None - if spendable_output.amount > TxWalletUtils.MAX_FEE: - outputs_to_sweep.append(spendable_output) - - assert len(outputs_to_sweep) >= num_outputs, "Wallet does not have enough sweepable outputs; run send tests" - - # sweep each output by key image - for output in outputs_to_sweep: - OutputUtils.test_output_wallet(output) - assert output.is_spent is False - assert output.tx is not None - assert isinstance(output.tx, MoneroTxWallet) - assert output.tx.is_locked is False - assert output.amount is not None - - if output.amount <= TxWalletUtils.MAX_FEE: - continue - - # sweep output to address - assert output.account_index is not None - assert output.subaddress_index is not None - assert output.key_image is not None - assert output.key_image.hex is not None - address: str = wallet.get_address(output.account_index, output.subaddress_index) - config: MoneroTxConfig = MoneroTxConfig() - config.address = address - config.key_image = output.key_image.hex - config.relay = True - tx: MoneroTxWallet = wallet.sweep_output(config) - - # test result tx - ctx: TxContext = TxContext() - ctx.wallet = wallet - ctx.config = config - ctx.config.can_split = False - ctx.is_send_response = True - ctx.is_sweep_response = True - ctx.is_sweep_output_response = True - TxWalletUtils.test_tx_wallet(tx, ctx) - - # get outputs after sweeping - after_outputs: list[MoneroOutputWallet] = wallet.get_outputs() - - # swept outputs are now spent - for after_output in after_outputs: - assert after_output.key_image is not None - - for output in outputs_to_sweep: - assert output.key_image is not None - if output.key_image.hex == after_output.key_image.hex: - assert after_output.is_spent is True, "Output should be spent" - - # Can sweep individual outputs identified by their key images - @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") - def test_sweep_dust_no_relay(self, wallet: MoneroWallet) -> None: - TestUtils.WALLET_TX_TRACKER.wait_for_txs_to_clear_pool(wallet) - - # sweep dust which returns empty list if no dust to sweep (dust does not exist after rct) - txs: list[MoneroTxWallet] = wallet.sweep_dust(False) - if len(txs) == 0: - return - - # test txs - ctx: TxContext = TxContext() - ctx.is_send_response = True - ctx.config = MoneroTxConfig() - ctx.config.relay = False - ctx.is_sweep_response = True - for tx in txs: - TxWalletUtils.test_tx_wallet(tx, ctx) - - # relay txs - metadatas: list[str] = [] - for tx in txs: - assert tx.metadata is not None - metadatas.append(tx.metadata) - - tx_hashes: list[str] = wallet.relay_txs(metadatas) - assert len(tx_hashes) == len(txs) - for tx_hash in tx_hashes: - assert len(tx_hash) == 64 - - # fetch and test txs - tx_query: MoneroTxQuery = MoneroTxQuery() - tx_query.hashes = tx_hashes - txs = wallet.get_txs(tx_query) - ctx.config.relay = True - for tx in txs: - TxWalletUtils.test_tx_wallet(tx, ctx) - - # Can sweep dust - @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") - def test_sweep_dust(self, wallet: MoneroWallet) -> None: - TestUtils.WALLET_TX_TRACKER.wait_for_txs_to_clear_pool(wallet) - - # sweep dust which returns empty list if no dust to sweep (dust does not exist after rct) - txs: list[MoneroTxWallet] = wallet.sweep_dust(True) - - # test any txs - ctx: TxContext = TxContext() - ctx.wallet = wallet - ctx.config = None - ctx.is_send_response = True - ctx.is_sweep_response = True - for tx in txs: - TxWalletUtils.test_tx_wallet(tx, ctx) - - # TODO: test sending to multiple accounts - # Can update a locked tx sent from/to the same account as blocks are added to the chain - @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") - @pytest.mark.skipif(TestUtils.TEST_NOTIFICATIONS is False, reason="TEST_NOTIFICATIONS disabled") - @pytest.mark.flaky(reruns=5, reruns_delay=10, only_rerun=["Daemon is busy", r"Cannot reconcile integrals:.*m_is_incoming"]) - def test_update_locked_same_account(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: - config: MoneroTxConfig = MoneroTxConfig() - config.address = wallet.get_primary_address() - config.amount = TxWalletUtils.MAX_FEE - config.account_index = 0 - config.can_split = False - config.relay = True - WalletSendUtils.test_send_and_update_txs(daemon, wallet, config) - - # Can update split locked txs sent from/to the same account as blocks are added to the chain - @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") - @pytest.mark.skipif(TestUtils.TEST_NOTIFICATIONS is False, reason="TEST_NOTIFICATIONS disabled") - @pytest.mark.skipif(TestUtils.LITE_MODE, reason="LITE_MODE enabled") - @pytest.mark.flaky(reruns=5, reruns_delay=10, only_rerun=["Daemon is busy", r"Cannot reconcile integrals:.*m_is_incoming"]) - def test_update_locked_same_account_split(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: - config: MoneroTxConfig = MoneroTxConfig() - config.address = wallet.get_primary_address() - config.amount = TxWalletUtils.MAX_FEE - config.account_index = 0 - config.can_split = True - config.relay = True - WalletSendUtils.test_send_and_update_txs(daemon, wallet, config) - - # TODO on wallet full is flaky due to `Cannot reconcile integrals: 0 vs 1. tx wallet m_is_incoming` error - # Can update a locked tx sent from/to different accounts as blocks are added to the chain - @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") - @pytest.mark.skipif(TestUtils.TEST_NOTIFICATIONS is False, reason="TEST_NOTIFICATIONS disabled") - @pytest.mark.skipif(TestUtils.LITE_MODE, reason="LITE_MODE enabled") - @pytest.mark.flaky(reruns=5, reruns_delay=10, only_rerun=["Daemon is busy", r"Cannot reconcile integrals:.*m_is_incoming"]) - def test_update_locked_different_accounts(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: - config: MoneroTxConfig = MoneroTxConfig() - config.address = wallet.get_subaddress(1, 0).address - config.amount = TxWalletUtils.MAX_FEE - config.account_index = 0 - config.can_split = False - config.relay = True - WalletSendUtils.test_send_and_update_txs(daemon, wallet, config) - - # Can update locked, split txs sent from/to different accounts as blocks are added to the chain - @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") - @pytest.mark.skipif(TestUtils.TEST_NOTIFICATIONS is False, reason="TEST_NOTIFICATIONS disabled") - @pytest.mark.skipif(TestUtils.LITE_MODE, reason="LITE_MODE enabled") - @pytest.mark.flaky(reruns=5, reruns_delay=10, only_rerun=["Daemon is busy", r"Cannot reconcile integrals:.*m_is_incoming"]) - def test_update_locked_different_accounts_split(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: - config: MoneroTxConfig = MoneroTxConfig() - config.address = wallet.get_subaddress(1, 0).address - config.amount = TxWalletUtils.MAX_FEE - config.account_index = 0 - config.can_split = True - config.relay = True - WalletSendUtils.test_send_and_update_txs(daemon, wallet, config) - - #endregion - - #region Non Relays Tests - - # Can get the daemon's max peer height - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_daemon_max_peer_height(self, wallet: MoneroWallet) -> None: - height: int = wallet.get_daemon_max_peer_height() - assert height > 0 - - # Can get the daemon's height - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_daemon_height(self, wallet: MoneroWallet) -> None: - assert wallet.is_connected_to_daemon(), "Wallet is not connected to daemon" - daemon_height: int = wallet.get_daemon_height() - assert daemon_height > 0 - - # Can create a random wallet - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_create_wallet_random(self) -> None: - """ - Can create a random wallet. - """ - config: MoneroWalletConfig = MoneroWalletConfig() - wallet: MoneroWallet = self._create_wallet(config) - path: str = wallet.get_path() - - try: - MoneroUtils.validate_address(wallet.get_primary_address(), TestUtils.NETWORK_TYPE) - MoneroUtils.validate_private_view_key(wallet.get_private_view_key()) - MoneroUtils.validate_private_spend_key(wallet.get_private_spend_key()) - MoneroUtils.validate_mnemonic(wallet.get_seed()) - if not isinstance(wallet, MoneroWalletRpc): - # TODO monero-wallet-rpc: get seed language - assert MoneroWallet.DEFAULT_LANGUAGE == wallet.get_seed_language() - finally: - self._close_wallet(wallet) - - # attempt to create wallet at same path - config = MoneroWalletConfig() - config.path = path - with pytest.raises(Exception) as exc_info: - self._create_wallet(config) - assert str(exc_info.value) == "Wallet already exists: " + path - - # attempt to create wallet with unknown language - config = MoneroWalletConfig() - config.language = "english" - with pytest.raises(Exception) as exc_info: - self._create_wallet(config) - assert str(exc_info.value) == "Unknown language: english" - - # Can create a wallet from a seed - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_create_wallet_from_seed(self, wallet: MoneroWallet, test_config: BaseTestMoneroWallet.Config) -> None: - # save for comparison - primary_address: str = wallet.get_primary_address() - private_view_key: str = wallet.get_private_view_key() - private_spend_key: str = wallet.get_private_spend_key() - - # recreate test wallet from seed - config: MoneroWalletConfig = MoneroWalletConfig() - config.seed = TestUtils.SEED - config.restore_height = TestUtils.FIRST_RECEIVE_HEIGHT - - w: MoneroWallet = self._create_wallet(config) - path: str = w.get_path() - try: - assert primary_address == w.get_primary_address() - assert private_view_key == w.get_private_view_key() - assert private_spend_key == w.get_private_spend_key() - assert TestUtils.SEED, w.get_seed() - if not isinstance(w, MoneroWalletRpc): - assert MoneroWallet.DEFAULT_LANGUAGE == w.get_seed_language() - finally: - self._close_wallet(w) - - # attempt to create wallet with two missing words - config = MoneroWalletConfig() - config.seed = test_config.seed - config.restore_height = TestUtils.FIRST_RECEIVE_HEIGHT - with pytest.raises(Exception) as exc_info: - self._create_wallet(config) - assert str(exc_info.value) == "Invalid mnemonic" - - # attempt to create wallet at same path - config = MoneroWalletConfig() - config.path = path - with pytest.raises(Exception) as exc_info: - self._create_wallet(config) - assert str(exc_info.value) == "Wallet already exists: " + path - - # Can create a wallet from a seed with offset - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_create_wallet_from_seed_with_offset(self) -> None: - # create test wallet with offset - config: MoneroWalletConfig = MoneroWalletConfig() - config.seed = TestUtils.SEED - config.restore_height = TestUtils.FIRST_RECEIVE_HEIGHT - config.seed_offset = "my secret offset!" - wallet: MoneroWallet = self._create_wallet(config) - try: - MoneroUtils.validate_mnemonic(wallet.get_seed()) - assert TestUtils.SEED != wallet.get_seed() - MoneroUtils.validate_address(wallet.get_primary_address(), TestUtils.NETWORK_TYPE) - assert TestUtils.ADDRESS != wallet.get_primary_address() - if not isinstance(wallet, MoneroWalletRpc): - # TODO monero-wallet-rpc: support - assert MoneroWallet.DEFAULT_LANGUAGE == wallet.get_seed_language() - finally: - self._close_wallet(wallet) - - # Can create a wallet from keys - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_create_wallet_from_keys(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: - # save for comparison - primary_address: str = wallet.get_primary_address() - private_view_key: str = wallet.get_private_view_key() - private_spend_key: str = wallet.get_private_spend_key() - - # recreate test wallet from keys - config: MoneroWalletConfig = MoneroWalletConfig() - config.primary_address = primary_address - config.private_view_key = private_view_key - config.private_spend_key = private_spend_key - config.restore_height = daemon.get_height() - w: MoneroWallet = self._create_wallet(config) - path: str = w.get_path() - - try: - assert primary_address == w.get_primary_address() - assert private_view_key == w.get_private_view_key() - assert private_spend_key == w.get_private_spend_key() - if not w.is_connected_to_daemon(): - # TODO monero-project: keys wallets not connected - logger.warning(f"WARNING: {WalletErrorUtils.CREATED_WALLET_KEYS_ERROR}") - assert w.is_connected_to_daemon(), WalletErrorUtils.CREATED_WALLET_KEYS_ERROR - if not isinstance(w, MoneroWalletRpc): - # TODO monero-wallet-rpc: cannot get seed from wallet created from keys? - MoneroUtils.validate_mnemonic(w.get_seed()) - assert MoneroWallet.DEFAULT_LANGUAGE == w.get_seed_language() - finally: - self._close_wallet(w) - - # recreate test wallet from spend key - if not isinstance(w, MoneroWalletRpc): # TODO monero-wallet-rpc: cannot create wallet from spend key? - config = MoneroWalletConfig() - config.private_spend_key = private_spend_key - config.restore_height = daemon.get_height() - w = self._create_wallet(config) - - try: - assert primary_address == w.get_primary_address() - assert private_view_key == w.get_private_view_key() - assert private_spend_key == w.get_private_spend_key() - if not w.is_connected_to_daemon(): - # TODO monero-project: keys wallets not connected - logger.warning(f"{WalletErrorUtils.CREATED_WALLET_KEYS_ERROR}") - assert w.is_connected_to_daemon(), WalletErrorUtils.CREATED_WALLET_KEYS_ERROR - if not isinstance(w, MoneroWalletRpc): - # TODO monero-wallet-rpc: cannot get seed from wallet created from keys? - MoneroUtils.validate_mnemonic(w.get_seed()) - assert MoneroWallet.DEFAULT_LANGUAGE == w.get_seed_language() - finally: - self._close_wallet(w) - - # attempt to create wallet at same path - config = MoneroWalletConfig() - config.path = path - with pytest.raises(Exception) as exc_info: - self._create_wallet(config) - assert str(exc_info.value) == "Wallet already exists: " + path - - # Can create wallets with subaddress lookahead - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_subaddress_lookahead(self, wallet: MoneroWallet) -> None: - receiver: MoneroWallet | None = None - try: - # create wallet with high subaddress lookahead - config: MoneroWalletConfig = MoneroWalletConfig() - config.account_lookahead = 1 - config.subaddress_lookahead = 100000 - receiver = self._create_wallet(config) - - # transfer funds to subaddress with high index - tx_config: MoneroTxConfig = MoneroTxConfig() - tx_config.account_index = 0 - dest: MoneroDestination = MoneroDestination() - dest.address = receiver.get_subaddress(0, 85000).address - dest.amount = TxWalletUtils.MAX_FEE - tx_config.destinations.append(dest) - tx_config.relay = True - - wallet.create_tx(tx_config) - - # observe unconfirmed funds - GenUtils.wait_for(1000) - receiver.sync() - assert receiver.get_balance() > 0 - finally: - if receiver is not None: - self._close_wallet(receiver) - - # Can get the wallet's version - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_version(self, wallet: MoneroWallet) -> None: - version: MoneroVersion = wallet.get_version() - assert version.number is not None - assert version.number > 0 - assert version.is_release is not None - - # Can get the wallet's path - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_path(self) -> None: - # create random wallet - config: MoneroWalletConfig = MoneroWalletConfig() - wallet: MoneroWallet = self._create_wallet(config) - - # set a random attribute - #String uuid = UUID.randomUUID().toString() - uuid: str = StringUtils.get_random_string() - wallet.set_attribute("uuid", uuid) - - # record the wallet's path then save and close - path: str = wallet.get_path() - self._close_wallet(wallet, True) - - # re-open the wallet using its path - wallet = self._open_wallet_from_path(path, None) - - # test the attribute - assert uuid == wallet.get_attribute("uuid") - self._close_wallet(wallet) - - # Can set the daemon connection - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_set_daemon_connection(self) -> None: - # create random wallet with default daemon connection - config: MoneroWalletConfig = MoneroWalletConfig() - wallet: MoneroWallet = self._create_wallet(config) - daemon_rpc_uri: str = self.get_daemon_rpc_uri() - connection: MoneroRpcConnection = MoneroRpcConnection( - daemon_rpc_uri, TestUtils.DAEMON_RPC_USERNAME, TestUtils.DAEMON_RPC_PASSWORD - ) - AssertUtils.assert_equals(connection, wallet.get_daemon_connection()) - assert wallet.is_connected_to_daemon() # uses default localhost connection - - # set empty server uri - wallet.set_daemon_connection("") - assert wallet.get_daemon_connection() is None - assert wallet.is_connected_to_daemon() is False - - # set offline server uri - wallet.set_daemon_connection(TestUtils.OFFLINE_SERVER_URI) - connection = MoneroRpcConnection(TestUtils.OFFLINE_SERVER_URI, "", "") - AssertUtils.assert_equals(connection, wallet.get_daemon_connection()) - assert wallet.is_connected_to_daemon() is False - - # set daemon with wrong credentials - wallet.set_daemon_connection(daemon_rpc_uri, "wronguser", "wrongpass") - connection = MoneroRpcConnection(daemon_rpc_uri, "wronguser", "wrongpass") - AssertUtils.assert_equals(connection, wallet.get_daemon_connection()) - if "" == TestUtils.DAEMON_RPC_USERNAME: - # TODO: monerod without authentication works with bad credentials? - assert wallet.is_connected_to_daemon() - else: - assert wallet.is_connected_to_daemon() is False - - # set daemon with authentication - wallet.set_daemon_connection( - daemon_rpc_uri, TestUtils.DAEMON_RPC_USERNAME, TestUtils.DAEMON_RPC_PASSWORD - ) - connection = MoneroRpcConnection( - daemon_rpc_uri, TestUtils.DAEMON_RPC_USERNAME, TestUtils.DAEMON_RPC_PASSWORD - ) - AssertUtils.assert_equals(connection, wallet.get_daemon_connection()) - assert wallet.is_connected_to_daemon() - - # nullify daemon connection - wallet.set_daemon_connection(None) - assert wallet.get_daemon_connection() is None - wallet.set_daemon_connection(daemon_rpc_uri) - connection = MoneroRpcConnection(daemon_rpc_uri) - AssertUtils.assert_equals(connection, wallet.get_daemon_connection()) - wallet.set_daemon_connection(None) - assert wallet.get_daemon_connection() is None - - # set daemon uri to non-daemon - if not TestUtils.IN_CONTAINER: # TODO sometimes this fails in container... - wallet.set_daemon_connection("www.getmonero.org") - connection = MoneroRpcConnection("www.getmonero.org") - AssertUtils.assert_equals(connection, wallet.get_daemon_connection()) - assert wallet.is_connected_to_daemon() is False - - # set daemon to invalid uri - wallet.set_daemon_connection("abc123") - assert wallet.is_connected_to_daemon() is False - - # attempt to sync - try: - with pytest.raises(Exception, match="Wallet is not connected to daemon"): - wallet.sync() - finally: - self._close_wallet(wallet) - - # Can get the seed - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_seed(self, wallet: MoneroWallet) -> None: - seed: str = wallet.get_seed() - MoneroUtils.validate_mnemonic(seed) - assert TestUtils.SEED == seed - - # Can get the language of the seed - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_seed_language(self, wallet: MoneroWallet) -> None: - language: str = wallet.get_seed_language() - assert MoneroWallet.DEFAULT_LANGUAGE == language - - # Can get a list of supported languages for the seed - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_seed_languages(self) -> None: - languages: list[str] = self._get_seed_languages() - assert len(languages) > 0 - for language in languages: - assert len(language) > 0 - - # Can get the private view key - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_private_view_key(self, wallet: MoneroWallet) -> None: - private_view_key: str = wallet.get_private_view_key() - MoneroUtils.validate_private_view_key(private_view_key) - - # Can get the private spend key - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_private_spend_key(self, wallet: MoneroWallet) -> None: - private_spend_key: str = wallet.get_private_spend_key() - MoneroUtils.validate_private_spend_key(private_spend_key) - - # Can get the public view key - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_public_view_key(self, wallet: MoneroWallet) -> None: - public_view_key: str = wallet.get_public_view_key() - MoneroUtils.validate_private_spend_key(public_view_key) - - # Can get the public spend key - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_public_spend_key(self, wallet: MoneroWallet) -> None: - public_spend_key: str = wallet.get_public_spend_key() - MoneroUtils.validate_private_spend_key(public_spend_key) - - # Can get the primary address - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_primary_address(self, wallet: MoneroWallet) -> None: - primary_address: str = wallet.get_primary_address() - MoneroUtils.validate_address(primary_address, TestUtils.NETWORK_TYPE) - assert wallet.get_address(0, 0) == primary_address - - # Can get the address of a subaddress at a specified account and subaddress index - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_subaddress_address(self, wallet: MoneroWallet) -> None: - assert wallet.get_primary_address() == wallet.get_address(0, 0) - for account in wallet.get_accounts(True): - for subaddress in account.subaddresses: - assert account.index is not None - assert subaddress.index is not None - assert subaddress.address == wallet.get_address(account.index, subaddress.index) - - # Can get addresses out of range of used accounts and subaddresses - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_subaddress_address_out_of_range(self, wallet: MoneroWallet) -> None: - accounts: list[MoneroAccount] = wallet.get_accounts(True) - account_idx: int = len(accounts) - 1 - subaddress_idx: int = len(accounts[account_idx].subaddresses) - address: str = wallet.get_address(account_idx, subaddress_idx) - assert address is not None - assert len(address) > 0 - - # Can get the account and subaddress indices of an address - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_address_indices(self, wallet: MoneroWallet) -> None: - # get last subaddress to test - accounts: list[MoneroAccount] = wallet.get_accounts(True) - account_idx: int = len(accounts) - 1 - subaddress_idx: int = len(accounts[account_idx].subaddresses) - 1 - address: str = wallet.get_address(account_idx, subaddress_idx) - assert address is not None - assert len(address) > 0 - - # get address index - subaddress: MoneroSubaddress = wallet.get_address_index(address) - assert account_idx == subaddress.account_index - assert subaddress_idx == subaddress.index - - # test valid but unfound address - non_wallet_address: str = WalletTestUtils.get_external_wallet_address() - with pytest.raises(Exception) as exc_info: - wallet.get_address_index(non_wallet_address) - assert str(exc_info.value) == "Address doesn't belong to the wallet" - - # test invalid address - with pytest.raises(Exception) as exc_info: - wallet.get_address_index("this is definitely not an address") - WalletErrorUtils.test_invalid_address_error(exc_info.value) - - # Can decode an integrated address - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_decode_integrated_address(self, wallet: MoneroWallet) -> None: - integrated_address: MoneroIntegratedAddress = wallet.get_integrated_address('', "03284e41c342f036") - decoded_address: MoneroIntegratedAddress = wallet.decode_integrated_address(integrated_address.integrated_address) - AssertUtils.assert_equals(integrated_address, decoded_address) - - # decode invalid address - with pytest.raises(Exception) as exc_info: - wallet.decode_integrated_address("bad address") - WalletErrorUtils.test_invalid_address_error(exc_info.value) - - # decode invalid payment id - with pytest.raises(Exception) as exc_info: - wallet.get_integrated_address(wallet.get_primary_address(), "invalid payment id") - assert str(exc_info.value) == "Invalid payment ID: invalid payment id" - - # Can sync (without progress) - # TODO test syncing from start height - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_sync_without_progress(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: - num_blocks: int = 100 - chain_height: int = daemon.get_height() - assert chain_height >= num_blocks - result: MoneroSyncResult = wallet.sync(chain_height - num_blocks) # sync end of chain - assert result.num_blocks_fetched >= 0 - assert result.received_money is not None - - # Is equal to a ground truth wallet accoring to on-chain data - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_wallet_equality_ground_truth(self, wallet: MoneroWallet) -> None: - TestUtils.WALLET_TX_TRACKER.wait_for_txs_to_clear_pool([wallet]) - wallet_gt: MoneroWalletFull = TestUtils.create_wallet_ground_truth( - TestUtils.NETWORK_TYPE, TestUtils.SEED, None, TestUtils.FIRST_RECEIVE_HEIGHT - ) - try: - WalletEqualityUtils.test_wallet_equality_on_chain(wallet_gt, wallet) - finally: - wallet_gt.close() - - # Can get the current height that the wallet is synchronized to - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_height(self, wallet: MoneroWallet) -> None: - height: int = wallet.get_height() - assert height >= 0 - - # Can get a blockchain height by date - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_height_by_date(self, wallet: MoneroWallet) -> None: - # collect dates to test starting 100 days ago - day_ms: int = 24 * 60 * 60 * 1000 - # TODO monero-project: today's date can throw exception as "in future" so we test up to yesterday - yesterday: int = GenUtils.current_timestamp() - day_ms - dates: list[datetime] = [] - date_range: list[int] = list(range(99)) - date_range.reverse() - - for i in date_range: - # subtract i days - dates.append(datetime.fromtimestamp((yesterday - day_ms * i) / 1000)) - - # test heights by date - last_height: Optional[int] = None - for date in dates: - height: int = wallet.get_height_by_date(date.year + 1900, date.month + 1, date.day) - assert (height >= 0) - if last_height is not None: - assert (height >= last_height) - last_height = height - - assert last_height is not None - assert (last_height >= 0) - height = wallet.get_height() - assert (height >= 0) - - # test future date - tomorrow: datetime = datetime.fromtimestamp((yesterday + day_ms * 2) / 1000) - with pytest.raises(MoneroError, match="specified date is in the future"): - wallet.get_height_by_date(tomorrow.year + 1900, tomorrow.month + 1, tomorrow.day) - - # Can get the locked and unlocked balances of the wallet, accounts and subaddresses - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_all_balances(self, wallet: MoneroWallet) -> None: - # fetch accounts with all info as reference - accounts: list[MoneroAccount] = wallet.get_accounts(True) - # test that balances add up between accounts and wallet - accounts_balance: int = 0 - accounts_unlocked_balance: int = 0 - for account in accounts: - assert account.index is not None - assert account.balance is not None - assert account.unlocked_balance is not None - accounts_balance += account.balance - accounts_unlocked_balance += account.unlocked_balance - - # test that balances add up between subaddresses and accounts - subaddresses_balance: int = 0 - subaddresses_unlocked_balance: int = 0 - for subaddress in account.subaddresses: - assert subaddress.account_index is not None - assert subaddress.index is not None - assert subaddress.balance is not None - assert subaddress.unlocked_balance is not None - subaddresses_balance += subaddress.balance - subaddresses_unlocked_balance += subaddress.unlocked_balance - - # test that balances are consistent with get_accounts() call - assert wallet.get_balance(subaddress.account_index, subaddress.index) == subaddress.balance - unlocked_balance: int = wallet.get_unlocked_balance(subaddress.account_index, subaddress.index) - assert unlocked_balance == subaddress.unlocked_balance - - assert wallet.get_balance(account.index) == subaddresses_balance - assert wallet.get_unlocked_balance(account.index) == subaddresses_unlocked_balance - - GenUtils.test_unsigned_big_integer(accounts_balance) - GenUtils.test_unsigned_big_integer(accounts_unlocked_balance) - assert wallet.get_balance() == accounts_balance - assert wallet.get_unlocked_balance() == accounts_unlocked_balance - - # Can get accounts without subaddresses - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_accounts_without_subaddresses(self, wallet: MoneroWallet) -> None: - accounts: list[MoneroAccount] = wallet.get_accounts() - assert len(accounts) > 0 - for account in accounts: - WalletUtils.test_account(account, TestUtils.NETWORK_TYPE) - assert len(account.subaddresses) == 0 - - # Can get accounts with subaddress - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_accounts_with_subaddresses(self, wallet: MoneroWallet) -> None: - accounts: list[MoneroAccount] = wallet.get_accounts(True) - assert len(accounts) > 0 - for account in accounts: - WalletUtils.test_account(account, TestUtils.NETWORK_TYPE) - assert len(account.subaddresses) > 0 - - # Can get an account at a specified index - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_account(self, wallet: MoneroWallet) -> None: - accounts: list[MoneroAccount] = wallet.get_accounts() - assert len(accounts) > 0 - for account in accounts: - WalletUtils.test_account(account, TestUtils.NETWORK_TYPE) - - # test without subaddresses - assert account.index is not None - retrieved: MoneroAccount = wallet.get_account(account.index) - assert len(retrieved.subaddresses) == 0 - - # test with subaddresses - retrieved = wallet.get_account(account.index, True) - assert len(retrieved.subaddresses) > 0 - - # Can create a new account without a label - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_create_account_without_label(self, wallet: MoneroWallet) -> None: - accounts_before: list[MoneroAccount] = wallet.get_accounts() - created_account: MoneroAccount = wallet.create_account() - WalletUtils.test_account(created_account, TestUtils.NETWORK_TYPE) - assert len(accounts_before) == len(wallet.get_accounts()) - 1 - - # Can create a new account with a label - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_create_account_with_label(self, wallet: MoneroWallet) -> None: - # create account with label - accounts_before: list[MoneroAccount] = wallet.get_accounts() - label: str = StringUtils.get_random_string() - created_account: MoneroAccount = wallet.create_account(label) - WalletUtils.test_account(created_account, TestUtils.NETWORK_TYPE) - assert created_account.index is not None - assert len(accounts_before) == len(wallet.get_accounts()) - 1 - assert label == wallet.get_subaddress(created_account.index, 0).label - - # fetch and test account - created_account = wallet.get_account(created_account.index) - WalletUtils.test_account(created_account, TestUtils.NETWORK_TYPE) - - # create account with same label - created_account = wallet.create_account(label) - WalletUtils.test_account(created_account, TestUtils.NETWORK_TYPE) - assert len(accounts_before) == len(wallet.get_accounts()) - 2 - assert created_account.index is not None - assert label == wallet.get_subaddress(created_account.index, 0).label - - # fetch and test account - created_account = wallet.get_account(created_account.index) - WalletUtils.test_account(created_account, TestUtils.NETWORK_TYPE) - - # Can set account labels - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_set_account_label(self, wallet: MoneroWallet) -> None: - # create account - if len(wallet.get_accounts()) < 2: - wallet.create_account() - - # set account label - label: str = StringUtils.get_random_string() - wallet.set_account_label(1, label) - assert label == wallet.get_subaddress(1, 0).label - - # Can get subaddresses at a aspecified account index - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_subaddresses(self, wallet: MoneroWallet) -> None: - accounts: list[MoneroAccount] = wallet.get_accounts() - assert len(accounts) > 0 - for account in accounts: - assert account.index is not None - subaddresses: list[MoneroSubaddress] = wallet.get_subaddresses(account.index) - assert len(subaddresses) > 0 - for subaddress in subaddresses: - WalletUtils.test_subaddress(subaddress) - assert account.index == subaddress.account_index - - # Can get subaddresses at a specified account index and subaddress indices - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_subaddresses_by_indices(self, wallet: MoneroWallet) -> None: - accounts: list[MoneroAccount] = wallet.get_accounts() - assert len(accounts) > 0 - for account in accounts: - - # get subaddresses - assert account.index is not None - subaddresses: list[MoneroSubaddress] = wallet.get_subaddresses(account.index) - assert len(subaddresses) > 0 - - # remove a subaddress for query if possible - if len(subaddresses) > 1: - subaddresses = list(filter(lambda sub: sub != subaddresses[0], subaddresses)) - - # get subaddress indices - subaddress_indices: list[int] = [] - for subaddress in subaddresses: - assert subaddress.index is not None - subaddress_indices.append(subaddress.index) - assert len(subaddress_indices) > 0 - - # fetch subaddresses by indices - fetched_subaddresses: list[MoneroSubaddress] = wallet.get_subaddresses(account.index, subaddress_indices) - - # original subaddresses (minus one removed if applicable) is equal to fetched subaddresses - AssertUtils.assert_list_equals(subaddresses, fetched_subaddresses) - - # Can get subaddress at a specified account index and subaddress index - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_subaddress_by_index(self, wallet: MoneroWallet) -> None: - accounts: list[MoneroAccount] = wallet.get_accounts() - assert len(accounts) > 0 - for account in accounts: - assert account.index is not None - subaddresses: list[MoneroSubaddress] = wallet.get_subaddresses(account.index) - assert len(subaddresses) > 0 - for subaddress in subaddresses: - assert subaddress.index is not None - WalletUtils.test_subaddress(subaddress) - AssertUtils.assert_equals(subaddress, wallet.get_subaddress(account.index, subaddress.index)) - # test plural call with single subaddr number - AssertUtils.assert_equals( - subaddress, wallet.get_subaddresses(account.index, [subaddress.index])[0] - ) - - # Can create a subaddress with and without a label - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_create_subaddress(self, wallet: MoneroWallet) -> None: - # create subaddresses across accounts - accounts: list[MoneroAccount] = wallet.get_accounts() - if len(accounts) < 2: - wallet.create_account() - accounts = wallet.get_accounts() - assert len(accounts) > 1 - account_idx: int = 0 - while account_idx < 2: - - # create subaddress with no label - subaddresses: list[MoneroSubaddress] = wallet.get_subaddresses(account_idx) - subaddress: MoneroSubaddress = wallet.create_subaddress(account_idx) - assert subaddress.label is None - WalletUtils.test_subaddress(subaddress) - subaddresses_new: list[MoneroSubaddress] = wallet.get_subaddresses(account_idx) - assert len(subaddresses_new) - 1 == len(subaddresses) - AssertUtils.assert_equals(subaddress, subaddresses_new[len(subaddresses_new) - 1]) - - # create subaddress with label - subaddresses = wallet.get_subaddresses(account_idx) - uuid: str = StringUtils.get_random_string() - subaddress = wallet.create_subaddress(account_idx, uuid) - assert (uuid == subaddress.label) - WalletUtils.test_subaddress(subaddress) - subaddresses_new = wallet.get_subaddresses(account_idx) - assert len(subaddresses) == len(subaddresses_new) - 1 - AssertUtils.assert_equals(subaddress, subaddresses_new[len(subaddresses_new) - 1]) - - account_idx += 1 - - # Can set subaddress labels - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_set_subaddress_label(self, wallet: MoneroWallet) -> None: - # create subaddresses - while len(wallet.get_subaddresses(0)) < 3: - wallet.create_subaddress(0) - - # set subaddress labels - subaddress_idx: int = 0 - while subaddress_idx < len(wallet.get_subaddresses(0)): - label: str = StringUtils.get_random_string() - wallet.set_subaddress_label(0, subaddress_idx, label) - assert label == wallet.get_subaddress(0, subaddress_idx).label - subaddress_idx += 1 - - # Can get transactions in the wallet - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_txs_wallet(self, wallet: MoneroWallet) -> None: - #non_default_incoming: bool = False - txs: list[MoneroTxWallet] = WalletTxsUtils.get_and_test_txs(wallet, None, None, True, TestUtils.REGTEST) - assert len(txs) > 0, "Wallet has no txs to test" - # TODO make consistent with test funded wallet - # assert TestUtils.FIRST_RECEIVE_HEIGHT == txs[0].get_height(), "First tx's restore height must match the restore height in TestUtils" - - # build test context - ctx: TxContext = TxContext() - ctx.wallet = wallet - - # test each transaction - block_per_height: dict[int, MoneroBlock] = {} - for i, tx in enumerate(txs): - TxWalletUtils.test_tx_wallet(tx, ctx) - - # test merging equivalent txs - it: MoneroTxWallet = txs[i] # is the same as tx - copy1: MoneroTxWallet = it.copy() - copy2: MoneroTxWallet = it.copy() - - if copy1.is_confirmed: - assert it.block is not None - copy1.block = it.block.copy() - copy1.block.txs = [copy1] - - if copy2.is_confirmed: - assert it.block is not None - copy2.block = it.block.copy() - copy2.block.txs = [copy2] - - copy1.merge(copy2) - TxWalletUtils.test_tx_wallet(copy1, ctx) - - # find non-default incoming - for transfer in it.incoming_transfers: - assert transfer.account_index is not None - assert transfer.subaddress_index is not None - #if transfer.account_index != 0 and transfer.subaddress_index != 0: - # non_default_incoming = True - - # ensure unique block reference per height - if it.is_confirmed: - h: int | None = it.get_height() - assert h is not None - block: MoneroBlock | None = block_per_height.get(h) - if block is None: - assert it.block is not None - block_per_height[i] = it.block - else: - AssertUtils.assert_equals(block, it.block) - assert block == it.block, "Block references for same height must be same" - - # ensure non-default account and subaddress testes - # TODO enable this after setting send-to-multiple order - #assert non_default_incoming, "No incoming transfers found to non-default account and subaddress; run send-to-multiple tests first" - - # Can get transactions by hash - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_txs_by_hash(self, wallet: MoneroWallet) -> None: - # max number of txs to test - max_num_txs: int = 10 - - # fetch all txs for testing - txs: list[MoneroTxWallet] = wallet.get_txs() - num_txs: int = len(txs) - assert num_txs > 1, f"Test requires at least 2 txs to fetch by hash, got {num_txs}" - - # randomly pick a few for fetching by hash - shuffle(txs) - txs = txs[0:min(max_num_txs, num_txs)] - - # test fetching by hash - tx_hash: str | None = txs[0].hash - assert tx_hash is not None - fetched_tx: MoneroTxWallet | None = wallet.get_tx(tx_hash) - assert fetched_tx is not None - assert tx_hash == fetched_tx.hash - TxWalletUtils.test_tx_wallet(fetched_tx) - - # test fetching by hashes - tx_id1: str | None = txs[0].hash - tx_id2: str | None = txs[1].hash - assert tx_id1 is not None - assert tx_id2 is not None - fetched_txs: list[MoneroTxWallet] = wallet.get_txs([tx_id1, tx_id2]) - num_fetched_txs: int = len(fetched_txs) - assert num_fetched_txs == 2, f"Expected 2 txs, got {num_fetched_txs}" - - # test fetching by hashes as collection - tx_hashes: list[str] = [] - for tx in txs: - assert tx.hash is not None - tx_hashes.append(tx.hash) - - fetched_txs = wallet.get_txs(tx_hashes) - assert len(txs) == len(fetched_txs) - for i, tx in enumerate(txs): - fetched_tx = fetched_txs[i] - assert tx.hash == fetched_tx.hash - TxWalletUtils.test_tx_wallet(fetched_tx) - - # test fetching with missing tx hashes - missing_hash: str = "d01ede9cde813b2a693069b640c4b99c5adbdb49fbbd8da2c16c8087d0c3e320" - tx_hashes.append(missing_hash) - fetched_txs = wallet.get_txs(tx_hashes) - assert len(txs) == len(fetched_txs) - for i, tx in enumerate(txs): - fetched_tx = fetched_txs[i] - assert tx.hash == fetched_tx.hash - TxWalletUtils.test_tx_wallet(fetched_tx) - - # Can get transactions with additional configuration - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_txs_with_query(self, wallet: MoneroWallet) -> None: - # get random transactions for testing - random_txs: list[MoneroTxWallet] = WalletTxsUtils.get_random_transactions(wallet, None, 3, 5) - for random_tx in random_txs: - TxWalletUtils.test_tx_wallet(random_tx, None) - - # get transactions by hash - tx_hashes: list[str] = [] - for random_tx in random_txs: - assert random_tx.hash is not None - tx_hashes.append(random_tx.hash) - query: MoneroTxQuery = MoneroTxQuery() - query.hash = random_tx.hash - txs: list[MoneroTxWallet] = WalletTxsUtils.get_and_test_txs(wallet, query, None, True, TestUtils.REGTEST) - assert len(txs) == 1 - # txs change with chain so check mergeability - merged: MoneroTxWallet = txs[0] - merged.merge(random_tx.copy()) - TxWalletUtils.test_tx_wallet(merged) - - # get transactions by hashes - query = MoneroTxQuery() - query.hashes = tx_hashes - txs = WalletTxsUtils.get_and_test_txs(wallet, query, None, None, TestUtils.REGTEST) - assert len(txs) == len(random_txs) - for tx in txs: - assert tx.hash in tx_hashes - - # get transactions with an outgoing transfer - ctx: TxContext = TxContext() - ctx.has_outgoing_transfer = True - query = MoneroTxQuery() - query.is_outgoing = True - txs = WalletTxsUtils.get_and_test_txs(wallet, query, ctx, True, TestUtils.REGTEST) - for tx in txs: - assert tx.is_outgoing is True - assert tx.outgoing_transfer is not None - TransferUtils.test_transfer(tx.outgoing_transfer, None) - - # get transactions without an outgoing transfer - ctx.has_outgoing_transfer = False - query = MoneroTxQuery() - query.is_outgoing = False - txs = WalletTxsUtils.get_and_test_txs(wallet, query, ctx, True, TestUtils.REGTEST) - for tx in txs: - assert tx.outgoing_transfer is None - - # get transactions with incoming transfers - ctx = TxContext() - ctx.has_incoming_transfers = True - query = MoneroTxQuery() - query.is_incoming = True - txs = WalletTxsUtils.get_and_test_txs(wallet, query, ctx, True, TestUtils.REGTEST) - for tx in txs: - assert tx.is_incoming is True - assert len(tx.incoming_transfers) > 0 - for transfer in tx.incoming_transfers: - TransferUtils.test_transfer(transfer, None) - - # get transactions without incoming transfers - ctx.has_incoming_transfers = False - query = MoneroTxQuery() - query.is_incoming = False - txs = WalletTxsUtils.get_and_test_txs(wallet, query, ctx, True, TestUtils.REGTEST) - for tx in txs: - assert tx.is_incoming is False - assert len(tx.incoming_transfers) == 0 - - # get transactions associated with an account - account_idx: int = 1 - query = MoneroTxQuery() - query.transfer_query = MoneroTransferQuery() - query.transfer_query.account_index = account_idx - txs = wallet.get_txs(query) - - for tx in txs: - found: bool = False - if tx.is_outgoing and tx.outgoing_transfer.account_index == account_idx: # type: ignore - found = True - elif len(tx.incoming_transfers) > 0: - for transfer in tx.incoming_transfers: - if transfer.account_index == account_idx: - found = True - break - - assert found, f"Transaction is not associated with account {account_idx}: \n{tx.serialize()}" - - # get txs with manually built query that are confirmed and have an outgoing transfer from account 0 - ctx = TxContext() - ctx.has_outgoing_transfer = True - tx_query: MoneroTxQuery = MoneroTxQuery() - tx_query.is_confirmed = True - tx_query.transfer_query = MoneroTransferQuery() - tx_query.transfer_query.account_index = 0 - tx_query.transfer_query.outgoing = True - txs = WalletTxsUtils.get_and_test_txs(wallet, tx_query, ctx, True, TestUtils.REGTEST) - for tx in txs: - if tx.is_confirmed is not True: - logger.warning(f"{tx.serialize()}") - assert tx.is_confirmed is True - assert tx.is_outgoing is True - assert tx.outgoing_transfer is not None - assert tx.outgoing_transfer.account_index == 0 - - # get txs with outgoing transfers that have destinations to account 1 - tx_query = MoneroTxQuery() - tx_query.is_confirmed = True - tx_query.transfer_query = MoneroTransferQuery() - tx_query.transfer_query.account_index = 0 - tx_query.transfer_query.has_destinations = True - - txs = WalletTxsUtils.get_and_test_txs(wallet, tx_query, None, None, TestUtils.REGTEST) - for tx in txs: - assert tx.is_outgoing is True - assert tx.outgoing_transfer is not None - assert len(tx.outgoing_transfer.destinations) > 0 - - # include outputs with transactions - ctx = TxContext() - ctx.include_outputs = True - tx_query = MoneroTxQuery() - tx_query.include_outputs = True - txs = WalletTxsUtils.get_and_test_txs(wallet, tx_query, ctx, True, TestUtils.REGTEST) - found: bool = False - for tx in txs: - if len(tx.outputs) > 0: - found = True - else: - # TODO: monero-wallet-rpc: return outputs for unconfirmed txs - assert tx.is_outgoing or (tx.is_incoming and tx.is_confirmed is False) - - assert found, "No outputs found in txs" - - # get txs with input query - # TODO no inputs returned to filter - - # get txs with output query - tx_query = MoneroTxQuery() - tx_query.output_query = MoneroOutputQuery() - tx_query.output_query.is_spent = False - tx_query.output_query.account_index = 1 - tx_query.output_query.subaddress_index = 2 - txs = wallet.get_txs(tx_query) - assert len(txs) > 0 - for tx in txs: - assert len(tx.outputs) > 0 - found = False - for output in tx.get_outputs_wallet(): - if output.is_spent is False and output.account_index == 1 and output.subaddress_index == 2: - found = True - break - - if not found: - raise Exception("Tx does not contain specified output") - - # get unlocked txs - tx_query = MoneroTxQuery() - tx_query.is_locked = False - txs = wallet.get_txs(tx_query) - assert len(txs) > 0 - for tx in txs: - assert tx.is_locked is False - - # get confirmed transactions sent from/to same wallet with a transfer with destinations - - tx_query = MoneroTxQuery() - tx_query.is_incoming = True - tx_query.is_outgoing = True - tx_query.include_outputs = True - tx_query.is_confirmed = True - tx_query.transfer_query = MoneroTransferQuery() - tx_query.transfer_query.has_destinations = True - - txs = wallet.get_txs(tx_query) - assert len(txs) > 0, "Wallet has no incoming/outgoing txs to test; run send from/to tests" - for tx in txs: - assert tx.is_incoming is True - assert tx.is_outgoing is True - assert tx.is_confirmed is True - assert len(tx.get_outputs_wallet()) > 0 - assert tx.outgoing_transfer is not None - assert len(tx.outgoing_transfer.destinations) > 0 - - # Can get transactions by height - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_txs_by_height(self, wallet: MoneroWallet) -> None: - # get all confirmed txs for testing - query: MoneroTxQuery = MoneroTxQuery() - query.is_confirmed = True - txs: list[MoneroTxWallet] = wallet.get_txs(query) - - # collect all tx heights - tx_heights: list[int] = [] - for tx in txs: - tx_height: Optional[int] = tx.get_height() - assert tx_height is not None - tx_heights.append(tx_height) - - # get height that most txs occur at - height_counts: dict[int, int] = GenUtils.count_num_instances(tx_heights) - assert len(height_counts) > 0, "Wallet has no confirmed txs; run send tests" - height_modes: set[int] = GenUtils.get_modes(height_counts) - mode_height: int = next(iter(height_modes)) - - # fetch txs at mode height - query = MoneroTxQuery() - query.height = mode_height - logger.debug(f"Getting mode txs by height; mode height {mode_height}") - mode_txs: list[MoneroTxWallet] = wallet.get_txs(query) - assert height_counts[mode_height] == len(mode_txs) - for tx in mode_txs: - assert mode_height == tx.get_height() - - # fetch txs at mode height by range - query = MoneroTxQuery() - query.min_height = mode_height - query.max_height = mode_height - logger.debug(f"Getting mode txs by range; mode height {mode_height}") - mode_txs_by_range: list[MoneroTxWallet] = wallet.get_txs(query) - # TODO test txs order is failing - TxWalletUtils.assert_list_txs_equals(mode_txs, mode_txs_by_range) - - # fetch all txs by range - query = MoneroTxQuery() - query.min_height = txs[0].get_height() - query.max_height = txs[-1].get_height() - all_txs: list[MoneroTxWallet] = wallet.get_txs(query) - # TODO test txs order is failing - TxWalletUtils.assert_list_txs_equals(txs, all_txs) - - # test some filtered by range - try: - query = MoneroTxQuery() - query.is_confirmed = True - txs = wallet.get_txs(query) - assert len(txs) > 0, "No transactions; run send to multiple test" - - # get and sort block heights in ascending order - heights: list[int] = [] - for tx in txs: - assert tx.block is not None - assert tx.block.height is not None - heights.append(tx.block.height) - - heights.sort() - - # pick minimum and maximum heights for filtering - min_height: int = -1 - max_height: int = -1 - if len(heights) == 1: - min_height = 0 - max_height = heights[0] - 1 - else: - min_height = heights[0] + 1 - max_height = heights[-1] - 1 - - # assert some transactions filtered - unfiltered_count: int = len(txs) - query = MoneroTxQuery() - query.min_height = min_height - query.max_height = max_height - txs = WalletTxsUtils.get_and_test_txs(wallet, query, None, True, TestUtils.REGTEST) - assert len(txs) < unfiltered_count - for tx in txs: - assert tx.block is not None - assert tx.block.height is not None - height: int = tx.block.height - assert height >= min_height and height <= max_height - - except Exception as e: - logger.debug(str(e)) - - # Can get transactions with payment id - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False or TestUtils.LITE_MODE, reason="TEST_NON_RELAYS disabled or LITE_MODE enabled") - def test_get_txs_with_payment_ids(self, wallet: MoneroWallet) -> None: - # get random transactions with payment ids for testing - tx_query: MoneroTxQuery = MoneroTxQuery() - tx_query.has_payment_id = True - random_txs: list[MoneroTxWallet] = WalletTxsUtils.get_random_transactions(wallet, tx_query, 2, 5) - assert len(random_txs) > 0, "No txs with payment ids to test" - for random_tx in random_txs: - assert random_tx.payment_id is not None and len(random_tx.payment_id) > 0 - - # get transactions by payment id - payment_ids: list[str] = [] - for tx in random_txs: - assert tx.payment_id is not None - payment_ids.append(tx.payment_id) - - assert len(payment_ids) > 1 - for payment_id in payment_ids: - tx_query = MoneroTxQuery() - tx_query.payment_id = payment_id - txs: list[MoneroTxWallet] = WalletTxsUtils.get_and_test_txs(wallet, tx_query, None, None, TestUtils.REGTEST) - assert len(txs) > 0 - first_payment_id: Optional[str] = txs[0].payment_id - assert first_payment_id is not None - MoneroUtils.validate_payment_id(first_payment_id) - - # get transactions by payment hashes - tx_query = MoneroTxQuery() - tx_query.payment_ids = payment_ids - txs: list[MoneroTxWallet] = WalletTxsUtils.get_and_test_txs(wallet, tx_query, None, None, TestUtils.REGTEST) - for tx in txs: - assert tx.payment_id is not None - assert tx.payment_id in payment_ids - - # Returns all known fields of txs regardless of filtering - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_txs_fields_with_filtering(self, wallet: MoneroWallet) -> None: - # fetch wallet txs - tx_query: MoneroTxQuery = MoneroTxQuery() - tx_query.is_confirmed = True - txs: list[MoneroTxWallet] = wallet.get_txs(tx_query) - - for tx in txs: - # find tx sent to same wallet with incoming transfer in different account than src account - if tx.outgoing_transfer is None or len(tx.incoming_transfers) == 0: - continue - for transfer in tx.incoming_transfers: - if transfer.account_index == tx.outgoing_transfer.account_index: - continue - - # fetch tx with filtering - tx_query = MoneroTxQuery() - tx_query.transfer_query = MoneroTransferQuery() - tx_query.transfer_query.incoming = True - tx_query.transfer_query.account_index = transfer.account_index - filtered_txs: list[MoneroTxWallet] = wallet.get_txs(tx_query) - - for filtered_tx in filtered_txs: - assert filtered_tx.hash is not None - if filtered_tx.hash == tx.hash: - tx.merge(filtered_tx) - # test is done - return - - raise Exception("Test requires tx sent from/to different accounts of same wallet but none found; run send tests") - - # Validates inputs when getting transactions - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False or TestUtils.LITE_MODE, reason="TEST_NON_RELAYS disabled or LITE_MODE enabled") - def test_validate_inputs_get_txs(self, wallet: MoneroWallet) -> None: - # fetch random txs for testing - random_txs: list[MoneroTxWallet] = WalletTxsUtils.get_random_transactions(wallet, None, 3, 5) - - # valid, invalid, and unknown tx hashes for tests - tx_hash: str | None = random_txs[0].hash - invalid_hash: str = "invalid_id" - unknown_hash1: str = "6c4982f2499ece80e10b627083c4f9b992a00155e98bcba72a9588ccb91d0a61" - unknown_hash2: str = "ff397104dd875882f5e7c66e4f852ee134f8cf45e21f0c40777c9188bc92e943" - assert tx_hash is not None and len(tx_hash) > 0 - - # fetch unknown tx hash - fetched_tx: MoneroTxWallet | None = wallet.get_tx(unknown_hash1) - assert fetched_tx is None - - # fetch unknown tx hash using query - tx_query: MoneroTxQuery = MoneroTxQuery() - tx_query.hash = unknown_hash1 - fetched_txs: list[MoneroTxWallet] = wallet.get_txs(tx_query) - assert len(fetched_txs) == 0 - - # fetch unknwon tx hash in list - txs: list[MoneroTxWallet] = wallet.get_txs([tx_hash, unknown_hash1]) - assert len(txs) == 1 - assert txs[0].hash == tx_hash - - # fetch unknwon tx hashes in list - txs = wallet.get_txs([tx_hash, unknown_hash1, unknown_hash2]) - assert len(txs) == 1 - assert txs[0].hash == tx_hash - - # fetch invalid hash - fetched_tx = wallet.get_tx(invalid_hash) - assert fetched_tx is None - - # fetch invalid hash list - txs = wallet.get_txs([tx_hash, invalid_hash]) - assert len(txs) == 1 - assert txs[0].hash == tx_hash - - # fetch invalid hashes in list - txs = wallet.get_txs([tx_hash, invalid_hash, "invalid_hash_2"]) - assert len(txs) == 1 - assert txs[0].hash == tx_hash - - # test collection of invalid hashes - tx_query = MoneroTxQuery() - tx_query.hashes = [tx_hash, invalid_hash, "invalid_hash_2"] - txs = wallet.get_txs(tx_query) - assert len(txs) == 1 - - # test txs - for tx in txs: - TxWalletUtils.test_tx_wallet(tx) - - # Can get transfers in the wallet, accounts, and subaddresses - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_transfers(self, wallet: MoneroWallet) -> None: - # get all transfers - WalletTransfersUtils.get_and_test_transfers(wallet, None, None, True) - - # get transfers by account index - non_default_incoming: bool = False - for account in wallet.get_accounts(True): - transfer_query: MoneroTransferQuery = MoneroTransferQuery() - transfer_query.account_index = account.index - account_transfers: list[MoneroTransfer] = WalletTransfersUtils.get_and_test_transfers(wallet, transfer_query, None, None) - for transfer in account_transfers: - assert transfer.account_index == account.index - - # get transfers by subaddress index - subaddress_transfers: list[MoneroTransfer] = [] - for subaddress in account.subaddresses: - subaddress_query: MoneroTransferQuery = MoneroTransferQuery() - subaddress_query.account_index = subaddress.account_index - subaddress_query.subaddress_index = subaddress.index - transfers: list[MoneroTransfer] = WalletTransfersUtils.get_and_test_transfers(wallet, subaddress_query, None, None) - - for transfer in transfers: - # test account and subaddress indices - assert subaddress.account_index == transfer.account_index - if transfer.is_incoming() is True: - assert isinstance(transfer, MoneroIncomingTransfer) - assert subaddress.index == transfer.subaddress_index - if transfer.account_index != 0 and transfer.subaddress_index != 0: - non_default_incoming = True - else: - assert isinstance(transfer, MoneroOutgoingTransfer) - assert subaddress.index in transfer.subaddress_indices - if transfer.account_index != 0: - for subaddr_idx in transfer.subaddress_indices: - if subaddr_idx > 0: - non_default_incoming = True - break - - # don't add duplicates - # TODO monero-wallet-rpc: duplicate outgoing transfers returned for different - # subaddress indices, way to return outgoing subaddress indices? - - found: bool = False - for subaddress_transfer in subaddress_transfers: - eq_hash: bool = transfer.tx.hash == subaddress_transfer.tx.hash - if transfer.serialize() == subaddress_transfer.serialize() and eq_hash: - found = True - break - - if not found: - subaddress_transfers.append(transfer) - - assert len(account_transfers) == len(subaddress_transfers) - - # collect unique subaddress indices - subaddress_indices: set[int] = set() - for transfer in subaddress_transfers: - if transfer.is_incoming(): - assert isinstance(transfer, MoneroIncomingTransfer) - assert transfer.subaddress_index is not None - subaddress_indices.add(transfer.subaddress_index) - else: - assert isinstance(transfer, MoneroOutgoingTransfer) - for idx in transfer.subaddress_indices: - subaddress_indices.add(idx) - - # get and test transfers by subaddress indices - transfer_query = MoneroTransferQuery() - transfer_query.account_index = account.index - for idx in subaddress_indices: - transfer_query.subaddress_indices.append(idx) - - transfers = WalletTransfersUtils.get_and_test_transfers(wallet, transfer_query, None, None) - # TODO monero-wallet-rpc: these may not be equal because outgoing transfers are always from subaddress 0 (#5171) - # and/or incoming transfers from/to same account are occluded (#4500) - assert len(subaddress_transfers) == len(transfers) - for transfer in transfers: - assert transfer.account_index == account.index - if transfer.is_incoming(): - assert isinstance(transfer, MoneroIncomingTransfer) - assert transfer.subaddress_index in subaddress_indices - else: - assert isinstance(transfer, MoneroOutgoingTransfer) - intersections: set[int] = set(subaddress_indices) - overlap: set[int] = intersections.intersection(transfer.subaddress_indices) - assert overlap is not None and len(overlap) > 0, "Subaddresses must overlap" - - # ensure transfer found with non-zero account and subaddress indices - assert non_default_incoming, "No transfers found in non-default account and subaddress; run send-to-multiple tests" - - # Can get transfers with additional configuration - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_transfers_with_query(self, wallet: MoneroWallet) -> None: - # get incoming transfers - query: MoneroTransferQuery = MoneroTransferQuery() - query.incoming = True - transfers: list[MoneroTransfer] = WalletTransfersUtils.get_and_test_transfers(wallet, query, None, True) - for transfer in transfers: - assert transfer.is_incoming() - - # get outgoing transfers - query = MoneroTransferQuery() - query.outgoing = True - transfers = WalletTransfersUtils.get_and_test_transfers(wallet, query, None, True) - for transfer in transfers: - assert transfer.is_outgoing() - - # get confirmed transfers to account 0 - query = MoneroTransferQuery() - query.account_index = 0 - query.tx_query = MoneroTxQuery() - query.tx_query.is_confirmed = True - transfers = WalletTransfersUtils.get_and_test_transfers(wallet, query, None, True) - for transfer in transfers: - assert transfer.account_index == 0 - assert transfer.tx is not None - assert transfer.tx.is_confirmed is True - - # get confirmed transfers to (1, 2) - query = MoneroTransferQuery() - query.account_index = 1 - query.subaddress_index = 2 - query.tx_query = MoneroTxQuery() - query.tx_query.is_confirmed = True - transfers = WalletTransfersUtils.get_and_test_transfers(wallet, query, None, True) - for transfer in transfers: - assert transfer.account_index == 1 - if transfer.is_incoming(): - assert isinstance(transfer, MoneroIncomingTransfer) - assert transfer.subaddress_index == 2 - else: - assert isinstance(transfer, MoneroOutgoingTransfer) - assert 2 in transfer.subaddress_indices - - assert transfer.tx is not None - assert transfer.tx.is_confirmed is True - - # get transfers in the tx pool - query = MoneroTransferQuery() - query.tx_query = MoneroTxQuery() - query.tx_query.in_tx_pool = True - transfers = WalletTransfersUtils.get_and_test_transfers(wallet, query, None, None) - for transfer in transfers: - assert transfer.tx is not None - assert transfer.tx.in_tx_pool is True - - # get random transactions - txs: list[MoneroTxWallet] = WalletTxsUtils.get_random_transactions(wallet, None, 3, 5) - - # get transfers with a tx hash - tx_hashes: list[str] = [] - for tx in txs: - assert tx.hash is not None - tx_hashes.append(tx.hash) - query = MoneroTransferQuery() - query.tx_query = MoneroTxQuery() - query.tx_query.hash = tx.hash - transfers = WalletTransfersUtils.get_and_test_transfers(wallet, query, None, True) - for transfer in transfers: - assert transfer.tx is not None - assert tx.hash == transfer.tx.hash - - # get transfers with tx hashes - query = MoneroTransferQuery() - query.tx_query = MoneroTxQuery() - query.tx_query.hashes = tx_hashes - transfers = WalletTransfersUtils.get_and_test_transfers(wallet, query, None, True) - for transfer in transfers: - assert transfer.tx is not None - assert transfer.tx.hash is not None - assert transfer.tx.hash in tx_hashes - - # TODO test that transfers with the same tx_hash have same tx reference - # TODO test transfers destinations - - # get transfers with pre-built query that are confirmed and have outgoing destinations - transfer_query: MoneroTransferQuery = MoneroTransferQuery() - transfer_query.outgoing = True - transfer_query.has_destinations = True - transfer_query.tx_query = MoneroTxQuery() - transfer_query.tx_query.is_confirmed = True - transfers = WalletTransfersUtils.get_and_test_transfers(wallet, transfer_query, None, None) - for transfer in transfers: - assert transfer.is_outgoing() is True - assert isinstance(transfer, MoneroOutgoingTransfer) - assert len(transfer.destinations) > 0 - assert transfer.tx is not None - assert transfer.tx.is_confirmed is True - - # get incoming transfers to account 0 which has outgoing transfers (i.e. originated from the same wallet) - query = MoneroTransferQuery() - query.account_index = 1 - query.incoming = True - query.tx_query = MoneroTxQuery() - query.tx_query.is_outgoing = True - transfers = wallet.get_transfers(query) - assert len(transfers) > 0 - for transfer in transfers: - assert transfer.is_incoming() is True - assert transfer.account_index == 1 - assert transfer.tx is not None - assert transfer.tx.is_outgoing is True - assert transfer.tx.outgoing_transfer is None - - # get incoming transfers to a spefici address - subaddress: str = wallet.get_address(1, 0) - query = MoneroTransferQuery() - query.incoming = True - query.address = subaddress - transfers = wallet.get_transfers(query) - assert len(transfers) > 0 - for transfer in transfers: - assert isinstance(transfer, MoneroIncomingTransfer) - assert transfer.account_index == 1 - assert transfer.subaddress_index == 0 - assert transfer.address == subaddress - - # Validates inputs when getting transfers - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False or TestUtils.LITE_MODE, reason="TEST_NON_RELAYS disabled or LITE_MODE enabled") - def test_validate_inputs_get_transfers(self, wallet: MoneroWallet) -> None: - # test with invalid hash - transfer_query: MoneroTransferQuery = MoneroTransferQuery() - transfer_query.tx_query = MoneroTxQuery() - transfer_query.tx_query.hash = "invalid_id" - - transfers: list[MoneroTransfer] = wallet.get_transfers(transfer_query) - assert len(transfers) == 0 - - # test invalid hash in list - random_txs: list[MoneroTxWallet] = WalletTxsUtils.get_random_transactions(wallet, None, 3, 5) - transfer_query.tx_query = MoneroTxQuery() - random_hash: str | None = random_txs[0].hash - assert random_hash is not None - transfer_query.tx_query.hashes.append(random_hash) - transfer_query.tx_query.hashes.append("invalid_id") - - transfers = wallet.get_transfers(transfer_query) - assert len(transfers) > 0 - - tx: MoneroTxWallet = transfers[0].tx - for transfer in transfers: - assert transfer.tx == tx - - # test unused subaddress indices - transfer_query = MoneroTransferQuery() - transfer_query.account_index = 0 - transfer_query.subaddress_indices.append(1234907) - transfers = wallet.get_transfers(transfer_query) - - # test invalid subaddress index - transfer_query = MoneroTransferQuery() - transfer_query.account_index = 0 - with pytest.raises(Exception): - transfer_query.subaddress_index = -1 - wallet.get_transfers(transfer_query) - - # TODO Can get incoming and outgoing transfers using convenience methods - - # Can get outputs in the wallet, accounts, and subaddresses - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_outputs(self, wallet: MoneroWallet) -> None: - # get all outputs - OutputUtils.get_and_test_outputs(wallet, None, True) - - # get outputs for each account - non_default_incoming: bool = False - accounts: list[MoneroAccount] = wallet.get_accounts(True) - for account in accounts: - # determine if account is used - is_used: bool = False - for subaddress in account.subaddresses: - if subaddress.is_used is True: - is_used = True - break - - # get outputs by account index - output_query: MoneroOutputQuery = MoneroOutputQuery() - output_query.account_index = account.index - account_outputs: list[MoneroOutputWallet] = OutputUtils.get_and_test_outputs(wallet, output_query, is_used) - for ouput in account_outputs: - assert ouput.account_index == account.index - - # get outputs by subaddress index - subaddress_outputs: list[MoneroOutputWallet] = [] - for subaddress in account.subaddresses: - subaddr_query: MoneroOutputQuery = MoneroOutputQuery() - subaddr_query.account_index = account.index - subaddr_query.subaddress_index = subaddress.index - outputs: list[MoneroOutputWallet] = OutputUtils.get_and_test_outputs(wallet, subaddr_query, subaddress.is_used) - for output in outputs: - assert subaddress.account_index == output.account_index - assert subaddress.index == output.subaddress_index - if output.account_index != 0 and output.subaddress_index != 0: - non_default_incoming = True - subaddress_outputs.append(output) - - assert len(subaddress_outputs) == len(account_outputs) - - # get outputs by subaddress indices - subaddress_indices: set[int] = set() - for output in subaddress_outputs: - assert output.subaddress_index is not None - subaddress_indices.add(output.subaddress_index) - - output_query = MoneroOutputQuery() - output_query.account_index = account.index - for sub_idx in subaddress_indices: - output_query.subaddress_indices.append(sub_idx) - - outputs = OutputUtils.get_and_test_outputs(wallet, output_query, is_used) - assert len(outputs) == len(subaddress_outputs) - - for output in outputs: - assert account.index == output.account_index - assert output.subaddress_index is not None - assert output.subaddress_index in subaddress_indices - - # ensure output found with non-zero account and subaddress indices - assert non_default_incoming, "No outputs found in non-default account and subaddress; run send-to-multiple tests" - - # Can get outputs with additional configuration - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_outputs_with_query(self, wallet: MoneroWallet) -> None: - # get unspent outputs to account 0 - output_query: MoneroOutputQuery = MoneroOutputQuery() - output_query.account_index = 0 - output_query.is_spent = False - outputs: list[MoneroOutputWallet] = OutputUtils.get_and_test_outputs(wallet, output_query, None) - - for output in outputs: - assert output.account_index == 0 - assert output.is_spent is False - - # get spent outputs to account 1 - output_query = MoneroOutputQuery() - output_query.account_index = 1 - output_query.is_spent = True - outputs = OutputUtils.get_and_test_outputs(wallet, output_query, True) - - for output in outputs: - assert output.account_index == 1 - assert output.is_spent is True - - # get random transactions - tx_query: MoneroTxQuery = MoneroTxQuery() - tx_query.is_confirmed = True - txs: list[MoneroTxWallet] = WalletTxsUtils.get_random_transactions(wallet, tx_query, 3, 5) - - # get outputs with a tx hash - tx_hashes: list[str] = [] - for tx in txs: - assert tx.hash is not None - tx_hashes.append(tx.hash) - output_query = MoneroOutputQuery() - output_query.set_tx_query(MoneroTxQuery(), True) - assert output_query.tx_query is not None - output_query.tx_query.hash = tx.hash - outputs = OutputUtils.get_and_test_outputs(wallet, output_query, True) - - for output in outputs: - assert output.tx is not None - assert output.tx.hash is not None - assert output.tx.hash in tx_hashes - - # get outputs with tx hashes - tx_query = MoneroTxQuery() - tx_query.hashes = tx_hashes - output_query = MoneroOutputQuery() - output_query.set_tx_query(tx_query, True) - outputs = OutputUtils.get_and_test_outputs(wallet, output_query, True) - - for output in outputs: - assert output.tx is not None - assert output.tx.hash is not None - assert output.tx.hash in tx_hashes - - # get confirmed outputs to specifi subaddress with pre-built query - account_idx: int = 0 - subaddress_idx: int = 1 - output_query = MoneroOutputQuery() - output_query.account_index = account_idx - output_query.subaddress_index = subaddress_idx - tx_query = MoneroTxQuery() - tx_query.is_confirmed = True - output_query.set_tx_query(tx_query, True) - output_query.min_amount = TxWalletUtils.MAX_FEE - outputs = OutputUtils.get_and_test_outputs(wallet, output_query, True) - - for output in outputs: - assert output.account_index == account_idx - assert output.subaddress_index == subaddress_idx - assert output.tx is not None - assert output.tx.is_confirmed is True - assert output.amount is not None - assert output.amount >= TxWalletUtils.MAX_FEE - - # get output by key image - output: MoneroOutputWallet = outputs[0] - assert output.key_image is not None - assert output.key_image.hex is not None - output_query = MoneroOutputQuery() - output_query.key_image = MoneroKeyImage() - output_query.key_image.hex = output.key_image.hex - outputs = wallet.get_outputs(output_query) - assert len(outputs) == 1 - output_result: MoneroOutputWallet = outputs[0] - assert output_result.key_image is not None - assert output.key_image.hex == output_result.key_image.hex - - # get outputs whose transaction is confirmed and has incoming and outgoing transfers - output_query = MoneroOutputQuery() - tx_query = MoneroTxQuery() - tx_query.is_confirmed = True - tx_query.is_incoming = True - tx_query.is_outgoing = True - tx_query.include_outputs = True - output_query.set_tx_query(tx_query, True) - outputs = wallet.get_outputs(output_query) - assert len(outputs) > 0 - - for output in outputs: - assert output.tx is not None - assert isinstance(output.tx, MoneroTxWallet) - assert output.tx.is_incoming is True - assert output.tx.is_outgoing is True - assert output.tx.is_confirmed is True - outputs_wallet: list[MoneroOutputWallet] = output.tx.get_outputs_wallet() - assert len(outputs_wallet) > 0 - assert output in outputs_wallet - - # Validates inputs when getting wallet outputs - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False or TestUtils.LITE_MODE, reason="TEST_NON_RELAYS disabled or LITE_MODE enabled") - def test_validate_inputs_get_outputs(self, wallet: MoneroWallet) -> None: - # test with invalid hash - output_query: MoneroOutputQuery = MoneroOutputQuery() - output_query.set_tx_query(MoneroTxQuery(), True) - assert output_query.tx_query is not None - output_query.tx_query.hash = "invalid_id" - - outputs: list[MoneroOutputWallet] = wallet.get_outputs(output_query) - assert len(outputs) == 0 - - # test invalid hash in list - tx_query: MoneroTxQuery = MoneroTxQuery() - tx_query.is_confirmed = True - tx_query.include_outputs = True - random_txs: list[MoneroTxWallet] = WalletTxsUtils.get_random_transactions(wallet, tx_query, 3, 5) - - for random_tx in random_txs: - assert len(random_tx.outputs) > 0 - - output_query = MoneroOutputQuery() - output_query.set_tx_query(MoneroTxQuery(), False) - assert output_query.tx_query is not None - random_hash: str | None = random_txs[0].hash - assert random_hash is not None and len(random_hash) > 0 - output_query.tx_query.hashes = [random_hash, "invalid_id"] - - outputs = wallet.get_outputs(output_query) - assert len(outputs) > 0 - assert len(outputs) == len(random_txs[0].outputs) - - tx: MoneroTx = outputs[0].tx - assert isinstance(tx, MoneroTxWallet) - - for output in outputs: - assert output.tx == tx - - # Can export outputs in hex format - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False or TestUtils.LITE_MODE, reason="TEST_NON_RELAYS disabled") - def test_export_outputs(self, wallet: MoneroWallet) -> None: - outputs_hex: str = wallet.export_outputs() - logger.debug(f"Exported outputs hex: {outputs_hex}") - # TODO: this will fail if wallet has no outputs; run these tests on new wallet - assert outputs_hex is not None and len(outputs_hex) > 0 - - # wallet exports outputs since last export by default - outputs_hex = wallet.export_outputs() - outputs_hex_all: str = wallet.export_outputs(True) - assert len(outputs_hex_all) > len(outputs_hex) - - # Can import outputs in hex format - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False or TestUtils.LITE_MODE, reason="TEST_NON_RELAYS disabled") - def test_import_outputs(self, wallet: MoneroWallet) -> None: - # export outputs hex - outputs_hex: str = wallet.export_outputs() - logger.debug(f"Exported outputs hex {outputs_hex}") - # import outputs hex - if len(outputs_hex) > 0: - num_imported: int = wallet.import_outputs(outputs_hex) - assert num_imported >= 0 - - # Has correct accounting across accounts, subaddresses, txs, transfers and outputs - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_accounting(self, wallet: MoneroWallet) -> None: - # pre-fetch wallet balances, accounts, subaddresses and txs - wallet_balance: int = wallet.get_balance() - wallet_unlocked_balance: int = wallet.get_unlocked_balance() - # includes subaddresses - accounts: list[MoneroAccount] = wallet.get_accounts(True) - - # test wallet balance - GenUtils.test_unsigned_big_integer(wallet_balance) - GenUtils.test_unsigned_big_integer(wallet_unlocked_balance) - assert wallet_balance >= wallet_unlocked_balance - - # test that wallet balance equals sum of account balances - accounts_balance: int = 0 - accounts_unlocked_balance: int = 0 - for account in accounts: - # test that account balance equals sum of subaddress balances - WalletUtils.test_account(account, TestUtils.NETWORK_TYPE) - assert account.balance is not None - assert account.unlocked_balance is not None - accounts_balance += account.balance - accounts_unlocked_balance += account.unlocked_balance - - assert wallet_balance == accounts_balance - assert wallet_unlocked_balance == accounts_unlocked_balance - - # TODO test that wallet balance equals net of wallet's incoming and outgoing tx amounts - - # balance may not equal sum of unspent outputs if unconfirmed txs - # TODO monero-wallet-rpc: reason not to return unspent outputs on unconfirmed txs? then this isn't necessary - txs: list[MoneroTxWallet] = wallet.get_txs() - has_unconfirmed_tx: bool = False - for tx in txs: - if tx.in_tx_pool: - has_unconfirmed_tx = True - - # wallet balance is sum of all unspent outputs - wallet_sum: int = 0 - output_query: MoneroOutputQuery = MoneroOutputQuery() - output_query.is_spent = False - for output in wallet.get_outputs(output_query): - assert output.amount is not None - wallet_sum += output.amount - - if wallet_balance != wallet_sum: - # txs may have changed in between calls to retry test - wallet_sum = 0 - for output in wallet.get_outputs(output_query): - assert output.amount is not None - wallet_sum += output.amount - - if wallet_balance != wallet_sum: - assert has_unconfirmed_tx, "Wallet balance must equal sum of unspent outputs if no unconfirmed txs" - - # account balances are sum of their unspent outputs - for account in accounts: - account_sum: int = 0 - output_query = MoneroOutputQuery() - output_query.account_index = account.index - output_query.is_spent = False - account_outputs: list[MoneroOutputWallet] = wallet.get_outputs(output_query) - for output in account_outputs: - assert output.amount is not None - account_sum += output.amount - - assert account.balance is not None - if account.balance != account_sum: - assert has_unconfirmed_tx, "Account balance must equal sum of its unspent outputs if no unconfirmed txs" - - # subaddress balances are sum of their unspent outputs - for subaddress in account.subaddresses: - subaddress_sum: int = 0 - output_query = MoneroOutputQuery() - output_query.account_index = account.index - output_query.subaddress_index = subaddress.index - output_query.is_spent = False - subaddress_outputs: list[MoneroOutputWallet] = wallet.get_outputs(output_query) - for output in subaddress_outputs: - assert output.amount is not None - subaddress_sum += output.amount - - if subaddress_sum != subaddress.balance: - assert has_unconfirmed_tx, "Subaddress balance must equal sum of its unspent outputs if no unconfirmed txs" - - # Can check a transfer using the transaction's secret key and the destination - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_check_tx_key(self, wallet: MoneroWallet) -> None: - # get random txs that are confirmed and have outgoing destinations - txs: list[MoneroTxWallet] = [] - try: - query: MoneroTxQuery = MoneroTxQuery() - query.is_confirmed = True - query.transfer_query = MoneroTransferQuery() - query.transfer_query.has_destinations = True - txs = WalletTxsUtils.get_random_transactions(wallet, query, 1, WalletUtils.MAX_TX_PROOFS) - except AssertionError as e: - if "found with" in str(e): - raise Exception("No txs with outgoing destinations found; run send tests") - raise - - # test good checks - assert len(txs) > 0, "No transactions found with outgoing destinations" - for tx in txs: - assert tx.hash is not None - key: str = wallet.get_tx_key(tx.hash) - assert tx.outgoing_transfer is not None - assert len(tx.outgoing_transfer.destinations) > 0 - for destination in tx.outgoing_transfer.destinations: - assert destination.address is not None - check: MoneroCheckTx = wallet.check_tx_key(tx.hash, key, destination.address) - assert destination.amount is not None - if destination.amount > 0: - # TODO monero-wallet-rpc: indicates amount received amount is 0 despite transaction with transfer to this address - # TODO monero-wallet-rpc: returns 0-4 errors, not consistent - assert check.received_amount is not None - if check.received_amount == 0: - msg: str = f"WARNING: key proof indicates no funds received despite transfer (txid={tx.hash}, key={key}, address={destination.address} amount={destination.amount})" - logger.warning(msg) - else: - assert check.received_amount == 0 - TxWalletUtils.test_check_tx(tx, check) - - # test get tx key with invalid hash - with pytest.raises(Exception) as exc_info: - wallet.get_tx_key("invalid_tx_id") - WalletErrorUtils.test_invalid_tx_hash_error(exc_info.value) - # test check with invalid tx hash - tx: MoneroTxWallet = txs[0] - assert tx.hash is not None - key: str = wallet.get_tx_key(tx.hash) - assert tx.outgoing_transfer is not None - destination: MoneroDestination = tx.outgoing_transfer.destinations[0] - assert destination.address is not None - with pytest.raises(Exception) as exc_info: - wallet.check_tx_key("invalid_tx_id", key, destination.address) - WalletErrorUtils.test_invalid_tx_hash_error(exc_info.value) - # test check with invalid key - with pytest.raises(Exception) as exc_info: - wallet.check_tx_key(tx.hash, "invalid_tx_key", destination.address) - WalletErrorUtils.test_invalid_tx_key_error(exc_info.value) - # test check with invalid address - with pytest.raises(Exception) as exc_info: - wallet.check_tx_key(tx.hash, key, "invalid_tx_address") - WalletErrorUtils.test_invalid_address_error(exc_info.value) - # test check with different address - different_address: Optional[str] = None - for a_tx in wallet.get_txs(): - if a_tx.outgoing_transfer is None or len(a_tx.outgoing_transfer.destinations) == 0: - continue - for a_destination in a_tx.outgoing_transfer.destinations: - assert a_destination.address is not None - if a_destination.address != destination.address: - different_address = a_destination.address - break - - assert different_address is not None, "Could not get a different outgoing address to test; run send tests" - check: MoneroCheckTx = wallet.check_tx_key(tx.hash, key, different_address) - assert check.is_good is True - assert check.received_amount is not None - assert check.received_amount >= 0 - TxWalletUtils.test_check_tx(tx, check) - - # Can prove a transaction by getting its signature - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_check_tx_proof(self, wallet: MoneroWallet) -> None: - # get random txs with outgoing destinations - txs: list[MoneroTxWallet] = [] - try: - query: MoneroTxQuery = MoneroTxQuery() - query.transfer_query = MoneroTransferQuery() - query.transfer_query.has_destinations = True - txs = WalletTxsUtils.get_random_transactions(wallet, query, 2, WalletUtils.MAX_TX_PROOFS) - except Exception as e: - if "found with" in str(e): - raise Exception("No txs with outgoing destinations found; run send tests") - raise - - # test good checks with messages - for tx in txs: - assert tx.hash is not None - assert tx.outgoing_transfer is not None - for destination in tx.outgoing_transfer.destinations: - assert destination.address is not None - signature: str = wallet.get_tx_proof(tx.hash, destination.address, "This transaction definitely happened.") - check: MoneroCheckTx = wallet.check_tx_proof(tx.hash, destination.address, "This transaction definitely happened.", signature) - TxWalletUtils.test_check_tx(tx, check) - - # test good check without message - tx: MoneroTx = txs[0] - assert tx.hash is not None - assert tx.outgoing_transfer is not None - assert len(tx.outgoing_transfer.destinations) > 0 - destination: MoneroDestination = tx.outgoing_transfer.destinations[0] - assert destination.address is not None - signature: str = wallet.get_tx_proof(tx.hash, destination.address) - check: MoneroCheckTx = wallet.check_tx_proof(tx.hash, destination.address, '', signature) - TxWalletUtils.test_check_tx(tx, check) - - # test get proof with invalid hash - with pytest.raises(Exception) as exc_info: - wallet.get_tx_proof("invalid_tx_id", destination.address) - WalletErrorUtils.test_invalid_tx_hash_error(exc_info.value) - # test check tx proof with invalid tx hash - with pytest.raises(Exception) as exc_info: - wallet.check_tx_proof("invalid_tx_id", destination.address, '', signature) - WalletErrorUtils.test_invalid_tx_hash_error(exc_info.value) - # test check with invalid address - with pytest.raises(Exception) as exc_info: - wallet.check_tx_proof(tx.hash, "invalid_tx_address", '', signature) - WalletErrorUtils.test_invalid_address_error(exc_info.value) - # test check with wrong message - signature = wallet.get_tx_proof(tx.hash, destination.address, "This is the right message") - check = wallet.check_tx_proof(tx.hash, destination.address, "This is the wrong message", signature) - assert check.is_good is False - TxWalletUtils.test_check_tx(tx, check) - - # test check with wrong signature - other_tx: MoneroTxWallet = txs[1] - assert other_tx.hash is not None - assert other_tx.outgoing_transfer is not None - assert len(other_tx.outgoing_transfer.destinations) > 0 - address: Optional[str] = other_tx.outgoing_transfer.destinations[0].address - assert address is not None - wrong_signature: str = wallet.get_tx_proof(other_tx.hash, address, "This is the right message") - try: - check = wallet.check_tx_proof(tx.hash, destination.address, "This is the right message", wrong_signature) - assert check.is_good is False - except Exception as e: - WalletErrorUtils.test_invalid_signature_error(e) - - # test check with empty signature - try: - check = wallet.check_tx_proof(tx.hash, destination.address, "This is the right message", "") - assert check.is_good is False - except Exception as e: - assert str(e) == "Must provide signature to check tx proof" - - # Can prove a spend using a generated signature and no destination public address - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disablde") - def test_check_spend_proof(self, wallet: MoneroWallet) -> None: - # get random confirmed outgoing txs - query: MoneroTxQuery = MoneroTxQuery() - query.is_incoming = False - query.in_tx_pool = False - query.is_failed = False - txs: list[MoneroTxWallet] = WalletTxsUtils.get_random_transactions(wallet, query, 2, WalletUtils.MAX_TX_PROOFS) - for tx in txs: - assert tx.is_confirmed is True - assert len(tx.incoming_transfers) == 0 - assert tx.outgoing_transfer is not None - - # test good checks with messages - for tx in txs: - assert tx.hash is not None - logger.debug(f"Getting tx hash {tx.hash} proof") - signature: str = wallet.get_spend_proof(tx.hash, "I am a message.") - logger.debug(f"Checking tx hash {tx.hash} proof") - result: bool = wallet.check_spend_proof(tx.hash, "I am a message.", signature) - assert result is True - - # test good check without message - tx: MoneroTxWallet = txs[0] - assert tx.hash is not None - signature: str = wallet.get_spend_proof(tx.hash) - result: bool = wallet.check_spend_proof(tx.hash, '', signature) - assert result is True - - # test get proof with invalid hash - with pytest.raises(Exception) as exc_info: - wallet.get_spend_proof("invalid_tx_id") - WalletErrorUtils.test_invalid_tx_hash_error(exc_info.value) - # test check with invalid tx hash - with pytest.raises(Exception) as exc_info: - wallet.check_spend_proof("invalid_tx_id", '', signature) - WalletErrorUtils.test_invalid_tx_hash_error(exc_info.value) - # test check with invalid message - signature = wallet.get_spend_proof(tx.hash, "This is the right message") - result = wallet.check_spend_proof(tx.hash, "This is the wrong message", signature) - assert result is False - - # test check with wrong signature - other_tx: MoneroTxWallet = txs[1] - assert other_tx.hash is not None - signature = wallet.get_spend_proof(other_tx.hash, "This is the right message") - result = wallet.check_spend_proof(tx.hash, "This is the right message", signature) - assert result is False - - # Can prove reserves in the wallet - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disablde") - def test_get_reserve_proof_wallet(self, wallet: MoneroWallet) -> None: - # get proof of entire wallet - signature: str = wallet.get_reserve_proof_wallet("Test message") - - # check proof of entire wallet - check: MoneroCheckReserve = wallet.check_reserve_proof(wallet.get_primary_address(), "Test message", signature) - assert check.is_good is True - TxWalletUtils.test_check_reserve(check) - balance: int = wallet.get_balance() - if balance != check.total_amount: - # TODO monero-wallet-rpc: this check fails with unconfirmed txs - query: MoneroTxQuery = MoneroTxQuery() - query.in_tx_pool = True - unconfirmed_txs: list[MoneroTxWallet] = wallet.get_txs(query) - assert len(unconfirmed_txs) > 0, "Reserve amount must equal balance unless wallet has unconfirmed txs" - - # test different wallet address - different_address: str = WalletTestUtils.get_external_wallet_address() - with pytest.raises(Exception) as exc_info: - wallet.check_reserve_proof(different_address, "Test message", signature) - WalletErrorUtils.test_no_subaddress_error(exc_info.value) - # test subaddress - with pytest.raises(Exception) as exc_info: - address: Optional[str] = wallet.get_subaddress(0, 1).address - assert address is not None - wallet.check_reserve_proof(address, "Test message", signature) - WalletErrorUtils.test_no_subaddress_error(exc_info.value) - # test wrong message - check = wallet.check_reserve_proof(wallet.get_primary_address(), "Wrong message", signature) - # TODO: specifically test reserve checks, probably separate objects - assert check.is_good is False - TxWalletUtils.test_check_reserve(check) - - # test wrong signature - with pytest.raises(Exception) as exc_info: - wallet.check_reserve_proof(wallet.get_primary_address(), "Test message", "wrong signature") - WalletErrorUtils.test_signature_header_error(exc_info.value) - # Can prove reserves in an account - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disablde") - def test_get_reserve_proof_account(self, wallet: MoneroWallet) -> None: - # test proofs of accounts - num_non_zero_tests: int = 0 - msg: str = "Test message" - accounts: list[MoneroAccount] = wallet.get_accounts() - signature: str = '' - for account in accounts: - assert account.balance is not None - assert account.index is not None - if account.balance > 0: - check_amount: int = int(account.balance/2) - signature = wallet.get_reserve_proof_account(account.index, check_amount, msg) - check: MoneroCheckReserve = wallet.check_reserve_proof(wallet.get_primary_address(), msg, signature) - assert check.is_good is True - TxWalletUtils.test_check_reserve(check) - assert check.total_amount is not None - assert check.total_amount >= 0 - num_non_zero_tests += 1 - else: - with pytest.raises(Exception) as exc_info: - wallet.get_reserve_proof_account(account.index, account.balance, msg) - logger.debug(str(exc_info.value)) - - with pytest.raises(Exception) as exc_info: - wallet.get_reserve_proof_account(account.index, TxWalletUtils.MAX_FEE, msg) - logger.debug(str(exc_info.value)) - - assert num_non_zero_tests > 1, "Must have more than one account with non-zero balance; run send-to-multiple tests" - - # test error when not enough balance for requested minimum reserve amount - # TODO monero-project#6595: an over-balance reserve proof should be rejected but isn't - account: MoneroAccount = accounts[0] - assert account.balance is not None - amount: int = account.balance + TxWalletUtils.MAX_FEE - try: - proof: str = wallet.get_reserve_proof_account(0, amount, "Test message") - reserve: MoneroCheckReserve = wallet.check_reserve_proof(wallet.get_primary_address(), "Test message", proof) - logger.warning(f"Got reserve proof despite insufficient balance: {reserve.serialize()}") - except Exception as e: - logger.debug(str(e)) - - # test different wallet address - different_address: str = WalletTestUtils.get_external_wallet_address() - with pytest.raises(Exception) as exc_info: - wallet.check_reserve_proof(different_address, "Test message", signature) - logger.debug(str(exc_info.value)) - - # test subaddress - address: Optional[str] = wallet.get_subaddress(0, 1).address - assert address is not None - with pytest.raises(Exception) as exc_info: - wallet.check_reserve_proof(address, "Test message", signature) - logger.debug(str(exc_info.value)) - - # test wrong message - check: MoneroCheckReserve = wallet.check_reserve_proof(wallet.get_primary_address(), "Wrong message", signature) - # TODO: specifically test reserve checks, probably separate objects - assert check.is_good is False - TxWalletUtils.test_check_reserve(check) - - # test wrong signature - with pytest.raises(Exception) as exc_info: - wallet.check_reserve_proof(wallet.get_primary_address(), "Test message", "wrong signature") - logger.debug(str(exc_info.value)) - - # Can get and set a transaction note - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_set_tx_note(self, wallet: MoneroWallet) -> None: - txs: list[MoneroTxWallet] = WalletTxsUtils.get_random_transactions(wallet, None, 1, 5) - - # set notes - uuid: str = StringUtils.get_random_string() - - for i, tx in enumerate(txs): - tx_hash: str | None = tx.hash - assert tx_hash is not None - wallet.set_tx_note(tx_hash, f"{uuid}{i}") - - # get notes - for i, tx in enumerate(txs): - tx_hash: str | None = tx.hash - assert tx_hash is not None - assert wallet.get_tx_note(tx_hash) == f"{uuid}{i}" - - # Can get and set multiple transaction notes - # TODO why does getting cached txs take 2 seconds when should already be cached? - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_set_tx_notes(self, wallet: MoneroWallet) -> None: - # set tx notes - uuid: str = StringUtils.get_random_string() - txs: list[MoneroTxWallet] = wallet.get_txs() - assert len(txs) >= 3, "Test requires 3 or more wallet transactions run send tests" - tx_hashes: list[str] = [] - tx_notes: list[str] = [] - for i, tx_hash in enumerate(tx_hashes): - assert tx_hash is not None - tx_hashes.append(tx_hash) - tx_notes.append(f"{uuid}{i}") - - wallet.set_tx_notes(tx_hashes, tx_notes) - - # get tx notes - tx_notes: list[str] = wallet.get_tx_notes(tx_hashes) - for i, tx_note in enumerate(tx_notes): - assert f"{uuid}{i}" == tx_note - - # TODO: test that get transaction has note - - # Can export signed key images - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_export_key_images(self, wallet: MoneroWallet) -> None: - result: MoneroKeyImageExportResult = wallet.export_key_images(True) - assert len(result.key_images) > 0, "No signed key images in wallet" - - for image in result.key_images: - assert isinstance(image, MoneroKeyImage) - assert image.hex is not None and len(image.hex) > 0 - assert image.signature is not None and len(image.signature) > 0 - - # wallet exports key images since last export by default - images: MoneroKeyImageExportResult = wallet.export_key_images() - images_all: MoneroKeyImageExportResult = wallet.export_key_images(True) - assert len(images_all.key_images) > len(images.key_images) - - # Can get new key images from the last import - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_new_key_images_from_last_import(self, wallet: MoneroWallet) -> None: - # get outputs hex - outputs_hex: str = wallet.export_outputs() - - # import outputs hex - if outputs_hex != "": - num_imported: int = wallet.import_outputs(outputs_hex) - assert num_imported >= 0 - - # get and test new key images from last import - export_result: MoneroKeyImageExportResult = wallet.get_new_key_images_from_last_import() - if len(export_result.key_images) == 0: - pytest.skip("wallet already knows every output's key image; run after tests that generate new ones") - for image in export_result.key_images: - assert image.hex is not None and len(image.hex) > 0 - assert image.signature is not None and len(image.signature) > 0 - - # Can import key images - # TODO monero-project: importing key images can cause erasure of incoming transfers per wallet2.cpp:11957 - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_import_key_images(self, wallet: MoneroWallet) -> None: - export_result: MoneroKeyImageExportResult = wallet.export_key_images() - assert len(export_result.key_images) > 0, "Wallet does not have any key images run send tests" - result: MoneroKeyImageImportResult = wallet.import_key_images(export_result.key_images) - assert result.height is not None and result.height > 0 - - # determine if non-zero spent and unspent amounts are expected - query: MoneroTxQuery = MoneroTxQuery() - query.is_outgoing = True - query.is_confirmed = True - txs: list[MoneroTxWallet] = wallet.get_txs(query) - balance: int = wallet.get_balance() - has_spent: bool = len(txs) > 0 - has_unspent: bool = balance > 0 - - # test amounts - GenUtils.test_unsigned_big_integer(result.spent_amount, has_spent) - GenUtils.test_unsigned_big_integer(result.unspent_amount, has_unspent) - - # Supports view-only and offline wallets to create, sign and submit transactions - @pytest.mark.skipif(TestUtils.LITE_MODE, reason="LITE_MODE enabled") - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False and TestUtils.TEST_RELAYS is False, reason="TEST_NON_RELAYS and TEST_RELAYS disabled") - def test_view_only_and_offline_wallets(self, wallet: MoneroWallet) -> None: - # create view-only and offline wallets - config: MoneroWalletConfig = MoneroWalletConfig() - config.primary_address = wallet.get_primary_address() - config.private_view_key = wallet.get_private_view_key() - config.restore_height = TestUtils.FIRST_RECEIVE_HEIGHT - view_only_wallet: MoneroWallet = self._create_wallet(config) - - config = MoneroWalletConfig() - config.primary_address = wallet.get_primary_address() - config.private_view_key = wallet.get_private_view_key() - config.private_spend_key = wallet.get_private_spend_key() - config.server = MoneroRpcConnection(TestUtils.OFFLINE_SERVER_URI) - config.restore_height = 0 - offline_wallet: MoneroWallet = self._create_wallet(config) - assert offline_wallet.is_connected_to_daemon() is False - view_only_wallet.sync() - - # test tx signing with wallets - try: - tester: ViewOnlyAndOfflineWalletTester = ViewOnlyAndOfflineWalletTester(wallet, view_only_wallet, offline_wallet) - tester.test() - finally: - self._close_wallet(view_only_wallet) - self._close_wallet(offline_wallet) - - # Can sign and verify messages - # TODO test with view-only wallet - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_sign_and_verify_messages(self, wallet: MoneroWallet) -> None: - msg: str = "This is a super important message which needs to be signed and verified." - subaddress1: MoneroSubaddress = MoneroSubaddress() - subaddress1.account_index = 0 - subaddress1.index = 0 - subaddress2: MoneroSubaddress = MoneroSubaddress() - subaddress2.account_index = 0 - subaddress2.index = 1 - subaddress3: MoneroSubaddress = MoneroSubaddress() - subaddress3.account_index = 1 - subaddress3.index = 0 - subaddresses: list[MoneroSubaddress] = [subaddress1, subaddress2, subaddress3] - - # test signing message with subaddresses - for subaddress in subaddresses: - assert subaddress.account_index is not None - assert subaddress.index is not None - account_idx: int = subaddress.account_index - idx: int = subaddress.index - - # sign and verify message with spend key - signature: str = wallet.sign_message(msg, MoneroMessageSignatureType.SIGN_WITH_SPEND_KEY, account_idx, idx) - result: MoneroMessageSignatureResult = wallet.verify_message(msg, wallet.get_address(account_idx, idx), signature) - WalletUtils.test_message_signature_result(result, True) - assert result.signature_type == MoneroMessageSignatureType.SIGN_WITH_SPEND_KEY - - # verify message with incorrect address - result = wallet.verify_message(msg, wallet.get_address(0, 2), signature) - WalletUtils.test_message_signature_result(result, False) - - # verify message with invalid address - result = wallet.verify_message(msg, "invalid address", signature) - WalletUtils.test_message_signature_result(result, False) - - # verify message with external address - result = wallet.verify_message(msg, WalletTestUtils.get_external_wallet_address(), signature) - WalletUtils.test_message_signature_result(result, False) - - # sign and verify message with view key - signature = wallet.sign_message(msg, MoneroMessageSignatureType.SIGN_WITH_VIEW_KEY, account_idx, idx) - result = wallet.verify_message(msg, wallet.get_address(account_idx, idx), signature) - WalletUtils.test_message_signature_result(result, True) - assert result.signature_type == MoneroMessageSignatureType.SIGN_WITH_VIEW_KEY - - # verify message with incorrect address - result = wallet.verify_message(msg, wallet.get_address(0, 2), signature) - WalletUtils.test_message_signature_result(result, False) - - # verify message with invalid address - result = wallet.verify_message(msg, "invalid address", signature) - WalletUtils.test_message_signature_result(result, False) - - # verify message with external address - result = wallet.verify_message(msg, WalletTestUtils.get_external_wallet_address(), signature) - WalletUtils.test_message_signature_result(result, False) - - # Has an address book - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_address_book(self, wallet: MoneroWallet) -> None: - # initial state - entries: list[MoneroAddressBookEntry] = wallet.get_address_book_entries() - num_entries_start: int = len(entries) - for entry in entries: - WalletUtils.test_address_book_entry(entry) - - # test adding standard addresses - NUM_ENTRIES: int = 5 - address: str = WalletTestUtils.get_external_wallet_address() - indices: list[int] = [] - for i in range(NUM_ENTRIES): - logger.debug(f"Adding address book entry ({i + 1})") - indices.append(wallet.add_address_book_entry(address, "hi there!")) - - entries = wallet.get_address_book_entries() - assert num_entries_start + NUM_ENTRIES == len(entries) - for idx in indices: - found: bool = False - for entry in entries: - if idx == entry.index: - WalletUtils.test_address_book_entry(entry) - assert entry.address == address - assert entry.description == "hi there!" - found = True - break - - assert found, f"Index {idx} not found in address book indices" - - # edit each address book entry - for idx in indices: - wallet.edit_address_book_entry(idx, False, '', True, "hello there!!") - - entries = wallet.get_address_book_entries(indices) - for entry in entries: - assert entry.description == "hello there!!" - - # delete entries at starting index - delete_idx: int = indices[0] - for i in range(len(indices)): - logger.debug(f"Deleting address book entry {i + 1}, delete_idx: {delete_idx}") - wallet.delete_address_book_entry(delete_idx) - entries = wallet.get_address_book_entries() - assert len(entries) == num_entries_start - - # test adding integrated addresses - indices = [] - # payment id less one character - payment_id: str = "03284e41c342f03" - integrated_addresses: dict[int, MoneroIntegratedAddress] = {} - integrated_descriptions: dict[int, str] = {} - for i in range(NUM_ENTRIES): - # create unique integrated address - integrated_address: MoneroIntegratedAddress = wallet.get_integrated_address('', f"{payment_id}{i}") - uuid: str = StringUtils.get_random_string() - idx: int = wallet.add_address_book_entry(integrated_address.integrated_address, uuid) - indices.append(idx) - integrated_addresses[idx] = integrated_address - integrated_descriptions[idx] = uuid - - entries = wallet.get_address_book_entries() - assert len(entries) == num_entries_start + NUM_ENTRIES - for idx in indices: - found: bool = False - for entry in entries: - if idx == entry.index: - WalletUtils.test_address_book_entry(entry) - assert integrated_descriptions[idx] == entry.description - assert integrated_addresses[idx].integrated_address == entry.address - assert entry.payment_id is None - found = True - break - assert found, f"Index {idx} not found in address bool indices" - - # delete entries at starting index - delete_idx = indices[0] - for i in range(len(indices)): - logger.debug(f"Deleting address book entry {i + 1}") - wallet.delete_address_book_entry(delete_idx) - - entries = wallet.get_address_book_entries() - assert num_entries_start == len(entries) - - # Can get and set arbitrary key/value attributes - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_set_attributes(self, wallet: MoneroWallet) -> None: - # set attributes - attrs: dict[str, str] = {} - for i in range(5): - key: str = f"attr{i}" - val: str = StringUtils.get_random_string() - attrs[key] = val - wallet.set_attribute(key, val) - - # test attributes - for key in attrs: - val = attrs[key] - assert val == wallet.get_attribute(key) - - # get an undefined attribute - assert wallet.get_attribute("unset_key") == "" - - # Can convert between a tx config and payment URI - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_payment_uri(self, wallet: MoneroWallet) -> None: - # test with address and amount - config1: MoneroTxConfig = MoneroTxConfig() - dest: MoneroDestination = MoneroDestination() - dest.address = wallet.get_address(0, 0) - dest.amount = 0 - config1.destinations.append(dest) - uri: str = wallet.get_payment_uri(config1) - config2: MoneroTxConfig = wallet.parse_payment_uri(uri) - AssertUtils.assert_equals(config1, config2) - - # test with subaddress and all fields - subaddress: MoneroSubaddress = wallet.get_subaddress(0, 1) - assert subaddress.address is not None - config1.destinations[0].address = subaddress.address - config1.destinations[0].amount = 425000000000 - config1.recipient_name = "John Doe" - config1.note = "OMZG XMR FTW" - uri = wallet.get_payment_uri(config1) - config2 = wallet.parse_payment_uri(uri) - AssertUtils.assert_equals(config1, config2) - - # test with undefined address - address: str | None = config1.destinations[0].address - config1.destinations[0].address = None - with pytest.raises(Exception, match="Cannot make URI from supplied parameters"): - wallet.get_payment_uri(config1) - - config1.destinations[0].address = address - - # test with standalone payment id - config1.payment_id = "03284e41c342f03603284e41c342f03603284e41c342f03603284e41c342f036" - with pytest.raises(Exception, match="Cannot make URI from supplied parameters"): - wallet.get_payment_uri(config1) - - # Can start and stop mining - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_mining(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: - status: MoneroMiningStatus = daemon.get_mining_status() - if status.is_active: - wallet.stop_mining() - wallet.start_mining(1, False, True) - wallet.stop_mining() - - # Can change the wallet password - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_change_password(self) -> None: - # create random wallet - config: MoneroWalletConfig = MoneroWalletConfig() - config.password = TestUtils.WALLET_PASSWORD - wallet: MoneroWallet = self._create_wallet(config) - path: str = wallet.get_path() - - # change password - new_password: str = "" - wallet.change_password(TestUtils.WALLET_PASSWORD, new_password) - - # close wallet without saving - self._close_wallet(wallet) - - # old password does not work (password change is auto saved) - config = MoneroWalletConfig() - config.path = path - config.password = TestUtils.WALLET_PASSWORD - with pytest.raises(Exception) as exc_info: - self._open_wallet(config) - # TODO: different errors from rpc and wallet2 - e_str = str(exc_info.value).lower() - assert "failed to open wallet" in e_str or "invalid password" in e_str - - # open wallet with new password - config = MoneroWalletConfig() - config.path = path - config.password = new_password - wallet = self._open_wallet(config) - - # change password with incorrect password - with pytest.raises(Exception) as exc_info: - wallet.change_password("badpassword", new_password) - assert "Invalid original password." == str(exc_info.value) - # save and close - self._close_wallet(wallet, True) - - # open wallet - config = MoneroWalletConfig() - config.path = path - config.password = new_password - wallet = self._open_wallet(config) - - # close wallet - self._close_wallet(wallet) - - # Can save and close the wallet in a single call - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_save_and_close(self) -> None: - # create random wallet - password: str = "" - config: MoneroWalletConfig = MoneroWalletConfig() - config.password = password - wallet: MoneroWallet = self._create_wallet(config) - path: str = wallet.get_path() - - # set an attribute - uuid: str = StringUtils.get_random_string() - wallet.set_attribute("id", uuid) - - # close the wallet without saving - self._close_wallet(wallet) - - # re-open the wallet and ensure attribute was not saved - config = MoneroWalletConfig() - config.path = path - config.password = password - wallet = self._open_wallet(config) - assert wallet.get_attribute("id") == "" - - # set the attribute and close with saving - wallet.set_attribute("id", uuid) - self._close_wallet(wallet, True) - - # re-open the wallet and ensure attribute was saved - wallet = self._open_wallet(config) - assert uuid == wallet.get_attribute("id") - self._close_wallet(wallet) - - # Can freeze and thaw outputs - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_freeze_outputs(self, wallet: MoneroWallet) -> None: - # get an available output - output_query: MoneroOutputQuery = MoneroOutputQuery() - output_query.is_spent = False - output_query.is_frozen = False - output_query.set_tx_query(MoneroTxQuery(), True) - assert output_query.tx_query is not None - output_query.tx_query.is_locked = False - outputs: list[MoneroOutputWallet] = wallet.get_outputs(output_query) - assert len(outputs) > 0 - for output in outputs: - assert output.is_frozen is False - - output: MoneroOutputWallet = outputs[0] - assert output.tx is not None - assert isinstance(output.tx, MoneroTxWallet) - assert output.tx.is_locked is False - assert output.is_spent is False - assert output.is_frozen is False - assert output.key_image is not None - assert output.key_image.hex is not None - assert wallet.is_output_frozen(output.key_image.hex) is False - - # freeze output by key image - output_query = MoneroOutputQuery() - output_query.is_frozen = True - num_frozen_before: int = len(wallet.get_outputs(output_query)) - wallet.freeze_output(output.key_image.hex) - is_frozen: bool = wallet.is_output_frozen(output.key_image.hex) - assert is_frozen - - # test querying - frozen_outputs: list[MoneroOutputWallet] = wallet.get_outputs(output_query) - num_frozen: int = len(frozen_outputs) - assert num_frozen == num_frozen_before + 1 - output_query = MoneroOutputQuery() - output_query.key_image = MoneroKeyImage() - output_query.key_image.hex = output.key_image.hex - output_query.is_frozen = True - outputs = wallet.get_outputs(output_query) - assert len(outputs) == 1 - output_frozen: MoneroOutputWallet = outputs[0] - assert output_frozen.is_frozen is True - assert output_frozen.key_image is not None - assert output.key_image.hex == output_frozen.key_image.hex - - # try to sweep frozen output - tx_config: MoneroTxConfig = MoneroTxConfig() - tx_config.address = wallet.get_primary_address() - tx_config.key_image = output.key_image.hex - with pytest.raises(Exception) as exc_info: - wallet.sweep_output(tx_config) - assert str(exc_info.value) == "No outputs found" - - # try to freeze empty key image - with pytest.raises(Exception) as exc_info: - wallet.freeze_output("") - assert str(exc_info.value) == "Must specify key image to freeze" - - # try to freeze bad key image - with pytest.raises(Exception) as exc_info: - wallet.freeze_output("123") - assert str(exc_info.value) == "failed to parse key image" - - # thaw output by key image - wallet.thaw_output(output.key_image.hex) - is_frozen = wallet.is_output_frozen(output.key_image.hex) - assert is_frozen is False - - # test querying - output_query = MoneroOutputQuery() - output_query.is_frozen = True - assert num_frozen_before == len(wallet.get_outputs(output_query)) - - output_query = MoneroOutputQuery() - output_query.key_image = MoneroKeyImage() - output_query.key_image.hex = output.key_image.hex - output_query.is_frozen = True - outputs = wallet.get_outputs(output_query) - assert len(outputs) == 0 - - output_query.is_frozen = False - outputs = wallet.get_outputs(output_query) - assert len(outputs) == 1 - - output_thawed: MoneroOutputWallet = outputs[0] - assert output_thawed.is_frozen is False - assert output_thawed.key_image is not None - assert output_thawed.key_image.hex == output.key_image.hex - - # Provides key images of spent outputs - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_input_key_images(self, wallet: MoneroWallet) -> None: - # get subaddress to test input key images - subaddress: Optional[MoneroSubaddress] = WalletTestUtils.select_subaddress_with_min_balance(wallet, TxWalletUtils.MAX_FEE) - assert subaddress is not None, "No subaddress with outputs found for test input key images; fund wallet" - assert subaddress.account_index is not None - assert subaddress.index is not None - account_index: int = subaddress.account_index - subaddress_index: int = subaddress.index - - # test unrelayed single transaction - tx_config: MoneroTxConfig = MoneroTxConfig() - tx_config.account_index = account_index - tx_config.destinations.append(MoneroDestination(wallet.get_primary_address(), TxWalletUtils.MAX_FEE)) - spend_tx: MoneroTxWallet = wallet.create_tx(tx_config) - TxWalletUtils.test_spend_tx(spend_tx) - - # test unrelayed split transactions - txs: list[MoneroTxWallet] = wallet.create_txs(tx_config) - for tx in txs: - TxWalletUtils.test_spend_tx(tx) - - # test unrelayed sweep dust - dust_key_images: list[str] = [] - txs = wallet.sweep_dust(False) - for tx in txs: - TxWalletUtils.test_spend_tx(tx) - for tx_input in tx.inputs: - assert tx_input.key_image is not None - assert tx_input.key_image.hex is not None - dust_key_images.append(tx_input.key_image.hex) - - # get available outputs above min amount - output_query: MoneroOutputQuery = MoneroOutputQuery() - output_query.account_index = account_index - output_query.subaddress_index = subaddress_index - output_query.is_spent = False - output_query.is_frozen = False - output_query.min_amount = TxWalletUtils.MAX_FEE - output_query.set_tx_query(MoneroTxQuery(), True) - assert output_query.tx_query is not None - output_query.tx_query.is_locked = False - outputs: list[MoneroOutputWallet] = wallet.get_outputs(output_query) - - assert len(outputs) > 0, "No outputs found" - logger.debug(f"Found {len(outputs)} outputs") - - # filter dust outputs - dust_outputs: list[MoneroOutputWallet] = [] - for output in outputs: - assert output.key_image is not None - assert output.key_image.hex is not None - if output.key_image.hex in dust_key_images: - dust_outputs.append(output) - - logger.debug(f"Found {len(dust_outputs)} dust outputs") - - # remove dust outputs from outputs - outputs = list(filter(lambda output: output not in dust_outputs, outputs)) - - assert len(outputs) > 0, "No available outputs found" - logger.debug(f"Using {len(outputs)} available outputs") - - # test unrelayed sweep output - tx_config = MoneroTxConfig() - tx_config.address = wallet.get_primary_address() - output_key_image: MoneroKeyImage | None = outputs[0].key_image - assert output_key_image is not None - tx_config.key_image = output_key_image.hex - spend_tx = wallet.sweep_output(tx_config) - TxWalletUtils.test_spend_tx(spend_tx) - - # test unrelayed sweep wallet ensuring all non-dust outputs are spent - available_key_images: set[str] = set() - for output in outputs: - assert output.key_image is not None - assert output.key_image.hex is not None - available_key_images.add(output.key_image.hex) - swept_key_images: set[str] = set() - tx_config = MoneroTxConfig() - tx_config.account_index = account_index - tx_config.subaddress_indices.append(subaddress_index) - tx_config.address = wallet.get_primary_address() - txs = wallet.sweep_unlocked(tx_config) - - for tx in txs: - TxWalletUtils.test_spend_tx(tx) - for input_wallet in tx.inputs: - assert input_wallet.key_image is not None - assert input_wallet.key_image.hex is not None - swept_key_images.add(input_wallet.key_image.hex) - - assert len(swept_key_images) > 0 - - # max skipped output is less than max fee amount - max_skipped_output: Optional[MoneroOutputWallet] = None - for output in outputs: - assert output.key_image is not None - assert output.key_image.hex is not None - assert output.amount is not None - if output.key_image.hex not in swept_key_images: - if max_skipped_output is None or max_skipped_output.amount < output.amount: # type: ignore - max_skipped_output = output - - if max_skipped_output is not None: - assert max_skipped_output.amount is not None - assert max_skipped_output.amount < TxWalletUtils.MAX_FEE - - # Can prove unrelayed txs - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_prove_unrelayed_txs(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: - # create unrelayed tx to verify - address1: str = WalletTestUtils.get_external_wallet_address() - address2: str = wallet.get_address(0, 0) - address3: str = wallet.get_address(1, 0) - tx_config: MoneroTxConfig = MoneroTxConfig() - tx_config.account_index = 0 - tx_config.destinations.append(MoneroDestination(address1, TxWalletUtils.MAX_FEE)) - tx_config.destinations.append(MoneroDestination(address2, TxWalletUtils.MAX_FEE * 2)) - tx_config.destinations.append(MoneroDestination(address3, TxWalletUtils.MAX_FEE * 3)) - tx: MoneroTxWallet = wallet.create_tx(tx_config) - assert tx.full_hex is not None - assert tx.hash is not None - assert tx.key is not None - - # submit tx to daemon but do not relay - result: MoneroSubmitTxResult = daemon.submit_tx_hex(tx.full_hex, True) - assert result.is_good - - # create random wallet to verify transfers - verifying_wallet: MoneroWallet = self._create_wallet(MoneroWalletConfig()) - - try: - # verify transfer 1 - check: MoneroCheckTx = verifying_wallet.check_tx_key(tx.hash, tx.key, address1) - assert check.is_good - assert check.in_tx_pool is True - assert check.num_confirmations == 0 - assert check.received_amount == TxWalletUtils.MAX_FEE - - # verify transfer 2 - check = verifying_wallet.check_tx_key(tx.hash, tx.key, address2) - assert check.is_good - assert check.in_tx_pool is True - assert check.num_confirmations == 0 - # + change amount - assert check.received_amount is not None - assert check.received_amount >= TxWalletUtils.MAX_FEE * 2 - - # verify transfer 3 - check = verifying_wallet.check_tx_key(tx.hash, tx.key, address3) - assert check.is_good - assert check.in_tx_pool is True - assert check.num_confirmations == 0 - assert TxWalletUtils.MAX_FEE * 3 == check.received_amount - finally: - # cleanup, otherwise it permanently ties up the dest outputs for entire session - daemon.flush_tx_pool(tx.hash) - self._close_wallet(verifying_wallet) - - # Can get the default fee priority - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_default_fee_priority(self, wallet: MoneroWallet) -> None: - default_priority: MoneroTxPriority = wallet.get_default_fee_priority() - assert int(default_priority) > 0 - - # Can indicate if multisig import is needed for correct balance information - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_is_multisig_needed(self, wallet: MoneroWallet) -> None: - # TODO test with multisig wallet - multisig_import_needed: bool = wallet.is_multisig_import_needed() - assert multisig_import_needed is False, "Expected non-multisig wallet" - - # Can tag accounts and query accounts by tag - @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_account_tags(self, wallet: MoneroWallet) -> None: - # get accounts - accounts: list[MoneroAccount] = wallet.get_accounts() - assert len(accounts) > 3, "Not enough accounts to test; run create account test" - - # tag some of the accounts - tag: MoneroAccountTag = MoneroAccountTag(f"my_tag_{StringUtils.get_random_string()}", "my tag label", [0, 1]) - assert tag.tag is not None - assert tag.label is not None - wallet.tag_accounts(tag.tag, tag.account_indices) - - # query accounts by tag - tagged_accounts: list[MoneroAccount] = wallet.get_accounts(False, tag.tag) - assert len(tagged_accounts) == 2 - assert tagged_accounts[0].index == 0 - assert tagged_accounts[0].tag == tag.tag - assert tagged_accounts[1].index == 1 - assert tagged_accounts[1].tag == tag.tag - - # set tag label - wallet.set_account_tag_label(tag.tag, tag.label) - - # fetch tags and ensure new tag is contained - tags: list[MoneroAccountTag] = wallet.get_account_tags() - found: bool = False - for a_tag in tags: - if a_tag.tag == tag.tag: - found = True - break - assert found, f"Could not find tag: {tag.serialize()}" - logger.debug(f"Found account tag: {tag.serialize()}") - - # re-tag an account - tag2: MoneroAccountTag = MoneroAccountTag(f"my_tag_{StringUtils.get_random_string()}", "my tag label 2", [1]) - assert tag2.tag is not None - assert tag2.label is not None - wallet.tag_accounts(tag2.tag, tag2.account_indices) - tagged_accounts2: list[MoneroAccount] = wallet.get_accounts(False, tag2.tag) - assert len(tagged_accounts2) == 1 - assert tagged_accounts2[0].index == 1 - assert tagged_accounts2[0].tag == tag2.tag - - # re-query original tag which only applies to one account now - tagged_accounts = wallet.get_accounts(False, tag.tag) - assert len(tagged_accounts) == 1 - assert tagged_accounts[0].index == 0 - assert tagged_accounts[0].tag == tag.tag - - # untag and query accounts - wallet.untag_accounts([0, 1]) - assert len(wallet.get_account_tags()) == 0 - with pytest.raises(Exception): - wallet.get_accounts(False, tag.tag) - - # a never-registered tag may raise or return nothing; either is acceptable - try: - assert len(wallet.get_accounts(False, "non_existing_tag")) == 0 - except Exception as e: - logger.debug(f"get_accounts with non-existing tag raised: {e}") - - # endregion - - #region Notification Tests - - # Can stop listening - @pytest.mark.skipif(TestUtils.TEST_NOTIFICATIONS is False, reason="TEST_NOTIFICATIONS disabled") - def test_stop_listening(self) -> None: - # create wallet and start background synchronizing - wallet: MoneroWallet = self._create_wallet(MoneroWalletConfig()) - - # add listener - listener: WalletNotificationCollector = WalletNotificationCollector() - wallet.add_listener(listener) - assert len(wallet.get_listeners()) == 1 - sleep(1) - - # remove listener and close - wallet.remove_listener(listener) - assert len(wallet.get_listeners()) == 0 - self._close_wallet(wallet) - - # Can be created and receive funds - # TODO this test is flaky on monero-wallet-rpc because of mining speed - @pytest.mark.skipif(TestUtils.TEST_NOTIFICATIONS is False, reason="TEST_NOTIFICATIONS disabled") - @pytest.mark.flaky(reruns=5, reruns_delay=10, only_rerun=[]) - def test_create_and_receive(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: - # create random wallet - receiver: MoneroWallet = self._create_wallet(MoneroWalletConfig()) - try: - # listen for received funds - my_listener: WalletNotificationCollector = WalletNotificationCollector() - receiver.add_listener(my_listener) - assert len(receiver.get_listeners()) > 0 - - # wait for txs to confirm and for sufficient unlocked balance - TestUtils.WALLET_TX_TRACKER.wait_for_txs_to_clear_pool(wallet) - TestUtils.WALLET_TX_TRACKER.wait_for_unlocked_balance(wallet, 0, None, TxWalletUtils.MAX_FEE) - - # send funds to the receiver - tx_config: MoneroTxConfig = MoneroTxConfig() - tx_config.account_index = 0 - tx_config.address = receiver.get_primary_address() - tx_config.amount = TxWalletUtils.MAX_FEE - tx_config.relay = True - sent_tx: MoneroTxWallet = wallet.create_tx(tx_config) - assert sent_tx.hash is not None - - # wait for funds to confirm - MiningUtils.try_start_mining() - while True: - tx: MoneroTxWallet | None = wallet.get_tx(sent_tx.hash) - assert tx is not None - assert tx.is_confirmed is not None - if tx.is_confirmed: - logger.debug(f"Confirmed tx at height {tx.get_height()}") - break - - assert tx.is_failed is False, f"Tx failed in mempool: {tx.hash}" - daemon.wait_for_next_block_header() - - # receiver should notify listeners of received outputs within a few rpc refresh / poll periods - deadline: float = monotonic() + TestUtils.SYNC_PERIOD_IN_MS * 10 / 1000 - while len(my_listener.outputs_received) == 0 and monotonic() < deadline: - sleep(1) - assert len(my_listener.outputs_received) > 0 - finally: - logger.debug(f"Closing receiver wallet...") - self._close_wallet(receiver) - logger.debug(f"Closed receiver wallet") - MiningUtils.try_stop_mining() - - #endregion - - #region Reset Tests - - # Can sweep subaddresses - @pytest.mark.skipif(TestUtils.TEST_RESETS is False, reason="TEST_RESETS disabled") - def test_sweep_subaddresses(self, wallet: MoneroWallet) -> None: - TestUtils.WALLET_TX_TRACKER.wait_for_txs_to_clear_pool(wallet) - NUM_SUBADDRESSES_TO_SWEEP: int = 2 - - # collect subaddresses with balance and unlocked balance - subaddresses: list[MoneroSubaddress] = [] - subaddresses_balance: list[MoneroSubaddress] = [] - subaddresses_unlocked: list[MoneroSubaddress] = [] - for account in wallet.get_accounts(True): - if account.index == 0: - # skip default account - continue - for subaddress in account.subaddresses: - subaddresses.append(subaddress) - assert subaddress.balance is not None - if subaddress.balance > TxWalletUtils.MAX_FEE: - subaddresses_balance.append(subaddress) - assert subaddress.unlocked_balance is not None - if subaddress.unlocked_balance > TxWalletUtils.MAX_FEE: - subaddresses_unlocked.append(subaddress) - - # test requires at least one more subaddresses than the number being swept to verify it does not change - msg: str = f"Test requires balance in at least {NUM_SUBADDRESSES_TO_SWEEP + 1} subaddresses from non-default acccount; run send-to-multiple tests" - assert len(subaddresses_balance) >= NUM_SUBADDRESSES_TO_SWEEP + 1, msg - assert len(subaddresses_unlocked) >= NUM_SUBADDRESSES_TO_SWEEP + 1, "Wallet is waiting on unlocked funds" - - # sweep from first unlocked subaddresses - for i in range(NUM_SUBADDRESSES_TO_SWEEP): - # sweep unlocked account - unlocked_subaddress: MoneroSubaddress = subaddresses_unlocked[i] - config: MoneroTxConfig = MoneroTxConfig() - config.address = wallet.get_primary_address() - assert unlocked_subaddress.account_index is not None - assert unlocked_subaddress.index is not None - config.account_index = unlocked_subaddress.account_index - config.subaddress_indices.append(unlocked_subaddress.index) - config.relay = True - txs: list[MoneroTxWallet] = wallet.sweep_unlocked(config) - - # test transactions - assert len(txs) > 0 - for tx in txs: - assert tx.tx_set is not None - assert tx in tx.tx_set.txs - ctx: TxContext = TxContext() - ctx.wallet = wallet - ctx.config = config - ctx.is_send_response = True - ctx.is_sweep_response = True - TxWalletUtils.test_tx_wallet(tx, ctx) - - # assert unlocked balance is less than max fee - subaddress: MoneroSubaddress = wallet.get_subaddress(unlocked_subaddress.account_index, unlocked_subaddress.index) - assert subaddress.unlocked_balance is not None - assert subaddress.unlocked_balance < TxWalletUtils.MAX_FEE - - # test subaddresses after sweeping - subaddresses_after: list[MoneroSubaddress] = [] - for account in wallet.get_accounts(True): - if account.index == 0: - # skip default account - continue - for subaddress in account.subaddresses: - subaddresses_after.append(subaddress) - - assert len(subaddresses) == len(subaddresses_after) - for i, subaddress_before in enumerate(subaddresses): - subaddress_after: MoneroSubaddress = subaddresses_after[i] - assert subaddress_after.unlocked_balance is not None - - # determine if subaddress was swept - swept: bool = False - for j in range(NUM_SUBADDRESSES_TO_SWEEP): - subaddress_unlocked: MoneroSubaddress = subaddresses_unlocked[j] - account_eq: bool = subaddress_unlocked.account_index == subaddress_before.account_index - subaddr_eq: bool = subaddress_unlocked.index == subaddress_before.index - if account_eq and subaddr_eq: - swept = True - break - - # assert unlocked balance is less than max fee if swept, unchanged otherwise - if swept: - assert subaddress_after.unlocked_balance < TxWalletUtils.MAX_FEE - else: - assert subaddress_before.unlocked_balance == subaddress_after.unlocked_balance - - # Can sweep accounts - @pytest.mark.skipif(TestUtils.TEST_RESETS is False, reason="TEST_RESETS disabled") - def test_sweep_accounts(self, wallet: MoneroWallet) -> None: - TestUtils.WALLET_TX_TRACKER.wait_for_txs_to_clear_pool(wallet) - NUM_ACCOUNTS_TO_SWEEP: int = 1 - - # collect accounts with sufficient balance and unlocked balance to cover the fee - accounts: list[MoneroAccount] = wallet.get_accounts(True) - accounts_balance: list[MoneroAccount] = [] - accounts_unlocked: list[MoneroAccount] = [] - for account in accounts: - if account.index == 0: - # skip default account - continue - assert account.balance is not None - assert account.unlocked_balance is not None - if account.balance > TxWalletUtils.MAX_FEE: - accounts_balance.append(account) - if account.unlocked_balance > TxWalletUtils.MAX_FEE: - accounts_unlocked.append(account) - - # test requires at least one more accounts than the number being swept to verify it does not change - - msg: str = f"Test requires balance greater than the fee in at least {NUM_ACCOUNTS_TO_SWEEP + 1} non-default accounts; run send-to-multiple tests" - assert len(accounts_balance) >= NUM_ACCOUNTS_TO_SWEEP + 1, msg - assert len(accounts_unlocked) >= NUM_ACCOUNTS_TO_SWEEP + 1, "Wallet is waiting on unlocked funds" - - # sweep from first unlocked accounts - for i in range(NUM_ACCOUNTS_TO_SWEEP): - # sweep unlocked account - unlocked_account: MoneroAccount = accounts_unlocked[i] - assert unlocked_account.index is not None - config: MoneroTxConfig = MoneroTxConfig() - config.address = wallet.get_primary_address() - config.account_index = unlocked_account.index - config.relay = True - txs: list[MoneroTxWallet] = wallet.sweep_unlocked(config) - - # test transactions - assert len(txs) > 0 - for tx in txs: - ctx: TxContext = TxContext() - ctx.wallet = wallet - ctx.config = config - ctx.is_send_response = True - ctx.is_sweep_response = True - TxWalletUtils.test_tx_wallet(tx, ctx) - assert tx.tx_set is not None - assert tx in tx.tx_set.txs - - # assert unlocked account balance less than max fee - account: MoneroAccount = wallet.get_account(unlocked_account.index) - - # test accounts after sweeping - accounts_after: list[MoneroAccount] = wallet.get_accounts(True) - assert len(accounts) == len(accounts_after) - for i, account_before in enumerate(accounts): - account_after: MoneroAccount = accounts_after[i] - assert account_after.unlocked_balance is not None - - # determine if account was swept - swept: bool = False - for j in range(NUM_ACCOUNTS_TO_SWEEP): - account_unlocked: MoneroAccount = accounts_unlocked[j] - if account_unlocked.index == account_before.index: - swept = True - break - - # assert unlocked balance is less than max fee if swept, unchanged otherwise - if swept: - assert account_after.unlocked_balance < TxWalletUtils.MAX_FEE - else: - assert account_after.unlocked_balance == account_after.unlocked_balance - - # Can sweep the whole wallet by accounts - @pytest.mark.skipif(TestUtils.TEST_RESETS is False, reason="TEST_RESETS disabled") - def test_sweep_wallet_by_accounts(self, wallet: MoneroWallet) -> None: - IntegrationTestUtils.fund_wallet_and_wait_for_unlocked(wallet) - WalletSendUtils.test_sweep_wallet(wallet, None) - - # Can sweep the whole wallet by subaddresses - @pytest.mark.skipif(TestUtils.TEST_RESETS is False, reason="TEST_RESETS disabled") - @pytest.mark.xfail(reason="TODO wallet2 error: No unlocked balance in the specified subaddress(es)") - def test_sweep_wallet_by_subaddresses(self, wallet: MoneroWallet) -> None: - IntegrationTestUtils.fund_wallet_and_wait_for_unlocked(wallet) - WalletSendUtils.test_sweep_wallet(wallet, True) - - # Can scan transactions by id - @pytest.mark.skipif(TestUtils.TEST_RESETS is False, reason="TEST_RESETS disabled") - def test_scan_txs(self, wallet: MoneroWallet) -> None: - config: MoneroWalletConfig = MoneroWalletConfig() - config.seed = wallet.get_seed() - config.restore_height = 0 - scan_wallet: MoneroWallet = self._create_wallet(config) - logger.debug("Created scan wallet") - WalletTxsUtils.test_scan_txs(wallet, scan_wallet) - - # Can rescan spent - @pytest.mark.skipif(TestUtils.TEST_RESETS is False, reason="TEST_RESETS disabled") - def test_rescan_spent(self, wallet: MoneroWallet) -> None: - wallet.rescan_spent() - - # Can rescan the blockchain - @pytest.mark.skipif(TestUtils.TEST_RESETS is False, reason="TEST_RELAYS disabled") - @pytest.mark.skip(reason="Disabled so tests don't delete local cache") - def test_rescan_blockchain(self, wallet: MoneroWallet) -> None: - wallet.rescan_blockchain() - for tx in wallet.get_txs(): - TxWalletUtils.test_tx_wallet(tx) - - #endregion - - #region Utils - - def _test_multisig_sample(self, m: int, n: int) -> None: - """ - Test multisig sample code. - - :param int m: multisig threshold. - :param int n: number of participants. - """ - # create participant wallets - wallets: list[MoneroWallet] = [] - - for i in range(n): - wallets.append(self._create_wallet(MoneroWalletConfig())) - logger.debug(f"Created multisig wallet participant {i + 1}") - - tester: MultisigSampleCodeTester = MultisigSampleCodeTester(m, wallets) - tester.test() - - if self.get_wallet_type() == WalletType.RPC: - TestUtils.free_wallet_rpc_resources() - - #endregion - - #endregion diff --git a/tests/test_monero_wallet_full.py b/tests/test_monero_wallet_full.py deleted file mode 100644 index 70672a17..00000000 --- a/tests/test_monero_wallet_full.py +++ /dev/null @@ -1,815 +0,0 @@ -import pytest -import logging -import os - -from typing import Optional -from typing_extensions import override - -from time import sleep -from monero import ( - MoneroWalletFull, MoneroWalletConfig, MoneroAccount, - MoneroSubaddress, MoneroWallet, MoneroNetworkType, - MoneroRpcConnection, MoneroUtils, MoneroDaemonRpc, - MoneroSyncResult, MoneroTxWallet, MoneroKeyImage -) - -from utils import ( - TestUtils as Utils, StringUtils, BaseTestClass, - AssertUtils, WalletUtils, WalletType, - SyncSeedTester, SyncProgressTester, - WalletEqualityUtils, WalletErrorUtils, MiningUtils -) -from test_monero_wallet_common import BaseTestMoneroWallet - -logger: logging.Logger = logging.getLogger("TestMoneroWalletFull") - - -@pytest.mark.integration -class TestMoneroWalletFull(BaseTestMoneroWallet): - """Full wallet integration tests.""" - - #region Overrides - - @classmethod - @override - def get_wallet_type(cls) -> WalletType: - return WalletType.FULL - - @pytest.fixture(scope="class") - @classmethod - @override - def wallet(cls) -> MoneroWalletFull: - """Test rpc wallet instance""" - return Utils.get_wallet_full() - - @override - def after_all(self) -> None: - super().after_all() - Utils.WALLET_FULL_TESTS_RUN = True - - @override - def _create_wallet(self, config: Optional[MoneroWalletConfig], start_syncing: bool = True) -> MoneroWalletFull: - # assign defaults - if config is None: - config = MoneroWalletConfig() - random: bool = self.is_random_wallet_config(config) - if config.path is None: - config.path = Utils.TEST_WALLETS_DIR + "/" + StringUtils.get_random_string() - if config.password is None: - config.password = Utils.WALLET_PASSWORD - if config.network_type is None: - config.network_type = Utils.NETWORK_TYPE - if config.server is None: - config.server = Utils.get_daemon_rpc_connection() - if config.restore_height is None and not random: - config.restore_height = 0 - - config.regtest = config.network_type == MoneroNetworkType.MAINNET and Utils.REGTEST - - # create wallet - wallet: MoneroWalletFull = MoneroWalletFull.create_wallet(config) - if not random: - assert config.restore_height == wallet.get_restore_height() - if start_syncing is not False and wallet.is_connected_to_daemon(): - wallet.start_syncing(Utils.SYNC_PERIOD_IN_MS) - return wallet - - @override - def _open_wallet(self, config: Optional[MoneroWalletConfig], start_syncing: bool = True) -> MoneroWalletFull: - # assign defaults - if config is None: - config = MoneroWalletConfig() - if config.password is None: - config.password = Utils.WALLET_PASSWORD - if config.network_type is None: - config.network_type = Utils.NETWORK_TYPE - if config.server is None: - config.server = Utils.get_daemon_rpc_connection() - - # open wallet - assert config.network_type is not None - assert config.path is not None - - wallet: MoneroWalletFull = MoneroWalletFull.open_wallet(config.path, config.password, config.network_type) - wallet.set_daemon_connection(config.server) - if start_syncing is not False and wallet.is_connected_to_daemon(): - wallet.start_syncing(Utils.SYNC_PERIOD_IN_MS) - return wallet - - @override - def _close_wallet(self, wallet: MoneroWallet, save: bool = False) -> None: - wallet.close(save) - - @override - def _get_seed_languages(self) -> list[str]: - return self.get_test_wallet().get_seed_languages() - - @override - @classmethod - def get_test_wallet(cls) -> MoneroWalletFull: - return super().get_test_wallet() # type: ignore - - #endregion - - #region Test Non Relays - - # TODO implement - @pytest.mark.not_implemented - @override - def test_account_tags(self, wallet: MoneroWallet) -> None: - return super().test_account_tags(wallet) - - # Can create a random full wallet - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_create_wallet_random_full(self, daemon: MoneroDaemonRpc) -> None: - # create random wallet with defaults - path: str = Utils.get_random_wallet_path() - config: MoneroWalletConfig = MoneroWalletConfig() - config.path = path - config.network_type = MoneroNetworkType.MAINNET - config.server = MoneroRpcConnection(Utils.OFFLINE_SERVER_URI) - wallet: MoneroWalletFull = self._create_wallet(config) - MoneroUtils.validate_mnemonic(wallet.get_seed()) - MoneroUtils.validate_address(wallet.get_primary_address(), MoneroNetworkType.MAINNET) - assert wallet.get_network_type() == MoneroNetworkType.MAINNET - AssertUtils.assert_equals(wallet.get_daemon_connection(), MoneroRpcConnection(Utils.OFFLINE_SERVER_URI)) - assert wallet.is_connected_to_daemon() is False - assert wallet.get_seed_language() == "English" - assert wallet.get_path() == path - assert wallet.is_synced() is False - # TODO monero-project: why does height of new unsynced wallet start at 1? - assert wallet.get_height() == 1 - assert wallet.get_restore_height() >= 0 - - # cannot get daemon chain height: wallet2 masks errors from untrusted daemons - with pytest.raises(Exception) as exc_info: - wallet.get_daemon_height() - assert str(exc_info.value) == "daemon error" - - # set daemon and check chain height - wallet.set_daemon_connection(daemon.get_rpc_connection()) - assert daemon.get_height() == wallet.get_daemon_height() - - # close wallet which releases resources - wallet.close() - - # create random wallet with non defaults - path = Utils.get_random_wallet_path() - config = MoneroWalletConfig() - config.path = path - config.network_type = MoneroNetworkType.TESTNET - config.language = "Spanish" - wallet = self._create_wallet(config, False) - MoneroUtils.validate_mnemonic(wallet.get_seed()) - MoneroUtils.validate_address(wallet.get_primary_address(), MoneroNetworkType.TESTNET) - assert wallet.get_network_type() == MoneroNetworkType.TESTNET - assert wallet.get_daemon_connection() is not None - assert wallet.get_daemon_connection() != daemon.get_rpc_connection() - AssertUtils.assert_equals(wallet.get_daemon_connection(), daemon.get_rpc_connection()) - assert wallet.is_connected_to_daemon() - assert wallet.get_seed_language() == "Spanish" - assert path == wallet.get_path() - assert wallet.is_synced() is False - # TODO monero-project: why is height of unsynced wallet 1? - assert wallet.get_height() == 1 - if daemon.is_connected(): - assert daemon.get_height() == wallet.get_restore_height() - else: - assert wallet.get_restore_height() >= 0 - - wallet.close() - - # Can create a full wallet from seed - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_create_wallet_from_seed_full(self, daemon: MoneroDaemonRpc) -> None: - # create unconnected wallet with seed - path: str = Utils.get_random_wallet_path() - config: MoneroWalletConfig = MoneroWalletConfig() - config.path = path - config.seed = Utils.SEED - config.server = MoneroRpcConnection(Utils.OFFLINE_SERVER_URI) - wallet: MoneroWalletFull = self._create_wallet(config) - assert wallet.get_seed() == Utils.SEED - assert wallet.get_primary_address() == Utils.ADDRESS - assert wallet.get_network_type() == Utils.NETWORK_TYPE - AssertUtils.assert_equals(MoneroRpcConnection(Utils.OFFLINE_SERVER_URI), wallet.get_daemon_connection()) - assert wallet.is_connected_to_daemon() is False - assert wallet.get_seed_language() == "English" - assert wallet.get_path() == path - assert wallet.is_synced() is False - assert wallet.get_height() == 1 - assert wallet.get_restore_height() == 0 - wallet.start_syncing() # succeeds while offline, syncing when a daemon becomes reachable - - wallet.close() - - # create wallet without restore height - path = Utils.get_random_wallet_path() - config = MoneroWalletConfig() - config.path = path - config.seed = Utils.SEED - wallet = self._create_wallet(config, False) - assert wallet.get_seed() == Utils.SEED - assert wallet.get_primary_address() == Utils.ADDRESS - assert wallet.get_network_type() == Utils.NETWORK_TYPE - assert wallet.get_daemon_connection() is not None - assert wallet.get_daemon_connection() != daemon.get_rpc_connection() - AssertUtils.assert_equals(wallet.get_daemon_connection(), daemon.get_rpc_connection()) - assert wallet.is_connected_to_daemon() - assert wallet.get_seed_language() == "English" - assert wallet.get_path() == path - assert wallet.is_synced() is False - assert wallet.get_height() == 1 - # TODO (java annotation) restore height is lost after closing only in JNI - assert wallet.get_restore_height() == 0 - wallet.close() - - # create wallet with seed, no connection, and restore height - restore_height: int = 10000 - path = Utils.get_random_wallet_path() - config = MoneroWalletConfig() - config.path = path - config.seed = Utils.SEED - config.restore_height = restore_height - config.server = MoneroRpcConnection(Utils.OFFLINE_SERVER_URI) - wallet = self._create_wallet(config) - assert wallet.get_seed() == Utils.SEED - assert wallet.get_primary_address() == Utils.ADDRESS - assert wallet.get_network_type() == Utils.NETWORK_TYPE - AssertUtils.assert_equals(MoneroRpcConnection(Utils.OFFLINE_SERVER_URI), wallet.get_daemon_connection()) - assert wallet.is_connected_to_daemon() is False - assert wallet.get_seed_language() == "English" - # TODO monero-project: why does height of new unsynced wallet start at 1? - assert wallet.get_height() == 1 - assert wallet.get_restore_height() == restore_height - assert wallet.get_path() == path - wallet.close(True) - config = MoneroWalletConfig() - config.path = path - config.server = MoneroRpcConnection(Utils.OFFLINE_SERVER_URI) - wallet = self._open_wallet(config) - assert wallet.is_connected_to_daemon() is False - assert wallet.is_synced() is False - assert wallet.get_height() == 1 - assert wallet.get_restore_height() == restore_height - wallet.close() - - # create wallet with seed, connection, and restore height - path = Utils.get_random_wallet_path() - config = MoneroWalletConfig() - config.path = path - config.seed = Utils.SEED - config.restore_height = restore_height - wallet = self._create_wallet(config, False) - assert wallet.get_seed() == Utils.SEED - assert wallet.get_primary_address() == Utils.ADDRESS - assert wallet.get_network_type() == Utils.NETWORK_TYPE - assert wallet.get_daemon_connection() is not None - assert wallet.get_daemon_connection() != daemon.get_rpc_connection() - AssertUtils.assert_equals(wallet.get_daemon_connection(), daemon.get_rpc_connection()) - assert wallet.is_connected_to_daemon() - assert wallet.get_seed_language() == "English" - assert wallet.get_path() == path - assert wallet.is_synced() is False - # TODO monero-project: why does height of new unsynced wallet start at 1? - assert wallet.get_height() == 1 - assert wallet.get_restore_height() == restore_height - wallet.close() - - # Can create a full wallet from keys - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_create_wallet_from_keys_pybind(self, wallet: MoneroWalletFull) -> None: - # recreate test wallet from keys - path: str = Utils.get_random_wallet_path() - config: MoneroWalletConfig = MoneroWalletConfig() - config.path = path - config.primary_address = wallet.get_primary_address() - config.private_view_key = wallet.get_private_view_key() - config.private_spend_key = wallet.get_private_spend_key() - config.restore_height = Utils.FIRST_RECEIVE_HEIGHT - wallet_keys: MoneroWalletFull = self._create_wallet(config) - - try: - # test wallet keys equality - assert wallet.get_seed() == wallet_keys.get_seed() - assert wallet.get_primary_address() == wallet_keys.get_primary_address() - assert wallet.get_private_view_key() == wallet_keys.get_private_view_key() - assert wallet.get_public_view_key() == wallet_keys.get_public_view_key() - assert wallet.get_private_spend_key() == wallet_keys.get_private_spend_key() - assert wallet.get_public_spend_key() == wallet_keys.get_public_spend_key() - assert Utils.FIRST_RECEIVE_HEIGHT == wallet_keys.get_restore_height() - assert wallet_keys.is_connected_to_daemon() - assert wallet_keys.is_synced() is False - finally: - wallet_keys.close() - - # Can sync a wallet with a randomly generated seed - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_sync_random(self, daemon: MoneroDaemonRpc) -> None: - assert daemon.is_connected(), "Not connected to daemon" - - # create test wallet - wallet: MoneroWalletFull = self._create_wallet(MoneroWalletConfig(), False) - restore_height: int = daemon.get_height() - - # test wallet's height before syncing - AssertUtils.assert_equals(Utils.get_daemon_rpc_connection(), wallet.get_daemon_connection()) - assert restore_height == wallet.get_daemon_height() - assert wallet.is_connected_to_daemon() - assert wallet.is_synced() is False - assert wallet.get_height() == 1 - assert wallet.get_restore_height() == restore_height - assert wallet.get_daemon_height() == daemon.get_height() - - # sync the wallet - progress_tester: SyncProgressTester = SyncProgressTester(wallet, wallet.get_restore_height(), wallet.get_daemon_height()) - result: MoneroSyncResult = wallet.sync(progress_tester) - progress_tester.on_done(wallet.get_daemon_height()) - - # test result after syncing - wallet_gt: MoneroWalletFull = Utils.create_wallet_ground_truth(Utils.NETWORK_TYPE, wallet.get_seed(), None, restore_height) - wallet_gt.sync() - - try: - assert wallet.is_connected_to_daemon() - assert wallet.is_synced() - assert result.num_blocks_fetched == 0 - assert result.received_money is False - assert wallet.get_height() == daemon.get_height() - - # sync the wallet with default params - wallet.sync() - assert wallet.is_synced() - assert wallet.get_height() == daemon.get_height() - - # compare wallet to ground truth - WalletEqualityUtils.test_wallet_full_equality_on_chain(wallet_gt, wallet) - finally: - wallet_gt.close(True) - wallet.close() - - # attempt to sync unconnected wallet - config: MoneroWalletConfig = MoneroWalletConfig() - config.server = MoneroRpcConnection(Utils.OFFLINE_SERVER_URI) - wallet = self._create_wallet(config) - try: - with pytest.raises(Exception) as exc_info: - wallet.sync() - assert str(exc_info.value) == "Wallet is not connected to daemon" - finally: - wallet.close() - - # Can sync a wallet created from seed from the genesis - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - @pytest.mark.skipif(Utils.LITE_MODE, reason="LITE_MODE enabled") - def test_sync_seed_from_genesis(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletFull) -> None: - self._test_sync_seed(daemon, wallet, None, None, True, False) - - # Can sync a wallet created from seed from a restore height - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - @pytest.mark.skipif(Utils.LITE_MODE, reason="LITE_MODE enabled") - def test_sync_seed_from_restore_height(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletFull) -> None: - self._test_sync_seed(daemon, wallet, None, Utils.FIRST_RECEIVE_HEIGHT) - - # Can sync a wallet created from seed from a start height - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - @pytest.mark.skipif(Utils.LITE_MODE, reason="LITE_MODE enabled") - def test_sync_seed_from_start_height(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletFull) -> None: - self._test_sync_seed(daemon, wallet, Utils.FIRST_RECEIVE_HEIGHT, None, False, True) - - # Can sync a wallet created from seed from a start height less than the restore height - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - @pytest.mark.skipif(Utils.LITE_MODE, reason="LITE_MODE enabled") - def test_sync_seed_start_height_lt_restore_height(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletFull) -> None: - self._test_sync_seed(daemon, wallet, Utils.FIRST_RECEIVE_HEIGHT, Utils.FIRST_RECEIVE_HEIGHT + 3) - - # Can sync a wallet created from seed from a start height greater than the restore height - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - @pytest.mark.skipif(Utils.LITE_MODE, reason="LITE_MODE enabled") - def test_sync_seed_start_height_gt_restore_height(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletFull) -> None: - self._test_sync_seed(daemon, wallet, Utils.FIRST_RECEIVE_HEIGHT + 3, Utils.FIRST_RECEIVE_HEIGHT) - - # Can sync a wallet created from keys - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - @pytest.mark.skipif(Utils.LITE_MODE, reason="LITE_MODE enabled") - def test_sync_wallet_from_keys(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletFull) -> None: - # recreate test wallet from keys - path: str = Utils.get_random_wallet_path() - config: MoneroWalletConfig = MoneroWalletConfig() - config.path = path - config.primary_address = wallet.get_primary_address() - config.private_view_key = wallet.get_private_view_key() - config.private_spend_key = wallet.get_private_spend_key() - config.restore_height = Utils.FIRST_RECEIVE_HEIGHT - wallet_keys: MoneroWalletFull = self._create_wallet(config, False) - - # create ground truth wallet for comparison - wallet_gt: MoneroWalletFull = Utils.create_wallet_ground_truth(Utils.NETWORK_TYPE, Utils.SEED, None, Utils.FIRST_RECEIVE_HEIGHT) - - # test wallet and close as final step - try: - assert wallet_keys.get_seed() == wallet_gt.get_seed() - assert wallet_keys.get_primary_address() == wallet_gt.get_primary_address() - assert wallet_keys.get_private_view_key() == wallet_gt.get_private_view_key() - assert wallet_keys.get_public_view_key() == wallet_gt.get_public_view_key() - assert wallet_keys.get_private_spend_key() == wallet_gt.get_private_spend_key() - assert wallet_keys.get_public_spend_key() == wallet_gt.get_public_spend_key() - assert Utils.FIRST_RECEIVE_HEIGHT == wallet_gt.get_restore_height() - assert wallet_keys.is_connected_to_daemon() - assert wallet_keys.is_synced() is False - - # sync the wallet - progress_tester: SyncProgressTester = SyncProgressTester(wallet_keys, Utils.FIRST_RECEIVE_HEIGHT, wallet_keys.get_daemon_max_peer_height()) - result: MoneroSyncResult = wallet_keys.sync(progress_tester) - progress_tester.on_done(wallet_keys.get_daemon_height()) - - # test result after syncing - assert wallet_keys.is_synced() - assert wallet_keys.get_daemon_height() - Utils.FIRST_RECEIVE_HEIGHT == result.num_blocks_fetched - assert result.received_money is True - assert wallet_keys.get_height() == daemon.get_height() - assert wallet_keys.get_daemon_height() == daemon.get_height() - - # wallet should be fully synced so first tx happens on true restore height - txs: list[MoneroTxWallet] = wallet.get_txs() - assert len(txs) > 0 - tx: MoneroTxWallet = txs[0] - tx_height: int | None = tx.get_height() - assert tx_height is not None - assert Utils.FIRST_RECEIVE_HEIGHT == tx_height - - # compare with ground truth - WalletEqualityUtils.test_wallet_full_equality_on_chain(wallet_gt, wallet_keys) - finally: - wallet_gt.close(True) - wallet_keys.close() - - # Can start and stop syncing - # TODO test start syncing, notification of syncs happening, stop syncing, no notifications, etc - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - @pytest.mark.skipif(Utils.LITE_MODE, reason="LITE_MODE enabled") - def test_start_stop_syncing(self, daemon: MoneroDaemonRpc) -> None: - # test unconnected wallet - config: MoneroWalletConfig = MoneroWalletConfig() - config.server = MoneroRpcConnection(Utils.OFFLINE_SERVER_URI) - config.path = Utils.get_random_wallet_path() - wallet: MoneroWalletFull = self._create_wallet(config) - try: - assert len(wallet.get_seed()) > 0 - assert wallet.get_height() == 1 - assert wallet.get_balance() == 0 - wallet.start_syncing() # succeeds while offline, syncing when a daemon becomes reachable - finally: - wallet.close() - - # test connecting wallet - config = MoneroWalletConfig() - config.path = Utils.get_random_wallet_path() - config.server = MoneroRpcConnection(Utils.OFFLINE_SERVER_URI) - wallet = self._create_wallet(config) - try: - assert len(wallet.get_seed()) > 0 - wallet.set_daemon_connection(daemon.get_rpc_connection()) - assert wallet.get_height() == 1 - assert wallet.is_synced() is False - assert wallet.get_balance() == 0 - chain_height: int = wallet.get_daemon_height() - wallet.set_restore_height(chain_height - 3) - wallet.start_syncing() - assert chain_height - 3 == wallet.get_restore_height() - AssertUtils.assert_equals(daemon.get_rpc_connection(), wallet.get_daemon_connection()) - wallet.stop_syncing() - wallet.sync() - wallet.stop_syncing() - wallet.stop_syncing() - finally: - wallet.close() - - # test that sync starts automatically - restore_height: int = daemon.get_height() - 100 - config = MoneroWalletConfig() - config.path = Utils.get_random_wallet_path() - config.seed = Utils.SEED - config.restore_height = restore_height - wallet = self._create_wallet(config, False) - try: - # start syncing - assert wallet.get_height() == 1 - assert wallet.get_restore_height() == restore_height - assert wallet.is_synced() is False - assert wallet.get_balance() == 0 - wallet.start_syncing(Utils.SYNC_PERIOD_IN_MS) - - # pause for sync to start - sleep(1 + (Utils.SYNC_PERIOD_IN_MS / 1000)) - - # test that wallet has started syncing - assert wallet.get_height() > 1 - - # stop syncing - wallet.stop_syncing() - - # TODO monero-project: wallet.cpp m_synchronized only ever set to true, never false - finally: - wallet.close() - - # Does not interfere with other wallet notifications - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - @pytest.mark.skipif(Utils.LITE_MODE, reason="LITE_MODE enabled") - def test_wallets_do_not_interfere(self, daemon: MoneroDaemonRpc) -> None: - # create 2 wallets with a recent restore height - height: int = daemon.get_height() - restore_height: int = height - 5 - config: MoneroWalletConfig = MoneroWalletConfig() - config.seed = Utils.SEED - config.restore_height = restore_height - wallet1: MoneroWalletFull = self._create_wallet(config, False) - - config = MoneroWalletConfig() - config.seed = Utils.SEED - config.restore_height = restore_height - wallet2: MoneroWalletFull = self._create_wallet(config, False) - - # track notifications of each wallet - tester1: SyncProgressTester = SyncProgressTester(wallet1, restore_height, height) - tester2: SyncProgressTester = SyncProgressTester(wallet2, restore_height, height) - wallet1.add_listener(tester1) - wallet2.add_listener(tester2) - - # sync first wallet and test that 2nd is not notified - wallet1.sync() - assert tester1.is_notified - assert not tester2.is_notified - - # sync 2nd wallet and test that 1st is not notified - tester3: SyncProgressTester = SyncProgressTester(wallet1, restore_height, height) - wallet1.add_listener(tester3) - wallet2.sync() - assert tester2.is_notified - assert not tester3.is_notified - - # Can create a subaddress with and without a label - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - @override - def test_create_subaddress(self, wallet: MoneroWalletFull) -> None: # type: ignore - # create subaddresses across accounts - accounts: list[MoneroAccount] = wallet.get_accounts() - if len(accounts) < 2: - wallet.create_account() - - accounts = wallet.get_accounts() - assert len(accounts) > 1 - account_idx: int = 0 - while account_idx < 2: - # create subaddress with no label - subaddresses: list[MoneroSubaddress] = wallet.get_subaddresses(account_idx) - subaddress: MoneroSubaddress = wallet.create_subaddress(account_idx) - assert subaddress.label is None - WalletUtils.test_subaddress(subaddress) - subaddresses_new: list[MoneroSubaddress] = wallet.get_subaddresses(account_idx) - assert len(subaddresses_new) - 1 == len(subaddresses) - AssertUtils.assert_equals(subaddress, subaddresses_new[len(subaddresses_new) - 1]) - - # create subaddress with label - subaddresses = wallet.get_subaddresses(account_idx) - uuid: str = StringUtils.get_random_string() - subaddress = wallet.create_subaddress(account_idx, uuid) - assert uuid == subaddress.label - WalletUtils.test_subaddress(subaddress) - subaddresses_new = wallet.get_subaddresses(account_idx) - assert len(subaddresses) == len(subaddresses_new) - 1 - AssertUtils.assert_equals(subaddress, subaddresses_new[len(subaddresses_new) - 1]) - account_idx += 1 - - # Can be closed - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_close(self) -> None: - # create test wallet - path: str = Utils.get_random_wallet_path() - config: MoneroWalletConfig = MoneroWalletConfig() - config.path = path - wallet: MoneroWalletFull = self._create_wallet(config) - wallet.sync() - assert wallet.get_height() > 1, "Wallet height is still 1" - assert wallet.is_synced(), "Wallet is not synced" - assert wallet.is_closed() is False - - # close wallet - wallet.close() - - assert wallet.is_closed() - - # attempt to interact with the wallet - with pytest.raises(Exception) as exc_info: - wallet.get_height() - WalletErrorUtils.test_wallet_is_closed_error(exc_info.value) - - with pytest.raises(Exception) as exc_info: - wallet.get_seed() - WalletErrorUtils.test_wallet_is_closed_error(exc_info.value) - - with pytest.raises(Exception) as exc_info: - wallet.sync() - WalletErrorUtils.test_wallet_is_closed_error(exc_info.value) - - with pytest.raises(Exception) as exc_info: - wallet.start_syncing() - WalletErrorUtils.test_wallet_is_closed_error(exc_info.value) - - with pytest.raises(Exception) as exc_info: - wallet.stop_syncing() - WalletErrorUtils.test_wallet_is_closed_error(exc_info.value) - - # re-open the wallet - config = MoneroWalletConfig() - config.path = path - - wallet = self._open_wallet(config) - assert wallet.is_closed() is False - wallet.sync() - assert wallet.get_daemon_height() == wallet.get_height() - assert wallet.is_closed() is False - - # close the wallet - wallet.close() - assert wallet.is_closed() - - # Supports multisig sample code - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_multisig_sample(self) -> None: - self._test_multisig_sample(1, 2) - self._test_multisig_sample(1, 4) - self._test_multisig_sample(2, 2) - self._test_multisig_sample(2, 3) - self._test_multisig_sample(2, 4) - - @pytest.mark.skipif(Utils.REGTEST, reason="Cannot retrieve accurate height by date from regtest fakechain") - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - @override - def test_get_height_by_date(self, wallet: MoneroWallet) -> None: - return super().test_get_height_by_date(wallet) - - @pytest.mark.skipif(Utils.REGTEST is False, reason="REGTEST disabled") - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_height_by_date_regtest(self, wallet: MoneroWallet) -> None: - # the base test's fixed dates fall outside a short regtest chain - with pytest.raises(RuntimeError): - super().test_get_height_by_date(wallet) - - #endregion - - #region Notification Tests - - # Can wait for the next block to be added and be notified of its height - @pytest.mark.skipif(Utils.TEST_NOTIFICATIONS is False, reason="TEST_NOTIFICATIONS disabled") - @pytest.mark.flaky(reruns=5, reruns_delay=10, only_rerun=[]) - def test_wait_for_next_block(self, wallet: MoneroWalletFull) -> None: - height_before: int = wallet.get_height() - MiningUtils.try_start_mining() - try: - height: int = wallet.wait_for_next_block() - # the notification carries the height of the new block, which is the chain - # length the wallet knew before it was added, so it is only greater when the wallet lagged behind - assert height >= height_before - finally: - MiningUtils.try_stop_mining() - - #endregion - - #region Disabled Tests - - @pytest.mark.skip(reason="TODO disabled because importing key images deletes corresponding incoming transfers: #5812") - @override - def test_import_key_images(self, wallet: MoneroWallet) -> None: - return super().test_import_key_images(wallet) - - #endregion - - #region Utils - - def _test_sync_seed( - self, - daemon: MoneroDaemonRpc, - wallet: MoneroWalletFull, - start_height: Optional[int], - restore_height: Optional[int], - skip_gt_comparison: bool = False, - test_post_sync_notifications: bool = False - ) -> None: - tester: SyncSeedTester = SyncSeedTester( - daemon, wallet, self._create_wallet, - start_height, restore_height, - skip_gt_comparison, test_post_sync_notifications - ) - tester.test() - - #endregion - - -@pytest.mark.unit -class TestMoneroWalletFullOffline(BaseTestClass): - """Full wallet unit tests that run against a disconnected wallet, no daemon needed.""" - - @pytest.fixture(scope="class") - @classmethod - def wallet(cls) -> MoneroWalletFull: - """Shared disconnected full wallet.""" - return Utils.get_wallet_full_offline() - - def test_get_default_ringdb_path_mainnet(self) -> None: - path: str = MoneroWalletFull.get_default_ringdb_path(MoneroNetworkType.MAINNET) - assert path.endswith(".shared-ringdb") - assert not path.endswith("testnet") - assert not path.endswith("stagenet") - - def test_get_default_ringdb_path_testnet(self) -> None: - path: str = MoneroWalletFull.get_default_ringdb_path(MoneroNetworkType.TESTNET) - assert path.endswith(os.path.join(".shared-ringdb", "testnet")) - - def test_get_default_ringdb_path_stagenet(self) -> None: - path: str = MoneroWalletFull.get_default_ringdb_path(MoneroNetworkType.STAGENET) - assert path.endswith(os.path.join(".shared-ringdb", "stagenet")) - - # import_key_images guards unset key image fields - def test_import_key_images_hex_not_defined(self, wallet: MoneroWalletFull) -> None: - with pytest.raises(RuntimeError) as exc_info: - wallet.import_key_images([MoneroKeyImage()]) - assert str(exc_info.value) == "key image hex is not defined" - - def test_import_key_images_signature_not_defined(self, wallet: MoneroWalletFull) -> None: - key_image: MoneroKeyImage = MoneroKeyImage() - key_image.hex = "a" * 64 - with pytest.raises(RuntimeError) as exc_info: - wallet.import_key_images([key_image]) - assert str(exc_info.value) == "key image signature is not defined" - - # Can be moved - def test_move_to(self) -> None: - config: MoneroWalletConfig = MoneroWalletConfig() - config.path = "" - config.password = Utils.WALLET_PASSWORD - config.network_type = MoneroNetworkType.MAINNET - wallet: MoneroWalletFull = MoneroWalletFull.create_wallet(config) - try: - seed: str = wallet.get_seed() - wallet.set_attribute("mykey", "myval1") - - # move the in-memory wallet to disk - path1: str = Utils.get_random_wallet_path() - assert MoneroWalletFull.wallet_exists(path1) is False - wallet.move_to(path1, Utils.WALLET_PASSWORD) - assert MoneroWalletFull.wallet_exists(path1) is True - assert wallet.get_seed() == seed - assert wallet.get_attribute("mykey") == "myval1" - - # moving to the same path saves in place - wallet.set_attribute("mykey", "myval2") - wallet.move_to(path1, Utils.WALLET_PASSWORD) - wallet.close() - wallet = MoneroWalletFull.open_wallet(path1, Utils.WALLET_PASSWORD, MoneroNetworkType.MAINNET) - assert wallet.get_seed() == seed - assert wallet.get_attribute("mykey") == "myval2" - - # move to a new path - path2: str = Utils.get_random_wallet_path() - wallet.set_attribute("mykey", "myval3") - wallet.move_to(path2, Utils.WALLET_PASSWORD) - assert MoneroWalletFull.wallet_exists(path1) is False - assert MoneroWalletFull.wallet_exists(path2) is True - wallet.close() - wallet = MoneroWalletFull.open_wallet(path2, Utils.WALLET_PASSWORD, MoneroNetworkType.MAINNET) - assert wallet.get_seed() == seed - assert wallet.get_attribute("mykey") == "myval3" - finally: - wallet.close() - - # Can export and import wallet files - def test_export_and_import_wallet_files(self) -> None: - config: MoneroWalletConfig = MoneroWalletConfig() - config.path = "" - config.password = Utils.WALLET_PASSWORD - config.network_type = MoneroNetworkType.MAINNET - wallet: MoneroWalletFull = MoneroWalletFull.create_wallet(config) - from_keys: MoneroWalletFull | None = None - from_both: MoneroWalletFull | None = None - try: - keys_data: bytes = wallet.get_keys_file_buffer(Utils.WALLET_PASSWORD, False) - cache_data: bytes = wallet.get_cache_file_buffer() - assert len(keys_data) > 0 - assert len(cache_data) > 0 - - # open from the keys buffer alone, then from keys + cache - from_keys = MoneroWalletFull.open_wallet_data(Utils.WALLET_PASSWORD, MoneroNetworkType.MAINNET, keys_data, b"", None, Utils.REGTEST) - from_both = MoneroWalletFull.open_wallet_data(Utils.WALLET_PASSWORD, MoneroNetworkType.MAINNET, keys_data, cache_data, None, Utils.REGTEST) - - for restored in (from_keys, from_both): - assert restored.get_seed() == wallet.get_seed() - assert restored.get_primary_address() == wallet.get_primary_address() - assert restored.get_private_view_key() == wallet.get_private_view_key() - assert restored.get_private_spend_key() == wallet.get_private_spend_key() - finally: - wallet.close() - if from_keys is not None: - from_keys.close() - if from_both is not None: - from_both.close() diff --git a/tests/test_monero_wallet_keys.py b/tests/test_monero_wallet_keys.py deleted file mode 100644 index 9295bb5d..00000000 --- a/tests/test_monero_wallet_keys.py +++ /dev/null @@ -1,1029 +0,0 @@ -import pytest -import logging - -from typing import Optional -from typing_extensions import override -from monero import ( - MoneroWalletKeys, MoneroWalletConfig, MoneroWallet, - MoneroUtils, MoneroAccount, MoneroSubaddress, - MoneroDaemonRpc, MoneroDaemon, MoneroIntegratedAddress, - MoneroMessageSignatureType, MoneroMessageSignatureResult -) -from utils import TestUtils as Utils, AssertUtils, WalletUtils, WalletType - -from test_monero_wallet_common import BaseTestMoneroWallet - -logger: logging.Logger = logging.getLogger("TestMoneroWalletKeys") - - -@pytest.mark.unit -class TestMoneroWalletKeys(BaseTestMoneroWallet): - """Keys-only wallet unit tests.""" - - _account_indices: list[int] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] - _subaddress_indices: list[int] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] - - #region Fixtures - - @pytest.fixture(scope="class") - @classmethod - @override - def wallet(cls) -> MoneroWalletKeys: - """Test keys wallet instance""" - return Utils.get_wallet_keys() - - @pytest.fixture(scope="class") - @classmethod - @override - def daemon(cls) -> MoneroDaemonRpc: - return MoneroDaemon() # type: ignore - - #endregion - - #region Overrides - - @classmethod - @override - def get_wallet_type(cls) -> WalletType: - return WalletType.KEYS - - @override - def after_all(self) -> None: - logger.info(f"Teardown test class {type(self).__name__}") - - @override - def before_each(self, request: pytest.FixtureRequest) -> None: - logger.info(f"Before {request.node.name}") # type: ignore - - @override - def after_each(self, request: pytest.FixtureRequest) -> None: - logger.info(f"After {request.node.name}") # type: ignore - - @classmethod - @override - def is_random_wallet_config(cls, config: Optional[MoneroWalletConfig]) -> bool: - assert config is not None - return super().is_random_wallet_config(config) and config.private_spend_key is None - - @override - def _create_wallet(self, config: Optional[MoneroWalletConfig]) -> MoneroWalletKeys: - # assign defaults - if config is None: - config = MoneroWalletConfig() - - random: bool = self.is_random_wallet_config(config) - if config.network_type is None: - config.network_type = Utils.NETWORK_TYPE - - # create wallet - if random: - wallet: MoneroWalletKeys = MoneroWalletKeys.create_wallet_random(config) - elif config.seed is not None and config.seed != "": - wallet = MoneroWalletKeys.create_wallet_from_seed(config) - elif config.primary_address is not None and config.private_view_key is not None: - wallet = MoneroWalletKeys.create_wallet_from_keys(config) - elif config.primary_address is not None and config.private_spend_key is not None: - wallet = MoneroWalletKeys.create_wallet_from_keys(config) - else: - raise Exception("Invalid configuration") - - return wallet - - @override - def _open_wallet(self, config: Optional[MoneroWalletConfig]) -> MoneroWallet: - raise NotImplementedError("TestMoneroWalletKeys._open_wallet(): not supported") - - @override - def _close_wallet(self, wallet: MoneroWallet, save: bool = False) -> None: - # a keys-only wallet has nothing to persist, so `save` is ignored - wallet.close() - - @override - def _get_seed_languages(self) -> list[str]: - return self.get_test_wallet().get_seed_languages() - - @classmethod - @override - def get_test_wallet(cls) -> MoneroWalletKeys: - return super().get_test_wallet() # type: ignore - - #endregion - - #region Not Supported Tests - - @pytest.mark.not_supported - @override - def test_send(self, wallet: MoneroWallet) -> None: - return super().test_send(wallet) - - @pytest.mark.not_implemented - @override - def test_send_with_payment_id(self, wallet: MoneroWallet) -> None: - return super().test_send_with_payment_id(wallet) - - @pytest.mark.not_supported - @override - def test_send_split(self, wallet: MoneroWallet) -> None: - return super().test_send_split(wallet) - - @pytest.mark.not_supported - @override - def test_create_then_relay(self, wallet: MoneroWallet) -> None: - return super().test_create_then_relay(wallet) - - @pytest.mark.not_supported - @override - def test_create_then_relay_split(self, wallet: MoneroWallet) -> None: - return super().test_create_then_relay_split(wallet) - - @pytest.mark.not_supported - @override - def test_get_txs_wallet(self, wallet: MoneroWallet) -> None: - return super().test_get_txs_wallet(wallet) - - @pytest.mark.not_supported - @override - def test_get_txs_by_hash(self, wallet: MoneroWallet) -> None: - return super().test_get_txs_by_hash(wallet) - - @pytest.mark.not_supported - @override - def test_get_txs_with_query(self, wallet: MoneroWallet) -> None: - return super().test_get_txs_with_query(wallet) - - @pytest.mark.not_supported - @override - def test_validate_inputs_get_txs(self, wallet: MoneroWallet) -> None: - return super().test_validate_inputs_get_txs(wallet) - - @pytest.mark.not_supported - @override - def test_get_transfers(self, wallet: MoneroWallet) -> None: - return super().test_get_transfers(wallet) - - @pytest.mark.not_supported - @override - def test_validate_inputs_get_transfers(self, wallet: MoneroWallet) -> None: - return super().test_validate_inputs_get_transfers(wallet) - - @pytest.mark.not_supported - @override - def test_get_outputs(self, wallet: MoneroWallet) -> None: - return super().test_get_outputs(wallet) - - @pytest.mark.not_supported - @override - def test_validate_inputs_get_outputs(self, wallet: MoneroWallet) -> None: - return super().test_validate_inputs_get_outputs(wallet) - - @pytest.mark.not_supported - @override - def test_accounting(self, wallet: MoneroWallet) -> None: - return super().test_accounting(wallet) - - @pytest.mark.not_supported - @override - def test_get_daemon_height(self, wallet: MoneroWallet) -> None: - return super().test_get_daemon_height(wallet) - - @pytest.mark.not_supported - @override - def test_get_daemon_max_peer_height(self, wallet: MoneroWallet) -> None: - return super().test_get_daemon_max_peer_height(wallet) - - @pytest.mark.not_supported - @override - def test_get_path(self) -> None: - return super().test_get_path() - - @pytest.mark.not_supported - @override - def test_set_daemon_connection(self) -> None: - return super().test_set_daemon_connection() - - @pytest.mark.not_supported - @override - def test_sync_without_progress(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: - return super().test_sync_without_progress(daemon, wallet) - - @pytest.mark.not_supported - @override - def test_subaddress_lookahead(self, wallet: MoneroWallet) -> None: - return super().test_subaddress_lookahead(wallet) - - @pytest.mark.not_supported - @override - def test_get_address_indices(self, wallet: MoneroWallet) -> None: - return super().test_get_address_indices(wallet) - - @pytest.mark.not_supported - @override - def test_wallet_equality_ground_truth(self, wallet: MoneroWallet) -> None: - return super().test_wallet_equality_ground_truth(wallet) - - @pytest.mark.not_supported - @override - def test_get_height(self, wallet: MoneroWallet) -> None: - return super().test_get_height(wallet) - - @pytest.mark.not_supported - @override - def test_get_height_by_date(self, wallet: MoneroWallet) -> None: - return super().test_get_height_by_date(wallet) - - @pytest.mark.not_supported - @override - def test_get_all_balances(self, wallet: MoneroWallet) -> None: - return super().test_get_all_balances(wallet) - - @pytest.mark.not_supported - @override - def test_create_account_without_label(self, wallet: MoneroWallet) -> None: - return super().test_create_account_without_label(wallet) - - @pytest.mark.not_supported - @override - def test_create_account_with_label(self, wallet: MoneroWallet) -> None: - return super().test_create_account_with_label(wallet) - - @pytest.mark.not_supported - @override - def test_set_account_label(self, wallet: MoneroWallet) -> None: - return super().test_set_account_label(wallet) - - @pytest.mark.not_supported - @override - def test_get_subaddresses_by_indices(self, wallet: MoneroWallet) -> None: - return super().test_get_subaddresses_by_indices(wallet) - - @pytest.mark.not_supported - @override - def test_create_subaddress(self, wallet: MoneroWallet) -> None: - return super().test_create_subaddress(wallet) - - @override - def test_set_subaddress_label(self, wallet: MoneroWallet) -> None: - # a keys-only wallet cannot enumerate its subaddresses, which this test needs - with pytest.raises(RuntimeError, match="does not have enumerable set of subaddresses"): - super().test_set_subaddress_label(wallet) - - @pytest.mark.not_supported - @override - def test_set_tx_note(self, wallet: MoneroWallet) -> None: - return super().test_set_tx_note(wallet) - - @pytest.mark.not_supported - @override - def test_set_tx_notes(self, wallet: MoneroWallet) -> None: - return super().test_set_tx_notes(wallet) - - @pytest.mark.not_supported - @override - def test_export_key_images(self, wallet: MoneroWallet) -> None: - return super().test_export_key_images(wallet) - - @pytest.mark.not_supported - @override - def test_get_new_key_images_from_last_import(self, wallet: MoneroWallet) -> None: - return super().test_get_new_key_images_from_last_import(wallet) - - @pytest.mark.not_supported - @override - def test_import_key_images(self, wallet: MoneroWallet) -> None: - return super().test_import_key_images(wallet) - - @pytest.mark.not_supported - @override - def test_set_attributes(self, wallet: MoneroWallet) -> None: - return super().test_set_attributes(wallet) - - @pytest.mark.not_supported - @override - def test_mining(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: - return super().test_mining(daemon, wallet) - - @pytest.mark.not_supported - @override - def test_change_password(self) -> None: - return super().test_change_password() - - @pytest.mark.not_supported - @override - def test_save_and_close(self) -> None: - return super().test_save_and_close() - - @pytest.mark.not_supported - @override - def test_validate_inputs_sending_funds(self, wallet: MoneroWallet) -> None: - return super().test_validate_inputs_sending_funds(wallet) - - @pytest.mark.not_supported - @override - def test_export_outputs(self, wallet: MoneroWallet) -> None: - return super().test_export_outputs(wallet) - - @pytest.mark.not_supported - @override - def test_import_outputs(self, wallet: MoneroWallet) -> None: - return super().test_import_outputs(wallet) - - @pytest.mark.not_supported - @override - def test_send_to_self(self, wallet: MoneroWallet) -> None: - return super().test_send_to_self(wallet) - - @pytest.mark.not_supported - @override - def test_send_to_external(self, wallet: MoneroWallet) -> None: - return super().test_send_to_external(wallet) - - @pytest.mark.not_supported - @override - def test_scan_txs(self, wallet: MoneroWallet) -> None: - return super().test_scan_txs(wallet) - - @pytest.mark.not_supported - @override - def test_get_default_fee_priority(self, wallet: MoneroWallet) -> None: - return super().test_get_default_fee_priority(wallet) - - @pytest.mark.not_supported - @override - def test_freeze_outputs(self, wallet: MoneroWallet) -> None: - return super().test_freeze_outputs(wallet) - - @pytest.mark.not_supported - @override - def test_get_outputs_with_query(self, wallet: MoneroWallet) -> None: - return super().test_get_outputs_with_query(wallet) - - @override - def test_input_key_images(self, wallet: MoneroWallet) -> None: - # a keys-only wallet cannot enumerate accounts/subaddresses, which this test needs - with pytest.raises(RuntimeError, match=r"get_accounts\(\) not supported"): - super().test_input_key_images(wallet) - - @pytest.mark.not_supported - @override - def test_send_from_subaddresses(self, wallet: MoneroWallet) -> None: - return super().test_send_from_subaddresses(wallet) - - @pytest.mark.not_supported - @override - def test_send_from_subaddresses_split(self, wallet: MoneroWallet) -> None: - return super().test_send_from_subaddresses_split(wallet) - - @pytest.mark.not_supported - @override - def test_send_to_multiple(self, wallet: MoneroWallet) -> None: - return super().test_send_to_multiple(wallet) - - @pytest.mark.not_supported - @override - def test_send_to_multiple_split(self, wallet: MoneroWallet) -> None: - return super().test_send_to_multiple_split(wallet) - - @pytest.mark.not_supported - @override - def test_send_dust_to_multiple_split(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: - return super().test_send_dust_to_multiple_split(daemon, wallet) - - @pytest.mark.not_supported - @override - def test_subtract_fee_from(self, wallet: MoneroWallet) -> None: - return super().test_subtract_fee_from(wallet) - - @pytest.mark.not_supported - @override - def test_subtract_fee_from_split(self, wallet: MoneroWallet) -> None: - return super().test_subtract_fee_from_split(wallet) - - @pytest.mark.not_supported - @override - def test_get_txs_by_height(self, wallet: MoneroWallet) -> None: - return super().test_get_txs_by_height(wallet) - - @pytest.mark.not_supported - @override - def test_get_txs_with_payment_ids(self, wallet: MoneroWallet) -> None: - return super().test_get_txs_with_payment_ids(wallet) - - @pytest.mark.not_supported - @override - def test_get_txs_fields_with_filtering(self, wallet: MoneroWallet) -> None: - return super().test_get_txs_fields_with_filtering(wallet) - - @pytest.mark.not_supported - @override - def test_get_transfers_with_query(self, wallet: MoneroWallet) -> None: - return super().test_get_transfers_with_query(wallet) - - @pytest.mark.not_supported - @override - def test_rescan_blockchain(self, wallet: MoneroWallet) -> None: - return super().test_rescan_blockchain(wallet) - - @pytest.mark.not_supported - @override - def test_check_tx_key(self, wallet: MoneroWallet) -> None: - return super().test_check_tx_key(wallet) - - @pytest.mark.not_supported - @override - def test_check_tx_proof(self, wallet: MoneroWallet) -> None: - return super().test_check_tx_proof(wallet) - - @pytest.mark.not_supported - @override - def test_check_spend_proof(self, wallet: MoneroWallet) -> None: - return super().test_check_spend_proof(wallet) - - @pytest.mark.not_supported - @override - def test_get_reserve_proof_wallet(self, wallet: MoneroWallet) -> None: - return super().test_get_reserve_proof_wallet(wallet) - - @pytest.mark.not_supported - @override - def test_get_reserve_proof_account(self, wallet: MoneroWallet) -> None: - return super().test_get_reserve_proof_account(wallet) - - @pytest.mark.not_supported - @override - def test_view_only_and_offline_wallets(self, wallet: MoneroWallet) -> None: - return super().test_view_only_and_offline_wallets(wallet) - - @pytest.mark.not_supported - @override - def test_sweep_outputs(self, wallet: MoneroWallet) -> None: - return super().test_sweep_outputs(wallet) - - @pytest.mark.not_supported - @override - def test_sweep_dust_no_relay(self, wallet: MoneroWallet) -> None: - return super().test_sweep_dust_no_relay(wallet) - - @pytest.mark.not_supported - @override - def test_sweep_dust(self, wallet: MoneroWallet) -> None: - return super().test_sweep_dust(wallet) - - @pytest.mark.not_supported - @override - def test_sweep_subaddresses(self, wallet: MoneroWallet) -> None: - return super().test_sweep_subaddresses(wallet) - - @pytest.mark.not_supported - @override - def test_sweep_accounts(self, wallet: MoneroWallet) -> None: - return super().test_sweep_accounts(wallet) - - @pytest.mark.not_supported - @override - def test_sweep_wallet_by_accounts(self, wallet: MoneroWallet) -> None: - return super().test_sweep_wallet_by_accounts(wallet) - - @pytest.mark.not_supported - @override - def test_sweep_wallet_by_subaddresses(self, wallet: MoneroWallet) -> None: - return super().test_sweep_wallet_by_subaddresses(wallet) - - @pytest.mark.not_supported - @override - def test_prove_unrelayed_txs(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: - return super().test_prove_unrelayed_txs(daemon, wallet) - - @pytest.mark.not_supported - @override - def test_address_book(self, wallet: MoneroWallet) -> None: - return super().test_address_book(wallet) - - @pytest.mark.not_supported - @override - def test_stop_listening(self) -> None: - return super().test_stop_listening() - - @pytest.mark.not_supported - @override - def test_create_and_receive(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: - return super().test_create_and_receive(daemon, wallet) - - @pytest.mark.not_supported - @override - def test_is_multisig_needed(self, wallet: MoneroWallet) -> None: - return super().test_is_multisig_needed(wallet) - - @pytest.mark.not_supported - @override - def test_rescan_spent(self, wallet: MoneroWallet) -> None: - return super().test_rescan_spent(wallet) - - @pytest.mark.not_supported - @override - def test_update_locked_same_account(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: - return super().test_update_locked_same_account(daemon, wallet) - - @pytest.mark.not_supported - @override - def test_update_locked_same_account_split(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: - return super().test_update_locked_same_account_split(daemon, wallet) - - @pytest.mark.not_supported - @override - def test_update_locked_different_accounts(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: - return super().test_update_locked_different_accounts(daemon, wallet) - - @pytest.mark.not_supported - @override - def test_update_locked_different_accounts_split(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: - return super().test_update_locked_different_accounts_split(daemon, wallet) - - @pytest.mark.not_supported - @override - def test_sync_with_pool_same_accounts(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: - return super().test_sync_with_pool_same_accounts(daemon, wallet) - - @pytest.mark.not_supported - @override - def test_sync_with_pool_submit_and_flush(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: - return super().test_sync_with_pool_submit_and_flush(daemon, wallet) - - @pytest.mark.not_supported - @override - def test_sync_with_pool_submit_and_relay(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: - return super().test_sync_with_pool_submit_and_relay(daemon, wallet) - - @pytest.mark.not_supported - @override - def test_sync_with_pool_relay(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: - return super().test_sync_with_pool_relay(daemon, wallet) - - @pytest.mark.not_supported - @override - def test_account_tags(self, wallet: MoneroWallet) -> None: - return super().test_account_tags(wallet) - - #endregion - - #region Tests - - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - @override - def test_create_wallet_random(self) -> None: - """ - Can create a random wallet. - """ - config: MoneroWalletConfig = MoneroWalletConfig() - wallet: MoneroWalletKeys = self._create_wallet(config) - - # validate wallet - MoneroUtils.validate_address(wallet.get_primary_address(), Utils.NETWORK_TYPE) - MoneroUtils.validate_private_view_key(wallet.get_private_view_key()) - MoneroUtils.validate_private_spend_key(wallet.get_private_spend_key()) - MoneroUtils.validate_mnemonic(wallet.get_seed()) - # TODO monero-wallet-rpc: get seed language - assert MoneroWallet.DEFAULT_LANGUAGE == wallet.get_seed_language() - - # attempt to create wallet with unknown language - config = MoneroWalletConfig() - config.language = "english" - with pytest.raises(Exception, match="Unknown language: english"): - self._create_wallet(config) - - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - @override - def test_create_wallet_from_seed(self, wallet: MoneroWallet, test_config: BaseTestMoneroWallet.Config) -> None: - # save for comparison - primary_address: str = wallet.get_primary_address() - private_view_key: str = wallet.get_private_view_key() - private_spend_key: str = wallet.get_private_spend_key() - - # recreate test wallet from seed - config: MoneroWalletConfig = MoneroWalletConfig() - config.seed = Utils.SEED - w: MoneroWallet = self._create_wallet(config) - - assert primary_address == w.get_primary_address() - assert private_view_key == w.get_private_view_key() - assert private_spend_key == w.get_private_spend_key() - assert Utils.SEED == w.get_seed() - assert MoneroWallet.DEFAULT_LANGUAGE == w.get_seed_language() - - # attempt to create wallet with two missing words - config = MoneroWalletConfig() - config.seed = test_config.seed - with pytest.raises(Exception) as exc_info: - self._create_wallet(config) - assert str(exc_info.value) == "Invalid mnemonic" - - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - @override - def test_create_wallet_from_seed_with_offset(self) -> None: - # create test wallet with offset - config: MoneroWalletConfig = MoneroWalletConfig() - config.seed = Utils.SEED - config.seed_offset = "my secret offset!" - wallet: MoneroWallet = self._create_wallet(config) - - MoneroUtils.validate_mnemonic(wallet.get_seed()) - assert Utils.SEED != wallet.get_seed() - MoneroUtils.validate_address(wallet.get_primary_address(), Utils.NETWORK_TYPE) - assert Utils.ADDRESS != wallet.get_primary_address() - assert MoneroWallet.DEFAULT_LANGUAGE == wallet.get_seed_language() - - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - @override - def test_create_wallet_from_keys(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: - # save for comparison - primary_address: str = wallet.get_primary_address() - private_view_key: str = wallet.get_private_view_key() - private_spend_key: str = wallet.get_private_spend_key() - - # recreate test wallet from keys - config: MoneroWalletConfig = MoneroWalletConfig() - config.primary_address = primary_address - config.private_view_key = private_view_key - config.private_spend_key = private_spend_key - w: MoneroWallet = self._create_wallet(config) - WalletUtils.test_wallet_keys(primary_address, private_view_key, private_spend_key, w) - assert w.get_network_type() == Utils.NETWORK_TYPE - assert not w.is_closed() - w.close() - - # recreate test wallet from spend key - config = MoneroWalletConfig() - config.primary_address = primary_address - config.private_spend_key = private_spend_key - w = self._create_wallet(config) - WalletUtils.test_wallet_keys(primary_address, private_view_key, private_spend_key, w) - assert w.get_network_type() == Utils.NETWORK_TYPE - assert not w.is_closed() - w.close() - - # recreate test wallet from view keys - config = MoneroWalletConfig() - config.primary_address = primary_address - config.private_view_key = private_view_key - w = self._create_wallet(config) - logger.info(f"Created wallet with config: {config.serialize()}") - assert primary_address == w.get_primary_address() - assert private_view_key == w.get_private_view_key() - assert w.get_network_type() == Utils.NETWORK_TYPE - assert w.is_view_only() - # a view-only keys wallet has no seed - with pytest.raises(RuntimeError, match="watch-only"): - w.get_seed() - assert not w.is_closed() - w.close() - - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_create_wallet_from_keys_no_keys(self) -> None: - """ - create_wallet_from_keys() must require at least one of the private spend/view keys. - """ - config: MoneroWalletConfig = MoneroWalletConfig() - config.network_type = Utils.NETWORK_TYPE - with pytest.raises(RuntimeError, match="Neither spend key nor view key supplied"): - MoneroWalletKeys.create_wallet_from_keys(config) - - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_create_wallet_from_keys_invalid_spend_key(self) -> None: - """ - create_wallet_from_keys() must fail to parse a malformed private spend key. - """ - config: MoneroWalletConfig = MoneroWalletConfig() - config.network_type = Utils.NETWORK_TYPE - config.private_spend_key = "not-a-valid-hex-secret-key" - with pytest.raises(RuntimeError, match="failed to parse secret spend key"): - MoneroWalletKeys.create_wallet_from_keys(config) - - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_create_wallet_from_keys_invalid_view_key(self) -> None: - """ - create_wallet_from_keys() must fail to parse a malformed private view key. - """ - config: MoneroWalletConfig = MoneroWalletConfig() - config.network_type = Utils.NETWORK_TYPE - config.primary_address = Utils.ADDRESS - config.private_view_key = "not-a-valid-hex-secret-key" - with pytest.raises(RuntimeError, match="failed to parse secret view key"): - MoneroWalletKeys.create_wallet_from_keys(config) - - # Test invalid wallet configuration - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_create_wallet_from_keys_view_key_without_address(self) -> None: - """ - create_wallet_from_keys() must require a primary address when a private view key is given. - """ - config: MoneroWalletConfig = MoneroWalletConfig() - config.network_type = Utils.NETWORK_TYPE - config.private_view_key = "a" * 64 - - with pytest.raises(RuntimeError, match="must provide address if providing private view key"): - MoneroWalletKeys.create_wallet_from_keys(config) - - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - @override - def test_get_subaddress_address(self, wallet: MoneroWallet) -> None: - assert wallet.get_primary_address() == (wallet.get_address(0, 0)) - accounts: list[MoneroAccount] = self._get_test_accounts(wallet, True) - - for account in accounts: - assert account is not None - assert account.index is not None - assert account.primary_address is not None - MoneroUtils.validate_address(account.primary_address, Utils.NETWORK_TYPE) - - for subaddress in account.subaddresses: - assert subaddress is not None - assert subaddress.index is not None - assert subaddress.address == wallet.get_address(account.index, subaddress.index) - - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - @override - def test_get_subaddress_address_out_of_range(self, wallet: MoneroWallet) -> None: - accounts: list[MoneroAccount] = self._get_test_accounts(wallet, True) - account_idx: int = len(accounts) - 1 - subaddress_idx: int = len(accounts[account_idx].subaddresses) - address: str = wallet.get_address(account_idx, subaddress_idx) - assert address is not None - assert len(address) > 0 - - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - @override - def test_get_account(self, wallet: MoneroWallet) -> None: - accounts: list[MoneroAccount] = self._get_test_accounts(wallet) - assert len(accounts) > 0 - for account in accounts: - WalletUtils.test_account(account, Utils.NETWORK_TYPE, False) - - # test without subaddresses - assert account.index is not None - retrieved: MoneroAccount = wallet.get_account(account.index) - assert len(retrieved.subaddresses) == 0 - - # test with subaddresses - retrieved = wallet.get_account(account.index) - retrieved.subaddresses = wallet.get_subaddresses(account.index, self._subaddress_indices) - - def test_get_account_with_subaddresses_not_supported(self, wallet: MoneroWallet) -> None: - with pytest.raises(RuntimeError) as exc_info: - wallet.get_account(0, True) - assert str(exc_info.value) == "monero_wallet_keys::get_account(account_idx, include_subaddresses) include_subaddresses must be false" - - @override - def test_get_accounts_without_subaddresses(self, wallet: MoneroWallet) -> None: - accounts: list[MoneroAccount] = self._get_test_accounts(wallet) - assert len(accounts) > 0 - for account in accounts: - WalletUtils.test_account(account, Utils.NETWORK_TYPE, False) - assert len(account.subaddresses) == 0 - - @override - def test_get_accounts_with_subaddresses(self, wallet: MoneroWallet) -> None: - accounts: list[MoneroAccount] = self._get_test_accounts(wallet, True) - assert len(accounts) > 0 - for account in accounts: - WalletUtils.test_account(account, Utils.NETWORK_TYPE, False) - assert len(account.subaddresses) > 0 - - @override - def test_get_subaddresses(self, wallet: MoneroWallet) -> None: - wallet = wallet - accounts: list[MoneroAccount] = self._get_test_accounts(wallet) - assert len(accounts) > 0 - for account in accounts: - assert account.index is not None - subaddresses: list[MoneroSubaddress] = wallet.get_subaddresses(account.index, self._subaddress_indices) - assert len(subaddresses) > 0 - for subaddress in subaddresses: - WalletUtils.test_subaddress(subaddress, False) - assert account.index == subaddress.account_index - - @override - def test_get_subaddress_by_index(self, wallet: MoneroWallet) -> None: - accounts: list[MoneroAccount] = self._get_test_accounts(wallet) - assert len(accounts) > 0 - for account in accounts: - assert account.index is not None - subaddresses: list[MoneroSubaddress] = wallet.get_subaddresses(account.index, self._subaddress_indices) - assert len(subaddresses) > 0 - - for subaddress in subaddresses: - assert subaddress.index is not None - WalletUtils.test_subaddress(subaddress, False) - AssertUtils.assert_equals(subaddress, self._get_subaddress(wallet, account.index, subaddress.index)) - # test plural call with single subaddr number - AssertUtils.assert_equals( - subaddress, wallet.get_subaddresses(account.index, [subaddress.index])[0] - ) - - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_is_closed(self) -> None: - """A keys-only wallet reports its open/closed state and rejects use once closed.""" - config: MoneroWalletConfig = MoneroWalletConfig() - config.network_type = Utils.NETWORK_TYPE - w: MoneroWalletKeys = MoneroWalletKeys.create_wallet_random(config) - - # a freshly created wallet is open - assert w.is_closed() is False - primary_address: str = w.get_primary_address() - - # closing it (without saving) marks it closed - w.close() - assert w.is_closed() is True - - # any accessor now raises "Wallet is closed" - with pytest.raises(RuntimeError, match="Wallet is closed"): - w.get_primary_address() - with pytest.raises(RuntimeError, match="Wallet is closed"): - w.get_private_view_key() - - # closing an already-closed wallet is a no-op (and does not re-raise) - w.close() - assert w.is_closed() is True - - # sanity: the address read before closing is unaffected - MoneroUtils.validate_address(primary_address, Utils.NETWORK_TYPE) - - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_close_with_save_not_supported(self) -> None: - """`close(save=True)` is rejected because a keys-only wallet has nothing to persist.""" - config: MoneroWalletConfig = MoneroWalletConfig() - config.network_type = Utils.NETWORK_TYPE - w: MoneroWalletKeys = MoneroWalletKeys.create_wallet_random(config) - - with pytest.raises(RuntimeError, match="does not support saving"): - w.close(True) - - # the failed save-and-close left the wallet open - assert w.is_closed() is False - w.close() - - #region Integrated Address - - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_integrated_address_with_empty_standard_address(self) -> None: - """An empty standard_address uses the wallet's own primary address (account 0, subaddress 0).""" - config: MoneroWalletConfig = MoneroWalletConfig() - config.network_type = Utils.NETWORK_TYPE - w: MoneroWalletKeys = MoneroWalletKeys.create_wallet_random(config) - try: - integrated: MoneroIntegratedAddress = w.get_integrated_address("", "a" * 16) - assert integrated.standard_address == w.get_primary_address() - assert integrated.payment_id == "a" * 16 - finally: - w.close() - - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_integrated_address_with_standard_address(self) -> None: - config: MoneroWalletConfig = MoneroWalletConfig() - config.network_type = Utils.NETWORK_TYPE - w: MoneroWalletKeys = MoneroWalletKeys.create_wallet_random(config) - try: - address: str = w.get_primary_address() - integrated: MoneroIntegratedAddress = w.get_integrated_address(address, "b" * 16) - assert integrated.standard_address == address - assert integrated.payment_id == "b" * 16 - finally: - w.close() - - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_integrated_address_invalid_address_raises(self) -> None: - config: MoneroWalletConfig = MoneroWalletConfig() - config.network_type = Utils.NETWORK_TYPE - w: MoneroWalletKeys = MoneroWalletKeys.create_wallet_random(config) - try: - with pytest.raises(RuntimeError, match="Invalid address"): - w.get_integrated_address("notanaddress", "a" * 16) - finally: - w.close() - - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_integrated_address_subaddress_raises(self) -> None: - config: MoneroWalletConfig = MoneroWalletConfig() - config.network_type = Utils.NETWORK_TYPE - w: MoneroWalletKeys = MoneroWalletKeys.create_wallet_random(config) - try: - subaddress: str = w.get_address(1, 1) - with pytest.raises(RuntimeError, match="Subaddress shouldn't be used"): - w.get_integrated_address(subaddress, "a" * 16) - finally: - w.close() - - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_integrated_address_already_integrated_raises(self) -> None: - config: MoneroWalletConfig = MoneroWalletConfig() - config.network_type = Utils.NETWORK_TYPE - w: MoneroWalletKeys = MoneroWalletKeys.create_wallet_random(config) - try: - integrated: str = w.get_integrated_address("", "a" * 16).integrated_address - with pytest.raises(RuntimeError, match="Already integrated address"): - w.get_integrated_address(integrated, "a" * 16) - finally: - w.close() - - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_integrated_address_missing_payment_id_raises(self) -> None: - config: MoneroWalletConfig = MoneroWalletConfig() - config.network_type = Utils.NETWORK_TYPE - w: MoneroWalletKeys = MoneroWalletKeys.create_wallet_random(config) - try: - with pytest.raises(RuntimeError, match="Payment ID shouldn't be left unspecified"): - w.get_integrated_address(w.get_primary_address(), "") - finally: - w.close() - - #endregion - - #region Message Signing - - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_sign_message_invalid_signature_type_base_address_raises(self) -> None: - config: MoneroWalletConfig = MoneroWalletConfig() - config.network_type = Utils.NETWORK_TYPE - w: MoneroWalletKeys = MoneroWalletKeys.create_wallet_random(config) - try: - invalid_type: MoneroMessageSignatureType = MoneroMessageSignatureType(99) # type: ignore - with pytest.raises(RuntimeError, match="Invalid signature type requested"): - w.sign_message("hello", invalid_type, 0, 0) - finally: - w.close() - - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_sign_message_invalid_signature_type_subaddress_raises(self) -> None: - config: MoneroWalletConfig = MoneroWalletConfig() - config.network_type = Utils.NETWORK_TYPE - w: MoneroWalletKeys = MoneroWalletKeys.create_wallet_random(config) - try: - invalid_type: MoneroMessageSignatureType = MoneroMessageSignatureType(99) # type: ignore - with pytest.raises(RuntimeError, match="Invalid signature type requested"): - w.sign_message("hello", invalid_type, 1, 1) - finally: - w.close() - - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_verify_message_no_signature_header(self) -> None: - config: MoneroWalletConfig = MoneroWalletConfig() - config.network_type = Utils.NETWORK_TYPE - w: MoneroWalletKeys = MoneroWalletKeys.create_wallet_random(config) - try: - result: MoneroMessageSignatureResult = w.verify_message("hello", w.get_primary_address(), "not-a-signature") - WalletUtils.test_message_signature_result(result, False) - finally: - w.close() - - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_verify_message_invalid_base58(self) -> None: - config: MoneroWalletConfig = MoneroWalletConfig() - config.network_type = Utils.NETWORK_TYPE - w: MoneroWalletKeys = MoneroWalletKeys.create_wallet_random(config) - try: - result: MoneroMessageSignatureResult = w.verify_message("hello", w.get_primary_address(), "SigV2!!!not-base58!!!") - WalletUtils.test_message_signature_result(result, False) - finally: - w.close() - - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_verify_message_wrong_decoded_size(self) -> None: - config: MoneroWalletConfig = MoneroWalletConfig() - config.network_type = Utils.NETWORK_TYPE - w: MoneroWalletKeys = MoneroWalletKeys.create_wallet_random(config) - try: - address: str = w.get_primary_address() - signature: str = w.sign_message("hello", MoneroMessageSignatureType.SIGN_WITH_SPEND_KEY, 0, 0) - # truncate the base58 payload so it decodes to fewer bytes than crypto::signature expects - truncated: str = signature[:5] + signature[5:-10] - result: MoneroMessageSignatureResult = w.verify_message("hello", address, truncated) - WalletUtils.test_message_signature_result(result, False) - finally: - w.close() - - #endregion - - #region Utils - - def _get_subaddress(self, wallet: MoneroWallet, account_idx: int, subaddress_idx: int) -> Optional[MoneroSubaddress]: - subaddress_indices: list[int] = [subaddress_idx] - subaddresses: list[MoneroSubaddress] = wallet.get_subaddresses(account_idx, subaddress_indices) - - if len(subaddresses) == 0: - return None - - return subaddresses[0] - - def _get_test_accounts(self, wallet: MoneroWallet, include_subaddresses: bool = False) -> list[MoneroAccount]: - account_indices: list[int] = self._account_indices - subaddress_indices: list[int] = self._subaddress_indices - accounts: list[MoneroAccount] = [] - for account_idx in account_indices: - account: MoneroAccount = wallet.get_account(account_idx) - - if include_subaddresses: - account.subaddresses = wallet.get_subaddresses(account_idx, subaddress_indices) - - accounts.append(account) - - return accounts - - #endregion diff --git a/tests/test_monero_wallet_model.py b/tests/test_monero_wallet_model.py deleted file mode 100644 index afad808f..00000000 --- a/tests/test_monero_wallet_model.py +++ /dev/null @@ -1,1859 +0,0 @@ -import pytest -import logging -import subprocess -import sys - -from monero import ( - MoneroTxQuery, MoneroTransferQuery, MoneroOutputQuery, - MoneroWalletConfig, MoneroDestination, MoneroUtils, - MoneroTxConfig, MoneroSubaddress, MoneroAccount, MoneroTxWallet, - MoneroOutputWallet, MoneroKeyImage, MoneroIntegratedAddress, - MoneroKeyImageImportResult, MoneroKeyImageExportResult, MoneroMessageSignatureResult, - MoneroMessageSignatureType, MoneroCheck, MoneroCheckTx, MoneroCheckReserve, - MoneroMultisigInfo, MoneroMultisigInitResult, MoneroMultisigSignResult, - MoneroAddressBookEntry, MoneroAccountTag, MoneroIncomingTransfer, - MoneroOutgoingTransfer, IncomingTransferComparator, OutputComparator, MoneroTx, MoneroTransfer, - MoneroTxSet, MoneroSyncResult, MoneroDecodedAddress, - MoneroAddressType, MoneroNetworkType, MoneroTxPriority, MoneroBlock -) -from utils import BaseTestClass, TestUtils, AssertUtils - -logger: logging.Logger = logging.getLogger("TestMoneroWalletModel") - - -@pytest.mark.unit -class TestMoneroWalletModel(BaseTestClass): - """Test monero wallet data model.""" - - #region Tests - - # Test output query expected behaviour - def test_output_query(self) -> None: - output_query: MoneroOutputQuery = MoneroOutputQuery() - tx_query: MoneroTxQuery = MoneroTxQuery() - - # test tx query property assign - try: - output_query.tx_query = tx_query # type: ignore - except AttributeError as e: - err_msg: str = str(e) - assert "object has no setter" in err_msg, err_msg - - # assign tx query to output query - output_query.set_tx_query(tx_query, True) - - assert output_query.tx_query is not None - assert output_query.tx_query == tx_query - assert tx_query.input_query is None - assert tx_query.output_query is not None - assert tx_query.output_query == output_query - - # reassign output query to tx query - output_query.tx_query.output_query = output_query - assert output_query.tx_query is not None - assert output_query == output_query.tx_query.output_query - - # remove tx query from output query - output_query.set_tx_query(None, True) - - assert output_query.tx_query is None - assert tx_query.output_query is None - - # Test input query expected behaviour - def test_input_query(self) -> None: - input_query: MoneroOutputQuery = MoneroOutputQuery() - tx_query: MoneroTxQuery = MoneroTxQuery() - - # assign tx query to input query - input_query.set_tx_query(tx_query, False) - - assert input_query.tx_query is not None - assert input_query.tx_query == tx_query - assert tx_query.output_query is None - assert tx_query.input_query is not None - assert tx_query.input_query == input_query - - # reassign input query to tx query - input_query.tx_query.input_query = input_query - assert input_query.tx_query is not None - assert input_query == input_query.tx_query.input_query - - # remove tx query from input query - input_query.set_tx_query(None, False) - - assert input_query.tx_query is None - assert tx_query.input_query is None - - # Test transfer query expected behaviour - def test_transfer_query(self) -> None: - transfer_query: MoneroTransferQuery = MoneroTransferQuery() - tx_query: MoneroTxQuery = MoneroTxQuery() - - # assign tx query to transfer query - transfer_query.tx_query = tx_query - - assert tx_query.transfer_query is not None - assert tx_query.transfer_query == transfer_query - - # reassign transfer query to tx query - transfer_query.tx_query.transfer_query = transfer_query - assert transfer_query.tx_query is not None - assert transfer_query == transfer_query.tx_query.transfer_query - - # remove tx query from transfer query - transfer_query.tx_query = None - - assert tx_query.transfer_query is None - - transfer_query: MoneroTransferQuery = MoneroTransferQuery() - transfer_query.tx_query = MoneroTxQuery() - - # check incoming/outgoing - assert transfer_query.incoming is None - assert transfer_query.outgoing is None - assert transfer_query.is_incoming() is None - assert transfer_query.is_outgoing() is None - - # set incoming - transfer_query.incoming = True - assert transfer_query.is_incoming() is True - assert transfer_query.outgoing is False - assert transfer_query.is_outgoing() is False - transfer_query.incoming = None - - # set outgoing - transfer_query.outgoing = True - assert transfer_query.is_outgoing() is True - assert transfer_query.incoming is False - assert transfer_query.is_incoming() is False - - # Test tx query expected behaviour - def test_tx_query(self) -> None: - tx_query: MoneroTxQuery = MoneroTxQuery() - transfer_query: MoneroTransferQuery = MoneroTransferQuery() - output_query: MoneroOutputQuery = MoneroOutputQuery() - input_query: MoneroOutputQuery = MoneroOutputQuery() - - # assign transfer query to tx query - tx_query.transfer_query = transfer_query - - assert tx_query.transfer_query == transfer_query - assert transfer_query.tx_query is not None - assert transfer_query.tx_query == tx_query - - # remove transfer query from tx query - tx_query.transfer_query = None - - assert tx_query.transfer_query != transfer_query - assert transfer_query.tx_query is None - - # assign output query to tx query - tx_query.output_query = output_query - - assert tx_query.output_query == output_query - assert output_query.tx_query is not None - assert output_query.tx_query == tx_query - - # remove output query from tx query - tx_query.output_query = None - - assert tx_query.output_query != output_query - assert output_query.tx_query is None - - # assign input query to tx query - tx_query.input_query = input_query - - assert tx_query.input_query == input_query - assert input_query.tx_query is not None - assert input_query.tx_query == tx_query - - # remove output query from tx query - tx_query.input_query = None - - assert tx_query.input_query != input_query - assert input_query.tx_query is None - - def test_destination(self) -> None: - amount: int = MoneroUtils.xmr_to_atomic_units(1) - dest: MoneroDestination = MoneroDestination(TestUtils.ADDRESS, amount) - logger.debug(f"Testing destination: {dest.serialize()}") - copy: MoneroDestination = dest.copy() - AssertUtils.assert_equals(dest, copy) - - def test_wallet_config(self) -> None: - config: MoneroWalletConfig = TestUtils.get_wallet_full_config(TestUtils.get_daemon_rpc_connection()) - logger.debug(f"Testing wallet config: {config.serialize()}") - copy: MoneroWalletConfig = config.copy() - AssertUtils.assert_equals(config, copy) - config_str: str = config.serialize() - deserialized_config: MoneroWalletConfig = MoneroWalletConfig.deserialize(config_str) - logger.debug(f"Deserialized config: {deserialized_config.serialize()}") - AssertUtils.assert_equals(config, deserialized_config) - - @pytest.mark.parametrize("json_fragment", ['{"networkType":-1}', '{"networkType":3}']) - def test_wallet_config_invalid_network_type(self, json_fragment: str) -> None: - with pytest.raises(Exception, match="Invalid network type"): - MoneroWalletConfig.deserialize(json_fragment) - - def test_tx_config(self) -> None: - config: MoneroTxConfig = MoneroTxConfig() - config.set_address(TestUtils.ADDRESS) - config.amount = MoneroUtils.xmr_to_atomic_units(0.5) - config.account_index = 0 - config.subaddress_indices = [i for i in range(10)] - config.below_amount = MoneroUtils.xmr_to_atomic_units(0.1) - config.can_split = True - config.fee = MoneroUtils.xmr_to_atomic_units(0.00075) - config.sweep_each_subaddress = False - config.priority = MoneroTxPriority.ELEVATED - config.key_image = "a" * 64 - - copy: MoneroTxConfig = config.copy() - AssertUtils.assert_equals(config, copy) - - config_str: str = config.serialize() - logger.debug(f"Serialized tx config: {config_str}") - - deserialized_config: MoneroTxConfig = MoneroTxConfig.deserialize(config_str) - AssertUtils.assert_equals(config, deserialized_config) - - @pytest.mark.parametrize("priority,priority_num", [ - (MoneroTxPriority.DEFAULT, 0), - (MoneroTxPriority.UNIMPORTANT, 1), - (MoneroTxPriority.NORMAL, 2), - (MoneroTxPriority.ELEVATED, 3), - ]) - def test_tx_config_priority_deserialize(self, priority: MoneroTxPriority, priority_num: int) -> None: - config: MoneroTxConfig = MoneroTxConfig.deserialize('{"priority": %d}' % priority_num) - assert config.priority == priority - - def test_tx_config_invalid_priority_deserialize(self) -> None: - with pytest.raises(RuntimeError) as exc_info: - MoneroTxConfig.deserialize('{"priority": 4}') - assert str(exc_info.value) == "Invalid priority number: 4" - - def test_get_normalized_destinations_uses_destinations_when_address_and_amount_unset(self) -> None: - config: MoneroTxConfig = MoneroTxConfig() - config.destinations = [MoneroDestination(TestUtils.ADDRESS, 100), MoneroDestination(TestUtils.MINING_ADDRESS, 200)] - assert config.get_normalized_destinations() == config.destinations - - def test_get_normalized_destinations_builds_single_destination(self) -> None: - config: MoneroTxConfig = MoneroTxConfig() - config.address = TestUtils.ADDRESS - config.amount = 500000 - assert len(config.destinations) == 0 # address/amount alone don't populate destinations - - normalized: list[MoneroDestination] = config.get_normalized_destinations() - assert len(normalized) == 1 - assert normalized[0].address == TestUtils.ADDRESS - assert normalized[0].amount == 500000 - - def test_get_normalized_destinations_conflicts_with_multiple_destinations(self) -> None: - config: MoneroTxConfig = MoneroTxConfig() - config.address = TestUtils.ADDRESS - config.amount = 500000 - config.destinations = [MoneroDestination(TestUtils.ADDRESS, 500000), MoneroDestination(TestUtils.MINING_ADDRESS, 1)] - with pytest.raises(RuntimeError) as exc_info: - config.get_normalized_destinations() - assert str(exc_info.value) == "Invalid tx configuration: single destination address/amount incompatible with multiple destinations" - - def test_get_normalized_destinations_address_mismatch(self) -> None: - config: MoneroTxConfig = MoneroTxConfig() - config.address = TestUtils.ADDRESS - config.amount = 500000 - config.destinations = [MoneroDestination(TestUtils.MINING_ADDRESS, 500000)] - with pytest.raises(RuntimeError) as exc_info: - config.get_normalized_destinations() - assert str(exc_info.value) == "Invalid tx configuration: single destination address does not match first destination address" - - def test_get_normalized_destinations_amount_mismatch(self) -> None: - config: MoneroTxConfig = MoneroTxConfig() - config.address = TestUtils.ADDRESS - config.amount = 500000 - config.destinations = [MoneroDestination(TestUtils.ADDRESS, 1)] - with pytest.raises(RuntimeError) as exc_info: - config.get_normalized_destinations() - assert str(exc_info.value) == "Invalid tx configuration: single destination amount does not match first destination amount" - - def test_get_normalized_destinations_matches_single_destination(self) -> None: - config: MoneroTxConfig = MoneroTxConfig() - config.address = TestUtils.ADDRESS - config.amount = 500000 - config.destinations = [MoneroDestination(TestUtils.ADDRESS, 500000)] - assert config.get_normalized_destinations() == config.destinations - - #endregion - - #region meets_criteria - - def test_tx_query_meets_criteria_matches_unconstrained_tx(self) -> None: - tx: MoneroTxWallet = MoneroTxWallet() - tx.hash = "a" * 64 - assert MoneroTxQuery().meets_criteria(tx) is True - - @pytest.mark.parametrize("field,value,other_value", [ - ("hash", "a" * 64, "b" * 64), - ("payment_id", "c" * 16, "d" * 16), - ("is_confirmed", True, False), - ("in_tx_pool", True, False), - ("relay", True, False), - ("is_failed", True, False), - ("is_miner_tx", True, False), - ("is_locked", True, False), - ("is_incoming", True, False), - ("is_outgoing", True, False), - ]) - def test_tx_query_meets_criteria_field_filters(self, field: str, value: object, other_value: object) -> None: - tx: MoneroTxWallet = MoneroTxWallet() - tx.hash = "a" * 64 - setattr(tx, field, value) - - query: MoneroTxQuery = MoneroTxQuery() - setattr(query, field, value) - assert query.meets_criteria(tx) is True - - setattr(query, field, other_value) - assert query.meets_criteria(tx) is False - - def test_tx_query_meets_criteria_has_payment_id(self) -> None: - with_payment_id: MoneroTxWallet = MoneroTxWallet() - with_payment_id.hash = "a" * 64 - with_payment_id.payment_id = "b" * 16 - without_payment_id: MoneroTxWallet = MoneroTxWallet() - without_payment_id.hash = "c" * 64 - - query_true: MoneroTxQuery = MoneroTxQuery() - query_true.has_payment_id = True - assert query_true.meets_criteria(with_payment_id) is True - assert query_true.meets_criteria(without_payment_id) is False - - query_false: MoneroTxQuery = MoneroTxQuery() - query_false.has_payment_id = False - assert query_false.meets_criteria(without_payment_id) is True - assert query_false.meets_criteria(with_payment_id) is False - - def test_tx_query_meets_criteria_hashes(self) -> None: - tx: MoneroTxWallet = MoneroTxWallet() - tx.hash = "a" * 64 - - query: MoneroTxQuery = MoneroTxQuery() - query.hashes = ["a" * 64, "b" * 64] - assert query.meets_criteria(tx) is True - - query.hashes = ["c" * 64] - assert query.meets_criteria(tx) is False - - def test_tx_query_meets_criteria_payment_ids(self) -> None: - with_payment_id: MoneroTxWallet = MoneroTxWallet() - with_payment_id.hash = "a" * 64 - with_payment_id.payment_id = "b" * 16 - without_payment_id: MoneroTxWallet = MoneroTxWallet() - without_payment_id.hash = "c" * 64 - - query: MoneroTxQuery = MoneroTxQuery() - query.payment_ids = ["b" * 16, "d" * 16] - assert query.meets_criteria(with_payment_id) is True - assert query.meets_criteria(without_payment_id) is False # tx has no payment id at all - - query.payment_ids = ["d" * 16] - assert query.meets_criteria(with_payment_id) is False # tx's payment id isn't in the list - - def test_tx_query_meets_criteria_height_filters(self) -> None: - def confirmed_tx(height: int) -> MoneroTxWallet: - tx: MoneroTxWallet = MoneroTxWallet() - tx.hash = "a" * 64 - block: MoneroBlock = MoneroBlock() - block.height = height - tx.block = block - return tx - - tx: MoneroTxWallet = confirmed_tx(100) - - height_query: MoneroTxQuery = MoneroTxQuery() - height_query.height = 100 - assert height_query.meets_criteria(tx) is True - height_query.height = 200 - assert height_query.meets_criteria(tx) is False - - min_query: MoneroTxQuery = MoneroTxQuery() - min_query.min_height = 50 - assert min_query.meets_criteria(tx) is True - min_query.min_height = 150 - assert min_query.meets_criteria(tx) is False - - max_query: MoneroTxQuery = MoneroTxQuery() - max_query.max_height = 150 - assert max_query.meets_criteria(tx) is True - max_query.max_height = 50 - assert max_query.meets_criteria(tx) is False - - # an unconfirmed tx (no height) never satisfies a height-bound query - unconfirmed: MoneroTxWallet = MoneroTxWallet() - unconfirmed.hash = "b" * 64 - assert min_query.meets_criteria(unconfirmed) is False - - def test_tx_query_meets_criteria_query_children_default_and_false(self) -> None: - tx: MoneroTxWallet = MoneroTxWallet() - tx.hash = "a" * 64 # no inputs -> fails an enforced input_query - - query: MoneroTxQuery = MoneroTxQuery() - query.input_query = MoneroOutputQuery() - - # query_children defaults to True, matching monero-cpp's default - assert query.meets_criteria(tx) is False - assert query.meets_criteria(tx, True) is False - assert query.meets_criteria(tx, False) is True - - def test_tx_query_meets_criteria_transfer_query(self) -> None: - def tx_with_outgoing(amount: int) -> MoneroTxWallet: - tx: MoneroTxWallet = MoneroTxWallet() - tx.hash = "a" * 64 - tx.outgoing_transfer = MoneroOutgoingTransfer() - tx.outgoing_transfer.amount = amount - tx.outgoing_transfer.tx = tx - return tx - - def tx_with_incoming(amount: int) -> MoneroTxWallet: - tx: MoneroTxWallet = MoneroTxWallet() - tx.hash = "a" * 64 - transfer: MoneroIncomingTransfer = MoneroIncomingTransfer() - transfer.amount = amount - transfer.tx = tx - tx.incoming_transfers = [transfer] - return tx - - query: MoneroTxQuery = MoneroTxQuery() - query.transfer_query = MoneroTransferQuery() - query.transfer_query.amount = 500 - - assert query.meets_criteria(tx_with_outgoing(500), True) is True # matches via outgoing - assert query.meets_criteria(tx_with_incoming(500), True) is True # matches via incoming - assert query.meets_criteria(tx_with_outgoing(1), True) is False # no transfer matches - - # outgoing fails the query but an incoming transfer still matches as a fallback - tx: MoneroTxWallet = tx_with_outgoing(1) - incoming: MoneroIncomingTransfer = MoneroIncomingTransfer() - incoming.amount = 500 - incoming.tx = tx - tx.incoming_transfers = [incoming] - assert query.meets_criteria(tx, True) is True - - def test_tx_query_meets_criteria_input_query(self) -> None: - tx_no_inputs: MoneroTxWallet = MoneroTxWallet() - tx_no_inputs.hash = "a" * 64 - - tx_with_input: MoneroTxWallet = MoneroTxWallet() - tx_with_input.hash = "b" * 64 - tx_input: MoneroOutputWallet = MoneroOutputWallet() - tx_input.amount = 100 - tx_with_input.inputs = [tx_input] - - query: MoneroTxQuery = MoneroTxQuery() - query.input_query = MoneroOutputQuery() - assert query.meets_criteria(tx_no_inputs, True) is False # no inputs at all - - query.input_query.amount = 999 - assert query.meets_criteria(tx_with_input, True) is False # no input matches - - query.input_query.amount = 100 - assert query.meets_criteria(tx_with_input, True) is True # one input matches - - def test_tx_query_meets_criteria_output_query(self) -> None: - tx_no_outputs: MoneroTxWallet = MoneroTxWallet() - tx_no_outputs.hash = "a" * 64 - - tx_with_output: MoneroTxWallet = MoneroTxWallet() - tx_with_output.hash = "b" * 64 - output: MoneroOutputWallet = MoneroOutputWallet() - output.amount = 100 - tx_with_output.outputs = [output] - - query: MoneroTxQuery = MoneroTxQuery() - query.output_query = MoneroOutputQuery() - assert query.meets_criteria(tx_no_outputs, True) is False # no outputs at all - - query.output_query.amount = 999 - assert query.meets_criteria(tx_with_output, True) is False # no output matches - - query.output_query.amount = 100 - assert query.meets_criteria(tx_with_output, True) is True # one output matches - - def test_tx_query_meets_criteria_none_tx_raises(self) -> None: - with pytest.raises(RuntimeError) as exc_info: - MoneroTxQuery().meets_criteria(None) # type: ignore - assert str(exc_info.value) == "nullptr given to monero_tx_query::meets_criteria()" - - def test_transfer_query_meets_criteria_matches_unconstrained_transfer(self) -> None: - transfer: MoneroIncomingTransfer = MoneroIncomingTransfer() - transfer.amount = 100 - assert MoneroTransferQuery().meets_criteria(transfer, False) is True - - @pytest.mark.parametrize("field,value,other_value", [ - ("amount", 100, 999), - ("account_index", 2, 5), - ]) - def test_transfer_query_meets_criteria_common_field_filters(self, field: str, value: object, other_value: object) -> None: - transfer: MoneroIncomingTransfer = MoneroIncomingTransfer() - transfer.amount = 1 - setattr(transfer, field, value) - - query: MoneroTransferQuery = MoneroTransferQuery() - setattr(query, field, value) - assert query.meets_criteria(transfer, False) is True - - setattr(query, field, other_value) - assert query.meets_criteria(transfer, False) is False - - def test_transfer_query_meets_criteria_incoming_outgoing_flags(self) -> None: - incoming: MoneroIncomingTransfer = MoneroIncomingTransfer() - incoming.amount = 1 - outgoing: MoneroOutgoingTransfer = MoneroOutgoingTransfer() - outgoing.amount = 1 - - incoming_query: MoneroTransferQuery = MoneroTransferQuery() - incoming_query.incoming = True - assert incoming_query.meets_criteria(incoming, False) is True - assert incoming_query.meets_criteria(outgoing, False) is False - - outgoing_query: MoneroTransferQuery = MoneroTransferQuery() - outgoing_query.outgoing = True - assert outgoing_query.meets_criteria(outgoing, False) is True - assert outgoing_query.meets_criteria(incoming, False) is False - - def test_transfer_query_meets_criteria_incoming_has_destinations_always_false(self) -> None: - # has_destinations is an outgoing-only concept; setting it on the query - # rejects an incoming transfer regardless of True/False - incoming: MoneroIncomingTransfer = MoneroIncomingTransfer() - incoming.amount = 1 - - query_true: MoneroTransferQuery = MoneroTransferQuery() - query_true.has_destinations = True - assert query_true.meets_criteria(incoming, False) is False - - query_false: MoneroTransferQuery = MoneroTransferQuery() - query_false.has_destinations = False - assert query_false.meets_criteria(incoming, False) is False - - def test_transfer_query_meets_criteria_incoming_address_fields(self) -> None: - incoming: MoneroIncomingTransfer = MoneroIncomingTransfer() - incoming.amount = 1 - incoming.address = TestUtils.ADDRESS - incoming.subaddress_index = 3 - - address_query: MoneroTransferQuery = MoneroTransferQuery() - address_query.address = TestUtils.ADDRESS - assert address_query.meets_criteria(incoming, False) is True - address_query.address = TestUtils.MINING_ADDRESS - assert address_query.meets_criteria(incoming, False) is False - - addresses_query: MoneroTransferQuery = MoneroTransferQuery() - addresses_query.addresses = [TestUtils.ADDRESS, TestUtils.MINING_ADDRESS] - assert addresses_query.meets_criteria(incoming, False) is True - addresses_query.addresses = [TestUtils.MINING_ADDRESS] - assert addresses_query.meets_criteria(incoming, False) is False - - subaddress_index_query: MoneroTransferQuery = MoneroTransferQuery() - subaddress_index_query.subaddress_index = 3 - assert subaddress_index_query.meets_criteria(incoming, False) is True - subaddress_index_query.subaddress_index = 9 - assert subaddress_index_query.meets_criteria(incoming, False) is False - - subaddress_indices_query: MoneroTransferQuery = MoneroTransferQuery() - subaddress_indices_query.subaddress_indices = [3, 4] - assert subaddress_indices_query.meets_criteria(incoming, False) is True - subaddress_indices_query.subaddress_indices = [9] - assert subaddress_indices_query.meets_criteria(incoming, False) is False - - def test_transfer_query_meets_criteria_outgoing_address_fields(self) -> None: - outgoing: MoneroOutgoingTransfer = MoneroOutgoingTransfer() - outgoing.amount = 1 - outgoing.addresses = [TestUtils.ADDRESS, TestUtils.MINING_ADDRESS] - - # a single address must be a member of the transfer's address list - address_query: MoneroTransferQuery = MoneroTransferQuery() - address_query.address = TestUtils.ADDRESS - assert address_query.meets_criteria(outgoing, False) is True - address_query.address = "9" + "z" * 94 - assert address_query.meets_criteria(outgoing, False) is False - assert address_query.meets_criteria(MoneroOutgoingTransfer(), False) is False # no addresses at all - - # a list of addresses only needs to intersect - addresses_query: MoneroTransferQuery = MoneroTransferQuery() - addresses_query.addresses = [TestUtils.MINING_ADDRESS, "9" + "z" * 94] - assert addresses_query.meets_criteria(outgoing, False) is True - addresses_query.addresses = ["9" + "z" * 94] - assert addresses_query.meets_criteria(outgoing, False) is False - - def test_transfer_query_meets_criteria_outgoing_subaddress_fields(self) -> None: - outgoing: MoneroOutgoingTransfer = MoneroOutgoingTransfer() - outgoing.amount = 1 - outgoing.subaddress_indices = [3, 4] - - subaddress_index_query: MoneroTransferQuery = MoneroTransferQuery() - subaddress_index_query.subaddress_index = 3 - assert subaddress_index_query.meets_criteria(outgoing, False) is True - subaddress_index_query.subaddress_index = 9 - assert subaddress_index_query.meets_criteria(outgoing, False) is False - assert subaddress_index_query.meets_criteria(MoneroOutgoingTransfer(), False) is False # no indices at all - - subaddress_indices_query: MoneroTransferQuery = MoneroTransferQuery() - subaddress_indices_query.subaddress_indices = [4, 100] - assert subaddress_indices_query.meets_criteria(outgoing, False) is True - subaddress_indices_query.subaddress_indices = [100, 200] - assert subaddress_indices_query.meets_criteria(outgoing, False) is False - - def test_transfer_query_meets_criteria_outgoing_has_destinations(self) -> None: - with_destinations: MoneroOutgoingTransfer = MoneroOutgoingTransfer() - with_destinations.amount = 1 - with_destinations.destinations = [MoneroDestination(TestUtils.ADDRESS, 1)] - without_destinations: MoneroOutgoingTransfer = MoneroOutgoingTransfer() - without_destinations.amount = 1 - - query_true: MoneroTransferQuery = MoneroTransferQuery() - query_true.has_destinations = True - assert query_true.meets_criteria(with_destinations, False) is True - assert query_true.meets_criteria(without_destinations, False) is False - - query_false: MoneroTransferQuery = MoneroTransferQuery() - query_false.has_destinations = False - assert query_false.meets_criteria(without_destinations, False) is True - assert query_false.meets_criteria(with_destinations, False) is False - - def test_transfer_query_meets_criteria_invalid_transfer_type_raises(self) -> None: - transfer: MoneroTransfer = MoneroTransfer() - transfer.amount = 1 - with pytest.raises(RuntimeError) as exc_info: - MoneroTransferQuery().meets_criteria(transfer, False) - assert str(exc_info.value) == "Transfer must be monero_incoming_transfer or monero_outgoing_transfer" - - def test_transfer_query_meets_criteria_query_parent_links_tx_query(self) -> None: - tx: MoneroTxWallet = MoneroTxWallet() - tx.hash = "a" * 64 - transfer: MoneroIncomingTransfer = MoneroIncomingTransfer() - transfer.amount = 100 - transfer.tx = tx - - query: MoneroTransferQuery = MoneroTransferQuery() - query.amount = 100 - query.tx_query = MoneroTxQuery() - query.tx_query.hash = "b" * 64 # does not match the transfer's tx - - # query_parent defaults to True: the mismatching tx_query rejects the transfer - assert query.meets_criteria(transfer) is False - assert query.meets_criteria(transfer, False) is True # bypassed when not querying the parent - - query.tx_query.hash = "a" * 64 - assert query.meets_criteria(transfer) is True - - def test_transfer_query_meets_criteria_none_transfer_raises(self) -> None: - with pytest.raises(RuntimeError) as exc_info: - MoneroTransferQuery().meets_criteria(None, False) # type: ignore - assert str(exc_info.value) == "nullptr given to monero_transfer_query::meets_criteria()" - - def test_output_query_meets_criteria_matches_unconstrained_output(self) -> None: - output: MoneroOutputWallet = MoneroOutputWallet() - output.amount = 1 - assert MoneroOutputQuery().meets_criteria(output, False) is True - - @pytest.mark.parametrize("field,value,other_value", [ - ("account_index", 2, 9), - ("subaddress_index", 5, 1), - ("amount", 100, 1), - ("is_spent", True, False), - ("is_frozen", False, True), - ]) - def test_output_query_meets_criteria_field_filters(self, field: str, value: object, other_value: object) -> None: - output: MoneroOutputWallet = MoneroOutputWallet() - output.amount = 1 - setattr(output, field, value) - - query: MoneroOutputQuery = MoneroOutputQuery() - setattr(query, field, value) - assert query.meets_criteria(output, False) is True - - setattr(query, field, other_value) - assert query.meets_criteria(output, False) is False - - @pytest.mark.parametrize("field,value", [ - ("account_index", 2), - ("subaddress_index", 5), - ("amount", 100), - ("is_spent", True), - ("is_frozen", False), - ]) - def test_output_query_meets_criteria_field_filters_require_output_value(self, field: str, value: object) -> None: - # a query constraint never matches an output that leaves the field unset - output: MoneroOutputWallet = MoneroOutputWallet() - query: MoneroOutputQuery = MoneroOutputQuery() - setattr(query, field, value) - assert query.meets_criteria(output, False) is False - - def test_output_query_meets_criteria_key_image(self) -> None: - output: MoneroOutputWallet = MoneroOutputWallet() - output.amount = 1 - output.key_image = MoneroKeyImage() - output.key_image.hex = "a" * 64 - output.key_image.signature = "b" * 128 - - hex_query: MoneroOutputQuery = MoneroOutputQuery() - hex_query.key_image = MoneroKeyImage() - hex_query.key_image.hex = "a" * 64 - assert hex_query.meets_criteria(output, False) is True - hex_query.key_image.hex = "c" * 64 - assert hex_query.meets_criteria(output, False) is False - - signature_query: MoneroOutputQuery = MoneroOutputQuery() - signature_query.key_image = MoneroKeyImage() - signature_query.key_image.signature = "b" * 128 - assert signature_query.meets_criteria(output, False) is True - signature_query.key_image.signature = "d" * 128 - assert signature_query.meets_criteria(output, False) is False - - # never matches an output with no key image at all - no_key_image_query: MoneroOutputQuery = MoneroOutputQuery() - no_key_image_query.key_image = MoneroKeyImage() - no_key_image_query.key_image.hex = "a" * 64 - assert no_key_image_query.meets_criteria(MoneroOutputWallet(), False) is False - - def test_output_query_meets_criteria_subaddress_indices(self) -> None: - output: MoneroOutputWallet = MoneroOutputWallet() - output.amount = 1 - output.subaddress_index = 7 - - query: MoneroOutputQuery = MoneroOutputQuery() - query.subaddress_indices = [7, 8] - assert query.meets_criteria(output, False) is True - - query.subaddress_indices = [1, 2] - assert query.meets_criteria(output, False) is False - - def test_output_query_meets_criteria_min_max_amount(self) -> None: - output: MoneroOutputWallet = MoneroOutputWallet() - output.amount = 50 - - min_query: MoneroOutputQuery = MoneroOutputQuery() - min_query.min_amount = 10 - assert min_query.meets_criteria(output, False) is True - min_query.min_amount = 100 - assert min_query.meets_criteria(output, False) is False - - max_query: MoneroOutputQuery = MoneroOutputQuery() - max_query.max_amount = 100 - assert max_query.meets_criteria(output, False) is True - max_query.max_amount = 10 - assert max_query.meets_criteria(output, False) is False - - def test_output_query_meets_criteria_query_parent_links_tx_query(self) -> None: - tx: MoneroTxWallet = MoneroTxWallet() - tx.hash = "a" * 64 - output: MoneroOutputWallet = MoneroOutputWallet() - output.amount = 1 - output.tx = tx - - query: MoneroOutputQuery = MoneroOutputQuery() - query.amount = 1 - tx_query: MoneroTxQuery = MoneroTxQuery() - tx_query.hash = "b" * 64 - query.set_tx_query(tx_query, True) - - # query_parent defaults to True: the mismatching tx_query rejects the output - assert query.meets_criteria(output) is False - assert query.meets_criteria(output, False) is True # bypassed when not querying the parent - - tx_query.hash = "a" * 64 - assert query.meets_criteria(output) is True - - def test_output_query_meets_criteria_none_output_raises(self) -> None: - with pytest.raises(RuntimeError) as exc_info: - MoneroOutputQuery().meets_criteria(None, False) # type: ignore - assert str(exc_info.value) == "nullptr given to monero_output_query::meets_criteria()" - - #endregion - - #region Serialize/deserialize integrity - - def test_subaddress_deserialize(self) -> None: - subaddress: MoneroSubaddress = MoneroSubaddress() - subaddress.account_index = 0 - subaddress.index = 1 - subaddress.address = TestUtils.ADDRESS - subaddress.label = "primary" - subaddress.balance = 1000000 - subaddress.unlocked_balance = 900000 - subaddress.is_used = True - subaddress.num_unspent_outputs = 3 - subaddress.num_blocks_to_unlock = 0 - AssertUtils.assert_serialization_integrity(subaddress) - - def test_account_deserialize(self) -> None: - account: MoneroAccount = MoneroAccount() - account.index = 0 - account.balance = 1000000 - account.unlocked_balance = 900000 - account.primary_address = TestUtils.ADDRESS - account.tag = "savings" - # subaddresses is serialized as a sub-array but from_property_tree() never - # reads it back (see test below) - AssertUtils.assert_serialization_integrity(account) - - def test_account_subaddresses_deserialize(self) -> None: - account: MoneroAccount = MoneroAccount() - account.subaddresses = [MoneroSubaddress()] - json_str: str = account.serialize() - logger.debug(f"Serialized account: {json_str}") - assert "subaddresses" in json_str - restored: MoneroAccount = MoneroAccount.deserialize(json_str) - logger.debug(f"Deserialized account re-serialized: {restored.serialize()}") - assert len(restored.subaddresses) == len(account.subaddresses) - - def test_destination_deserialize(self) -> None: - destination: MoneroDestination = MoneroDestination(TestUtils.ADDRESS, 500000) - AssertUtils.assert_serialization_integrity(destination) - - def test_transfer_query_deserialize(self) -> None: - query: MoneroTransferQuery = MoneroTransferQuery() - query.amount = 500000 - query.account_index = 0 - query.incoming = True - query.address = TestUtils.ADDRESS - query.subaddress_index = 1 - query.subaddress_indices = [0, 1, 2] - query.has_destinations = False - # addresses, destinations and tx_query all raise "not implemented" (see below) - AssertUtils.assert_serialization_integrity(query) - - @pytest.mark.parametrize("json_fragment", [ - '{"addresses":["' + TestUtils.ADDRESS + '"]}', - '{"destinations":[{"address":"' + TestUtils.ADDRESS + '","amount":1}]}', - '{"txQuery":{}}', - ]) - def test_transfer_query_unimplemented_fields(self, json_fragment: str) -> None: - with pytest.raises(Exception, match="not implemented"): - MoneroTransferQuery.deserialize(json_fragment) - - def test_transfer_query_deserialize_from_block(self) -> None: - tx_query: MoneroTxQuery = MoneroTxQuery() - tx_query.hash = "a" * 64 - transfer_query: MoneroTransferQuery = MoneroTransferQuery() - transfer_query.amount = 500000 - transfer_query.account_index = 0 - tx_query.transfer_query = transfer_query - - # deserialize_from_block expects a block node wrapping the tx query under "txs" - block_json: str = '{"txs":[' + tx_query.serialize() + ']}' - restored: MoneroTransferQuery = MoneroTransferQuery.deserialize_from_block(block_json) - assert restored.amount == 500000 - assert restored.account_index == 0 - assert restored.tx_query is not None - assert restored.tx_query.hash == "a" * 64 - - def test_transfer_query_deserialize_from_block_no_nested_query(self) -> None: - # a tx with no nested transferQuery gets an empty one, linked to the tx query - tx_query: MoneroTxQuery = MoneroTxQuery() - tx_query.hash = "a" * 64 - block_json: str = '{"txs":[' + tx_query.serialize() + ']}' - restored: MoneroTransferQuery = MoneroTransferQuery.deserialize_from_block(block_json) - assert restored.amount is None - assert restored.tx_query is not None - assert restored.tx_query.hash == "a" * 64 - - def test_transfer_query_deserialize_from_block_no_txs(self) -> None: - restored: MoneroTransferQuery = MoneroTransferQuery.deserialize_from_block('{"txs": []}') - assert restored.amount is None - assert restored.tx_query is None - - def test_output_wallet_deserialize(self) -> None: - output_wallet: MoneroOutputWallet = MoneroOutputWallet() - output_wallet.amount = 1000000 - output_wallet.index = 2 - key_image: MoneroKeyImage = MoneroKeyImage() - key_image.hex = "a" * 64 - key_image.signature = "b" * 128 - output_wallet.key_image = key_image - output_wallet.account_index = 0 - output_wallet.subaddress_index = 1 - output_wallet.is_spent = False - output_wallet.is_frozen = False - AssertUtils.assert_serialization_integrity(output_wallet) - - def test_output_query_deserialize(self) -> None: - query: MoneroOutputQuery = MoneroOutputQuery() - query.amount = 1000000 - query.index = 2 - query.account_index = 0 - query.subaddress_index = 1 - query.is_spent = False - query.is_frozen = False - query.subaddress_indices = [0, 1] - query.min_amount = 100000 - query.max_amount = 2000000 - AssertUtils.assert_serialization_integrity(query) - - def test_output_query_deserialize_from_block(self) -> None: - tx_query: MoneroTxQuery = MoneroTxQuery() - tx_query.hash = "a" * 64 - tx_query.input_query = MoneroOutputQuery() - tx_query.input_query.amount = 5 - tx_query.input_query.index = 1 - tx_query.output_query = MoneroOutputQuery() - tx_query.output_query.amount = 7 - tx_query.output_query.index = 2 - - # deserialize_from_block expects a block node wrapping the tx query under "txs" - block_json: str = '{"txs":[' + tx_query.serialize() + ']}' - restored: MoneroOutputQuery = MoneroOutputQuery.deserialize_from_block(block_json) - assert restored.amount == 7 - assert restored.index == 2 - assert restored.tx_query is not None - assert restored.tx_query.hash == "a" * 64 - # the input query is built alongside the output query and linked back too - assert restored.tx_query.input_query is not None - assert restored.tx_query.input_query.amount == 5 - - def test_output_query_deserialize_from_block_no_txs(self) -> None: - restored: MoneroOutputQuery = MoneroOutputQuery.deserialize_from_block('{"txs": []}') - assert restored.amount is None - assert restored.tx_query is None - - def test_tx_wallet_deserialize(self) -> None: - tx_wallet: MoneroTxWallet = MoneroTxWallet() - tx_wallet.hash = "a" * 64 - tx_wallet.is_miner_tx = False - tx_wallet.fee = 7500000 - tx_wallet.relay = True - tx_wallet.is_relayed = True - tx_wallet.is_confirmed = True - tx_wallet.in_tx_pool = False - tx_wallet.num_confirmations = 10 - tx_wallet.unlock_time = 0 - tx_wallet.is_incoming = True - tx_wallet.is_outgoing = False - tx_wallet.note = "thanks" - tx_wallet.is_locked = False - tx_wallet.input_sum = 2000000 - tx_wallet.output_sum = 1900000 - # tx_set, incoming_transfers, outgoing_transfer, change_address, - # change_amount, num_dummy_outputs and extra_hex all raise "not - # implemented" (see below), same as their monero_tx base counterparts - # (version, inputs, outputs, ...) tested in test_monero_daemon_model.py - AssertUtils.assert_serialization_integrity(tx_wallet) - - @pytest.mark.parametrize("json_fragment", [ - '{"txSet":{}}', - '{"incomingTransfers":[]}', - '{"outgoingTransfer":{}}', - '{"changeAddress":"' + TestUtils.ADDRESS + '"}', - '{"changeAmount":1}', - '{"numDummyOutputs":1}', - '{"extraHex":"deadbeef"}', - ]) - def test_tx_wallet_unimplemented_fields(self, json_fragment: str) -> None: - with pytest.raises(Exception, match="not implemented"): - MoneroTxWallet.deserialize(json_fragment) - - def test_tx_query_deserialize(self) -> None: - tx_query: MoneroTxQuery = MoneroTxQuery() - tx_query.hash = "a" * 64 - tx_query.is_confirmed = True - tx_query.hashes = ["a" * 64, "b" * 64] - tx_query.has_payment_id = False - tx_query.payment_ids = ["c" * 16] - tx_query.height = 3000000 - tx_query.min_height = 2999990 - tx_query.max_height = 3000010 - tx_query.include_outputs = False - # is_outgoing/is_incoming are deliberately not set here: monero_tx_query - # redeclares them as its own fields shadowing monero_tx_wallet's, and - # deserializing populates both copies at once (see test below) - AssertUtils.assert_serialization_integrity(tx_query) - - def test_tx_query_is_incoming_deserialize_not_duplicated(self) -> None: - tx_query: MoneroTxQuery = MoneroTxQuery() - tx_query.is_incoming = True - tx_query.is_outgoing = False - json_str: str = tx_query.serialize() - logger.debug(f"Serialized tx query: {json_str}") - assert json_str.count("isIncoming") == 1 - assert json_str.count("isOutgoing") == 1 - - restored: MoneroTxQuery = MoneroTxQuery.deserialize(json_str) - assert restored.is_incoming == tx_query.is_incoming - assert restored.is_outgoing == tx_query.is_outgoing - - restored_json: str = restored.serialize() - incoming_count: int = restored_json.count("isIncoming") - outgoing_count: int = restored_json.count("isOutgoing") - logger.debug(f"Deserialized tx query re-serialized: {restored_json}") - logger.debug(f"'isIncoming' occurs {incoming_count} time(s), 'isOutgoing' occurs {outgoing_count} time(s) (expected 1 each -- >1 means duplicated, i.e. malformed)") - assert incoming_count == 1 - assert outgoing_count == 1 - - def test_tx_query_nested_transfer_query_deserialize(self) -> None: - # transfer_query is a nested sub-object that to_rapidjson_val() and - # from_property_tree() both handle recursively - tx_query: MoneroTxQuery = MoneroTxQuery() - tx_query.height = 3000000 - transfer_query: MoneroTransferQuery = MoneroTransferQuery() - transfer_query.incoming = True - transfer_query.amount = 500000 - transfer_query.account_index = 0 - tx_query.transfer_query = transfer_query - - json_str: str = tx_query.serialize() - logger.debug(f"Serialized nested tx query: {json_str}") - assert "transferQuery" in json_str - - restored: MoneroTxQuery = MoneroTxQuery.deserialize(json_str) - assert restored.height == tx_query.height - assert restored.transfer_query is not None - assert restored.transfer_query.incoming == transfer_query.incoming - assert restored.transfer_query.amount == transfer_query.amount - assert restored.transfer_query.account_index == transfer_query.account_index - - def test_tx_query_input_and_output_query_deserialize(self) -> None: - # TODO input_query/output_query are read by from_property_tree() but never written by to_rapidjson_val() - tx_query: MoneroTxQuery = MoneroTxQuery.deserialize( - '{"inputQuery":{"amount":5,"index":1},"outputQuery":{"amount":7,"index":2}}' - ) - assert tx_query.input_query is not None - assert tx_query.input_query.amount == 5 - assert tx_query.input_query.index == 1 - assert tx_query.output_query is not None - assert tx_query.output_query.amount == 7 - assert tx_query.output_query.index == 2 - - def test_tx_query_input_and_output_query_serialize_round_trip(self) -> None: - tx_query: MoneroTxQuery = MoneroTxQuery() - tx_query.input_query = MoneroOutputQuery() - tx_query.input_query.amount = 5 - tx_query.input_query.index = 1 - tx_query.output_query = MoneroOutputQuery() - tx_query.output_query.amount = 7 - tx_query.output_query.index = 2 - - json_str: str = tx_query.serialize() - logger.debug(f"Serialized tx query with input/output query: {json_str}") - assert "inputQuery" in json_str - assert "outputQuery" in json_str - - restored: MoneroTxQuery = MoneroTxQuery.deserialize(json_str) - assert restored.input_query is not None - assert restored.input_query.amount == 5 - assert restored.input_query.index == 1 - assert restored.output_query is not None - assert restored.output_query.amount == 7 - assert restored.output_query.index == 2 - - def test_tx_query_deserialize_from_block(self) -> None: - tx_query: MoneroTxQuery = MoneroTxQuery() - tx_query.hash = "a" * 64 - tx_query.is_confirmed = True - tx_query.hashes = ["a" * 64, "b" * 64] - tx_query.min_height = 100 - tx_query.max_height = 200 - - # deserialize_from_block expects a block node wrapping the query under "txs" - block_json: str = '{"txs":[' + tx_query.serialize() + ']}' - restored: MoneroTxQuery = MoneroTxQuery.deserialize_from_block(block_json) - assert restored.hash == "a" * 64 - assert restored.is_confirmed is True - assert list(restored.hashes) == ["a" * 64, "b" * 64] - assert restored.min_height == 100 - assert restored.max_height == 200 - - # the query is linked back to its parent block - assert restored.block is not None - assert restored.block.txs[0] is restored - - def test_tx_query_deserialize_from_block_no_txs(self) -> None: - restored: MoneroTxQuery = MoneroTxQuery.deserialize_from_block('{"txs": []}') - assert restored.hash is None - assert restored.block is None - - def test_integrated_address_deserialize(self) -> None: - address: MoneroIntegratedAddress = MoneroIntegratedAddress() - address.standard_address = TestUtils.ADDRESS - address.payment_id = "d" * 16 - address.integrated_address = TestUtils.ADDRESS - AssertUtils.assert_serialization_integrity(address) - - def test_key_image_import_result_deserialize(self) -> None: - result: MoneroKeyImageImportResult = MoneroKeyImageImportResult() - result.height = 3000000 - result.spent_amount = 500000 - result.unspent_amount = 1500000 - AssertUtils.assert_serialization_integrity(result) - - def test_message_signature_result_deserialize(self) -> None: - result: MoneroMessageSignatureResult = MoneroMessageSignatureResult() - result.is_good = True - result.is_old = False - result.version = 2 - result.signature_type = MoneroMessageSignatureType.SIGN_WITH_SPEND_KEY - AssertUtils.assert_serialization_integrity(result) - - def test_message_signature_result_invalid_signature_type_deserialize(self) -> None: - with pytest.raises(RuntimeError) as exc_info: - MoneroMessageSignatureResult.deserialize('{"signatureType": "bogus"}') - assert str(exc_info.value) == "Invalid message signature type: bogus" - - def test_check_tx_deserialize(self) -> None: - check: MoneroCheckTx = MoneroCheckTx() - check.is_good = True - check.in_tx_pool = False - check.num_confirmations = 10 - check.received_amount = 500000 - AssertUtils.assert_serialization_integrity(check) - - def test_check_reserve_deserialize(self) -> None: - check: MoneroCheckReserve = MoneroCheckReserve() - check.is_good = True - check.total_amount = 1000000 - check.unconfirmed_spent_amount = 0 - AssertUtils.assert_serialization_integrity(check) - - def test_multisig_info_deserialize(self) -> None: - info: MoneroMultisigInfo = MoneroMultisigInfo() - info.is_multisig = True - info.is_ready = True - info.threshold = 2 - info.num_participants = 3 - AssertUtils.assert_serialization_integrity(info) - - def test_multisig_init_result_deserialize(self) -> None: - result: MoneroMultisigInitResult = MoneroMultisigInitResult() - result.address = TestUtils.ADDRESS - result.multisig_hex = "deadbeef" - AssertUtils.assert_serialization_integrity(result) - - def test_multisig_sign_result_deserialize(self) -> None: - result: MoneroMultisigSignResult = MoneroMultisigSignResult() - result.signed_multisig_tx_hex = "deadbeef" - result.tx_hashes = ["a" * 64, "b" * 64] - AssertUtils.assert_serialization_integrity(result) - - def test_address_book_entry_deserialize(self) -> None: - entry: MoneroAddressBookEntry = MoneroAddressBookEntry() - entry.index = 0 - entry.address = TestUtils.ADDRESS - entry.description = "friend" - entry.payment_id = "e" * 16 - AssertUtils.assert_serialization_integrity(entry) - - def test_address_book_entry_constructor_with_payment_id_deserialize(self) -> None: - entry: MoneroAddressBookEntry = MoneroAddressBookEntry(0, TestUtils.ADDRESS, "friend", "e" * 16) - assert entry.index == 0 - assert entry.address == TestUtils.ADDRESS - assert entry.description == "friend" - assert entry.payment_id == "e" * 16 - AssertUtils.assert_serialization_integrity(entry) - - def test_account_tag_deserialize(self) -> None: - tag: MoneroAccountTag = MoneroAccountTag() - tag.tag = "savings" - tag.label = "Savings accounts" - tag.account_indices = [0, 1, 2] - AssertUtils.assert_serialization_integrity(tag) - - def test_account_tag_constructor_deserialize(self) -> None: - tag: MoneroAccountTag = MoneroAccountTag("savings", "Savings accounts") - assert tag.tag == "savings" - assert tag.label == "Savings accounts" - assert len(tag.account_indices) == 0 - AssertUtils.assert_serialization_integrity(tag) - - def test_tx_set_deserialize(self) -> None: - tx_set: MoneroTxSet = MoneroTxSet() - tx_set.unsigned_tx_hex = "deadbeef" - tx_set.multisig_tx_hex = "beefdead" - AssertUtils.assert_serialization_integrity(tx_set) - - def test_tx_set_signed_tx_hex_deserialize(self) -> None: - tx_set: MoneroTxSet = MoneroTxSet() - tx_set.signed_tx_hex = "deadbeef" - AssertUtils.assert_serialization_integrity(tx_set) - - def test_tx_set_txs_deserialize(self) -> None: - json_str: str = '{"txs": [{"hash": "' + "a" * 64 + '"}, {"hash": "' + "b" * 64 + '"}]}' - tx_set: MoneroTxSet = MoneroTxSet.deserialize(json_str) - assert len(tx_set.txs) == 2 - assert all(isinstance(tx, MoneroTxWallet) for tx in tx_set.txs) - assert tx_set.txs[0].hash == "a" * 64 - assert tx_set.txs[1].hash == "b" * 64 - - def test_sync_result_deserialize(self) -> None: - result: MoneroSyncResult = MoneroSyncResult() - result.num_blocks_fetched = 42 - result.received_money = True - AssertUtils.assert_serialization_integrity(result) - - def test_check_deserialize(self) -> None: - check: MoneroCheck = MoneroCheck() - check.is_good = True - AssertUtils.assert_serialization_integrity(check) - - def test_incoming_transfer_deserialize(self) -> None: - transfer: MoneroIncomingTransfer = MoneroIncomingTransfer() - transfer.amount = 500000 - transfer.account_index = 0 - transfer.subaddress_index = 1 - transfer.address = TestUtils.ADDRESS - transfer.num_suggested_confirmations = 10 - AssertUtils.assert_serialization_integrity(transfer) - - def test_outgoing_transfer_deserialize(self) -> None: - transfer: MoneroOutgoingTransfer = MoneroOutgoingTransfer() - transfer.amount = 500000 - transfer.account_index = 0 - transfer.subaddress_indices = [0, 1] - transfer.addresses = [TestUtils.ADDRESS] - transfer.destinations = [MoneroDestination(TestUtils.ADDRESS, 500000)] - AssertUtils.assert_serialization_integrity(transfer) - - def test_decoded_address_deserialize(self) -> None: - address: MoneroDecodedAddress = MoneroDecodedAddress( - TestUtils.ADDRESS, MoneroAddressType.PRIMARY_ADDRESS, MoneroNetworkType.MAINNET - ) - AssertUtils.assert_serialization_integrity(address) - - @pytest.mark.parametrize("json_fragment", [ - '{"networkType":-1}', - '{"networkType":3}', - '{"addressType":-1}', - '{"addressType":3}', - ]) - def test_decoded_address_invalid_enum_range(self, json_fragment: str) -> None: - with pytest.raises(Exception, match="Invalid (network|address) type"): - MoneroDecodedAddress.deserialize(json_fragment) - - def test_key_image_export_result_deserialize(self) -> None: - result: MoneroKeyImageExportResult = MoneroKeyImageExportResult() - result.offset = 3 - key_image: MoneroKeyImage = MoneroKeyImage() - key_image.hex = "a" * 64 - key_image.signature = "b" * 128 - result.key_images = [key_image] - AssertUtils.assert_serialization_integrity(result) - - #endregion - - #region Copy / merge / comparators - - def test_incoming_transfer_copy(self) -> None: - transfer: MoneroIncomingTransfer = MoneroIncomingTransfer() - transfer.amount = 500000 - transfer.account_index = 0 - transfer.subaddress_index = 1 - transfer.address = TestUtils.ADDRESS - transfer.num_suggested_confirmations = 10 - - copy: MoneroIncomingTransfer = transfer.copy() - assert copy is not transfer - assert copy.serialize() == transfer.serialize() - - def test_incoming_transfer_merge(self) -> None: - a: MoneroIncomingTransfer = MoneroIncomingTransfer() - a.amount = 500000 - a.account_index = 0 - a.subaddress_index = 1 - # a.tx is left unset on both sides so merge() won't recurse into tx merge - - b: MoneroIncomingTransfer = a.copy() - b.address = TestUtils.ADDRESS # a.address is unset -> merge fills the gap - a.merge(b) - assert a.address == TestUtils.ADDRESS - - def test_incoming_transfer_merge_recurses_into_tx_merge(self) -> None: - tx_a: MoneroTxWallet = MoneroTxWallet() - tx_a.hash = "a" * 64 - tx_a.is_confirmed = True - - tx_b: MoneroTxWallet = MoneroTxWallet() - tx_b.hash = "a" * 64 - tx_b.is_confirmed = True - tx_b.num_confirmations = 9 # tx_a's num_confirmations is unset -> merge fills the gap - - a: MoneroIncomingTransfer = MoneroIncomingTransfer() - a.tx = tx_a - a.account_index = 0 - a.amount = 100 - - b: MoneroIncomingTransfer = MoneroIncomingTransfer() - b.tx = tx_b - b.account_index = 0 - b.amount = 100 - - # transfers on different txs -> merge delegates to tx merge (which comes back to merging transfers) - a.merge(b) - assert tx_a.num_confirmations == 9 - - def test_incoming_transfer_merge_zero_amount_conflict_keeps_original(self) -> None: - tx: MoneroTxWallet = MoneroTxWallet() - tx.hash = "a" * 64 - - a: MoneroIncomingTransfer = MoneroIncomingTransfer() - a.tx = tx - a.account_index = 0 - a.amount = 500 - - b: MoneroIncomingTransfer = MoneroIncomingTransfer() - b.tx = tx - b.account_index = 0 - b.amount = 0 - - # conflicting amounts where one side is 0 are a known monero-project quirk (failed tx in - # pool): merge() warns and leaves the amount as-is rather than reconciling it - a.merge(b) - assert a.amount == 500 - - def test_tx_wallet_merge_incoming_transfers_with_unset_indices_are_kept_distinct(self) -> None: - """ - merge_incoming_transfer() dedups incoming transfers by (account_index, subaddress_index) - when reconciling two txs' transfer lists. Previously it dereferenced both indices - unconditionally (boost::optional UB when unset), reachable via TxWallet.merge() with - user-constructed MoneroIncomingTransfer objects that never had an index assigned. Since - identity can't be verified without both indices, unset-index transfers must be kept as - distinct entries rather than crashing or being silently coalesced. Run in an isolated - subprocess: locally this UB just gives a wrong (deduped) result, but the same - optional::get() assertion has been observed to abort the whole process in CI's build - (NDEBUG/ODR ambiguity between monero-cpp and monero-python's own compiled units), which a - plain in-process assertion can't survive. - """ - script: str = ( - "import monero, sys\n" - "tx_a = monero.MoneroTxWallet()\n" - "tx_a.hash = 'a' * 64\n" - "tx_a.is_confirmed = True\n" - "transfer_a = monero.MoneroIncomingTransfer()\n" # account_index/subaddress_index intentionally unset - "transfer_a.tx = tx_a\n" - "tx_a.incoming_transfers = [transfer_a]\n" - "tx_b = monero.MoneroTxWallet()\n" - "tx_b.hash = 'a' * 64\n" - "tx_b.is_confirmed = True\n" - "transfer_b = monero.MoneroIncomingTransfer()\n" # account_index/subaddress_index intentionally unset - "transfer_b.tx = tx_b\n" - "tx_b.incoming_transfers = [transfer_b]\n" - "tx_a.merge(tx_b)\n" - "n = len(tx_a.incoming_transfers) if tx_a.incoming_transfers else 0\n" - "sys.exit(0 if n == 2 else f'incoming_transfers not kept distinct: len={n}')\n" - ) - result: subprocess.CompletedProcess[str] = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, timeout=30) - logger.debug(f"subprocess exit code: {result.returncode}, stderr: {result.stderr.strip()}") - assert result.returncode == 0, ( - f"TxWallet.merge() did not keep unset-index incoming transfers distinct " - f"(exit code {result.returncode}): {result.stderr.strip()[-300:]}" - ) - - def test_incoming_transfer_lt_comparator(self) -> None: - t1: MoneroIncomingTransfer = MoneroIncomingTransfer() - t1.tx = MoneroTxWallet() - t1.account_index = 0 - t1.subaddress_index = 0 - - t2: MoneroIncomingTransfer = MoneroIncomingTransfer() - t2.tx = MoneroTxWallet() - t2.account_index = 0 - t2.subaddress_index = 1 - - assert t1 < t2 - assert not (t2 < t1) - assert IncomingTransferComparator.compare(t1, t2) - assert not IncomingTransferComparator.compare(t2, t1) - - transfers: list[MoneroIncomingTransfer] = [t2, t1] - transfers.sort() - assert transfers[0] is t1 - assert transfers[1] is t2 - - def test_outgoing_transfer_copy(self) -> None: - transfer: MoneroOutgoingTransfer = MoneroOutgoingTransfer() - transfer.amount = 500000 - transfer.account_index = 0 - transfer.addresses = [TestUtils.ADDRESS] - transfer.subaddress_indices = [0] - transfer.destinations = [MoneroDestination(TestUtils.ADDRESS, 500000)] - - copy: MoneroOutgoingTransfer = transfer.copy() - assert copy is not transfer - assert copy.serialize() == transfer.serialize() - - def test_outgoing_transfer_merge(self) -> None: - a: MoneroOutgoingTransfer = MoneroOutgoingTransfer() - a.amount = 500000 - a.account_index = 0 - # a.addresses/subaddress_indices/destinations left empty on both sides so far - - b: MoneroOutgoingTransfer = a.copy() - b.addresses = [TestUtils.ADDRESS] - b.subaddress_indices = [0] - b.destinations = [MoneroDestination(TestUtils.ADDRESS, 500000)] - a.merge(b) # a's lists are empty -> merge adopts b's - assert a.addresses == [TestUtils.ADDRESS] - assert a.subaddress_indices == [0] - assert len(a.destinations) == 1 - - def test_outgoing_transfer_merge_destinations_with_unset_fields(self) -> None: - # destinations with unset address/amount are a reachable state; merge() - # must compare them without dereferencing the empty optionals - a: MoneroOutgoingTransfer = MoneroOutgoingTransfer() - a.amount = 500000 - a.account_index = 0 - a.destinations = [MoneroDestination()] - b: MoneroOutgoingTransfer = a.copy() - b.destinations = [MoneroDestination()] - a.merge(b) # equal (empty) destinations -> no error - assert len(a.destinations) == 1 - - def test_outgoing_transfer_merge_conflicting_destinations_raises(self) -> None: - a: MoneroOutgoingTransfer = MoneroOutgoingTransfer() - a.amount = 500000 - a.account_index = 0 - a.destinations = [MoneroDestination(TestUtils.ADDRESS, 1)] - b: MoneroOutgoingTransfer = a.copy() - b.destinations = [MoneroDestination(TestUtils.ADDRESS, 2)] - with pytest.raises(RuntimeError) as exc_info: - a.merge(b) - assert str(exc_info.value) == "Destination vectors are different" - - def test_output_wallet_copy(self) -> None: - output: MoneroOutputWallet = MoneroOutputWallet() - output.amount = 1000000 - output.index = 2 - output.account_index = 0 - output.subaddress_index = 1 - output.is_spent = False - output.is_frozen = False - - copy: MoneroOutputWallet = output.copy() - assert copy is not output - assert copy.serialize() == output.serialize() - - def test_output_wallet_merge(self) -> None: - a: MoneroOutputWallet = MoneroOutputWallet() - a.amount = 1000000 - a.index = 2 - a.account_index = 0 - a.subaddress_index = 1 - # a.tx is left unset on both sides so merge() won't recurse into tx merge - - b: MoneroOutputWallet = a.copy() - b.is_spent = True # a.is_spent is unset -> merge fills the gap - a.merge(b) - assert a.is_spent is True - - def test_output_wallet_lt_comparator(self) -> None: - o1: MoneroOutputWallet = MoneroOutputWallet() - o1.tx = MoneroTx() - o1.account_index = 0 - o1.subaddress_index = 0 - o1.index = 0 - o1.key_image = MoneroKeyImage() - o1.key_image.hex = "a" * 64 - - o2: MoneroOutputWallet = MoneroOutputWallet() - o2.tx = MoneroTx() - o2.account_index = 0 - o2.subaddress_index = 0 - o2.index = 1 - o2.key_image = MoneroKeyImage() - o2.key_image.hex = "b" * 64 - - assert o1 < o2 - assert not (o2 < o1) - assert OutputComparator.compare(o1, o2) - assert not OutputComparator.compare(o2, o1) - - def test_output_wallet_lt_comparator_account_index(self) -> None: - tx: MoneroTx = MoneroTx() - o1: MoneroOutputWallet = MoneroOutputWallet() - o1.tx = tx - o1.account_index = 0 - o1.subaddress_index = 0 - o1.index = 0 - o1.key_image = MoneroKeyImage() - o1.key_image.hex = "a" * 64 - - o2: MoneroOutputWallet = o1.copy() - o2.account_index = 1 # only the account index differs - - assert OutputComparator.compare(o1, o2) - assert not OutputComparator.compare(o2, o1) - - def test_output_wallet_lt_comparator_subaddress_index(self) -> None: - tx: MoneroTx = MoneroTx() - o1: MoneroOutputWallet = MoneroOutputWallet() - o1.tx = tx - o1.account_index = 0 - o1.subaddress_index = 0 - o1.index = 0 - o1.key_image = MoneroKeyImage() - o1.key_image.hex = "a" * 64 - - o2: MoneroOutputWallet = o1.copy() - o2.subaddress_index = 1 # same account index, only the subaddress index differs - - assert OutputComparator.compare(o1, o2) - assert not OutputComparator.compare(o2, o1) - - def test_output_wallet_lt_comparator_key_image(self) -> None: - tx: MoneroTx = MoneroTx() - o1: MoneroOutputWallet = MoneroOutputWallet() - o1.tx = tx - o1.account_index = 0 - o1.subaddress_index = 0 - o1.index = 0 - o1.key_image = MoneroKeyImage() - o1.key_image.hex = "a" * 64 - - o2: MoneroOutputWallet = o1.copy() - o2.key_image = MoneroKeyImage() - o2.key_image.hex = "b" * 64 # account/subaddress/index tied -> falls back to key image hex - - assert OutputComparator.compare(o1, o2) - assert not OutputComparator.compare(o2, o1) - - outputs: list[MoneroOutputWallet] = [o2, o1] - outputs.sort() - assert outputs[0] is o1 - assert outputs[1] is o2 - - def test_tx_wallet_copy(self) -> None: - tx: MoneroTxWallet = MoneroTxWallet() - tx.hash = "a" * 64 - tx.is_confirmed = True - tx.note = "hello" - - copy: MoneroTxWallet = tx.copy() - assert copy is not tx - assert copy.serialize() == tx.serialize() - - def test_tx_wallet_copy_re_copies_inputs_as_output_wallet(self) -> None: - tx: MoneroTxWallet = MoneroTxWallet() - tx.hash = "a" * 64 - - key_image: MoneroKeyImage = MoneroKeyImage() - key_image.hex = "1" * 64 - tx_input: MoneroOutputWallet = MoneroOutputWallet() - tx_input.tx = tx - tx_input.key_image = key_image - tx_input.amount = 1234 - tx_input.account_index = 2 - tx_input.subaddress_index = 3 - tx_input.is_spent = True - tx_input.is_frozen = False - tx.inputs = [tx_input] - - copy: MoneroTxWallet = tx.copy() - assert isinstance(copy.inputs[0], MoneroOutputWallet) - assert copy.inputs[0] is not tx_input - assert copy.inputs[0].amount == 1234 - assert copy.inputs[0].account_index == 2 - assert copy.inputs[0].subaddress_index == 3 - assert copy.inputs[0].is_spent is True - assert copy.inputs[0].is_frozen is False - assert copy.inputs[0].key_image.hex == "1" * 64 # type: ignore - assert copy.inputs[0].tx is copy - - def test_tx_wallet_merge(self) -> None: - a: MoneroTxWallet = MoneroTxWallet() - a.hash = "a" * 64 - a.is_confirmed = True # required: base monero_tx::merge() dereferences is_confirmed directly - - b: MoneroTxWallet = a.copy() - b.note = "hello" # a.note is unset -> merge fills the gap - a.merge(b) - assert a.note == "hello" - - def test_tx_wallet_merge_is_locked_can_become_false(self) -> None: - a: MoneroTxWallet = MoneroTxWallet() - a.hash = "a" * 64 - a.is_confirmed = True - a.is_locked = False # self: already unlocked - b: MoneroTxWallet = a.copy() - b.is_locked = True # other: still locked - a.merge(b) - assert a.is_locked is False - - def test_tx_wallet_inputs_deserialize_as_output_wallet(self) -> None: - tx: MoneroTxWallet = MoneroTxWallet() - tx.hash = "a" * 64 - tx_input: MoneroOutputWallet = MoneroOutputWallet() - tx_input.amount = 500000 - tx_input.index = 7 - tx_input.account_index = 1 - tx_input.subaddress_index = 2 - tx_input.is_spent = True - tx_input.is_frozen = False - tx_input.key_image = MoneroKeyImage() - tx_input.key_image.hex = "k" * 64 - tx.inputs = [tx_input] - - json_str: str = tx.serialize() - assert "accountIndex" in json_str - assert "isSpent" in json_str - - # monero_tx::from_property_tree parses inputs as MoneroOutput; the wallet - # deserializer re-parses them as MoneroOutputWallet in place - restored: MoneroTxWallet = MoneroTxWallet.deserialize(json_str) - assert len(restored.inputs) == 1 - assert isinstance(restored.inputs[0], MoneroOutputWallet) - assert restored.inputs[0].account_index == 1 - assert restored.inputs[0].subaddress_index == 2 - assert restored.inputs[0].is_spent is True - assert restored.inputs[0].is_frozen is False - assert restored.inputs[0].key_image is not None - assert restored.inputs[0].key_image.hex == "k" * 64 - assert restored.inputs[0].tx is restored - - def test_tx_wallet_outputs_deserialize_as_output_wallet(self) -> None: - tx: MoneroTxWallet = MoneroTxWallet() - tx.hash = "a" * 64 - output: MoneroOutputWallet = MoneroOutputWallet() - output.amount = 500000 - output.index = 3 - output.account_index = 2 - output.subaddress_index = 1 - output.is_spent = True - output.is_frozen = False - tx.outputs = [output] - - json_str: str = tx.serialize() - assert "accountIndex" in json_str - assert "isSpent" in json_str - - restored: MoneroTxWallet = MoneroTxWallet.deserialize(json_str) - assert len(restored.outputs) == 1 - assert isinstance(restored.outputs[0], MoneroOutputWallet) - assert restored.outputs[0].account_index == 2 - assert restored.outputs[0].subaddress_index == 1 - assert restored.outputs[0].is_spent is True - assert restored.outputs[0].is_frozen is False - - def test_tx_wallet_get_outputs_wallet_after_deserialize(self) -> None: - tx: MoneroTxWallet = MoneroTxWallet() - tx.hash = "a" * 64 - output: MoneroOutputWallet = MoneroOutputWallet() - output.amount = 500000 - output.index = 3 - tx.outputs = [output] - - restored: MoneroTxWallet = MoneroTxWallet.deserialize(tx.serialize()) - # once deserialize works: raises "nullptr given to monero_output_query::meets_criteria()" - outputs_wallet: list[MoneroOutputWallet] = restored.get_outputs_wallet() - assert len(outputs_wallet) == 1 - assert outputs_wallet[0].amount == 500000 - - def test_tx_wallet_filter_inputs_wallet(self) -> None: - def make_input(account_index: int, amount: int) -> MoneroOutputWallet: - tx_input: MoneroOutputWallet = MoneroOutputWallet() - tx_input.account_index = account_index - tx_input.amount = amount - return tx_input - - tx: MoneroTxWallet = MoneroTxWallet() - tx.hash = "a" * 64 - tx.inputs = [make_input(0, 100), make_input(1, 200), make_input(0, 300)] - - query: MoneroOutputQuery = MoneroOutputQuery() - query.account_index = 0 - - # filter returns the matches and drops the rest from tx.inputs in place - matched: list[MoneroOutputWallet] = tx.filter_inputs_wallet(query) - assert [i.amount for i in matched] == [100, 300] - assert all(isinstance(i, MoneroOutputWallet) for i in matched) - assert [i.amount for i in tx.inputs] == [100, 300] - - # an unconstrained query keeps everything - assert len(tx.filter_inputs_wallet(MoneroOutputQuery())) == 2 - - def test_tx_wallet_get_inputs_wallet(self) -> None: - def make_input(account_index: int, amount: int) -> MoneroOutputWallet: - tx_input: MoneroOutputWallet = MoneroOutputWallet() - tx_input.account_index = account_index - tx_input.amount = amount - return tx_input - - tx: MoneroTxWallet = MoneroTxWallet() - tx.hash = "a" * 64 - tx.inputs = [make_input(0, 100), make_input(1, 200), make_input(0, 300)] - - query: MoneroOutputQuery = MoneroOutputQuery() - query.account_index = 0 - - # get_inputs_wallet() does not mutate tx.inputs - matched: list[MoneroOutputWallet] = tx.get_inputs_wallet(query) - assert [i.amount for i in matched] == [100, 300] - assert len(tx.inputs) == 3 - - # unconstrained default query (no args) returns all inputs - assert len(tx.get_inputs_wallet()) == 3 - - def test_tx_wallet_filter_outputs_wallet(self) -> None: - def make_output(account_index: int, amount: int) -> MoneroOutputWallet: - output: MoneroOutputWallet = MoneroOutputWallet() - output.account_index = account_index - output.amount = amount - return output - - tx: MoneroTxWallet = MoneroTxWallet() - tx.hash = "a" * 64 - tx.outputs = [make_output(0, 100), make_output(1, 200), make_output(0, 300)] - - query: MoneroOutputQuery = MoneroOutputQuery() - query.account_index = 0 - - # filter returns the matches and drops the rest from tx.outputs in place - matched: list[MoneroOutputWallet] = tx.filter_outputs_wallet(query) - assert [o.amount for o in matched] == [100, 300] - assert all(isinstance(o, MoneroOutputWallet) for o in matched) - assert [o.amount for o in tx.outputs] == [100, 300] - - # an unconstrained query keeps everything - assert len(tx.filter_outputs_wallet(MoneroOutputQuery())) == 2 - - def test_tx_wallet_filter_transfers(self) -> None: - tx: MoneroTxWallet = MoneroTxWallet() - tx.hash = "a" * 64 - - outgoing: MoneroOutgoingTransfer = MoneroOutgoingTransfer() - outgoing.amount = 1000 - - incoming_1: MoneroIncomingTransfer = MoneroIncomingTransfer() - incoming_1.account_index = 0 - incoming_1.amount = 100 - - incoming_2: MoneroIncomingTransfer = MoneroIncomingTransfer() - incoming_2.account_index = 1 - incoming_2.amount = 200 - - tx.outgoing_transfer = outgoing - tx.incoming_transfers = [incoming_1, incoming_2] - - query: MoneroTransferQuery = MoneroTransferQuery() - query.incoming = True - query.account_index = 0 - - # filter returns the matches and drops the rest (outgoing_transfer cleared, incoming_2 removed) - matched: list[MoneroTransfer] = tx.filter_transfers(query) - assert [t.amount for t in matched] == [100] - assert tx.outgoing_transfer is None - assert [t.amount for t in tx.incoming_transfers] == [100] - - def test_tx_wallet_get_transfers(self) -> None: - tx: MoneroTxWallet = MoneroTxWallet() - tx.hash = "a" * 64 - tx.outgoing_transfer = MoneroOutgoingTransfer() - tx.outgoing_transfer.amount = 1000 - tx.incoming_transfers = [MoneroIncomingTransfer(), MoneroIncomingTransfer()] - tx.incoming_transfers[0].amount = 100 - tx.incoming_transfers[1].amount = 200 - - # no-arg overload delegates to an empty query -> outgoing then incoming, in order - all_transfers: list[MoneroTransfer] = tx.get_transfers() - assert [t.amount for t in all_transfers] == [1000, 100, 200] - assert isinstance(all_transfers[0], MoneroOutgoingTransfer) - assert all(isinstance(t, MoneroIncomingTransfer) for t in all_transfers[1:]) - - # get_transfers() does not mutate the tx - assert tx.outgoing_transfer is not None - assert len(tx.incoming_transfers) == 2 - - def test_tx_wallet_get_transfers_with_query(self) -> None: - tx: MoneroTxWallet = MoneroTxWallet() - tx.hash = "a" * 64 - tx.outgoing_transfer = MoneroOutgoingTransfer() - tx.outgoing_transfer.amount = 1000 - tx.incoming_transfers = [MoneroIncomingTransfer(), MoneroIncomingTransfer()] - tx.incoming_transfers[0].amount = 100 - tx.incoming_transfers[1].amount = 200 - - incoming_query: MoneroTransferQuery = MoneroTransferQuery() - incoming_query.incoming = True - assert [t.amount for t in tx.get_transfers(incoming_query)] == [100, 200] - - outgoing_query: MoneroTransferQuery = MoneroTransferQuery() - outgoing_query.outgoing = True - assert [t.amount for t in tx.get_transfers(outgoing_query)] == [1000] - - no_match_query: MoneroTransferQuery = MoneroTransferQuery() - no_match_query.amount = 999999 - assert tx.get_transfers(no_match_query) == [] - - def test_tx_wallet_copy_preserves_output_wallet_type(self) -> None: - tx: MoneroTxWallet = MoneroTxWallet() - tx.hash = "a" * 64 - output: MoneroOutputWallet = MoneroOutputWallet() - output.amount = 500000 - output.account_index = 2 - output.is_spent = True - tx.outputs = [output] - - copy: MoneroTxWallet = tx.copy() - assert len(copy.outputs) == 1 - assert isinstance(copy.outputs[0], MoneroOutputWallet) - assert copy.outputs[0].account_index == 2 - assert copy.outputs[0].is_spent is True - - def test_transfer_query_copy(self) -> None: - query: MoneroTransferQuery = MoneroTransferQuery() - query.amount = 500000 - query.incoming = True - query.address = TestUtils.ADDRESS - - copy: MoneroTransferQuery = query.copy() - assert copy is not query - assert copy.serialize() == query.serialize() - - def test_transfer_query_copy_deep_copies_destinations(self) -> None: - query: MoneroTransferQuery = MoneroTransferQuery() - destination: MoneroDestination = MoneroDestination(TestUtils.ADDRESS, 100) - query.destinations = [destination] - - copy: MoneroTransferQuery = query.copy() - assert len(copy.destinations) == 1 - assert copy.destinations[0] is not destination - assert copy.destinations[0].address == TestUtils.ADDRESS - assert copy.destinations[0].amount == 100 - - def test_output_query_copy(self) -> None: - query: MoneroOutputQuery = MoneroOutputQuery() - query.amount = 1000000 - query.min_amount = 100000 - query.max_amount = 2000000 - - copy: MoneroOutputQuery = query.copy() - assert copy is not query - assert copy.serialize() == query.serialize() - - def test_tx_query_copy(self) -> None: - query: MoneroTxQuery = MoneroTxQuery() - query.hash = "a" * 64 - query.height = 3000000 - query.is_confirmed = True - - copy: MoneroTxQuery = query.copy() - assert copy is not query - assert copy.serialize() == query.serialize() - - def test_tx_query_decontextualize(self) -> None: - query: MoneroTxQuery = MoneroTxQuery() - query.hash = "a" * 64 - query.is_incoming = True - query.is_outgoing = False - query.transfer_query = MoneroTransferQuery() - query.input_query = MoneroOutputQuery() - query.output_query = MoneroOutputQuery() - - # mutates and returns the same query, for convenience - decontextualized: MoneroTxQuery = MoneroTxQuery.decontextualize(query) - assert decontextualized is query - assert query.is_incoming is None - assert query.is_outgoing is None - assert query.transfer_query is None - assert query.input_query is None - assert query.output_query is None - - # criteria that don't require looking up other transfers/outputs are untouched - assert query.hash == "a" * 64 - - #endregion diff --git a/tests/test_monero_wallet_rpc.py b/tests/test_monero_wallet_rpc.py deleted file mode 100644 index 71f479a5..00000000 --- a/tests/test_monero_wallet_rpc.py +++ /dev/null @@ -1,364 +0,0 @@ -import pytest -import logging - -from monero import ( - MoneroWallet, MoneroWalletConfig, MoneroWalletRpc, - MoneroAccount, MoneroError, MoneroDaemonRpc, - MoneroTxWallet, MoneroUtils, MoneroSubaddress -) - -from typing_extensions import override -from utils import ( - TestUtils as Utils, StringUtils, WalletType, - WalletNotificationCollector, WalletErrorUtils, WalletUtils, AssertUtils -) -from test_monero_wallet_common import BaseTestMoneroWallet - -logger: logging.Logger = logging.getLogger("TestMoneroWalletRpc") - - -@pytest.mark.integration -class TestMoneroWalletRpc(BaseTestMoneroWallet): - """Rpc wallet integration tests.""" - - @classmethod - @override - def get_wallet_type(cls) -> WalletType: - return WalletType.RPC - - #region Overrides - - @pytest.fixture(scope="class") - @classmethod - @override - def wallet(cls) -> MoneroWalletRpc: - """Test rpc wallet instance.""" - return cls.get_test_wallet() - - @classmethod - @override - def get_test_wallet(cls) -> MoneroWalletRpc: - return super().get_test_wallet() # type: ignore - - @override - def _open_wallet(self, config: MoneroWalletConfig | None) -> MoneroWalletRpc: - return Utils.open_wallet_rpc(config) - - @override - def _create_wallet(self, config: MoneroWalletConfig) -> MoneroWalletRpc: - return Utils.create_wallet_rpc(config) - - @override - def _close_wallet(self, wallet: MoneroWallet, save: bool = False) -> None: - wallet.close(save) - Utils.free_wallet_rpc_resource(wallet) - - @override - def _get_seed_languages(self) -> list[str]: - return self.get_test_wallet().get_seed_languages() - - @override - def before_all(self) -> None: - super().before_all() - # if full tests ran, wait for full wallet's pool txs to confirm - # TODO calling monero_wallet_full::sync() on a closed wallet causes segmentation fault - #if Utils.WALLET_FULL_TESTS_RUN: - # Utils.clear_wallet_full_txs_pool() - - @override - def after_all(self) -> None: - super().after_all() - Utils.free_wallet_rpc_resources() - - @override - def after_each(self, request: pytest.FixtureRequest) -> None: - super().after_each(request) - Utils.free_wallet_rpc_resources() - - @override - def get_daemon_rpc_uri(self) -> str: - return Utils.DAEMON_RPC_URI if not Utils.IN_CONTAINER else Utils.CONTAINER_DAEMON_RPC_URI - - #endregion - - #region Tests - - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_offline_wallet(self) -> None: - offline_wallet: MoneroWalletRpc = MoneroWalletRpc(Utils.OFFLINE_SERVER_URI, Utils.WALLET_RPC_USERNAME, Utils.WALLET_PASSWORD) - with pytest.raises(Exception) as exc_info: - offline_wallet.is_view_only() - WalletErrorUtils.test_wallet_is_not_connected_error(exc_info.value) - - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_sync_progress(self, wallet: MoneroWalletRpc) -> None: - listener: WalletNotificationCollector = WalletNotificationCollector() - # expected error message - ERR_MSG: str = "Monero Wallet RPC does not support reporting sync progress" - - # sync with listener - with pytest.raises(Exception) as exc_info: - wallet.sync(listener) - assert str(exc_info.value) == ERR_MSG - - # sync with listener from start height - with pytest.raises(Exception) as exc_info: - wallet.sync(0, listener) - assert str(exc_info.value) == ERR_MSG - - # Can set the poll period for wallet notifications - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_set_poll_period_in_ms(self, wallet: MoneroWalletRpc) -> None: - try: - wallet.set_poll_period_in_ms(1000) - finally: - # restore the configured period so later tests poll at the expected rate - wallet.set_poll_period_in_ms(Utils.SYNC_PERIOD_IN_MS) - - # Can get a subaddress via monero_wallet_rpc's - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_get_subaddress_rpc(self, wallet: MoneroWalletRpc) -> None: - account_idx: int = 0 - subaddress_idx: int = 0 - - subaddress: MoneroSubaddress = wallet.get_subaddress(account_idx, subaddress_idx) - WalletUtils.test_subaddress(subaddress) - assert subaddress.account_index == account_idx - assert subaddress.index == subaddress_idx - - plural: list[MoneroSubaddress] = wallet.get_subaddresses(account_idx, [subaddress_idx]) - assert len(plural) == 1 - AssertUtils.assert_equals(subaddress, plural[0]) - - assert subaddress.address == wallet.get_address(account_idx, subaddress_idx) - - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - @override - def test_get_subaddress_address_out_of_range(self, wallet: MoneroWallet) -> None: - accounts: list[MoneroAccount] = wallet.get_accounts(True) - account_idx: int = len(accounts) - 1 - subaddress_idx: int = len(accounts[account_idx].subaddresses) - address: str = wallet.get_address(account_idx, subaddress_idx) - assert address is None or len(address) == 0 - - # Can create a wallet with a randomly generated seed - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_create_wallet_random_rpc(self) -> None: - # create random wallet with defaults - path: str = StringUtils.get_random_string() - config: MoneroWalletConfig = MoneroWalletConfig() - config.path = path - wallet: MoneroWalletRpc = self._create_wallet(config) - seed: str = wallet.get_seed() - MoneroUtils.validate_mnemonic(seed) - assert Utils.SEED != seed - MoneroUtils.validate_address(wallet.get_primary_address(), Utils.NETWORK_TYPE) - # very quick because restore height is chain height - wallet.sync() - self._close_wallet(wallet) - - # create random wallet non defaults - path = StringUtils.get_random_string() - config = MoneroWalletConfig() - config.path = path - config.language = "Spanish" - wallet = self._create_wallet(config) - MoneroUtils.validate_mnemonic(wallet.get_seed()) - assert seed != wallet.get_seed() - seed = wallet.get_seed() - MoneroUtils.validate_address(wallet.get_primary_address(), Utils.NETWORK_TYPE) - - # attempt to create wallet which already exists - with pytest.raises(MoneroError) as exc_info: - wallet.create_wallet(config) - assert str(exc_info.value) == f"Wallet already exists: {path}" - assert seed == wallet.get_seed() - - self._close_wallet(wallet) - - # Can create a RPC wallet from a seed - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_create_wallet_from_seed_rpc(self, daemon: MoneroDaemonRpc) -> None: - # create wallet with seed and defaults - path: str = StringUtils.get_random_string() - config: MoneroWalletConfig = MoneroWalletConfig() - config.path = path - config.seed = Utils.SEED - config.restore_height = Utils.FIRST_RECEIVE_HEIGHT - wallet: MoneroWalletRpc = self._create_wallet(config) - - # validate wallet - assert Utils.SEED == wallet.get_seed() - assert Utils.ADDRESS == wallet.get_primary_address() - wallet.sync() - assert daemon.get_height() == wallet.get_height() - txs: list[MoneroTxWallet] = wallet.get_txs() - # expect used wallet - assert len(txs) > 0, "Wallet is not used" - assert Utils.FIRST_RECEIVE_HEIGHT == txs[0].get_height() - # TODO: monero-wallet-rpc: if wallet is not closed, primary address will not change - self._close_wallet(wallet) - - # create wallet with non-defaults - path = StringUtils.get_random_string() - config = MoneroWalletConfig() - config.path = path - config.seed = Utils.SEED - config.restore_height = Utils.FIRST_RECEIVE_HEIGHT - config.language = "German" - config.seed_offset = "my offset!" - config.save_current = False - wallet = self._create_wallet(config) - - # validate wallet - MoneroUtils.validate_mnemonic(wallet.get_seed()) - assert wallet.get_seed() != Utils.SEED - assert wallet.get_primary_address() != Utils.ADDRESS - assert not wallet.is_view_only() - wallet.sync() - assert daemon.get_height() == wallet.get_height() - txs = wallet.get_txs() - # expect non used wallet - assert len(txs) == 0, "Wallet is used" - self._close_wallet(wallet) - - # Can open wallets - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_open_wallet(self)-> None: - # create names of tests wallets - num_test_wallets: int = 1 - names: list[str] = [ ] - for i in range(num_test_wallets): - logger.debug(f"Creating test wallet {i + 1}") - names.append(StringUtils.get_random_string()) - - # create test wallets - seeds: list[str] = [] - for name in names: - config: MoneroWalletConfig = MoneroWalletConfig() - config.path = name - wallet: MoneroWalletRpc = self._create_wallet(config) - seeds.append(wallet.get_seed()) - self._close_wallet(wallet, True) - - # open test wallets - wallets: list[MoneroWalletRpc] = [] - for i in range(num_test_wallets): - config: MoneroWalletConfig = MoneroWalletConfig() - config.path = names[i] - config.password = Utils.WALLET_PASSWORD - wallet: MoneroWalletRpc = self._open_wallet(config) - assert seeds[i] == wallet.get_seed() - wallets.append(wallet) - - # attempt to open non-existent - config: MoneroWalletConfig = MoneroWalletConfig() - config.path = "btc_integrity" - config.password = Utils.WALLET_PASSWORD - with pytest.raises(Exception): - self._open_wallet(config) - - # close wallets: - for wallet in wallets: - self._close_wallet(wallet) - - # Supports multisig sample code - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_multisig_sample(self) -> None: - self._test_multisig_sample(1, 2) - self._test_multisig_sample(2, 2) - - # Can save the wallet - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_save(self, wallet: MoneroWallet) -> None: - wallet.save() - - # Can close a wallet - @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") - def test_close(self, daemon: MoneroDaemonRpc) -> None: - # create a test wallet - path: str = StringUtils.get_random_string() - config: MoneroWalletConfig = MoneroWalletConfig() - config.path = path - wallet: MoneroWalletRpc = self._create_wallet(config) - wallet.sync() - - # close the wallet - wallet.close() - Utils.free_wallet_rpc_resource(wallet) - - # attempt to interact with the wallet - with pytest.raises(Exception) as exc_info: - wallet.get_height() - WalletErrorUtils.test_no_wallet_file_error(exc_info.value) - - with pytest.raises(Exception) as exc_info: - wallet.get_seed() - WalletErrorUtils.test_no_wallet_file_error(exc_info.value) - - with pytest.raises(Exception) as exc_info: - wallet.sync() - WalletErrorUtils.test_no_wallet_file_error(exc_info.value) - - # re-open the wallet - wallet.open_wallet(path, Utils.WALLET_PASSWORD) - wallet.sync() - assert daemon.get_height() == wallet.get_height() - - # close the wallet - self._close_wallet(wallet, True) - - # Can stop the RPC server - @pytest.mark.skip(reason="Disabled so server not actually stopped") - def test_stop(self, wallet: MoneroWalletRpc) -> None: - wallet.stop() - - #endregion - - #region Not Supported Tests - - @pytest.mark.not_supported - @override - def test_get_daemon_max_peer_height(self, wallet: MoneroWallet) -> None: - return super().test_get_daemon_max_peer_height(wallet) - - @pytest.mark.not_supported - @override - def test_get_daemon_height(self, wallet: MoneroWallet) -> None: - return super().test_get_daemon_height(wallet) - - @pytest.mark.not_supported - @override - def test_get_seed_language(self, wallet: MoneroWallet) -> None: - return super().test_get_seed_language(wallet) - - @pytest.mark.not_supported - @override - def test_get_height_by_date(self, wallet: MoneroWallet) -> None: - return super().test_get_height_by_date(wallet) - - @pytest.mark.not_supported - @override - def test_subaddress_lookahead(self, wallet: MoneroWallet) -> None: - return super().test_subaddress_lookahead(wallet) - - @pytest.mark.xfail(reason="TODO monero-project") - @override - def test_get_public_view_key(self, wallet: MoneroWallet) -> None: - return super().test_get_public_view_key(wallet) - - @pytest.mark.xfail(reason="TODO monero-project") - @override - def test_get_public_spend_key(self, wallet: MoneroWallet) -> None: - return super().test_get_public_spend_key(wallet) - - #endregion - - #region Disabled Tests - - @pytest.mark.skip(reason="TODO https://github.com/monero-project/monero/issues/5812") - @override - def test_import_key_images(self, wallet: MoneroWallet) -> None: - return super().test_import_key_images(wallet) - - #endregion diff --git a/tests/utils/__init__.py b/tests/utils/__init__.py index 3711aa34..53a529c3 100644 --- a/tests/utils/__init__.py +++ b/tests/utils/__init__.py @@ -36,6 +36,7 @@ from .wallet_type import WalletType from .view_only_and_offline_wallet_tester import ViewOnlyAndOfflineWalletTester from .daemon_notification_collector import DaemonNotificationCollector +from .fake_daemon_rpc_server import FakeDaemonRpcServer from .wallet_notification_collector import WalletNotificationCollector from .submit_then_relay_tx_tester import SubmitThenRelayTxTester from .multisig_sample_code_tester import MultisigSampleCodeTester @@ -101,5 +102,6 @@ 'WalletSendUtils', 'WalletTestUtils', 'TxsStructureTester', - 'DaemonNotificationCollector' + 'DaemonNotificationCollector', + 'FakeDaemonRpcServer' ] diff --git a/tests/utils/block_generation.py b/tests/utils/block_generation.py new file mode 100644 index 00000000..708c70eb --- /dev/null +++ b/tests/utils/block_generation.py @@ -0,0 +1,23 @@ +from monero import MoneroDaemon + +MAX_GENERATE_DIFFICULTY: int = 100 +"""Highest difficulty at which blocks are generated instead of mined. + +`generateblocks` hashes with one thread in the light mode of RandomX, about 75 hashes per second, so a block takes difficulty / 75 seconds +(0.04 s at difficulty 1, 6.7 s at 500). The miner of the daemon hashes with the full dataset and is much faster: at a high difficulty +mining makes the blocks sooner, at a low one it makes dozens while the tests sleep, and the chain grows past what they want. +""" + + +def is_generation_fast(daemon: MoneroDaemon) -> bool: + """Indicates if the daemon generates blocks faster than it mines them: a regtest daemon with a low difficulty. + + :param MoneroDaemon daemon: daemon to ask the difficulty of. + :returns bool: `True` if blocks should be generated, `False` if they should be mined. + """ + try: + info = daemon.get_info() + difficulty: int = (info.difficulty_high or 0) << 64 | (info.difficulty_low or 0) + return info.is_regtest is not False and 0 < difficulty <= MAX_GENERATE_DIFFICULTY + except Exception: + return False diff --git a/tests/utils/blockchain_utils.py b/tests/utils/blockchain_utils.py index 4cc9024c..b789a094 100644 --- a/tests/utils/blockchain_utils.py +++ b/tests/utils/blockchain_utils.py @@ -4,6 +4,7 @@ from time import sleep from monero import MoneroNetworkType, MoneroGenerateBlocksResult, MoneroDaemonRpc, MoneroBlockHeader +from .block_generation import is_generation_fast from .string_utils import StringUtils from .test_utils import TestUtils as Utils from .mining_utils import MiningUtils @@ -18,6 +19,9 @@ class BlockchainUtils(ABC): CHECK_BLOCK_TIMEOUT_SECONDS: int = 5 """Timeout in seconds to check blockchain mining progress.""" + GENERATE_BLOCKS_PER_REQUEST: int = 5 + """Blocks that a request of generateblocks makes in regtest. At a high difficulty a block takes seconds, and a request has a timeout.""" + @classmethod def get_height(cls) -> int: """Get current blockchain height. @@ -58,6 +62,13 @@ def wait_for_height(cls, height: int) -> int: # return last height return current_height + # on regtest with a low difficulty the blocks are generated, which makes the ones that are asked for and no more. The miner makes blocks + # while the loop below sleeps, and at a low difficulty that is dozens of blocks: the chain grows by more than the tests want, and the + # transactions of the setup, which some tests look for in the last 100 blocks, are left below them. At a high difficulty the miner is + # faster than generating, so it mines. If something is mining already, its blocks are waited for + if Utils.REGTEST and not MiningUtils.is_mining() and is_generation_fast(daemon): + return cls._generate_blocks_until(daemon, current_height, height) + # start mining if not active stop_mining: bool = False if not MiningUtils.is_mining(): @@ -83,6 +94,25 @@ def wait_for_height(cls, height: int) -> int: return current_height + @classmethod + def _generate_blocks_until(cls, daemon: MoneroDaemonRpc, current_height: int, height: int) -> int: + """Generate blocks to the mining address until the blockchain has a height (regtest only). + + :param MoneroDaemonRpc daemon: daemon that generates the blocks. + :param int current_height: height of the blockchain. + :param int height: height to reach. + :returns int: blockchain height. + """ + while current_height < height: + p: str = StringUtils.get_percentage(current_height, height) + logger.info(f"[{p}] Generating blocks ({current_height}/{height})") + num_blocks: int = min(cls.GENERATE_BLOCKS_PER_REQUEST, height - current_height) + MiningUtils.generate_blocks(Utils.MINING_ADDRESS, num_blocks, daemon) + current_height = daemon.get_height() + + logger.info(f"[100%] Reached blockchain height: {current_height}") + return current_height + @classmethod def wait_until_blockchain_ready(cls) -> int: """Wait until blockchain is ready. diff --git a/tests/utils/fake_daemon_rpc_server.py b/tests/utils/fake_daemon_rpc_server.py new file mode 100644 index 00000000..94906279 --- /dev/null +++ b/tests/utils/fake_daemon_rpc_server.py @@ -0,0 +1,122 @@ +import json +import logging +import threading + +from time import sleep + +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from typing import Any, override + +logger: logging.Logger = logging.getLogger("FakeDaemonRpcServer") + + +class _Handler(BaseHTTPRequestHandler): + """Answers the json rpc requests of a daemon poller, with a new block at each request.""" + + server: "FakeDaemonRpcServer" # type: ignore[assignment] + + def do_POST(self) -> None: + """Answer a request with the last block header, a block newer than the one of the previous request.""" + try: + length: int = int(self.headers.get("Content-Length", "0")) + body: dict[str, Any] = json.loads(self.rfile.read(length) or b"{}") + height: int = self.server.next_height() + if self.server.response_delay > 0: + sleep(self.server.response_delay) + response: dict[str, Any] = { + "jsonrpc": "2.0", + "id": body.get("id", "0"), + "result": { + "status": "OK", + "untrusted": False, + "block_header": { + "hash": f"{height:064x}", + "prev_hash": f"{height - 1:064x}", + "miner_tx_hash": f"{height + 1:064x}", + "height": height, + "major_version": 16, + "minor_version": 16, + "timestamp": 1700000000 + height, + "nonce": 1, + "orphan_status": False, + "depth": 0, + "difficulty": 5, + "cumulative_difficulty": 5 * height, + "reward": 600000000000, + "block_size": 100, + "block_weight": 100, + "num_txes": 0, + "long_term_weight": 100, + "pow_hash": "" + } + } + } + data: bytes = json.dumps(response).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + except Exception as e: + # a request that is not json (the daemon connection probes the server too) + logger.debug(f"Request not answered: {e}") + self.send_error(404) + + @override + def log_message(self, format: str, *args: Any) -> None: + pass + + +class FakeDaemonRpcServer(ThreadingHTTPServer): + """A daemon rpc server for unit tests, that needs no node: every request for the last block header gets a new block, + so the poller of a `MoneroDaemonRpc` notifies its listeners at each poll. + + Use it as a context manager. + """ + + def __init__(self, first_height: int = 100, response_delay: float = 0.0) -> None: + """Initialize a new FakeDaemonRpcServer. + + :param int first_height: height of the first block. + :param float response_delay: seconds that the server takes to answer a request, to have requests in flight. + """ + super().__init__(("127.0.0.1", 0), _Handler) + self._first_height: int = first_height + self._height: int = first_height + self.response_delay: float = response_delay + self._lock: threading.Lock = threading.Lock() + self._thread: threading.Thread = threading.Thread(target=self.serve_forever, daemon=True) + + @property + def uri(self) -> str: + """Uri of the server. + + :returns str: uri to give to a `MoneroDaemonRpc`. + """ + return f"http://127.0.0.1:{self.server_address[1]}" + + @property + def num_requests(self) -> int: + """Number of requests received so far. + + :returns int: number of requests received. + """ + return self._height - self._first_height + + def next_height(self) -> int: + """Get the height of the block of the next response. + + :returns int: new block height. + """ + with self._lock: + self._height += 1 + return self._height + + def __enter__(self) -> "FakeDaemonRpcServer": + self._thread.start() + return self + + def __exit__(self, *args: Any) -> None: + self.shutdown() + self.server_close() + self._thread.join(timeout=5) diff --git a/tests/utils/integration_test_utils.py b/tests/utils/integration_test_utils.py index 863d50ce..8a692114 100644 --- a/tests/utils/integration_test_utils.py +++ b/tests/utils/integration_test_utils.py @@ -18,6 +18,9 @@ class IntegrationTestUtils(ABC): __test__ = False + _LAST_SETUP: WalletType | None = None + """Wallet type that the integration environment was set up for last, in this session.""" + @classmethod def setup_blockchain(cls) -> None: """Setup blockchain for integration tests.""" @@ -32,6 +35,11 @@ def setup(cls, wallet_type: WalletType) -> None: """ if wallet_type == WalletType.KEYS or wallet_type == WalletType.UNDEFINED: return + # once for each run of classes of the same type, as when all the tests of a wallet type were in a class: the classes of the + # topics that came from it would do the same work again. It is not once for the whole session: the wallets of the types have + # the same seed, so the tests of a type spend the funds of the next one, which is funded again when its classes start + if wallet_type == cls._LAST_SETUP: + return cls.setup_blockchain() # get test wallet wallet: MoneroWallet @@ -59,6 +67,8 @@ def setup(cls, wallet_type: WalletType) -> None: if num_wallet_txs < len(txs): logger.info(f"Funded test wallet {type_str}") + cls._LAST_SETUP = wallet_type + @classmethod def fund_wallet_and_wait_for_unlocked(cls, wallet: MoneroWallet) -> list[MoneroTxWallet]: """Fund wallet used for integration tests and wait for unlocked balance. diff --git a/tests/utils/test_utils.py b/tests/utils/test_utils.py index be7b02e4..3fceea5e 100644 --- a/tests/utils/test_utils.py +++ b/tests/utils/test_utils.py @@ -335,6 +335,23 @@ def get_daemon_rpc_connection(cls) -> MoneroRpcConnection: """ return MoneroRpcConnection(cls.DAEMON_RPC_URI, cls.DAEMON_RPC_USERNAME, cls.DAEMON_RPC_PASSWORD) + @classmethod + def close_wallets(cls) -> None: + """Close the test wallets that were opened, saving the full and the rpc one. The tests of a wallet type + share the wallet for the whole session, and this is called at its end.""" + for wallet, save in ((cls._WALLET_FULL, True), (cls._WALLET_RPC, True), (cls._WALLET_KEYS, False)): + if wallet is None: + continue + closed: bool = not cls.is_wallet_rpc_open(wallet) if isinstance(wallet, MoneroWalletRpc) else wallet.is_closed() + if closed: + continue + try: + wallet.close(save) + except Exception as e: + # an rpc wallet that a test already closed + if "No wallet file" != str(e): + raise + @classmethod def get_wallet_keys_config(cls) -> MoneroWalletConfig: """Get test wallet keys configuration. @@ -500,6 +517,24 @@ def get_wallet_rpc_connection(cls) -> MoneroRpcConnection: cls.WALLET_RPC_ZMQ_URI if cls.WALLET_RPC_ZMQ_ENABLED else '' ) + @classmethod + def is_wallet_rpc_open(cls, wallet: MoneroWalletRpc) -> bool: + """Indicates if the wallet rpc server has a wallet open, by asking it for the primary address. + + MoneroWalletRpc.is_closed() is not used: it takes the error "No wallet file" for a closed wallet only with the code -8, and the + server answers it with -13 (WALLET_RPC_ERROR_CODE_NOT_OPEN), so it never says that a server has no wallet open. + + :param MoneroWalletRpc wallet: wallet rpc to ask. + :returns bool: `True` if the server has a wallet open, `False` if it has none. + """ + try: + wallet.get_primary_address() + return True + except MoneroRpcError as e: + if "No wallet file" in str(e): + return False + raise + @classmethod def get_wallet_rpc(cls) -> MoneroWalletRpc: """Get rpc test wallet. @@ -513,21 +548,23 @@ def get_wallet_rpc(cls) -> MoneroWalletRpc: rpc: MoneroRpcConnection = cls.get_wallet_rpc_connection() cls._WALLET_RPC = MoneroWalletRpc(rpc) - # attempt to open test wallet - try: - cls._WALLET_RPC.open_wallet(cls.WALLET_NAME, cls.WALLET_PASSWORD) - except MoneroRpcError as e: - # -1 returned when wallet does not exist or fails to open e.g. it's already open by another application - if e.code == -1: - # create wallet - config = MoneroWalletConfig() - config.path = cls.WALLET_NAME - config.password = cls.WALLET_PASSWORD - config.seed = cls.SEED - config.restore_height = cls.FIRST_RECEIVE_HEIGHT - cls._WALLET_RPC.create_wallet(config) - else: - raise + # attempt to open test wallet. It is not opened again when the server has it open: the test classes share it, and opening an open + # wallet fails with -1, which would create it from the seed. That wallet has no outgoing destinations, accounts or subaddresses + if not cls.is_wallet_rpc_open(cls._WALLET_RPC): + try: + cls._WALLET_RPC.open_wallet(cls.WALLET_NAME, cls.WALLET_PASSWORD) + except MoneroRpcError as e: + # -1 returned when wallet does not exist or fails to open e.g. it's already open by another application + if e.code == -1: + # create wallet + config = MoneroWalletConfig() + config.path = cls.WALLET_NAME + config.password = cls.WALLET_PASSWORD + config.seed = cls.SEED + config.restore_height = cls.FIRST_RECEIVE_HEIGHT + cls._WALLET_RPC.create_wallet(config) + else: + raise # ensure we're testing the right wallet assert cls.SEED == cls._WALLET_RPC.get_seed() diff --git a/tests/utils/wallet_tx_tracker.py b/tests/utils/wallet_tx_tracker.py index 3fa5d0c1..823a04fa 100644 --- a/tests/utils/wallet_tx_tracker.py +++ b/tests/utils/wallet_tx_tracker.py @@ -6,6 +6,8 @@ MoneroTxWallet, MoneroMiningStatus ) +from .block_generation import is_generation_fast + logger: logging.Logger = logging.getLogger("WalletTxTracker") @@ -25,6 +27,8 @@ class WalletTxTracker: """Sync period in milliseconds.""" _mining_address: str """Mining address.""" + _can_generate_blocks: bool | None = None + """Indicates if the daemon generates blocks on request (regtest only), `None` until it is tried.""" @property def sync_period(self) -> float: @@ -49,6 +53,24 @@ def _sleep(self) -> None: """Sleep for one sync period.""" sleep(self.sync_period) + def _generate_block(self) -> bool: + """Generate one block, to clear the pool, when the difficulty is low. The CPU miner is not used for it then: it makes blocks without + stopping and the chain grows past 10000 outputs, where monero-project fails the txs it creates with "Transaction sanity check failed". + + :returns bool: `True` if a block was generated, `False` if the daemon can not generate blocks (not regtest) or mining is faster. + """ + if self._can_generate_blocks is False: + return False + if not is_generation_fast(self._daemon): + return False + try: + self._daemon.generate_blocks(self._mining_address, 1) + self._can_generate_blocks = True + except Exception as e: + logger.debug(f"The daemon can not generate blocks: {e}") + self._can_generate_blocks = False + return self._can_generate_blocks + def _wait_for_txs_to_clear(self, clear_from_wallet: bool, wallets: list[MoneroWallet]) -> None: """Wait for wallet txs to clear pool. @@ -114,10 +136,18 @@ def _wait_for_txs_to_clear(self, clear_from_wallet: bool, wallets: list[MoneroWa self._daemon.stop_mining() break - # log message and start mining if first iteration + # log message on the first iteration if is_first: - is_first = False logger.info(f"Waiting for wallet txs to clear from the pool in order to fully sync and avoid double spend attempts: {tx_hashes_pool}") + + # on regtest a block is generated on each iteration, and the wallets are synced in the next one + if self._generate_block(): + is_first = False + continue + + # start mining if first iteration + if is_first: + is_first = False mining_status: MoneroMiningStatus = self._daemon.get_mining_status() if mining_status.is_active is not True: try: diff --git a/tests/wallet/__init__.py b/tests/wallet/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/wallet/base_test_monero_wallet.py b/tests/wallet/base_test_monero_wallet.py new file mode 100644 index 00000000..a6479d3e --- /dev/null +++ b/tests/wallet/base_test_monero_wallet.py @@ -0,0 +1,228 @@ +from __future__ import annotations + +import logging +from abc import abstractmethod +from configparser import ConfigParser +from typing import Optional + +import pytest +from monero import MoneroDaemonRpc, MoneroMiningStatus, MoneroWallet, MoneroWalletConfig +from typing_extensions import override + +from utils import ( + BaseTestClass, + IntegrationTestUtils, + MiningUtils, + MultisigSampleCodeTester, + TestUtils, + WalletType, +) + +logger: logging.Logger = logging.getLogger("TestMoneroWalletCommon") + + +class BaseTestMoneroWallet(BaseTestClass): + """Common wallet tests that every Monero wallet implementation should support.""" + + _test_wallet: Optional[MoneroWallet] = None + """Private reference to test wallet instance.""" + + @classmethod + def get_wallet_type(cls) -> WalletType: + """Wallet type to test.""" + return WalletType.UNDEFINED + + @classmethod + def supports_save(cls) -> bool: + wallet_type: WalletType = cls.get_wallet_type() + return wallet_type == WalletType.FULL or wallet_type == WalletType.RPC + + class Config: + """Wallet test configuration.""" + + seed: str = "" + """Test wallet seed.""" + + @classmethod + def parse(cls, parser: ConfigParser) -> BaseTestMoneroWallet.Config: + """Parse wallet test configuration. + + :param ConfigParser parser: configuration parser. + :returns BaseTestMoneroWallet.Config: wallet test configuration. + """ + section: str = "test_create_wallet_from_seed" + if not parser.has_section(section): + # raise exception if section not found + raise Exception(f"Cannot find section '{section}' in test_monero_wallet_common.ini") + config: BaseTestMoneroWallet.Config = cls() + # parse configuration + config.seed = parser.get(section, "seed") + return config + + @classmethod + def _get_test_daemon(cls) -> MoneroDaemonRpc: + """Get the daemon to test. + + :returns MoneroDaemonRpc: the daemon to test. + """ + return TestUtils.get_daemon_rpc() + + @classmethod + def get_test_wallet(cls) -> MoneroWallet: + """Get the main wallet to test. + + :returns MoneroWallet: the wallet to test. + """ + if cls._test_wallet is None: + wallet_type: WalletType = cls.get_wallet_type() + if wallet_type == WalletType.FULL: + cls._test_wallet = TestUtils.get_wallet_full() + elif wallet_type == WalletType.RPC: + cls._test_wallet = TestUtils.get_wallet_rpc() + elif wallet_type == WalletType.KEYS: + cls._test_wallet = TestUtils.get_wallet_keys() + else: + raise Exception("Cannot get test wallet: No wallet type setup for tests") + + return cls._test_wallet + + @abstractmethod + def _open_wallet(self, config: Optional[MoneroWalletConfig]) -> MoneroWallet: + """Open a test wallet with default configuration for each wallet type. + + :param MoneroWalletConfig | None config: configures the wallet to open. + :returns MoneroWallet: is the opened wallet. + """ + ... + + @abstractmethod + def _create_wallet(self, config: MoneroWalletConfig) -> MoneroWallet: + """Create a test wallet with default configuration for each wallet type. + + :param MoneroWalletConfig config: configures the wallet to create. + :returns MoneroWallet: is the created wallet. + """ + ... + + @abstractmethod + def _close_wallet(self, wallet: MoneroWallet, save: bool = False) -> None: + """Close a test wallet with customization for each wallet type. + + :param MoneroWallet wallet: the wallet to close. + :param bool save: whether or not to save the wallet. + """ + ... + + @abstractmethod + def _get_seed_languages(self) -> list[str]: + """Get the wallet's supported languages for the seed. This is an + instance method for wallet rpc and a static utility for other wallets. + + :returns list[str]: the wallet's supported languages. + """ + ... + + def _open_wallet_from_path(self, path: str, password: str | None) -> MoneroWallet: + """Open a wallet from path. + + :param str path: wallet path to open. + :param str | None password: wallet password. + :returns MoneroWallet: opened wallet. + """ + config: MoneroWalletConfig = MoneroWalletConfig() + config.path = path + config.password = password + + return self._open_wallet(config) + + def get_daemon_rpc_uri(self) -> str: + return TestUtils.DAEMON_RPC_URI + + @classmethod + def is_random_wallet_config(cls, config: Optional[MoneroWalletConfig]) -> bool: + """Check if config is valid to create a random wallet. + + :param MoneroWalletConfig | None config: config to check. + :returns bool: `True` if config is valid to create a random wallet, `False` otherwise. + """ + assert config is not None + return config.seed is None and config.primary_address is None + + # Test wallet configuration + @pytest.fixture(scope="class") + @classmethod + def test_config(cls) -> BaseTestMoneroWallet.Config: + """Test configuration.""" + parser: ConfigParser = ConfigParser() + parser.read('tests/config/test_monero_wallet_common.ini') + return BaseTestMoneroWallet.Config.parse(parser) + + # Test daemon fixture + @pytest.fixture(scope="class") + @classmethod + def daemon(cls) -> MoneroDaemonRpc: + """Test rpc daemon instance.""" + return TestUtils.get_daemon_rpc() + + # Test wallet fixture + @pytest.fixture(scope="class") + @classmethod + def wallet(cls) -> MoneroWallet: + """Test wallet instance.""" + pytest.skip("No wallet test instance setup") + + # Before all tests + @override + def before_all(self) -> None: + super().before_all() + IntegrationTestUtils.setup(self.get_wallet_type()) + + # After all tests + @override + def after_all(self) -> None: + super().after_all() + daemon: MoneroDaemonRpc = self._get_test_daemon() + MiningUtils.try_stop_mining(daemon) + # the wallet is not closed here: the classes of the topics share it, and TestUtils.close_wallets() closes it + # when the session ends (see conftest.py) + + # Before each test + @override + def before_each(self, request: pytest.FixtureRequest) -> None: + super().before_each(request) + daemon: MoneroDaemonRpc = self._get_test_daemon() + wallet: MoneroWallet = self.get_test_wallet() + status: MoneroMiningStatus = daemon.get_mining_status() + + if status.is_active is True: + wallet.stop_mining() + + # After each test + @override + def after_each(self, request: pytest.FixtureRequest) -> None: + super().after_each(request) + daemon: MoneroDaemonRpc = self._get_test_daemon() + status: MoneroMiningStatus = daemon.get_mining_status() + + if status.is_active is True: + logger.warning(f"Mining is active after test {request.node.name}") # type: ignore + + def _test_multisig_sample(self, m: int, n: int) -> None: + """ + Test multisig sample code. + + :param int m: multisig threshold. + :param int n: number of participants. + """ + # create participant wallets + wallets: list[MoneroWallet] = [] + + for i in range(n): + wallets.append(self._create_wallet(MoneroWalletConfig())) + logger.debug(f"Created multisig wallet participant {i + 1}") + + tester: MultisigSampleCodeTester = MultisigSampleCodeTester(m, wallets) + tester.test() + + if self.get_wallet_type() == WalletType.RPC: + TestUtils.free_wallet_rpc_resources() diff --git a/tests/wallet/conftest.py b/tests/wallet/conftest.py new file mode 100644 index 00000000..a82096e6 --- /dev/null +++ b/tests/wallet/conftest.py @@ -0,0 +1,63 @@ +from __future__ import annotations + +from typing import Any, Generator + +import pytest + +from utils import TestUtils + + +@pytest.fixture(scope="session", autouse=True) +def close_test_wallets() -> Generator[None, Any, None]: + """The wallet of each type is open for all the tests of its type, in all the files, and is closed at the end.""" + yield + TestUtils.close_wallets() + + +_SEND_TESTS = "tests/wallet/test_send.py" + +_WALLET_TYPES = ("TestMoneroWalletFull", "TestMoneroWalletRpc", "TestMoneroWalletKeys") +"""The classes of each type of wallet start with these, in the order that the types run.""" + + +def _is_wallet_test(item: pytest.Item) -> bool: + """A test of tests/wallet that is not about the models, which are unit tests that make nothing.""" + return item.nodeid.startswith("tests/wallet/") and not item.nodeid.startswith("tests/wallet/model/") + + +def _wallet_type_rank(item: pytest.Item) -> int: + """The place of the type of wallet that a test is for, in `_WALLET_TYPES`. The tests that are not for a type come after.""" + parts: list[str] = item.nodeid.split("::") + test_class: str = parts[1] if len(parts) > 2 else "" + for rank, prefix in enumerate(_WALLET_TYPES): + if test_class.startswith(prefix): + return rank + return len(_WALLET_TYPES) + + +def pytest_collection_modifyitems(items: list[pytest.Item]) -> None: + """The tests of tests/wallet run one type of wallet at a time, and the send tests first. + + A file of a topic has a class for each type of wallet (full, rpc and keys), and the files run in alphabetical order, so the types + would alternate: the full wallet of a topic, the rpc wallet of the same one, and the next topic. The wallet of a type is the same for + all its tests, and the tests of a type use what the ones before made in it, so all the tests of a type run, and then the ones of + the next: as when they were in a class for each type. + + Inside a type the send tests are the first. Some tests use what they made in the wallet: the proofs look for transactions with + outgoing destinations, and the ones of the payment ids for the transactions that were sent with one ("run send tests", they say). The + sends were the first tests when all of them were in a class, the relays tests, and test_proofs.py and test_txs.py come before + test_send.py in the alphabet. + + Only the tests of tests/wallet move, in the places that they have: everything else stays where it was. It is a stable sort, so inside + the groups the order is the one of the files. + """ + positions: list[int] = [i for i, item in enumerate(items) if _is_wallet_test(item)] + if not positions: + return + wallet_items: list[pytest.Item] = [items[i] for i in positions] + reordered: list[pytest.Item] = sorted( + wallet_items, + key=lambda item: (_wallet_type_rank(item), 0 if item.nodeid.startswith(_SEND_TESTS) else 1), + ) + for position, item in zip(positions, reordered): + items[position] = item diff --git a/tests/wallet/model/__init__.py b/tests/wallet/model/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/wallet/model/test_accounts.py b/tests/wallet/model/test_accounts.py new file mode 100644 index 00000000..07c830fc --- /dev/null +++ b/tests/wallet/model/test_accounts.py @@ -0,0 +1,111 @@ +from __future__ import annotations + +import logging + +import pytest +from monero import ( + MoneroAccount, + MoneroAccountTag, + MoneroAddressBookEntry, + MoneroAddressType, + MoneroDecodedAddress, + MoneroIntegratedAddress, + MoneroNetworkType, + MoneroSubaddress, +) + +from utils import AssertUtils, BaseTestClass, TestUtils + +logger: logging.Logger = logging.getLogger("TestMoneroWalletModelAccounts") + + +@pytest.mark.unit +class TestMoneroWalletModelAccounts(BaseTestClass): + """Wallet account model unit tests.""" + + def test_subaddress_deserialize(self) -> None: + subaddress: MoneroSubaddress = MoneroSubaddress() + subaddress.account_index = 0 + subaddress.index = 1 + subaddress.address = TestUtils.ADDRESS + subaddress.label = "primary" + subaddress.balance = 1000000 + subaddress.unlocked_balance = 900000 + subaddress.is_used = True + subaddress.num_unspent_outputs = 3 + subaddress.num_blocks_to_unlock = 0 + AssertUtils.assert_serialization_integrity(subaddress) + + def test_account_deserialize(self) -> None: + account: MoneroAccount = MoneroAccount() + account.index = 0 + account.balance = 1000000 + account.unlocked_balance = 900000 + account.primary_address = TestUtils.ADDRESS + account.tag = "savings" + # subaddresses is serialized as a sub-array but from_property_tree() never + # reads it back (see test below) + AssertUtils.assert_serialization_integrity(account) + + def test_account_subaddresses_deserialize(self) -> None: + account: MoneroAccount = MoneroAccount() + account.subaddresses = [MoneroSubaddress()] + json_str: str = account.serialize() + logger.debug(f"Serialized account: {json_str}") + assert "subaddresses" in json_str + restored: MoneroAccount = MoneroAccount.deserialize(json_str) + logger.debug(f"Deserialized account re-serialized: {restored.serialize()}") + assert len(restored.subaddresses) == len(account.subaddresses) + + def test_integrated_address_deserialize(self) -> None: + address: MoneroIntegratedAddress = MoneroIntegratedAddress() + address.standard_address = TestUtils.ADDRESS + address.payment_id = "d" * 16 + address.integrated_address = TestUtils.ADDRESS + AssertUtils.assert_serialization_integrity(address) + + def test_address_book_entry_deserialize(self) -> None: + entry: MoneroAddressBookEntry = MoneroAddressBookEntry() + entry.index = 0 + entry.address = TestUtils.ADDRESS + entry.description = "friend" + entry.payment_id = "e" * 16 + AssertUtils.assert_serialization_integrity(entry) + + def test_address_book_entry_constructor_with_payment_id_deserialize(self) -> None: + entry: MoneroAddressBookEntry = MoneroAddressBookEntry(0, TestUtils.ADDRESS, "friend", "e" * 16) + assert entry.index == 0 + assert entry.address == TestUtils.ADDRESS + assert entry.description == "friend" + assert entry.payment_id == "e" * 16 + AssertUtils.assert_serialization_integrity(entry) + + def test_account_tag_deserialize(self) -> None: + tag: MoneroAccountTag = MoneroAccountTag() + tag.tag = "savings" + tag.label = "Savings accounts" + tag.account_indices = [0, 1, 2] + AssertUtils.assert_serialization_integrity(tag) + + def test_account_tag_constructor_deserialize(self) -> None: + tag: MoneroAccountTag = MoneroAccountTag("savings", "Savings accounts") + assert tag.tag == "savings" + assert tag.label == "Savings accounts" + assert len(tag.account_indices) == 0 + AssertUtils.assert_serialization_integrity(tag) + + def test_decoded_address_deserialize(self) -> None: + address: MoneroDecodedAddress = MoneroDecodedAddress( + TestUtils.ADDRESS, MoneroAddressType.PRIMARY_ADDRESS, MoneroNetworkType.MAINNET + ) + AssertUtils.assert_serialization_integrity(address) + + @pytest.mark.parametrize("json_fragment", [ + '{"networkType":-1}', + '{"networkType":3}', + '{"addressType":-1}', + '{"addressType":3}', + ]) + def test_decoded_address_invalid_enum_range(self, json_fragment: str) -> None: + with pytest.raises(Exception, match="Invalid (network|address) type"): + MoneroDecodedAddress.deserialize(json_fragment) diff --git a/tests/wallet/model/test_config.py b/tests/wallet/model/test_config.py new file mode 100644 index 00000000..faf18110 --- /dev/null +++ b/tests/wallet/model/test_config.py @@ -0,0 +1,128 @@ +from __future__ import annotations + +import logging + +import pytest +from monero import MoneroDestination, MoneroTxConfig, MoneroTxPriority, MoneroUtils, MoneroWalletConfig + +from utils import AssertUtils, BaseTestClass, TestUtils + +logger: logging.Logger = logging.getLogger("TestMoneroWalletModelConfig") + + +@pytest.mark.unit +class TestMoneroWalletModelConfig(BaseTestClass): + """Wallet config model unit tests.""" + + def test_destination(self) -> None: + amount: int = MoneroUtils.xmr_to_atomic_units(1) + dest: MoneroDestination = MoneroDestination(TestUtils.ADDRESS, amount) + logger.debug(f"Testing destination: {dest.serialize()}") + copy: MoneroDestination = dest.copy() + AssertUtils.assert_equals(dest, copy) + + def test_wallet_config(self) -> None: + config: MoneroWalletConfig = TestUtils.get_wallet_full_config(TestUtils.get_daemon_rpc_connection()) + logger.debug(f"Testing wallet config: {config.serialize()}") + copy: MoneroWalletConfig = config.copy() + AssertUtils.assert_equals(config, copy) + config_str: str = config.serialize() + deserialized_config: MoneroWalletConfig = MoneroWalletConfig.deserialize(config_str) + logger.debug(f"Deserialized config: {deserialized_config.serialize()}") + AssertUtils.assert_equals(config, deserialized_config) + + @pytest.mark.parametrize("json_fragment", ['{"networkType":-1}', '{"networkType":3}']) + def test_wallet_config_invalid_network_type(self, json_fragment: str) -> None: + with pytest.raises(Exception, match="Invalid network type"): + MoneroWalletConfig.deserialize(json_fragment) + + def test_tx_config(self) -> None: + config: MoneroTxConfig = MoneroTxConfig() + config.set_address(TestUtils.ADDRESS) + config.amount = MoneroUtils.xmr_to_atomic_units(0.5) + config.account_index = 0 + config.subaddress_indices = [i for i in range(10)] + config.below_amount = MoneroUtils.xmr_to_atomic_units(0.1) + config.can_split = True + config.fee = MoneroUtils.xmr_to_atomic_units(0.00075) + config.sweep_each_subaddress = False + config.priority = MoneroTxPriority.ELEVATED + config.key_image = "a" * 64 + + copy: MoneroTxConfig = config.copy() + AssertUtils.assert_equals(config, copy) + + config_str: str = config.serialize() + logger.debug(f"Serialized tx config: {config_str}") + + deserialized_config: MoneroTxConfig = MoneroTxConfig.deserialize(config_str) + AssertUtils.assert_equals(config, deserialized_config) + + @pytest.mark.parametrize("priority,priority_num", [ + (MoneroTxPriority.DEFAULT, 0), + (MoneroTxPriority.UNIMPORTANT, 1), + (MoneroTxPriority.NORMAL, 2), + (MoneroTxPriority.ELEVATED, 3), + ]) + def test_tx_config_priority_deserialize(self, priority: MoneroTxPriority, priority_num: int) -> None: + config: MoneroTxConfig = MoneroTxConfig.deserialize('{"priority": %d}' % priority_num) + assert config.priority == priority + + def test_tx_config_invalid_priority_deserialize(self) -> None: + with pytest.raises(RuntimeError) as exc_info: + MoneroTxConfig.deserialize('{"priority": 4}') + assert str(exc_info.value) == "Invalid priority number: 4" + + def test_get_normalized_destinations_uses_destinations_when_address_and_amount_unset(self) -> None: + config: MoneroTxConfig = MoneroTxConfig() + config.destinations = [MoneroDestination(TestUtils.ADDRESS, 100), MoneroDestination(TestUtils.MINING_ADDRESS, 200)] + assert config.get_normalized_destinations() == config.destinations + + def test_get_normalized_destinations_builds_single_destination(self) -> None: + config: MoneroTxConfig = MoneroTxConfig() + config.address = TestUtils.ADDRESS + config.amount = 500000 + assert len(config.destinations) == 0 # address/amount alone don't populate destinations + + normalized: list[MoneroDestination] = config.get_normalized_destinations() + assert len(normalized) == 1 + assert normalized[0].address == TestUtils.ADDRESS + assert normalized[0].amount == 500000 + + def test_get_normalized_destinations_conflicts_with_multiple_destinations(self) -> None: + config: MoneroTxConfig = MoneroTxConfig() + config.address = TestUtils.ADDRESS + config.amount = 500000 + config.destinations = [MoneroDestination(TestUtils.ADDRESS, 500000), MoneroDestination(TestUtils.MINING_ADDRESS, 1)] + with pytest.raises(RuntimeError) as exc_info: + config.get_normalized_destinations() + assert str(exc_info.value) == "Invalid tx configuration: single destination address/amount incompatible with multiple destinations" + + def test_get_normalized_destinations_address_mismatch(self) -> None: + config: MoneroTxConfig = MoneroTxConfig() + config.address = TestUtils.ADDRESS + config.amount = 500000 + config.destinations = [MoneroDestination(TestUtils.MINING_ADDRESS, 500000)] + with pytest.raises(RuntimeError) as exc_info: + config.get_normalized_destinations() + assert str(exc_info.value) == "Invalid tx configuration: single destination address does not match first destination address" + + def test_get_normalized_destinations_amount_mismatch(self) -> None: + config: MoneroTxConfig = MoneroTxConfig() + config.address = TestUtils.ADDRESS + config.amount = 500000 + config.destinations = [MoneroDestination(TestUtils.ADDRESS, 1)] + with pytest.raises(RuntimeError) as exc_info: + config.get_normalized_destinations() + assert str(exc_info.value) == "Invalid tx configuration: single destination amount does not match first destination amount" + + def test_get_normalized_destinations_matches_single_destination(self) -> None: + config: MoneroTxConfig = MoneroTxConfig() + config.address = TestUtils.ADDRESS + config.amount = 500000 + config.destinations = [MoneroDestination(TestUtils.ADDRESS, 500000)] + assert config.get_normalized_destinations() == config.destinations + + def test_destination_deserialize(self) -> None: + destination: MoneroDestination = MoneroDestination(TestUtils.ADDRESS, 500000) + AssertUtils.assert_serialization_integrity(destination) diff --git a/tests/wallet/model/test_output_query.py b/tests/wallet/model/test_output_query.py new file mode 100644 index 00000000..2c382332 --- /dev/null +++ b/tests/wallet/model/test_output_query.py @@ -0,0 +1,239 @@ +from __future__ import annotations + +import logging + +import pytest +from monero import MoneroKeyImage, MoneroOutputQuery, MoneroOutputWallet, MoneroTxQuery, MoneroTxWallet + +from utils import AssertUtils, BaseTestClass + +logger: logging.Logger = logging.getLogger("TestMoneroWalletModelOutputQuery") + + +@pytest.mark.unit +class TestMoneroWalletModelOutputQuery(BaseTestClass): + """Wallet output query model unit tests.""" + + # Test output query expected behaviour + def test_output_query(self) -> None: + output_query: MoneroOutputQuery = MoneroOutputQuery() + tx_query: MoneroTxQuery = MoneroTxQuery() + + # test tx query property assign + try: + output_query.tx_query = tx_query # type: ignore + except AttributeError as e: + err_msg: str = str(e) + assert "object has no setter" in err_msg, err_msg + + # assign tx query to output query + output_query.set_tx_query(tx_query, True) + + assert output_query.tx_query is not None + assert output_query.tx_query == tx_query + assert tx_query.input_query is None + assert tx_query.output_query is not None + assert tx_query.output_query == output_query + + # reassign output query to tx query + output_query.tx_query.output_query = output_query + assert output_query.tx_query is not None + assert output_query == output_query.tx_query.output_query + + # remove tx query from output query + output_query.set_tx_query(None, True) + + assert output_query.tx_query is None + assert tx_query.output_query is None + + # Test input query expected behaviour + def test_input_query(self) -> None: + input_query: MoneroOutputQuery = MoneroOutputQuery() + tx_query: MoneroTxQuery = MoneroTxQuery() + + # assign tx query to input query + input_query.set_tx_query(tx_query, False) + + assert input_query.tx_query is not None + assert input_query.tx_query == tx_query + assert tx_query.output_query is None + assert tx_query.input_query is not None + assert tx_query.input_query == input_query + + # reassign input query to tx query + input_query.tx_query.input_query = input_query + assert input_query.tx_query is not None + assert input_query == input_query.tx_query.input_query + + # remove tx query from input query + input_query.set_tx_query(None, False) + + assert input_query.tx_query is None + assert tx_query.input_query is None + + def test_output_query_meets_criteria_matches_unconstrained_output(self) -> None: + output: MoneroOutputWallet = MoneroOutputWallet() + output.amount = 1 + assert MoneroOutputQuery().meets_criteria(output, False) is True + + @pytest.mark.parametrize("field,value,other_value", [ + ("account_index", 2, 9), + ("subaddress_index", 5, 1), + ("amount", 100, 1), + ("is_spent", True, False), + ("is_frozen", False, True), + ]) + def test_output_query_meets_criteria_field_filters(self, field: str, value: object, other_value: object) -> None: + output: MoneroOutputWallet = MoneroOutputWallet() + output.amount = 1 + setattr(output, field, value) + + query: MoneroOutputQuery = MoneroOutputQuery() + setattr(query, field, value) + assert query.meets_criteria(output, False) is True + + setattr(query, field, other_value) + assert query.meets_criteria(output, False) is False + + @pytest.mark.parametrize("field,value", [ + ("account_index", 2), + ("subaddress_index", 5), + ("amount", 100), + ("is_spent", True), + ("is_frozen", False), + ]) + def test_output_query_meets_criteria_field_filters_require_output_value(self, field: str, value: object) -> None: + # a query constraint never matches an output that leaves the field unset + output: MoneroOutputWallet = MoneroOutputWallet() + query: MoneroOutputQuery = MoneroOutputQuery() + setattr(query, field, value) + assert query.meets_criteria(output, False) is False + + def test_output_query_meets_criteria_key_image(self) -> None: + output: MoneroOutputWallet = MoneroOutputWallet() + output.amount = 1 + output.key_image = MoneroKeyImage() + output.key_image.hex = "a" * 64 + output.key_image.signature = "b" * 128 + + hex_query: MoneroOutputQuery = MoneroOutputQuery() + hex_query.key_image = MoneroKeyImage() + hex_query.key_image.hex = "a" * 64 + assert hex_query.meets_criteria(output, False) is True + hex_query.key_image.hex = "c" * 64 + assert hex_query.meets_criteria(output, False) is False + + signature_query: MoneroOutputQuery = MoneroOutputQuery() + signature_query.key_image = MoneroKeyImage() + signature_query.key_image.signature = "b" * 128 + assert signature_query.meets_criteria(output, False) is True + signature_query.key_image.signature = "d" * 128 + assert signature_query.meets_criteria(output, False) is False + + # never matches an output with no key image at all + no_key_image_query: MoneroOutputQuery = MoneroOutputQuery() + no_key_image_query.key_image = MoneroKeyImage() + no_key_image_query.key_image.hex = "a" * 64 + assert no_key_image_query.meets_criteria(MoneroOutputWallet(), False) is False + + def test_output_query_meets_criteria_subaddress_indices(self) -> None: + output: MoneroOutputWallet = MoneroOutputWallet() + output.amount = 1 + output.subaddress_index = 7 + + query: MoneroOutputQuery = MoneroOutputQuery() + query.subaddress_indices = [7, 8] + assert query.meets_criteria(output, False) is True + + query.subaddress_indices = [1, 2] + assert query.meets_criteria(output, False) is False + + def test_output_query_meets_criteria_min_max_amount(self) -> None: + output: MoneroOutputWallet = MoneroOutputWallet() + output.amount = 50 + + min_query: MoneroOutputQuery = MoneroOutputQuery() + min_query.min_amount = 10 + assert min_query.meets_criteria(output, False) is True + min_query.min_amount = 100 + assert min_query.meets_criteria(output, False) is False + + max_query: MoneroOutputQuery = MoneroOutputQuery() + max_query.max_amount = 100 + assert max_query.meets_criteria(output, False) is True + max_query.max_amount = 10 + assert max_query.meets_criteria(output, False) is False + + def test_output_query_meets_criteria_query_parent_links_tx_query(self) -> None: + tx: MoneroTxWallet = MoneroTxWallet() + tx.hash = "a" * 64 + output: MoneroOutputWallet = MoneroOutputWallet() + output.amount = 1 + output.tx = tx + + query: MoneroOutputQuery = MoneroOutputQuery() + query.amount = 1 + tx_query: MoneroTxQuery = MoneroTxQuery() + tx_query.hash = "b" * 64 + query.set_tx_query(tx_query, True) + + # query_parent defaults to True: the mismatching tx_query rejects the output + assert query.meets_criteria(output) is False + assert query.meets_criteria(output, False) is True # bypassed when not querying the parent + + tx_query.hash = "a" * 64 + assert query.meets_criteria(output) is True + + def test_output_query_meets_criteria_none_output_raises(self) -> None: + with pytest.raises(RuntimeError) as exc_info: + MoneroOutputQuery().meets_criteria(None, False) # type: ignore + assert str(exc_info.value) == "nullptr given to monero_output_query::meets_criteria()" + + def test_output_query_deserialize(self) -> None: + query: MoneroOutputQuery = MoneroOutputQuery() + query.amount = 1000000 + query.index = 2 + query.account_index = 0 + query.subaddress_index = 1 + query.is_spent = False + query.is_frozen = False + query.subaddress_indices = [0, 1] + query.min_amount = 100000 + query.max_amount = 2000000 + AssertUtils.assert_serialization_integrity(query) + + def test_output_query_deserialize_from_block(self) -> None: + tx_query: MoneroTxQuery = MoneroTxQuery() + tx_query.hash = "a" * 64 + tx_query.input_query = MoneroOutputQuery() + tx_query.input_query.amount = 5 + tx_query.input_query.index = 1 + tx_query.output_query = MoneroOutputQuery() + tx_query.output_query.amount = 7 + tx_query.output_query.index = 2 + + # deserialize_from_block expects a block node wrapping the tx query under "txs" + block_json: str = '{"txs":[' + tx_query.serialize() + ']}' + restored: MoneroOutputQuery = MoneroOutputQuery.deserialize_from_block(block_json) + assert restored.amount == 7 + assert restored.index == 2 + assert restored.tx_query is not None + assert restored.tx_query.hash == "a" * 64 + # the input query is built alongside the output query and linked back too + assert restored.tx_query.input_query is not None + assert restored.tx_query.input_query.amount == 5 + + def test_output_query_deserialize_from_block_no_txs(self) -> None: + restored: MoneroOutputQuery = MoneroOutputQuery.deserialize_from_block('{"txs": []}') + assert restored.amount is None + assert restored.tx_query is None + + def test_output_query_copy(self) -> None: + query: MoneroOutputQuery = MoneroOutputQuery() + query.amount = 1000000 + query.min_amount = 100000 + query.max_amount = 2000000 + + copy: MoneroOutputQuery = query.copy() + assert copy is not query + assert copy.serialize() == query.serialize() diff --git a/tests/wallet/model/test_outputs.py b/tests/wallet/model/test_outputs.py new file mode 100644 index 00000000..83035e72 --- /dev/null +++ b/tests/wallet/model/test_outputs.py @@ -0,0 +1,131 @@ +from __future__ import annotations + +import logging + +import pytest +from monero import MoneroKeyImage, MoneroOutputWallet, MoneroTx, OutputComparator + +from utils import AssertUtils, BaseTestClass + +logger: logging.Logger = logging.getLogger("TestMoneroWalletModelOutputs") + + +@pytest.mark.unit +class TestMoneroWalletModelOutputs(BaseTestClass): + """Wallet output model unit tests.""" + + def test_output_wallet_deserialize(self) -> None: + output_wallet: MoneroOutputWallet = MoneroOutputWallet() + output_wallet.amount = 1000000 + output_wallet.index = 2 + key_image: MoneroKeyImage = MoneroKeyImage() + key_image.hex = "a" * 64 + key_image.signature = "b" * 128 + output_wallet.key_image = key_image + output_wallet.account_index = 0 + output_wallet.subaddress_index = 1 + output_wallet.is_spent = False + output_wallet.is_frozen = False + AssertUtils.assert_serialization_integrity(output_wallet) + + def test_output_wallet_copy(self) -> None: + output: MoneroOutputWallet = MoneroOutputWallet() + output.amount = 1000000 + output.index = 2 + output.account_index = 0 + output.subaddress_index = 1 + output.is_spent = False + output.is_frozen = False + + copy: MoneroOutputWallet = output.copy() + assert copy is not output + assert copy.serialize() == output.serialize() + + def test_output_wallet_merge(self) -> None: + a: MoneroOutputWallet = MoneroOutputWallet() + a.amount = 1000000 + a.index = 2 + a.account_index = 0 + a.subaddress_index = 1 + # a.tx is left unset on both sides so merge() won't recurse into tx merge + + b: MoneroOutputWallet = a.copy() + b.is_spent = True # a.is_spent is unset -> merge fills the gap + a.merge(b) + assert a.is_spent is True + + def test_output_wallet_lt_comparator(self) -> None: + o1: MoneroOutputWallet = MoneroOutputWallet() + o1.tx = MoneroTx() + o1.account_index = 0 + o1.subaddress_index = 0 + o1.index = 0 + o1.key_image = MoneroKeyImage() + o1.key_image.hex = "a" * 64 + + o2: MoneroOutputWallet = MoneroOutputWallet() + o2.tx = MoneroTx() + o2.account_index = 0 + o2.subaddress_index = 0 + o2.index = 1 + o2.key_image = MoneroKeyImage() + o2.key_image.hex = "b" * 64 + + assert o1 < o2 + assert not (o2 < o1) + assert OutputComparator.compare(o1, o2) + assert not OutputComparator.compare(o2, o1) + + def test_output_wallet_lt_comparator_account_index(self) -> None: + tx: MoneroTx = MoneroTx() + o1: MoneroOutputWallet = MoneroOutputWallet() + o1.tx = tx + o1.account_index = 0 + o1.subaddress_index = 0 + o1.index = 0 + o1.key_image = MoneroKeyImage() + o1.key_image.hex = "a" * 64 + + o2: MoneroOutputWallet = o1.copy() + o2.account_index = 1 # only the account index differs + + assert OutputComparator.compare(o1, o2) + assert not OutputComparator.compare(o2, o1) + + def test_output_wallet_lt_comparator_subaddress_index(self) -> None: + tx: MoneroTx = MoneroTx() + o1: MoneroOutputWallet = MoneroOutputWallet() + o1.tx = tx + o1.account_index = 0 + o1.subaddress_index = 0 + o1.index = 0 + o1.key_image = MoneroKeyImage() + o1.key_image.hex = "a" * 64 + + o2: MoneroOutputWallet = o1.copy() + o2.subaddress_index = 1 # same account index, only the subaddress index differs + + assert OutputComparator.compare(o1, o2) + assert not OutputComparator.compare(o2, o1) + + def test_output_wallet_lt_comparator_key_image(self) -> None: + tx: MoneroTx = MoneroTx() + o1: MoneroOutputWallet = MoneroOutputWallet() + o1.tx = tx + o1.account_index = 0 + o1.subaddress_index = 0 + o1.index = 0 + o1.key_image = MoneroKeyImage() + o1.key_image.hex = "a" * 64 + + o2: MoneroOutputWallet = o1.copy() + o2.key_image = MoneroKeyImage() + o2.key_image.hex = "b" * 64 # account/subaddress/index tied -> falls back to key image hex + + assert OutputComparator.compare(o1, o2) + assert not OutputComparator.compare(o2, o1) + + outputs: list[MoneroOutputWallet] = [o2, o1] + outputs.sort() + assert outputs[0] is o1 + assert outputs[1] is o2 diff --git a/tests/wallet/model/test_results.py b/tests/wallet/model/test_results.py new file mode 100644 index 00000000..7eeadd2a --- /dev/null +++ b/tests/wallet/model/test_results.py @@ -0,0 +1,103 @@ +from __future__ import annotations + +import logging + +import pytest +from monero import ( + MoneroCheck, + MoneroCheckReserve, + MoneroCheckTx, + MoneroKeyImage, + MoneroKeyImageExportResult, + MoneroKeyImageImportResult, + MoneroMessageSignatureResult, + MoneroMessageSignatureType, + MoneroMultisigInfo, + MoneroMultisigInitResult, + MoneroMultisigSignResult, + MoneroSyncResult, +) + +from utils import AssertUtils, BaseTestClass, TestUtils + +logger: logging.Logger = logging.getLogger("TestMoneroWalletModelResults") + + +@pytest.mark.unit +class TestMoneroWalletModelResults(BaseTestClass): + """Wallet result model unit tests.""" + + def test_key_image_import_result_deserialize(self) -> None: + result: MoneroKeyImageImportResult = MoneroKeyImageImportResult() + result.height = 3000000 + result.spent_amount = 500000 + result.unspent_amount = 1500000 + AssertUtils.assert_serialization_integrity(result) + + def test_message_signature_result_deserialize(self) -> None: + result: MoneroMessageSignatureResult = MoneroMessageSignatureResult() + result.is_good = True + result.is_old = False + result.version = 2 + result.signature_type = MoneroMessageSignatureType.SIGN_WITH_SPEND_KEY + AssertUtils.assert_serialization_integrity(result) + + def test_message_signature_result_invalid_signature_type_deserialize(self) -> None: + with pytest.raises(RuntimeError) as exc_info: + MoneroMessageSignatureResult.deserialize('{"signatureType": "bogus"}') + assert str(exc_info.value) == "Invalid message signature type: bogus" + + def test_check_tx_deserialize(self) -> None: + check: MoneroCheckTx = MoneroCheckTx() + check.is_good = True + check.in_tx_pool = False + check.num_confirmations = 10 + check.received_amount = 500000 + AssertUtils.assert_serialization_integrity(check) + + def test_check_reserve_deserialize(self) -> None: + check: MoneroCheckReserve = MoneroCheckReserve() + check.is_good = True + check.total_amount = 1000000 + check.unconfirmed_spent_amount = 0 + AssertUtils.assert_serialization_integrity(check) + + def test_multisig_info_deserialize(self) -> None: + info: MoneroMultisigInfo = MoneroMultisigInfo() + info.is_multisig = True + info.is_ready = True + info.threshold = 2 + info.num_participants = 3 + AssertUtils.assert_serialization_integrity(info) + + def test_multisig_init_result_deserialize(self) -> None: + result: MoneroMultisigInitResult = MoneroMultisigInitResult() + result.address = TestUtils.ADDRESS + result.multisig_hex = "deadbeef" + AssertUtils.assert_serialization_integrity(result) + + def test_multisig_sign_result_deserialize(self) -> None: + result: MoneroMultisigSignResult = MoneroMultisigSignResult() + result.signed_multisig_tx_hex = "deadbeef" + result.tx_hashes = ["a" * 64, "b" * 64] + AssertUtils.assert_serialization_integrity(result) + + def test_sync_result_deserialize(self) -> None: + result: MoneroSyncResult = MoneroSyncResult() + result.num_blocks_fetched = 42 + result.received_money = True + AssertUtils.assert_serialization_integrity(result) + + def test_check_deserialize(self) -> None: + check: MoneroCheck = MoneroCheck() + check.is_good = True + AssertUtils.assert_serialization_integrity(check) + + def test_key_image_export_result_deserialize(self) -> None: + result: MoneroKeyImageExportResult = MoneroKeyImageExportResult() + result.offset = 3 + key_image: MoneroKeyImage = MoneroKeyImage() + key_image.hex = "a" * 64 + key_image.signature = "b" * 128 + result.key_images = [key_image] + AssertUtils.assert_serialization_integrity(result) diff --git a/tests/wallet/model/test_transfer_query.py b/tests/wallet/model/test_transfer_query.py new file mode 100644 index 00000000..06584303 --- /dev/null +++ b/tests/wallet/model/test_transfer_query.py @@ -0,0 +1,306 @@ +from __future__ import annotations + +import logging + +import pytest +from monero import ( + MoneroDestination, + MoneroIncomingTransfer, + MoneroOutgoingTransfer, + MoneroTransfer, + MoneroTransferQuery, + MoneroTxQuery, + MoneroTxWallet, +) + +from utils import AssertUtils, BaseTestClass, TestUtils + +logger: logging.Logger = logging.getLogger("TestMoneroWalletModelTransferQuery") + + +@pytest.mark.unit +class TestMoneroWalletModelTransferQuery(BaseTestClass): + """Wallet transfer query model unit tests.""" + + # Test transfer query expected behaviour + def test_transfer_query(self) -> None: + transfer_query: MoneroTransferQuery = MoneroTransferQuery() + tx_query: MoneroTxQuery = MoneroTxQuery() + + # assign tx query to transfer query + transfer_query.tx_query = tx_query + + assert tx_query.transfer_query is not None + assert tx_query.transfer_query == transfer_query + + # reassign transfer query to tx query + transfer_query.tx_query.transfer_query = transfer_query + assert transfer_query.tx_query is not None + assert transfer_query == transfer_query.tx_query.transfer_query + + # remove tx query from transfer query + transfer_query.tx_query = None + + assert tx_query.transfer_query is None + + transfer_query: MoneroTransferQuery = MoneroTransferQuery() + transfer_query.tx_query = MoneroTxQuery() + + # check incoming/outgoing + assert transfer_query.incoming is None + assert transfer_query.outgoing is None + assert transfer_query.is_incoming() is None + assert transfer_query.is_outgoing() is None + + # set incoming + transfer_query.incoming = True + assert transfer_query.is_incoming() is True + assert transfer_query.outgoing is False + assert transfer_query.is_outgoing() is False + transfer_query.incoming = None + + # set outgoing + transfer_query.outgoing = True + assert transfer_query.is_outgoing() is True + assert transfer_query.incoming is False + assert transfer_query.is_incoming() is False + + def test_transfer_query_meets_criteria_matches_unconstrained_transfer(self) -> None: + transfer: MoneroIncomingTransfer = MoneroIncomingTransfer() + transfer.amount = 100 + assert MoneroTransferQuery().meets_criteria(transfer, False) is True + + @pytest.mark.parametrize("field,value,other_value", [ + ("amount", 100, 999), + ("account_index", 2, 5), + ]) + def test_transfer_query_meets_criteria_common_field_filters(self, field: str, value: object, other_value: object) -> None: + transfer: MoneroIncomingTransfer = MoneroIncomingTransfer() + transfer.amount = 1 + setattr(transfer, field, value) + + query: MoneroTransferQuery = MoneroTransferQuery() + setattr(query, field, value) + assert query.meets_criteria(transfer, False) is True + + setattr(query, field, other_value) + assert query.meets_criteria(transfer, False) is False + + def test_transfer_query_meets_criteria_incoming_outgoing_flags(self) -> None: + incoming: MoneroIncomingTransfer = MoneroIncomingTransfer() + incoming.amount = 1 + outgoing: MoneroOutgoingTransfer = MoneroOutgoingTransfer() + outgoing.amount = 1 + + incoming_query: MoneroTransferQuery = MoneroTransferQuery() + incoming_query.incoming = True + assert incoming_query.meets_criteria(incoming, False) is True + assert incoming_query.meets_criteria(outgoing, False) is False + + outgoing_query: MoneroTransferQuery = MoneroTransferQuery() + outgoing_query.outgoing = True + assert outgoing_query.meets_criteria(outgoing, False) is True + assert outgoing_query.meets_criteria(incoming, False) is False + + def test_transfer_query_meets_criteria_incoming_has_destinations_always_false(self) -> None: + # has_destinations is an outgoing-only concept; setting it on the query + # rejects an incoming transfer regardless of True/False + incoming: MoneroIncomingTransfer = MoneroIncomingTransfer() + incoming.amount = 1 + + query_true: MoneroTransferQuery = MoneroTransferQuery() + query_true.has_destinations = True + assert query_true.meets_criteria(incoming, False) is False + + query_false: MoneroTransferQuery = MoneroTransferQuery() + query_false.has_destinations = False + assert query_false.meets_criteria(incoming, False) is False + + def test_transfer_query_meets_criteria_incoming_address_fields(self) -> None: + incoming: MoneroIncomingTransfer = MoneroIncomingTransfer() + incoming.amount = 1 + incoming.address = TestUtils.ADDRESS + incoming.subaddress_index = 3 + + address_query: MoneroTransferQuery = MoneroTransferQuery() + address_query.address = TestUtils.ADDRESS + assert address_query.meets_criteria(incoming, False) is True + address_query.address = TestUtils.MINING_ADDRESS + assert address_query.meets_criteria(incoming, False) is False + + addresses_query: MoneroTransferQuery = MoneroTransferQuery() + addresses_query.addresses = [TestUtils.ADDRESS, TestUtils.MINING_ADDRESS] + assert addresses_query.meets_criteria(incoming, False) is True + addresses_query.addresses = [TestUtils.MINING_ADDRESS] + assert addresses_query.meets_criteria(incoming, False) is False + + subaddress_index_query: MoneroTransferQuery = MoneroTransferQuery() + subaddress_index_query.subaddress_index = 3 + assert subaddress_index_query.meets_criteria(incoming, False) is True + subaddress_index_query.subaddress_index = 9 + assert subaddress_index_query.meets_criteria(incoming, False) is False + + subaddress_indices_query: MoneroTransferQuery = MoneroTransferQuery() + subaddress_indices_query.subaddress_indices = [3, 4] + assert subaddress_indices_query.meets_criteria(incoming, False) is True + subaddress_indices_query.subaddress_indices = [9] + assert subaddress_indices_query.meets_criteria(incoming, False) is False + + def test_transfer_query_meets_criteria_outgoing_address_fields(self) -> None: + outgoing: MoneroOutgoingTransfer = MoneroOutgoingTransfer() + outgoing.amount = 1 + outgoing.addresses = [TestUtils.ADDRESS, TestUtils.MINING_ADDRESS] + + # a single address must be a member of the transfer's address list + address_query: MoneroTransferQuery = MoneroTransferQuery() + address_query.address = TestUtils.ADDRESS + assert address_query.meets_criteria(outgoing, False) is True + address_query.address = "9" + "z" * 94 + assert address_query.meets_criteria(outgoing, False) is False + assert address_query.meets_criteria(MoneroOutgoingTransfer(), False) is False # no addresses at all + + # a list of addresses only needs to intersect + addresses_query: MoneroTransferQuery = MoneroTransferQuery() + addresses_query.addresses = [TestUtils.MINING_ADDRESS, "9" + "z" * 94] + assert addresses_query.meets_criteria(outgoing, False) is True + addresses_query.addresses = ["9" + "z" * 94] + assert addresses_query.meets_criteria(outgoing, False) is False + + def test_transfer_query_meets_criteria_outgoing_subaddress_fields(self) -> None: + outgoing: MoneroOutgoingTransfer = MoneroOutgoingTransfer() + outgoing.amount = 1 + outgoing.subaddress_indices = [3, 4] + + subaddress_index_query: MoneroTransferQuery = MoneroTransferQuery() + subaddress_index_query.subaddress_index = 3 + assert subaddress_index_query.meets_criteria(outgoing, False) is True + subaddress_index_query.subaddress_index = 9 + assert subaddress_index_query.meets_criteria(outgoing, False) is False + assert subaddress_index_query.meets_criteria(MoneroOutgoingTransfer(), False) is False # no indices at all + + subaddress_indices_query: MoneroTransferQuery = MoneroTransferQuery() + subaddress_indices_query.subaddress_indices = [4, 100] + assert subaddress_indices_query.meets_criteria(outgoing, False) is True + subaddress_indices_query.subaddress_indices = [100, 200] + assert subaddress_indices_query.meets_criteria(outgoing, False) is False + + def test_transfer_query_meets_criteria_outgoing_has_destinations(self) -> None: + with_destinations: MoneroOutgoingTransfer = MoneroOutgoingTransfer() + with_destinations.amount = 1 + with_destinations.destinations = [MoneroDestination(TestUtils.ADDRESS, 1)] + without_destinations: MoneroOutgoingTransfer = MoneroOutgoingTransfer() + without_destinations.amount = 1 + + query_true: MoneroTransferQuery = MoneroTransferQuery() + query_true.has_destinations = True + assert query_true.meets_criteria(with_destinations, False) is True + assert query_true.meets_criteria(without_destinations, False) is False + + query_false: MoneroTransferQuery = MoneroTransferQuery() + query_false.has_destinations = False + assert query_false.meets_criteria(without_destinations, False) is True + assert query_false.meets_criteria(with_destinations, False) is False + + def test_transfer_query_meets_criteria_invalid_transfer_type_raises(self) -> None: + transfer: MoneroTransfer = MoneroTransfer() + transfer.amount = 1 + with pytest.raises(RuntimeError) as exc_info: + MoneroTransferQuery().meets_criteria(transfer, False) + assert str(exc_info.value) == "Transfer must be monero_incoming_transfer or monero_outgoing_transfer" + + def test_transfer_query_meets_criteria_query_parent_links_tx_query(self) -> None: + tx: MoneroTxWallet = MoneroTxWallet() + tx.hash = "a" * 64 + transfer: MoneroIncomingTransfer = MoneroIncomingTransfer() + transfer.amount = 100 + transfer.tx = tx + + query: MoneroTransferQuery = MoneroTransferQuery() + query.amount = 100 + query.tx_query = MoneroTxQuery() + query.tx_query.hash = "b" * 64 # does not match the transfer's tx + + # query_parent defaults to True: the mismatching tx_query rejects the transfer + assert query.meets_criteria(transfer) is False + assert query.meets_criteria(transfer, False) is True # bypassed when not querying the parent + + query.tx_query.hash = "a" * 64 + assert query.meets_criteria(transfer) is True + + def test_transfer_query_meets_criteria_none_transfer_raises(self) -> None: + with pytest.raises(RuntimeError) as exc_info: + MoneroTransferQuery().meets_criteria(None, False) # type: ignore + assert str(exc_info.value) == "nullptr given to monero_transfer_query::meets_criteria()" + + def test_transfer_query_deserialize(self) -> None: + query: MoneroTransferQuery = MoneroTransferQuery() + query.amount = 500000 + query.account_index = 0 + query.incoming = True + query.address = TestUtils.ADDRESS + query.subaddress_index = 1 + query.subaddress_indices = [0, 1, 2] + query.has_destinations = False + # addresses, destinations and tx_query all raise "not implemented" (see below) + AssertUtils.assert_serialization_integrity(query) + + @pytest.mark.parametrize("json_fragment", [ + '{"addresses":["' + TestUtils.ADDRESS + '"]}', + '{"destinations":[{"address":"' + TestUtils.ADDRESS + '","amount":1}]}', + '{"txQuery":{}}', + ]) + def test_transfer_query_unimplemented_fields(self, json_fragment: str) -> None: + with pytest.raises(Exception, match="not implemented"): + MoneroTransferQuery.deserialize(json_fragment) + + def test_transfer_query_deserialize_from_block(self) -> None: + tx_query: MoneroTxQuery = MoneroTxQuery() + tx_query.hash = "a" * 64 + transfer_query: MoneroTransferQuery = MoneroTransferQuery() + transfer_query.amount = 500000 + transfer_query.account_index = 0 + tx_query.transfer_query = transfer_query + + # deserialize_from_block expects a block node wrapping the tx query under "txs" + block_json: str = '{"txs":[' + tx_query.serialize() + ']}' + restored: MoneroTransferQuery = MoneroTransferQuery.deserialize_from_block(block_json) + assert restored.amount == 500000 + assert restored.account_index == 0 + assert restored.tx_query is not None + assert restored.tx_query.hash == "a" * 64 + + def test_transfer_query_deserialize_from_block_no_nested_query(self) -> None: + # a tx with no nested transferQuery gets an empty one, linked to the tx query + tx_query: MoneroTxQuery = MoneroTxQuery() + tx_query.hash = "a" * 64 + block_json: str = '{"txs":[' + tx_query.serialize() + ']}' + restored: MoneroTransferQuery = MoneroTransferQuery.deserialize_from_block(block_json) + assert restored.amount is None + assert restored.tx_query is not None + assert restored.tx_query.hash == "a" * 64 + + def test_transfer_query_deserialize_from_block_no_txs(self) -> None: + restored: MoneroTransferQuery = MoneroTransferQuery.deserialize_from_block('{"txs": []}') + assert restored.amount is None + assert restored.tx_query is None + + def test_transfer_query_copy(self) -> None: + query: MoneroTransferQuery = MoneroTransferQuery() + query.amount = 500000 + query.incoming = True + query.address = TestUtils.ADDRESS + + copy: MoneroTransferQuery = query.copy() + assert copy is not query + assert copy.serialize() == query.serialize() + + def test_transfer_query_copy_deep_copies_destinations(self) -> None: + query: MoneroTransferQuery = MoneroTransferQuery() + destination: MoneroDestination = MoneroDestination(TestUtils.ADDRESS, 100) + query.destinations = [destination] + + copy: MoneroTransferQuery = query.copy() + assert len(copy.destinations) == 1 + assert copy.destinations[0] is not destination + assert copy.destinations[0].address == TestUtils.ADDRESS + assert copy.destinations[0].amount == 100 diff --git a/tests/wallet/model/test_transfers.py b/tests/wallet/model/test_transfers.py new file mode 100644 index 00000000..872a5ed0 --- /dev/null +++ b/tests/wallet/model/test_transfers.py @@ -0,0 +1,177 @@ +from __future__ import annotations + +import logging + +import pytest +from monero import ( + IncomingTransferComparator, + MoneroDestination, + MoneroIncomingTransfer, + MoneroOutgoingTransfer, + MoneroTxWallet, +) + +from utils import AssertUtils, BaseTestClass, TestUtils + +logger: logging.Logger = logging.getLogger("TestMoneroWalletModelTransfers") + + +@pytest.mark.unit +class TestMoneroWalletModelTransfers(BaseTestClass): + """Wallet transfer model unit tests.""" + + def test_incoming_transfer_deserialize(self) -> None: + transfer: MoneroIncomingTransfer = MoneroIncomingTransfer() + transfer.amount = 500000 + transfer.account_index = 0 + transfer.subaddress_index = 1 + transfer.address = TestUtils.ADDRESS + transfer.num_suggested_confirmations = 10 + AssertUtils.assert_serialization_integrity(transfer) + + def test_outgoing_transfer_deserialize(self) -> None: + transfer: MoneroOutgoingTransfer = MoneroOutgoingTransfer() + transfer.amount = 500000 + transfer.account_index = 0 + transfer.subaddress_indices = [0, 1] + transfer.addresses = [TestUtils.ADDRESS] + transfer.destinations = [MoneroDestination(TestUtils.ADDRESS, 500000)] + AssertUtils.assert_serialization_integrity(transfer) + + def test_incoming_transfer_copy(self) -> None: + transfer: MoneroIncomingTransfer = MoneroIncomingTransfer() + transfer.amount = 500000 + transfer.account_index = 0 + transfer.subaddress_index = 1 + transfer.address = TestUtils.ADDRESS + transfer.num_suggested_confirmations = 10 + + copy: MoneroIncomingTransfer = transfer.copy() + assert copy is not transfer + assert copy.serialize() == transfer.serialize() + + def test_incoming_transfer_merge(self) -> None: + a: MoneroIncomingTransfer = MoneroIncomingTransfer() + a.amount = 500000 + a.account_index = 0 + a.subaddress_index = 1 + # a.tx is left unset on both sides so merge() won't recurse into tx merge + + b: MoneroIncomingTransfer = a.copy() + b.address = TestUtils.ADDRESS # a.address is unset -> merge fills the gap + a.merge(b) + assert a.address == TestUtils.ADDRESS + + def test_incoming_transfer_merge_recurses_into_tx_merge(self) -> None: + tx_a: MoneroTxWallet = MoneroTxWallet() + tx_a.hash = "a" * 64 + tx_a.is_confirmed = True + + tx_b: MoneroTxWallet = MoneroTxWallet() + tx_b.hash = "a" * 64 + tx_b.is_confirmed = True + tx_b.num_confirmations = 9 # tx_a's num_confirmations is unset -> merge fills the gap + + a: MoneroIncomingTransfer = MoneroIncomingTransfer() + a.tx = tx_a + a.account_index = 0 + a.amount = 100 + + b: MoneroIncomingTransfer = MoneroIncomingTransfer() + b.tx = tx_b + b.account_index = 0 + b.amount = 100 + + # transfers on different txs -> merge delegates to tx merge (which comes back to merging transfers) + a.merge(b) + assert tx_a.num_confirmations == 9 + + def test_incoming_transfer_merge_zero_amount_conflict_keeps_original(self) -> None: + tx: MoneroTxWallet = MoneroTxWallet() + tx.hash = "a" * 64 + + a: MoneroIncomingTransfer = MoneroIncomingTransfer() + a.tx = tx + a.account_index = 0 + a.amount = 500 + + b: MoneroIncomingTransfer = MoneroIncomingTransfer() + b.tx = tx + b.account_index = 0 + b.amount = 0 + + # conflicting amounts where one side is 0 are a known monero-project quirk (failed tx in + # pool): merge() warns and leaves the amount as-is rather than reconciling it + a.merge(b) + assert a.amount == 500 + + def test_incoming_transfer_lt_comparator(self) -> None: + t1: MoneroIncomingTransfer = MoneroIncomingTransfer() + t1.tx = MoneroTxWallet() + t1.account_index = 0 + t1.subaddress_index = 0 + + t2: MoneroIncomingTransfer = MoneroIncomingTransfer() + t2.tx = MoneroTxWallet() + t2.account_index = 0 + t2.subaddress_index = 1 + + assert t1 < t2 + assert not (t2 < t1) + assert IncomingTransferComparator.compare(t1, t2) + assert not IncomingTransferComparator.compare(t2, t1) + + transfers: list[MoneroIncomingTransfer] = [t2, t1] + transfers.sort() + assert transfers[0] is t1 + assert transfers[1] is t2 + + def test_outgoing_transfer_copy(self) -> None: + transfer: MoneroOutgoingTransfer = MoneroOutgoingTransfer() + transfer.amount = 500000 + transfer.account_index = 0 + transfer.addresses = [TestUtils.ADDRESS] + transfer.subaddress_indices = [0] + transfer.destinations = [MoneroDestination(TestUtils.ADDRESS, 500000)] + + copy: MoneroOutgoingTransfer = transfer.copy() + assert copy is not transfer + assert copy.serialize() == transfer.serialize() + + def test_outgoing_transfer_merge(self) -> None: + a: MoneroOutgoingTransfer = MoneroOutgoingTransfer() + a.amount = 500000 + a.account_index = 0 + # a.addresses/subaddress_indices/destinations left empty on both sides so far + + b: MoneroOutgoingTransfer = a.copy() + b.addresses = [TestUtils.ADDRESS] + b.subaddress_indices = [0] + b.destinations = [MoneroDestination(TestUtils.ADDRESS, 500000)] + a.merge(b) # a's lists are empty -> merge adopts b's + assert a.addresses == [TestUtils.ADDRESS] + assert a.subaddress_indices == [0] + assert len(a.destinations) == 1 + + def test_outgoing_transfer_merge_destinations_with_unset_fields(self) -> None: + # destinations with unset address/amount are a reachable state; merge() + # must compare them without dereferencing the empty optionals + a: MoneroOutgoingTransfer = MoneroOutgoingTransfer() + a.amount = 500000 + a.account_index = 0 + a.destinations = [MoneroDestination()] + b: MoneroOutgoingTransfer = a.copy() + b.destinations = [MoneroDestination()] + a.merge(b) # equal (empty) destinations -> no error + assert len(a.destinations) == 1 + + def test_outgoing_transfer_merge_conflicting_destinations_raises(self) -> None: + a: MoneroOutgoingTransfer = MoneroOutgoingTransfer() + a.amount = 500000 + a.account_index = 0 + a.destinations = [MoneroDestination(TestUtils.ADDRESS, 1)] + b: MoneroOutgoingTransfer = a.copy() + b.destinations = [MoneroDestination(TestUtils.ADDRESS, 2)] + with pytest.raises(RuntimeError) as exc_info: + a.merge(b) + assert str(exc_info.value) == "Destination vectors are different" diff --git a/tests/wallet/model/test_tx_query.py b/tests/wallet/model/test_tx_query.py new file mode 100644 index 00000000..06500347 --- /dev/null +++ b/tests/wallet/model/test_tx_query.py @@ -0,0 +1,417 @@ +from __future__ import annotations + +import logging + +import pytest +from monero import ( + MoneroBlock, + MoneroIncomingTransfer, + MoneroOutgoingTransfer, + MoneroOutputQuery, + MoneroOutputWallet, + MoneroTransferQuery, + MoneroTxQuery, + MoneroTxWallet, +) + +from utils import AssertUtils, BaseTestClass + +logger: logging.Logger = logging.getLogger("TestMoneroWalletModelTxQuery") + + +@pytest.mark.unit +class TestMoneroWalletModelTxQuery(BaseTestClass): + """Wallet tx query model unit tests.""" + + # Test tx query expected behaviour + def test_tx_query(self) -> None: + tx_query: MoneroTxQuery = MoneroTxQuery() + transfer_query: MoneroTransferQuery = MoneroTransferQuery() + output_query: MoneroOutputQuery = MoneroOutputQuery() + input_query: MoneroOutputQuery = MoneroOutputQuery() + + # assign transfer query to tx query + tx_query.transfer_query = transfer_query + + assert tx_query.transfer_query == transfer_query + assert transfer_query.tx_query is not None + assert transfer_query.tx_query == tx_query + + # remove transfer query from tx query + tx_query.transfer_query = None + + assert tx_query.transfer_query != transfer_query + assert transfer_query.tx_query is None + + # assign output query to tx query + tx_query.output_query = output_query + + assert tx_query.output_query == output_query + assert output_query.tx_query is not None + assert output_query.tx_query == tx_query + + # remove output query from tx query + tx_query.output_query = None + + assert tx_query.output_query != output_query + assert output_query.tx_query is None + + # assign input query to tx query + tx_query.input_query = input_query + + assert tx_query.input_query == input_query + assert input_query.tx_query is not None + assert input_query.tx_query == tx_query + + # remove output query from tx query + tx_query.input_query = None + + assert tx_query.input_query != input_query + assert input_query.tx_query is None + + def test_tx_query_meets_criteria_matches_unconstrained_tx(self) -> None: + tx: MoneroTxWallet = MoneroTxWallet() + tx.hash = "a" * 64 + assert MoneroTxQuery().meets_criteria(tx) is True + + @pytest.mark.parametrize("field,value,other_value", [ + ("hash", "a" * 64, "b" * 64), + ("payment_id", "c" * 16, "d" * 16), + ("is_confirmed", True, False), + ("in_tx_pool", True, False), + ("relay", True, False), + ("is_failed", True, False), + ("is_miner_tx", True, False), + ("is_locked", True, False), + ("is_incoming", True, False), + ("is_outgoing", True, False), + ]) + def test_tx_query_meets_criteria_field_filters(self, field: str, value: object, other_value: object) -> None: + tx: MoneroTxWallet = MoneroTxWallet() + tx.hash = "a" * 64 + setattr(tx, field, value) + + query: MoneroTxQuery = MoneroTxQuery() + setattr(query, field, value) + assert query.meets_criteria(tx) is True + + setattr(query, field, other_value) + assert query.meets_criteria(tx) is False + + def test_tx_query_meets_criteria_has_payment_id(self) -> None: + with_payment_id: MoneroTxWallet = MoneroTxWallet() + with_payment_id.hash = "a" * 64 + with_payment_id.payment_id = "b" * 16 + without_payment_id: MoneroTxWallet = MoneroTxWallet() + without_payment_id.hash = "c" * 64 + + query_true: MoneroTxQuery = MoneroTxQuery() + query_true.has_payment_id = True + assert query_true.meets_criteria(with_payment_id) is True + assert query_true.meets_criteria(without_payment_id) is False + + query_false: MoneroTxQuery = MoneroTxQuery() + query_false.has_payment_id = False + assert query_false.meets_criteria(without_payment_id) is True + assert query_false.meets_criteria(with_payment_id) is False + + def test_tx_query_meets_criteria_hashes(self) -> None: + tx: MoneroTxWallet = MoneroTxWallet() + tx.hash = "a" * 64 + + query: MoneroTxQuery = MoneroTxQuery() + query.hashes = ["a" * 64, "b" * 64] + assert query.meets_criteria(tx) is True + + query.hashes = ["c" * 64] + assert query.meets_criteria(tx) is False + + def test_tx_query_meets_criteria_payment_ids(self) -> None: + with_payment_id: MoneroTxWallet = MoneroTxWallet() + with_payment_id.hash = "a" * 64 + with_payment_id.payment_id = "b" * 16 + without_payment_id: MoneroTxWallet = MoneroTxWallet() + without_payment_id.hash = "c" * 64 + + query: MoneroTxQuery = MoneroTxQuery() + query.payment_ids = ["b" * 16, "d" * 16] + assert query.meets_criteria(with_payment_id) is True + assert query.meets_criteria(without_payment_id) is False # tx has no payment id at all + + query.payment_ids = ["d" * 16] + assert query.meets_criteria(with_payment_id) is False # tx's payment id isn't in the list + + def test_tx_query_meets_criteria_height_filters(self) -> None: + def confirmed_tx(height: int) -> MoneroTxWallet: + tx: MoneroTxWallet = MoneroTxWallet() + tx.hash = "a" * 64 + block: MoneroBlock = MoneroBlock() + block.height = height + tx.block = block + return tx + + tx: MoneroTxWallet = confirmed_tx(100) + + height_query: MoneroTxQuery = MoneroTxQuery() + height_query.height = 100 + assert height_query.meets_criteria(tx) is True + height_query.height = 200 + assert height_query.meets_criteria(tx) is False + + min_query: MoneroTxQuery = MoneroTxQuery() + min_query.min_height = 50 + assert min_query.meets_criteria(tx) is True + min_query.min_height = 150 + assert min_query.meets_criteria(tx) is False + + max_query: MoneroTxQuery = MoneroTxQuery() + max_query.max_height = 150 + assert max_query.meets_criteria(tx) is True + max_query.max_height = 50 + assert max_query.meets_criteria(tx) is False + + # an unconfirmed tx (no height) never satisfies a height-bound query + unconfirmed: MoneroTxWallet = MoneroTxWallet() + unconfirmed.hash = "b" * 64 + assert min_query.meets_criteria(unconfirmed) is False + + def test_tx_query_meets_criteria_query_children_default_and_false(self) -> None: + tx: MoneroTxWallet = MoneroTxWallet() + tx.hash = "a" * 64 # no inputs -> fails an enforced input_query + + query: MoneroTxQuery = MoneroTxQuery() + query.input_query = MoneroOutputQuery() + + # query_children defaults to True, matching monero-cpp's default + assert query.meets_criteria(tx) is False + assert query.meets_criteria(tx, True) is False + assert query.meets_criteria(tx, False) is True + + def test_tx_query_meets_criteria_transfer_query(self) -> None: + def tx_with_outgoing(amount: int) -> MoneroTxWallet: + tx: MoneroTxWallet = MoneroTxWallet() + tx.hash = "a" * 64 + tx.outgoing_transfer = MoneroOutgoingTransfer() + tx.outgoing_transfer.amount = amount + tx.outgoing_transfer.tx = tx + return tx + + def tx_with_incoming(amount: int) -> MoneroTxWallet: + tx: MoneroTxWallet = MoneroTxWallet() + tx.hash = "a" * 64 + transfer: MoneroIncomingTransfer = MoneroIncomingTransfer() + transfer.amount = amount + transfer.tx = tx + tx.incoming_transfers = [transfer] + return tx + + query: MoneroTxQuery = MoneroTxQuery() + query.transfer_query = MoneroTransferQuery() + query.transfer_query.amount = 500 + + assert query.meets_criteria(tx_with_outgoing(500), True) is True # matches via outgoing + assert query.meets_criteria(tx_with_incoming(500), True) is True # matches via incoming + assert query.meets_criteria(tx_with_outgoing(1), True) is False # no transfer matches + + # outgoing fails the query but an incoming transfer still matches as a fallback + tx: MoneroTxWallet = tx_with_outgoing(1) + incoming: MoneroIncomingTransfer = MoneroIncomingTransfer() + incoming.amount = 500 + incoming.tx = tx + tx.incoming_transfers = [incoming] + assert query.meets_criteria(tx, True) is True + + def test_tx_query_meets_criteria_input_query(self) -> None: + tx_no_inputs: MoneroTxWallet = MoneroTxWallet() + tx_no_inputs.hash = "a" * 64 + + tx_with_input: MoneroTxWallet = MoneroTxWallet() + tx_with_input.hash = "b" * 64 + tx_input: MoneroOutputWallet = MoneroOutputWallet() + tx_input.amount = 100 + tx_with_input.inputs = [tx_input] + + query: MoneroTxQuery = MoneroTxQuery() + query.input_query = MoneroOutputQuery() + assert query.meets_criteria(tx_no_inputs, True) is False # no inputs at all + + query.input_query.amount = 999 + assert query.meets_criteria(tx_with_input, True) is False # no input matches + + query.input_query.amount = 100 + assert query.meets_criteria(tx_with_input, True) is True # one input matches + + def test_tx_query_meets_criteria_output_query(self) -> None: + tx_no_outputs: MoneroTxWallet = MoneroTxWallet() + tx_no_outputs.hash = "a" * 64 + + tx_with_output: MoneroTxWallet = MoneroTxWallet() + tx_with_output.hash = "b" * 64 + output: MoneroOutputWallet = MoneroOutputWallet() + output.amount = 100 + tx_with_output.outputs = [output] + + query: MoneroTxQuery = MoneroTxQuery() + query.output_query = MoneroOutputQuery() + assert query.meets_criteria(tx_no_outputs, True) is False # no outputs at all + + query.output_query.amount = 999 + assert query.meets_criteria(tx_with_output, True) is False # no output matches + + query.output_query.amount = 100 + assert query.meets_criteria(tx_with_output, True) is True # one output matches + + def test_tx_query_meets_criteria_none_tx_raises(self) -> None: + with pytest.raises(RuntimeError) as exc_info: + MoneroTxQuery().meets_criteria(None) # type: ignore + assert str(exc_info.value) == "nullptr given to monero_tx_query::meets_criteria()" + + def test_tx_query_deserialize(self) -> None: + tx_query: MoneroTxQuery = MoneroTxQuery() + tx_query.hash = "a" * 64 + tx_query.is_confirmed = True + tx_query.hashes = ["a" * 64, "b" * 64] + tx_query.has_payment_id = False + tx_query.payment_ids = ["c" * 16] + tx_query.height = 3000000 + tx_query.min_height = 2999990 + tx_query.max_height = 3000010 + tx_query.include_outputs = False + # is_outgoing/is_incoming are deliberately not set here: monero_tx_query + # redeclares them as its own fields shadowing monero_tx_wallet's, and + # deserializing populates both copies at once (see test below) + AssertUtils.assert_serialization_integrity(tx_query) + + def test_tx_query_is_incoming_deserialize_not_duplicated(self) -> None: + tx_query: MoneroTxQuery = MoneroTxQuery() + tx_query.is_incoming = True + tx_query.is_outgoing = False + json_str: str = tx_query.serialize() + logger.debug(f"Serialized tx query: {json_str}") + assert json_str.count("isIncoming") == 1 + assert json_str.count("isOutgoing") == 1 + + restored: MoneroTxQuery = MoneroTxQuery.deserialize(json_str) + assert restored.is_incoming == tx_query.is_incoming + assert restored.is_outgoing == tx_query.is_outgoing + + restored_json: str = restored.serialize() + incoming_count: int = restored_json.count("isIncoming") + outgoing_count: int = restored_json.count("isOutgoing") + logger.debug(f"Deserialized tx query re-serialized: {restored_json}") + logger.debug(f"'isIncoming' occurs {incoming_count} time(s), 'isOutgoing' occurs {outgoing_count} time(s) (expected 1 each -- >1 means duplicated, i.e. malformed)") + assert incoming_count == 1 + assert outgoing_count == 1 + + def test_tx_query_nested_transfer_query_deserialize(self) -> None: + # transfer_query is a nested sub-object that to_rapidjson_val() and + # from_property_tree() both handle recursively + tx_query: MoneroTxQuery = MoneroTxQuery() + tx_query.height = 3000000 + transfer_query: MoneroTransferQuery = MoneroTransferQuery() + transfer_query.incoming = True + transfer_query.amount = 500000 + transfer_query.account_index = 0 + tx_query.transfer_query = transfer_query + + json_str: str = tx_query.serialize() + logger.debug(f"Serialized nested tx query: {json_str}") + assert "transferQuery" in json_str + + restored: MoneroTxQuery = MoneroTxQuery.deserialize(json_str) + assert restored.height == tx_query.height + assert restored.transfer_query is not None + assert restored.transfer_query.incoming == transfer_query.incoming + assert restored.transfer_query.amount == transfer_query.amount + assert restored.transfer_query.account_index == transfer_query.account_index + + def test_tx_query_input_and_output_query_deserialize(self) -> None: + # TODO input_query/output_query are read by from_property_tree() but never written by to_rapidjson_val() + tx_query: MoneroTxQuery = MoneroTxQuery.deserialize( + '{"inputQuery":{"amount":5,"index":1},"outputQuery":{"amount":7,"index":2}}' + ) + assert tx_query.input_query is not None + assert tx_query.input_query.amount == 5 + assert tx_query.input_query.index == 1 + assert tx_query.output_query is not None + assert tx_query.output_query.amount == 7 + assert tx_query.output_query.index == 2 + + def test_tx_query_input_and_output_query_serialize_round_trip(self) -> None: + tx_query: MoneroTxQuery = MoneroTxQuery() + tx_query.input_query = MoneroOutputQuery() + tx_query.input_query.amount = 5 + tx_query.input_query.index = 1 + tx_query.output_query = MoneroOutputQuery() + tx_query.output_query.amount = 7 + tx_query.output_query.index = 2 + + json_str: str = tx_query.serialize() + logger.debug(f"Serialized tx query with input/output query: {json_str}") + assert "inputQuery" in json_str + assert "outputQuery" in json_str + + restored: MoneroTxQuery = MoneroTxQuery.deserialize(json_str) + assert restored.input_query is not None + assert restored.input_query.amount == 5 + assert restored.input_query.index == 1 + assert restored.output_query is not None + assert restored.output_query.amount == 7 + assert restored.output_query.index == 2 + + def test_tx_query_deserialize_from_block(self) -> None: + tx_query: MoneroTxQuery = MoneroTxQuery() + tx_query.hash = "a" * 64 + tx_query.is_confirmed = True + tx_query.hashes = ["a" * 64, "b" * 64] + tx_query.min_height = 100 + tx_query.max_height = 200 + + # deserialize_from_block expects a block node wrapping the query under "txs" + block_json: str = '{"txs":[' + tx_query.serialize() + ']}' + restored: MoneroTxQuery = MoneroTxQuery.deserialize_from_block(block_json) + assert restored.hash == "a" * 64 + assert restored.is_confirmed is True + assert list(restored.hashes) == ["a" * 64, "b" * 64] + assert restored.min_height == 100 + assert restored.max_height == 200 + + # the query is linked back to its parent block + assert restored.block is not None + assert restored.block.txs[0] is restored + + def test_tx_query_deserialize_from_block_no_txs(self) -> None: + restored: MoneroTxQuery = MoneroTxQuery.deserialize_from_block('{"txs": []}') + assert restored.hash is None + assert restored.block is None + + def test_tx_query_copy(self) -> None: + query: MoneroTxQuery = MoneroTxQuery() + query.hash = "a" * 64 + query.height = 3000000 + query.is_confirmed = True + + copy: MoneroTxQuery = query.copy() + assert copy is not query + assert copy.serialize() == query.serialize() + + def test_tx_query_decontextualize(self) -> None: + query: MoneroTxQuery = MoneroTxQuery() + query.hash = "a" * 64 + query.is_incoming = True + query.is_outgoing = False + query.transfer_query = MoneroTransferQuery() + query.input_query = MoneroOutputQuery() + query.output_query = MoneroOutputQuery() + + # mutates and returns the same query, for convenience + decontextualized: MoneroTxQuery = MoneroTxQuery.decontextualize(query) + assert decontextualized is query + assert query.is_incoming is None + assert query.is_outgoing is None + assert query.transfer_query is None + assert query.input_query is None + assert query.output_query is None + + # criteria that don't require looking up other transfers/outputs are untouched + assert query.hash == "a" * 64 diff --git a/tests/wallet/model/test_txs.py b/tests/wallet/model/test_txs.py new file mode 100644 index 00000000..4699bebe --- /dev/null +++ b/tests/wallet/model/test_txs.py @@ -0,0 +1,397 @@ +from __future__ import annotations + +import logging +import subprocess +import sys + +import pytest +from monero import ( + MoneroIncomingTransfer, + MoneroKeyImage, + MoneroOutgoingTransfer, + MoneroOutputQuery, + MoneroOutputWallet, + MoneroTransfer, + MoneroTransferQuery, + MoneroTxSet, + MoneroTxWallet, +) + +from utils import AssertUtils, BaseTestClass, TestUtils + +logger: logging.Logger = logging.getLogger("TestMoneroWalletModelTxs") + + +@pytest.mark.unit +class TestMoneroWalletModelTxs(BaseTestClass): + """Wallet tx model unit tests.""" + + def test_tx_wallet_deserialize(self) -> None: + tx_wallet: MoneroTxWallet = MoneroTxWallet() + tx_wallet.hash = "a" * 64 + tx_wallet.is_miner_tx = False + tx_wallet.fee = 7500000 + tx_wallet.relay = True + tx_wallet.is_relayed = True + tx_wallet.is_confirmed = True + tx_wallet.in_tx_pool = False + tx_wallet.num_confirmations = 10 + tx_wallet.unlock_time = 0 + tx_wallet.is_incoming = True + tx_wallet.is_outgoing = False + tx_wallet.note = "thanks" + tx_wallet.is_locked = False + tx_wallet.input_sum = 2000000 + tx_wallet.output_sum = 1900000 + # tx_set, incoming_transfers, outgoing_transfer, change_address, + # change_amount, num_dummy_outputs and extra_hex all raise "not + # implemented" (see below), same as their monero_tx base counterparts + # (version, inputs, outputs, ...) tested in test_monero_daemon_model.py + AssertUtils.assert_serialization_integrity(tx_wallet) + + @pytest.mark.parametrize("json_fragment", [ + '{"txSet":{}}', + '{"incomingTransfers":[]}', + '{"outgoingTransfer":{}}', + '{"changeAddress":"' + TestUtils.ADDRESS + '"}', + '{"changeAmount":1}', + '{"numDummyOutputs":1}', + '{"extraHex":"deadbeef"}', + ]) + def test_tx_wallet_unimplemented_fields(self, json_fragment: str) -> None: + with pytest.raises(Exception, match="not implemented"): + MoneroTxWallet.deserialize(json_fragment) + + def test_tx_set_deserialize(self) -> None: + tx_set: MoneroTxSet = MoneroTxSet() + tx_set.unsigned_tx_hex = "deadbeef" + tx_set.multisig_tx_hex = "beefdead" + AssertUtils.assert_serialization_integrity(tx_set) + + def test_tx_set_signed_tx_hex_deserialize(self) -> None: + tx_set: MoneroTxSet = MoneroTxSet() + tx_set.signed_tx_hex = "deadbeef" + AssertUtils.assert_serialization_integrity(tx_set) + + def test_tx_set_txs_deserialize(self) -> None: + json_str: str = '{"txs": [{"hash": "' + "a" * 64 + '"}, {"hash": "' + "b" * 64 + '"}]}' + tx_set: MoneroTxSet = MoneroTxSet.deserialize(json_str) + assert len(tx_set.txs) == 2 + assert all(isinstance(tx, MoneroTxWallet) for tx in tx_set.txs) + assert tx_set.txs[0].hash == "a" * 64 + assert tx_set.txs[1].hash == "b" * 64 + + def test_tx_wallet_merge_incoming_transfers_with_unset_indices_are_kept_distinct(self) -> None: + """ + merge_incoming_transfer() dedups incoming transfers by (account_index, subaddress_index) + when reconciling two txs' transfer lists. Previously it dereferenced both indices + unconditionally (boost::optional UB when unset), reachable via TxWallet.merge() with + user-constructed MoneroIncomingTransfer objects that never had an index assigned. Since + identity can't be verified without both indices, unset-index transfers must be kept as + distinct entries rather than crashing or being silently coalesced. Run in an isolated + subprocess: locally this UB just gives a wrong (deduped) result, but the same + optional::get() assertion has been observed to abort the whole process in CI's build + (NDEBUG/ODR ambiguity between monero-cpp and monero-python's own compiled units), which a + plain in-process assertion can't survive. + """ + script: str = ( + "import monero, sys\n" + "tx_a = monero.MoneroTxWallet()\n" + "tx_a.hash = 'a' * 64\n" + "tx_a.is_confirmed = True\n" + "transfer_a = monero.MoneroIncomingTransfer()\n" # account_index/subaddress_index intentionally unset + "transfer_a.tx = tx_a\n" + "tx_a.incoming_transfers = [transfer_a]\n" + "tx_b = monero.MoneroTxWallet()\n" + "tx_b.hash = 'a' * 64\n" + "tx_b.is_confirmed = True\n" + "transfer_b = monero.MoneroIncomingTransfer()\n" # account_index/subaddress_index intentionally unset + "transfer_b.tx = tx_b\n" + "tx_b.incoming_transfers = [transfer_b]\n" + "tx_a.merge(tx_b)\n" + "n = len(tx_a.incoming_transfers) if tx_a.incoming_transfers else 0\n" + "sys.exit(0 if n == 2 else f'incoming_transfers not kept distinct: len={n}')\n" + ) + result: subprocess.CompletedProcess[str] = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, timeout=30) + logger.debug(f"subprocess exit code: {result.returncode}, stderr: {result.stderr.strip()}") + assert result.returncode == 0, ( + f"TxWallet.merge() did not keep unset-index incoming transfers distinct " + f"(exit code {result.returncode}): {result.stderr.strip()[-300:]}" + ) + + def test_tx_wallet_copy(self) -> None: + tx: MoneroTxWallet = MoneroTxWallet() + tx.hash = "a" * 64 + tx.is_confirmed = True + tx.note = "hello" + + copy: MoneroTxWallet = tx.copy() + assert copy is not tx + assert copy.serialize() == tx.serialize() + + def test_tx_wallet_copy_re_copies_inputs_as_output_wallet(self) -> None: + tx: MoneroTxWallet = MoneroTxWallet() + tx.hash = "a" * 64 + + key_image: MoneroKeyImage = MoneroKeyImage() + key_image.hex = "1" * 64 + tx_input: MoneroOutputWallet = MoneroOutputWallet() + tx_input.tx = tx + tx_input.key_image = key_image + tx_input.amount = 1234 + tx_input.account_index = 2 + tx_input.subaddress_index = 3 + tx_input.is_spent = True + tx_input.is_frozen = False + tx.inputs = [tx_input] + + copy: MoneroTxWallet = tx.copy() + assert isinstance(copy.inputs[0], MoneroOutputWallet) + assert copy.inputs[0] is not tx_input + assert copy.inputs[0].amount == 1234 + assert copy.inputs[0].account_index == 2 + assert copy.inputs[0].subaddress_index == 3 + assert copy.inputs[0].is_spent is True + assert copy.inputs[0].is_frozen is False + assert copy.inputs[0].key_image.hex == "1" * 64 # type: ignore + assert copy.inputs[0].tx is copy + + def test_tx_wallet_merge(self) -> None: + a: MoneroTxWallet = MoneroTxWallet() + a.hash = "a" * 64 + a.is_confirmed = True # required: base monero_tx::merge() dereferences is_confirmed directly + + b: MoneroTxWallet = a.copy() + b.note = "hello" # a.note is unset -> merge fills the gap + a.merge(b) + assert a.note == "hello" + + def test_tx_wallet_merge_is_locked_can_become_false(self) -> None: + a: MoneroTxWallet = MoneroTxWallet() + a.hash = "a" * 64 + a.is_confirmed = True + a.is_locked = False # self: already unlocked + b: MoneroTxWallet = a.copy() + b.is_locked = True # other: still locked + a.merge(b) + assert a.is_locked is False + + def test_tx_wallet_inputs_deserialize_as_output_wallet(self) -> None: + tx: MoneroTxWallet = MoneroTxWallet() + tx.hash = "a" * 64 + tx_input: MoneroOutputWallet = MoneroOutputWallet() + tx_input.amount = 500000 + tx_input.index = 7 + tx_input.account_index = 1 + tx_input.subaddress_index = 2 + tx_input.is_spent = True + tx_input.is_frozen = False + tx_input.key_image = MoneroKeyImage() + tx_input.key_image.hex = "k" * 64 + tx.inputs = [tx_input] + + json_str: str = tx.serialize() + assert "accountIndex" in json_str + assert "isSpent" in json_str + + # monero_tx::from_property_tree parses inputs as MoneroOutput; the wallet + # deserializer re-parses them as MoneroOutputWallet in place + restored: MoneroTxWallet = MoneroTxWallet.deserialize(json_str) + assert len(restored.inputs) == 1 + assert isinstance(restored.inputs[0], MoneroOutputWallet) + assert restored.inputs[0].account_index == 1 + assert restored.inputs[0].subaddress_index == 2 + assert restored.inputs[0].is_spent is True + assert restored.inputs[0].is_frozen is False + assert restored.inputs[0].key_image is not None + assert restored.inputs[0].key_image.hex == "k" * 64 + assert restored.inputs[0].tx is restored + + def test_tx_wallet_outputs_deserialize_as_output_wallet(self) -> None: + tx: MoneroTxWallet = MoneroTxWallet() + tx.hash = "a" * 64 + output: MoneroOutputWallet = MoneroOutputWallet() + output.amount = 500000 + output.index = 3 + output.account_index = 2 + output.subaddress_index = 1 + output.is_spent = True + output.is_frozen = False + tx.outputs = [output] + + json_str: str = tx.serialize() + assert "accountIndex" in json_str + assert "isSpent" in json_str + + restored: MoneroTxWallet = MoneroTxWallet.deserialize(json_str) + assert len(restored.outputs) == 1 + assert isinstance(restored.outputs[0], MoneroOutputWallet) + assert restored.outputs[0].account_index == 2 + assert restored.outputs[0].subaddress_index == 1 + assert restored.outputs[0].is_spent is True + assert restored.outputs[0].is_frozen is False + + def test_tx_wallet_get_outputs_wallet_after_deserialize(self) -> None: + tx: MoneroTxWallet = MoneroTxWallet() + tx.hash = "a" * 64 + output: MoneroOutputWallet = MoneroOutputWallet() + output.amount = 500000 + output.index = 3 + tx.outputs = [output] + + restored: MoneroTxWallet = MoneroTxWallet.deserialize(tx.serialize()) + # once deserialize works: raises "nullptr given to monero_output_query::meets_criteria()" + outputs_wallet: list[MoneroOutputWallet] = restored.get_outputs_wallet() + assert len(outputs_wallet) == 1 + assert outputs_wallet[0].amount == 500000 + + def test_tx_wallet_filter_inputs_wallet(self) -> None: + def make_input(account_index: int, amount: int) -> MoneroOutputWallet: + tx_input: MoneroOutputWallet = MoneroOutputWallet() + tx_input.account_index = account_index + tx_input.amount = amount + return tx_input + + tx: MoneroTxWallet = MoneroTxWallet() + tx.hash = "a" * 64 + tx.inputs = [make_input(0, 100), make_input(1, 200), make_input(0, 300)] + + query: MoneroOutputQuery = MoneroOutputQuery() + query.account_index = 0 + + # filter returns the matches and drops the rest from tx.inputs in place + matched: list[MoneroOutputWallet] = tx.filter_inputs_wallet(query) + assert [i.amount for i in matched] == [100, 300] + assert all(isinstance(i, MoneroOutputWallet) for i in matched) + assert [i.amount for i in tx.inputs] == [100, 300] + + # an unconstrained query keeps everything + assert len(tx.filter_inputs_wallet(MoneroOutputQuery())) == 2 + + def test_tx_wallet_get_inputs_wallet(self) -> None: + def make_input(account_index: int, amount: int) -> MoneroOutputWallet: + tx_input: MoneroOutputWallet = MoneroOutputWallet() + tx_input.account_index = account_index + tx_input.amount = amount + return tx_input + + tx: MoneroTxWallet = MoneroTxWallet() + tx.hash = "a" * 64 + tx.inputs = [make_input(0, 100), make_input(1, 200), make_input(0, 300)] + + query: MoneroOutputQuery = MoneroOutputQuery() + query.account_index = 0 + + # get_inputs_wallet() does not mutate tx.inputs + matched: list[MoneroOutputWallet] = tx.get_inputs_wallet(query) + assert [i.amount for i in matched] == [100, 300] + assert len(tx.inputs) == 3 + + # unconstrained default query (no args) returns all inputs + assert len(tx.get_inputs_wallet()) == 3 + + def test_tx_wallet_filter_outputs_wallet(self) -> None: + def make_output(account_index: int, amount: int) -> MoneroOutputWallet: + output: MoneroOutputWallet = MoneroOutputWallet() + output.account_index = account_index + output.amount = amount + return output + + tx: MoneroTxWallet = MoneroTxWallet() + tx.hash = "a" * 64 + tx.outputs = [make_output(0, 100), make_output(1, 200), make_output(0, 300)] + + query: MoneroOutputQuery = MoneroOutputQuery() + query.account_index = 0 + + # filter returns the matches and drops the rest from tx.outputs in place + matched: list[MoneroOutputWallet] = tx.filter_outputs_wallet(query) + assert [o.amount for o in matched] == [100, 300] + assert all(isinstance(o, MoneroOutputWallet) for o in matched) + assert [o.amount for o in tx.outputs] == [100, 300] + + # an unconstrained query keeps everything + assert len(tx.filter_outputs_wallet(MoneroOutputQuery())) == 2 + + def test_tx_wallet_filter_transfers(self) -> None: + tx: MoneroTxWallet = MoneroTxWallet() + tx.hash = "a" * 64 + + outgoing: MoneroOutgoingTransfer = MoneroOutgoingTransfer() + outgoing.amount = 1000 + + incoming_1: MoneroIncomingTransfer = MoneroIncomingTransfer() + incoming_1.account_index = 0 + incoming_1.amount = 100 + + incoming_2: MoneroIncomingTransfer = MoneroIncomingTransfer() + incoming_2.account_index = 1 + incoming_2.amount = 200 + + tx.outgoing_transfer = outgoing + tx.incoming_transfers = [incoming_1, incoming_2] + + query: MoneroTransferQuery = MoneroTransferQuery() + query.incoming = True + query.account_index = 0 + + # filter returns the matches and drops the rest (outgoing_transfer cleared, incoming_2 removed) + matched: list[MoneroTransfer] = tx.filter_transfers(query) + assert [t.amount for t in matched] == [100] + assert tx.outgoing_transfer is None + assert [t.amount for t in tx.incoming_transfers] == [100] + + def test_tx_wallet_get_transfers(self) -> None: + tx: MoneroTxWallet = MoneroTxWallet() + tx.hash = "a" * 64 + tx.outgoing_transfer = MoneroOutgoingTransfer() + tx.outgoing_transfer.amount = 1000 + tx.incoming_transfers = [MoneroIncomingTransfer(), MoneroIncomingTransfer()] + tx.incoming_transfers[0].amount = 100 + tx.incoming_transfers[1].amount = 200 + + # no-arg overload delegates to an empty query -> outgoing then incoming, in order + all_transfers: list[MoneroTransfer] = tx.get_transfers() + assert [t.amount for t in all_transfers] == [1000, 100, 200] + assert isinstance(all_transfers[0], MoneroOutgoingTransfer) + assert all(isinstance(t, MoneroIncomingTransfer) for t in all_transfers[1:]) + + # get_transfers() does not mutate the tx + assert tx.outgoing_transfer is not None + assert len(tx.incoming_transfers) == 2 + + def test_tx_wallet_get_transfers_with_query(self) -> None: + tx: MoneroTxWallet = MoneroTxWallet() + tx.hash = "a" * 64 + tx.outgoing_transfer = MoneroOutgoingTransfer() + tx.outgoing_transfer.amount = 1000 + tx.incoming_transfers = [MoneroIncomingTransfer(), MoneroIncomingTransfer()] + tx.incoming_transfers[0].amount = 100 + tx.incoming_transfers[1].amount = 200 + + incoming_query: MoneroTransferQuery = MoneroTransferQuery() + incoming_query.incoming = True + assert [t.amount for t in tx.get_transfers(incoming_query)] == [100, 200] + + outgoing_query: MoneroTransferQuery = MoneroTransferQuery() + outgoing_query.outgoing = True + assert [t.amount for t in tx.get_transfers(outgoing_query)] == [1000] + + no_match_query: MoneroTransferQuery = MoneroTransferQuery() + no_match_query.amount = 999999 + assert tx.get_transfers(no_match_query) == [] + + def test_tx_wallet_copy_preserves_output_wallet_type(self) -> None: + tx: MoneroTxWallet = MoneroTxWallet() + tx.hash = "a" * 64 + output: MoneroOutputWallet = MoneroOutputWallet() + output.amount = 500000 + output.account_index = 2 + output.is_spent = True + tx.outputs = [output] + + copy: MoneroTxWallet = tx.copy() + assert len(copy.outputs) == 1 + assert isinstance(copy.outputs[0], MoneroOutputWallet) + assert copy.outputs[0].account_index == 2 + assert copy.outputs[0].is_spent is True diff --git a/tests/wallet/test_accounts.py b/tests/wallet/test_accounts.py new file mode 100644 index 00000000..7a991ca3 --- /dev/null +++ b/tests/wallet/test_accounts.py @@ -0,0 +1,606 @@ +from __future__ import annotations + +import logging +from typing import Optional + +import pytest +from monero import ( + MoneroAccount, + MoneroAccountTag, + MoneroAddressBookEntry, + MoneroIntegratedAddress, + MoneroSubaddress, + MoneroWallet, + MoneroWalletFull, + MoneroWalletRpc, +) +from typing_extensions import override + +from utils import ( + AssertUtils, + GenUtils, + StringUtils, + TestUtils, + TestUtils as Utils, + WalletTestUtils, + WalletUtils, +) +from .base_test_monero_wallet import BaseTestMoneroWallet +from .wallet_support import FullWalletSupport, RpcWalletSupport, KeysWalletSupport + +logger: logging.Logger = logging.getLogger("TestMoneroWalletAccounts") + + +class BaseTestMoneroWalletAccounts(BaseTestMoneroWallet): + """Common wallet accounts tests.""" + + # Can get the locked and unlocked balances of the wallet, accounts and subaddresses + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_all_balances(self, wallet: MoneroWallet) -> None: + # fetch accounts with all info as reference + accounts: list[MoneroAccount] = wallet.get_accounts(True) + # test that balances add up between accounts and wallet + accounts_balance: int = 0 + accounts_unlocked_balance: int = 0 + for account in accounts: + assert account.index is not None + assert account.balance is not None + assert account.unlocked_balance is not None + accounts_balance += account.balance + accounts_unlocked_balance += account.unlocked_balance + + # test that balances add up between subaddresses and accounts + subaddresses_balance: int = 0 + subaddresses_unlocked_balance: int = 0 + for subaddress in account.subaddresses: + assert subaddress.account_index is not None + assert subaddress.index is not None + assert subaddress.balance is not None + assert subaddress.unlocked_balance is not None + subaddresses_balance += subaddress.balance + subaddresses_unlocked_balance += subaddress.unlocked_balance + + # test that balances are consistent with get_accounts() call + assert wallet.get_balance(subaddress.account_index, subaddress.index) == subaddress.balance + unlocked_balance: int = wallet.get_unlocked_balance(subaddress.account_index, subaddress.index) + assert unlocked_balance == subaddress.unlocked_balance + + assert wallet.get_balance(account.index) == subaddresses_balance + assert wallet.get_unlocked_balance(account.index) == subaddresses_unlocked_balance + + GenUtils.test_unsigned_big_integer(accounts_balance) + GenUtils.test_unsigned_big_integer(accounts_unlocked_balance) + assert wallet.get_balance() == accounts_balance + assert wallet.get_unlocked_balance() == accounts_unlocked_balance + + # Can get accounts without subaddresses + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_accounts_without_subaddresses(self, wallet: MoneroWallet) -> None: + accounts: list[MoneroAccount] = wallet.get_accounts() + assert len(accounts) > 0 + for account in accounts: + WalletUtils.test_account(account, TestUtils.NETWORK_TYPE) + assert len(account.subaddresses) == 0 + + # Can get accounts with subaddress + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_accounts_with_subaddresses(self, wallet: MoneroWallet) -> None: + accounts: list[MoneroAccount] = wallet.get_accounts(True) + assert len(accounts) > 0 + for account in accounts: + WalletUtils.test_account(account, TestUtils.NETWORK_TYPE) + assert len(account.subaddresses) > 0 + + # Can get an account at a specified index + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_account(self, wallet: MoneroWallet) -> None: + accounts: list[MoneroAccount] = wallet.get_accounts() + assert len(accounts) > 0 + for account in accounts: + WalletUtils.test_account(account, TestUtils.NETWORK_TYPE) + + # test without subaddresses + assert account.index is not None + retrieved: MoneroAccount = wallet.get_account(account.index) + assert len(retrieved.subaddresses) == 0 + + # test with subaddresses + retrieved = wallet.get_account(account.index, True) + assert len(retrieved.subaddresses) > 0 + + # Can create a new account without a label + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_create_account_without_label(self, wallet: MoneroWallet) -> None: + accounts_before: list[MoneroAccount] = wallet.get_accounts() + created_account: MoneroAccount = wallet.create_account() + WalletUtils.test_account(created_account, TestUtils.NETWORK_TYPE) + assert len(accounts_before) == len(wallet.get_accounts()) - 1 + + # Can create a new account with a label + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_create_account_with_label(self, wallet: MoneroWallet) -> None: + # create account with label + accounts_before: list[MoneroAccount] = wallet.get_accounts() + label: str = StringUtils.get_random_string() + created_account: MoneroAccount = wallet.create_account(label) + WalletUtils.test_account(created_account, TestUtils.NETWORK_TYPE) + assert created_account.index is not None + assert len(accounts_before) == len(wallet.get_accounts()) - 1 + assert label == wallet.get_subaddress(created_account.index, 0).label + + # fetch and test account + created_account = wallet.get_account(created_account.index) + WalletUtils.test_account(created_account, TestUtils.NETWORK_TYPE) + + # create account with same label + created_account = wallet.create_account(label) + WalletUtils.test_account(created_account, TestUtils.NETWORK_TYPE) + assert len(accounts_before) == len(wallet.get_accounts()) - 2 + assert created_account.index is not None + assert label == wallet.get_subaddress(created_account.index, 0).label + + # fetch and test account + created_account = wallet.get_account(created_account.index) + WalletUtils.test_account(created_account, TestUtils.NETWORK_TYPE) + + # Can set account labels + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_set_account_label(self, wallet: MoneroWallet) -> None: + # create account + if len(wallet.get_accounts()) < 2: + wallet.create_account() + + # set account label + label: str = StringUtils.get_random_string() + wallet.set_account_label(1, label) + assert label == wallet.get_subaddress(1, 0).label + + # Can get subaddresses at a aspecified account index + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_subaddresses(self, wallet: MoneroWallet) -> None: + accounts: list[MoneroAccount] = wallet.get_accounts() + assert len(accounts) > 0 + for account in accounts: + assert account.index is not None + subaddresses: list[MoneroSubaddress] = wallet.get_subaddresses(account.index) + assert len(subaddresses) > 0 + for subaddress in subaddresses: + WalletUtils.test_subaddress(subaddress) + assert account.index == subaddress.account_index + + # Can get subaddresses at a specified account index and subaddress indices + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_subaddresses_by_indices(self, wallet: MoneroWallet) -> None: + accounts: list[MoneroAccount] = wallet.get_accounts() + assert len(accounts) > 0 + for account in accounts: + + # get subaddresses + assert account.index is not None + subaddresses: list[MoneroSubaddress] = wallet.get_subaddresses(account.index) + assert len(subaddresses) > 0 + + # remove a subaddress for query if possible + if len(subaddresses) > 1: + subaddresses = list(filter(lambda sub: sub != subaddresses[0], subaddresses)) + + # get subaddress indices + subaddress_indices: list[int] = [] + for subaddress in subaddresses: + assert subaddress.index is not None + subaddress_indices.append(subaddress.index) + assert len(subaddress_indices) > 0 + + # fetch subaddresses by indices + fetched_subaddresses: list[MoneroSubaddress] = wallet.get_subaddresses(account.index, subaddress_indices) + + # original subaddresses (minus one removed if applicable) is equal to fetched subaddresses + AssertUtils.assert_list_equals(subaddresses, fetched_subaddresses) + + # Can get subaddress at a specified account index and subaddress index + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_subaddress_by_index(self, wallet: MoneroWallet) -> None: + accounts: list[MoneroAccount] = wallet.get_accounts() + assert len(accounts) > 0 + for account in accounts: + assert account.index is not None + subaddresses: list[MoneroSubaddress] = wallet.get_subaddresses(account.index) + assert len(subaddresses) > 0 + for subaddress in subaddresses: + assert subaddress.index is not None + WalletUtils.test_subaddress(subaddress) + AssertUtils.assert_equals(subaddress, wallet.get_subaddress(account.index, subaddress.index)) + # test plural call with single subaddr number + AssertUtils.assert_equals( + subaddress, wallet.get_subaddresses(account.index, [subaddress.index])[0] + ) + + # Can create a subaddress with and without a label + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_create_subaddress(self, wallet: MoneroWallet) -> None: + # create subaddresses across accounts + accounts: list[MoneroAccount] = wallet.get_accounts() + if len(accounts) < 2: + wallet.create_account() + accounts = wallet.get_accounts() + assert len(accounts) > 1 + account_idx: int = 0 + while account_idx < 2: + + # create subaddress with no label + subaddresses: list[MoneroSubaddress] = wallet.get_subaddresses(account_idx) + subaddress: MoneroSubaddress = wallet.create_subaddress(account_idx) + assert subaddress.label is None + WalletUtils.test_subaddress(subaddress) + subaddresses_new: list[MoneroSubaddress] = wallet.get_subaddresses(account_idx) + assert len(subaddresses_new) - 1 == len(subaddresses) + AssertUtils.assert_equals(subaddress, subaddresses_new[len(subaddresses_new) - 1]) + + # create subaddress with label + subaddresses = wallet.get_subaddresses(account_idx) + uuid: str = StringUtils.get_random_string() + subaddress = wallet.create_subaddress(account_idx, uuid) + assert (uuid == subaddress.label) + WalletUtils.test_subaddress(subaddress) + subaddresses_new = wallet.get_subaddresses(account_idx) + assert len(subaddresses) == len(subaddresses_new) - 1 + AssertUtils.assert_equals(subaddress, subaddresses_new[len(subaddresses_new) - 1]) + + account_idx += 1 + + # Can set subaddress labels + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_set_subaddress_label(self, wallet: MoneroWallet) -> None: + # create subaddresses + while len(wallet.get_subaddresses(0)) < 3: + wallet.create_subaddress(0) + + # set subaddress labels + subaddress_idx: int = 0 + while subaddress_idx < len(wallet.get_subaddresses(0)): + label: str = StringUtils.get_random_string() + wallet.set_subaddress_label(0, subaddress_idx, label) + assert label == wallet.get_subaddress(0, subaddress_idx).label + subaddress_idx += 1 + + # Can tag accounts and query accounts by tag + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_account_tags(self, wallet: MoneroWallet) -> None: + # get accounts + accounts: list[MoneroAccount] = wallet.get_accounts() + assert len(accounts) > 3, "Not enough accounts to test; run create account test" + + # tag some of the accounts + tag: MoneroAccountTag = MoneroAccountTag(f"my_tag_{StringUtils.get_random_string()}", "my tag label", [0, 1]) + assert tag.tag is not None + assert tag.label is not None + wallet.tag_accounts(tag.tag, tag.account_indices) + + # query accounts by tag + tagged_accounts: list[MoneroAccount] = wallet.get_accounts(False, tag.tag) + assert len(tagged_accounts) == 2 + assert tagged_accounts[0].index == 0 + assert tagged_accounts[0].tag == tag.tag + assert tagged_accounts[1].index == 1 + assert tagged_accounts[1].tag == tag.tag + + # set tag label + wallet.set_account_tag_label(tag.tag, tag.label) + + # fetch tags and ensure new tag is contained + tags: list[MoneroAccountTag] = wallet.get_account_tags() + found: bool = False + for a_tag in tags: + if a_tag.tag == tag.tag: + found = True + break + assert found, f"Could not find tag: {tag.serialize()}" + logger.debug(f"Found account tag: {tag.serialize()}") + + # re-tag an account + tag2: MoneroAccountTag = MoneroAccountTag(f"my_tag_{StringUtils.get_random_string()}", "my tag label 2", [1]) + assert tag2.tag is not None + assert tag2.label is not None + wallet.tag_accounts(tag2.tag, tag2.account_indices) + tagged_accounts2: list[MoneroAccount] = wallet.get_accounts(False, tag2.tag) + assert len(tagged_accounts2) == 1 + assert tagged_accounts2[0].index == 1 + assert tagged_accounts2[0].tag == tag2.tag + + # re-query original tag which only applies to one account now + tagged_accounts = wallet.get_accounts(False, tag.tag) + assert len(tagged_accounts) == 1 + assert tagged_accounts[0].index == 0 + assert tagged_accounts[0].tag == tag.tag + + # untag and query accounts + wallet.untag_accounts([0, 1]) + assert len(wallet.get_account_tags()) == 0 + with pytest.raises(Exception): + wallet.get_accounts(False, tag.tag) + + # a never-registered tag may raise or return nothing; either is acceptable + try: + assert len(wallet.get_accounts(False, "non_existing_tag")) == 0 + except Exception as e: + logger.debug(f"get_accounts with non-existing tag raised: {e}") + + # Has an address book + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_address_book(self, wallet: MoneroWallet) -> None: + # initial state + entries: list[MoneroAddressBookEntry] = wallet.get_address_book_entries() + num_entries_start: int = len(entries) + for entry in entries: + WalletUtils.test_address_book_entry(entry) + + # test adding standard addresses + NUM_ENTRIES: int = 5 + address: str = WalletTestUtils.get_external_wallet_address() + indices: list[int] = [] + for i in range(NUM_ENTRIES): + logger.debug(f"Adding address book entry ({i + 1})") + indices.append(wallet.add_address_book_entry(address, "hi there!")) + + entries = wallet.get_address_book_entries() + assert num_entries_start + NUM_ENTRIES == len(entries) + for idx in indices: + found: bool = False + for entry in entries: + if idx == entry.index: + WalletUtils.test_address_book_entry(entry) + assert entry.address == address + assert entry.description == "hi there!" + found = True + break + + assert found, f"Index {idx} not found in address book indices" + + # edit each address book entry + for idx in indices: + wallet.edit_address_book_entry(idx, False, '', True, "hello there!!") + + entries = wallet.get_address_book_entries(indices) + for entry in entries: + assert entry.description == "hello there!!" + + # delete entries at starting index + delete_idx: int = indices[0] + for i in range(len(indices)): + logger.debug(f"Deleting address book entry {i + 1}, delete_idx: {delete_idx}") + wallet.delete_address_book_entry(delete_idx) + entries = wallet.get_address_book_entries() + assert len(entries) == num_entries_start + + # test adding integrated addresses + indices = [] + # payment id less one character + payment_id: str = "03284e41c342f03" + integrated_addresses: dict[int, MoneroIntegratedAddress] = {} + integrated_descriptions: dict[int, str] = {} + for i in range(NUM_ENTRIES): + # create unique integrated address + integrated_address: MoneroIntegratedAddress = wallet.get_integrated_address('', f"{payment_id}{i}") + uuid: str = StringUtils.get_random_string() + idx: int = wallet.add_address_book_entry(integrated_address.integrated_address, uuid) + indices.append(idx) + integrated_addresses[idx] = integrated_address + integrated_descriptions[idx] = uuid + + entries = wallet.get_address_book_entries() + assert len(entries) == num_entries_start + NUM_ENTRIES + for idx in indices: + found: bool = False + for entry in entries: + if idx == entry.index: + WalletUtils.test_address_book_entry(entry) + assert integrated_descriptions[idx] == entry.description + assert integrated_addresses[idx].integrated_address == entry.address + assert entry.payment_id is None + found = True + break + assert found, f"Index {idx} not found in address bool indices" + + # delete entries at starting index + delete_idx = indices[0] + for i in range(len(indices)): + logger.debug(f"Deleting address book entry {i + 1}") + wallet.delete_address_book_entry(delete_idx) + + entries = wallet.get_address_book_entries() + assert num_entries_start == len(entries) + + +@pytest.mark.integration +class TestMoneroWalletFullAccounts(FullWalletSupport, BaseTestMoneroWalletAccounts): + """Full wallet accounts integration tests.""" + + # TODO implement + @pytest.mark.not_implemented + @override + def test_account_tags(self, wallet: MoneroWallet) -> None: + return super().test_account_tags(wallet) + + # Can create a subaddress with and without a label + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + @override + def test_create_subaddress(self, wallet: MoneroWalletFull) -> None: # type: ignore + # create subaddresses across accounts + accounts: list[MoneroAccount] = wallet.get_accounts() + if len(accounts) < 2: + wallet.create_account() + + accounts = wallet.get_accounts() + assert len(accounts) > 1 + account_idx: int = 0 + while account_idx < 2: + # create subaddress with no label + subaddresses: list[MoneroSubaddress] = wallet.get_subaddresses(account_idx) + subaddress: MoneroSubaddress = wallet.create_subaddress(account_idx) + assert subaddress.label is None + WalletUtils.test_subaddress(subaddress) + subaddresses_new: list[MoneroSubaddress] = wallet.get_subaddresses(account_idx) + assert len(subaddresses_new) - 1 == len(subaddresses) + AssertUtils.assert_equals(subaddress, subaddresses_new[len(subaddresses_new) - 1]) + + # create subaddress with label + subaddresses = wallet.get_subaddresses(account_idx) + uuid: str = StringUtils.get_random_string() + subaddress = wallet.create_subaddress(account_idx, uuid) + assert uuid == subaddress.label + WalletUtils.test_subaddress(subaddress) + subaddresses_new = wallet.get_subaddresses(account_idx) + assert len(subaddresses) == len(subaddresses_new) - 1 + AssertUtils.assert_equals(subaddress, subaddresses_new[len(subaddresses_new) - 1]) + account_idx += 1 + + +@pytest.mark.integration +class TestMoneroWalletRpcAccounts(RpcWalletSupport, BaseTestMoneroWalletAccounts): + """Rpc wallet accounts integration tests.""" + + # Can get a subaddress via monero_wallet_rpc's + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_subaddress_rpc(self, wallet: MoneroWalletRpc) -> None: + account_idx: int = 0 + subaddress_idx: int = 0 + + subaddress: MoneroSubaddress = wallet.get_subaddress(account_idx, subaddress_idx) + WalletUtils.test_subaddress(subaddress) + assert subaddress.account_index == account_idx + assert subaddress.index == subaddress_idx + + plural: list[MoneroSubaddress] = wallet.get_subaddresses(account_idx, [subaddress_idx]) + assert len(plural) == 1 + AssertUtils.assert_equals(subaddress, plural[0]) + + assert subaddress.address == wallet.get_address(account_idx, subaddress_idx) + + +@pytest.mark.unit +class TestMoneroWalletKeysAccounts(KeysWalletSupport, BaseTestMoneroWalletAccounts): + """Keys-only wallet accounts unit tests.""" + + def _get_subaddress(self, wallet: MoneroWallet, account_idx: int, subaddress_idx: int) -> Optional[MoneroSubaddress]: + subaddress_indices: list[int] = [subaddress_idx] + subaddresses: list[MoneroSubaddress] = wallet.get_subaddresses(account_idx, subaddress_indices) + + if len(subaddresses) == 0: + return None + + return subaddresses[0] + + @pytest.mark.not_supported + @override + def test_get_all_balances(self, wallet: MoneroWallet) -> None: + return super().test_get_all_balances(wallet) + + @pytest.mark.not_supported + @override + def test_create_account_without_label(self, wallet: MoneroWallet) -> None: + return super().test_create_account_without_label(wallet) + + @pytest.mark.not_supported + @override + def test_create_account_with_label(self, wallet: MoneroWallet) -> None: + return super().test_create_account_with_label(wallet) + + @pytest.mark.not_supported + @override + def test_set_account_label(self, wallet: MoneroWallet) -> None: + return super().test_set_account_label(wallet) + + @pytest.mark.not_supported + @override + def test_get_subaddresses_by_indices(self, wallet: MoneroWallet) -> None: + return super().test_get_subaddresses_by_indices(wallet) + + @pytest.mark.not_supported + @override + def test_create_subaddress(self, wallet: MoneroWallet) -> None: + return super().test_create_subaddress(wallet) + + @override + def test_set_subaddress_label(self, wallet: MoneroWallet) -> None: + # a keys-only wallet cannot enumerate its subaddresses, which this test needs + with pytest.raises(RuntimeError, match="does not have enumerable set of subaddresses"): + super().test_set_subaddress_label(wallet) + + @pytest.mark.not_supported + @override + def test_address_book(self, wallet: MoneroWallet) -> None: + return super().test_address_book(wallet) + + @pytest.mark.not_supported + @override + def test_account_tags(self, wallet: MoneroWallet) -> None: + return super().test_account_tags(wallet) + + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + @override + def test_get_account(self, wallet: MoneroWallet) -> None: + accounts: list[MoneroAccount] = self._get_test_accounts(wallet) + assert len(accounts) > 0 + for account in accounts: + WalletUtils.test_account(account, Utils.NETWORK_TYPE, False) + + # test without subaddresses + assert account.index is not None + retrieved: MoneroAccount = wallet.get_account(account.index) + assert len(retrieved.subaddresses) == 0 + + # test with subaddresses + retrieved = wallet.get_account(account.index) + retrieved.subaddresses = wallet.get_subaddresses(account.index, self._subaddress_indices) + + def test_get_account_with_subaddresses_not_supported(self, wallet: MoneroWallet) -> None: + with pytest.raises(RuntimeError) as exc_info: + wallet.get_account(0, True) + assert str(exc_info.value) == "monero_wallet_keys::get_account(account_idx, include_subaddresses) include_subaddresses must be false" + + @override + def test_get_accounts_without_subaddresses(self, wallet: MoneroWallet) -> None: + accounts: list[MoneroAccount] = self._get_test_accounts(wallet) + assert len(accounts) > 0 + for account in accounts: + WalletUtils.test_account(account, Utils.NETWORK_TYPE, False) + assert len(account.subaddresses) == 0 + + @override + def test_get_accounts_with_subaddresses(self, wallet: MoneroWallet) -> None: + accounts: list[MoneroAccount] = self._get_test_accounts(wallet, True) + assert len(accounts) > 0 + for account in accounts: + WalletUtils.test_account(account, Utils.NETWORK_TYPE, False) + assert len(account.subaddresses) > 0 + + @override + def test_get_subaddresses(self, wallet: MoneroWallet) -> None: + wallet = wallet + accounts: list[MoneroAccount] = self._get_test_accounts(wallet) + assert len(accounts) > 0 + for account in accounts: + assert account.index is not None + subaddresses: list[MoneroSubaddress] = wallet.get_subaddresses(account.index, self._subaddress_indices) + assert len(subaddresses) > 0 + for subaddress in subaddresses: + WalletUtils.test_subaddress(subaddress, False) + assert account.index == subaddress.account_index + + @override + def test_get_subaddress_by_index(self, wallet: MoneroWallet) -> None: + accounts: list[MoneroAccount] = self._get_test_accounts(wallet) + assert len(accounts) > 0 + for account in accounts: + assert account.index is not None + subaddresses: list[MoneroSubaddress] = wallet.get_subaddresses(account.index, self._subaddress_indices) + assert len(subaddresses) > 0 + + for subaddress in subaddresses: + assert subaddress.index is not None + WalletUtils.test_subaddress(subaddress, False) + AssertUtils.assert_equals(subaddress, self._get_subaddress(wallet, account.index, subaddress.index)) + # test plural call with single subaddr number + AssertUtils.assert_equals( + subaddress, wallet.get_subaddresses(account.index, [subaddress.index])[0] + ) diff --git a/tests/wallet/test_connection.py b/tests/wallet/test_connection.py new file mode 100644 index 00000000..6d0c1c39 --- /dev/null +++ b/tests/wallet/test_connection.py @@ -0,0 +1,148 @@ +from __future__ import annotations + +import logging + +import pytest +from monero import MoneroRpcConnection, MoneroWallet, MoneroWalletConfig, MoneroWalletRpc +from typing_extensions import override + +from utils import AssertUtils, TestUtils, TestUtils as Utils, WalletErrorUtils +from .base_test_monero_wallet import BaseTestMoneroWallet +from .wallet_support import FullWalletSupport, RpcWalletSupport, KeysWalletSupport + +logger: logging.Logger = logging.getLogger("TestMoneroWalletConnection") + + +class BaseTestMoneroWalletConnection(BaseTestMoneroWallet): + """Common wallet connection tests.""" + + # Can get the daemon's max peer height + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_daemon_max_peer_height(self, wallet: MoneroWallet) -> None: + height: int = wallet.get_daemon_max_peer_height() + assert height > 0 + + # Can get the daemon's height + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_daemon_height(self, wallet: MoneroWallet) -> None: + assert wallet.is_connected_to_daemon(), "Wallet is not connected to daemon" + daemon_height: int = wallet.get_daemon_height() + assert daemon_height > 0 + + # Can set the daemon connection + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_set_daemon_connection(self) -> None: + # create random wallet with default daemon connection + config: MoneroWalletConfig = MoneroWalletConfig() + wallet: MoneroWallet = self._create_wallet(config) + daemon_rpc_uri: str = self.get_daemon_rpc_uri() + connection: MoneroRpcConnection = MoneroRpcConnection( + daemon_rpc_uri, TestUtils.DAEMON_RPC_USERNAME, TestUtils.DAEMON_RPC_PASSWORD + ) + AssertUtils.assert_equals(connection, wallet.get_daemon_connection()) + assert wallet.is_connected_to_daemon() # uses default localhost connection + + # set empty server uri + wallet.set_daemon_connection("") + assert wallet.get_daemon_connection() is None + assert wallet.is_connected_to_daemon() is False + + # set offline server uri + wallet.set_daemon_connection(TestUtils.OFFLINE_SERVER_URI) + connection = MoneroRpcConnection(TestUtils.OFFLINE_SERVER_URI, "", "") + AssertUtils.assert_equals(connection, wallet.get_daemon_connection()) + assert wallet.is_connected_to_daemon() is False + + # set daemon with wrong credentials + wallet.set_daemon_connection(daemon_rpc_uri, "wronguser", "wrongpass") + connection = MoneroRpcConnection(daemon_rpc_uri, "wronguser", "wrongpass") + AssertUtils.assert_equals(connection, wallet.get_daemon_connection()) + if "" == TestUtils.DAEMON_RPC_USERNAME: + # TODO: monerod without authentication works with bad credentials? + assert wallet.is_connected_to_daemon() + else: + assert wallet.is_connected_to_daemon() is False + + # set daemon with authentication + wallet.set_daemon_connection( + daemon_rpc_uri, TestUtils.DAEMON_RPC_USERNAME, TestUtils.DAEMON_RPC_PASSWORD + ) + connection = MoneroRpcConnection( + daemon_rpc_uri, TestUtils.DAEMON_RPC_USERNAME, TestUtils.DAEMON_RPC_PASSWORD + ) + AssertUtils.assert_equals(connection, wallet.get_daemon_connection()) + assert wallet.is_connected_to_daemon() + + # nullify daemon connection + wallet.set_daemon_connection(None) + assert wallet.get_daemon_connection() is None + wallet.set_daemon_connection(daemon_rpc_uri) + connection = MoneroRpcConnection(daemon_rpc_uri) + AssertUtils.assert_equals(connection, wallet.get_daemon_connection()) + wallet.set_daemon_connection(None) + assert wallet.get_daemon_connection() is None + + # set daemon uri to non-daemon + if not TestUtils.IN_CONTAINER: # TODO sometimes this fails in container... + wallet.set_daemon_connection("www.getmonero.org") + connection = MoneroRpcConnection("www.getmonero.org") + AssertUtils.assert_equals(connection, wallet.get_daemon_connection()) + assert wallet.is_connected_to_daemon() is False + + # set daemon to invalid uri + wallet.set_daemon_connection("abc123") + assert wallet.is_connected_to_daemon() is False + + # attempt to sync + try: + with pytest.raises(Exception, match="Wallet is not connected to daemon"): + wallet.sync() + finally: + self._close_wallet(wallet) + + +@pytest.mark.integration +class TestMoneroWalletFullConnection(FullWalletSupport, BaseTestMoneroWalletConnection): + """Full wallet connection integration tests.""" + + +@pytest.mark.integration +class TestMoneroWalletRpcConnection(RpcWalletSupport, BaseTestMoneroWalletConnection): + """Rpc wallet connection integration tests.""" + + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_offline_wallet(self) -> None: + offline_wallet: MoneroWalletRpc = MoneroWalletRpc(Utils.OFFLINE_SERVER_URI, Utils.WALLET_RPC_USERNAME, Utils.WALLET_PASSWORD) + with pytest.raises(Exception) as exc_info: + offline_wallet.is_view_only() + WalletErrorUtils.test_wallet_is_not_connected_error(exc_info.value) + + @pytest.mark.not_supported + @override + def test_get_daemon_max_peer_height(self, wallet: MoneroWallet) -> None: + return super().test_get_daemon_max_peer_height(wallet) + + @pytest.mark.not_supported + @override + def test_get_daemon_height(self, wallet: MoneroWallet) -> None: + return super().test_get_daemon_height(wallet) + + +@pytest.mark.unit +class TestMoneroWalletKeysConnection(KeysWalletSupport, BaseTestMoneroWalletConnection): + """Keys-only wallet connection unit tests.""" + + @pytest.mark.not_supported + @override + def test_get_daemon_height(self, wallet: MoneroWallet) -> None: + return super().test_get_daemon_height(wallet) + + @pytest.mark.not_supported + @override + def test_get_daemon_max_peer_height(self, wallet: MoneroWallet) -> None: + return super().test_get_daemon_max_peer_height(wallet) + + @pytest.mark.not_supported + @override + def test_set_daemon_connection(self) -> None: + return super().test_set_daemon_connection() diff --git a/tests/wallet/test_creation.py b/tests/wallet/test_creation.py new file mode 100644 index 00000000..2949aa77 --- /dev/null +++ b/tests/wallet/test_creation.py @@ -0,0 +1,1074 @@ +from __future__ import annotations + +import logging + +import pytest +from monero import ( + MoneroDaemonRpc, + MoneroDestination, + MoneroError, + MoneroNetworkType, + MoneroRpcConnection, + MoneroTxConfig, + MoneroTxWallet, + MoneroUtils, + MoneroVersion, + MoneroWallet, + MoneroWalletConfig, + MoneroWalletFull, + MoneroWalletKeys, + MoneroWalletRpc, +) +from typing_extensions import override + +from utils import ( + AssertUtils, + GenUtils, + StringUtils, + SyncProgressTester, + TestUtils, + TestUtils as Utils, + TxWalletUtils, + ViewOnlyAndOfflineWalletTester, + WalletErrorUtils, + WalletUtils, +) +from .base_test_monero_wallet import BaseTestMoneroWallet +from .wallet_support import FullWalletSupport, RpcWalletSupport, KeysWalletSupport + +logger: logging.Logger = logging.getLogger("TestMoneroWalletCreation") + + +class BaseTestMoneroWalletCreation(BaseTestMoneroWallet): + """Common wallet creation tests.""" + + # Can create a random wallet + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_create_wallet_random(self) -> None: + """ + Can create a random wallet. + """ + config: MoneroWalletConfig = MoneroWalletConfig() + wallet: MoneroWallet = self._create_wallet(config) + path: str = wallet.get_path() + + try: + MoneroUtils.validate_address(wallet.get_primary_address(), TestUtils.NETWORK_TYPE) + MoneroUtils.validate_private_view_key(wallet.get_private_view_key()) + MoneroUtils.validate_private_spend_key(wallet.get_private_spend_key()) + MoneroUtils.validate_mnemonic(wallet.get_seed()) + if not isinstance(wallet, MoneroWalletRpc): + # TODO monero-wallet-rpc: get seed language + assert MoneroWallet.DEFAULT_LANGUAGE == wallet.get_seed_language() + finally: + self._close_wallet(wallet) + + # attempt to create wallet at same path + config = MoneroWalletConfig() + config.path = path + with pytest.raises(Exception) as exc_info: + self._create_wallet(config) + assert str(exc_info.value) == "Wallet already exists: " + path + + # attempt to create wallet with unknown language + config = MoneroWalletConfig() + config.language = "english" + with pytest.raises(Exception) as exc_info: + self._create_wallet(config) + assert str(exc_info.value) == "Unknown language: english" + + # Can create a wallet from a seed + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_create_wallet_from_seed(self, wallet: MoneroWallet, test_config: BaseTestMoneroWallet.Config) -> None: + # save for comparison + primary_address: str = wallet.get_primary_address() + private_view_key: str = wallet.get_private_view_key() + private_spend_key: str = wallet.get_private_spend_key() + + # recreate test wallet from seed + config: MoneroWalletConfig = MoneroWalletConfig() + config.seed = TestUtils.SEED + config.restore_height = TestUtils.FIRST_RECEIVE_HEIGHT + + w: MoneroWallet = self._create_wallet(config) + path: str = w.get_path() + try: + assert primary_address == w.get_primary_address() + assert private_view_key == w.get_private_view_key() + assert private_spend_key == w.get_private_spend_key() + assert TestUtils.SEED, w.get_seed() + if not isinstance(w, MoneroWalletRpc): + assert MoneroWallet.DEFAULT_LANGUAGE == w.get_seed_language() + finally: + self._close_wallet(w) + + # attempt to create wallet with two missing words + config = MoneroWalletConfig() + config.seed = test_config.seed + config.restore_height = TestUtils.FIRST_RECEIVE_HEIGHT + with pytest.raises(Exception) as exc_info: + self._create_wallet(config) + assert str(exc_info.value) == "Invalid mnemonic" + + # attempt to create wallet at same path + config = MoneroWalletConfig() + config.path = path + with pytest.raises(Exception) as exc_info: + self._create_wallet(config) + assert str(exc_info.value) == "Wallet already exists: " + path + + # Can create a wallet from a seed with offset + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_create_wallet_from_seed_with_offset(self) -> None: + # create test wallet with offset + config: MoneroWalletConfig = MoneroWalletConfig() + config.seed = TestUtils.SEED + config.restore_height = TestUtils.FIRST_RECEIVE_HEIGHT + config.seed_offset = "my secret offset!" + wallet: MoneroWallet = self._create_wallet(config) + try: + MoneroUtils.validate_mnemonic(wallet.get_seed()) + assert TestUtils.SEED != wallet.get_seed() + MoneroUtils.validate_address(wallet.get_primary_address(), TestUtils.NETWORK_TYPE) + assert TestUtils.ADDRESS != wallet.get_primary_address() + if not isinstance(wallet, MoneroWalletRpc): + # TODO monero-wallet-rpc: support + assert MoneroWallet.DEFAULT_LANGUAGE == wallet.get_seed_language() + finally: + self._close_wallet(wallet) + + # Can create a wallet from keys + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_create_wallet_from_keys(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: + # save for comparison + primary_address: str = wallet.get_primary_address() + private_view_key: str = wallet.get_private_view_key() + private_spend_key: str = wallet.get_private_spend_key() + + # recreate test wallet from keys + config: MoneroWalletConfig = MoneroWalletConfig() + config.primary_address = primary_address + config.private_view_key = private_view_key + config.private_spend_key = private_spend_key + config.restore_height = daemon.get_height() + w: MoneroWallet = self._create_wallet(config) + path: str = w.get_path() + + try: + assert primary_address == w.get_primary_address() + assert private_view_key == w.get_private_view_key() + assert private_spend_key == w.get_private_spend_key() + if not w.is_connected_to_daemon(): + # TODO monero-project: keys wallets not connected + logger.warning(f"WARNING: {WalletErrorUtils.CREATED_WALLET_KEYS_ERROR}") + assert w.is_connected_to_daemon(), WalletErrorUtils.CREATED_WALLET_KEYS_ERROR + if not isinstance(w, MoneroWalletRpc): + # TODO monero-wallet-rpc: cannot get seed from wallet created from keys? + MoneroUtils.validate_mnemonic(w.get_seed()) + assert MoneroWallet.DEFAULT_LANGUAGE == w.get_seed_language() + finally: + self._close_wallet(w) + + # recreate test wallet from spend key + if not isinstance(w, MoneroWalletRpc): # TODO monero-wallet-rpc: cannot create wallet from spend key? + config = MoneroWalletConfig() + config.private_spend_key = private_spend_key + config.restore_height = daemon.get_height() + w = self._create_wallet(config) + + try: + assert primary_address == w.get_primary_address() + assert private_view_key == w.get_private_view_key() + assert private_spend_key == w.get_private_spend_key() + if not w.is_connected_to_daemon(): + # TODO monero-project: keys wallets not connected + logger.warning(f"{WalletErrorUtils.CREATED_WALLET_KEYS_ERROR}") + assert w.is_connected_to_daemon(), WalletErrorUtils.CREATED_WALLET_KEYS_ERROR + if not isinstance(w, MoneroWalletRpc): + # TODO monero-wallet-rpc: cannot get seed from wallet created from keys? + MoneroUtils.validate_mnemonic(w.get_seed()) + assert MoneroWallet.DEFAULT_LANGUAGE == w.get_seed_language() + finally: + self._close_wallet(w) + + # attempt to create wallet at same path + config = MoneroWalletConfig() + config.path = path + with pytest.raises(Exception) as exc_info: + self._create_wallet(config) + assert str(exc_info.value) == "Wallet already exists: " + path + + # Can create wallets with subaddress lookahead + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_subaddress_lookahead(self, wallet: MoneroWallet) -> None: + receiver: MoneroWallet | None = None + try: + # create wallet with high subaddress lookahead + config: MoneroWalletConfig = MoneroWalletConfig() + config.account_lookahead = 1 + config.subaddress_lookahead = 100000 + receiver = self._create_wallet(config) + + # transfer funds to subaddress with high index + tx_config: MoneroTxConfig = MoneroTxConfig() + tx_config.account_index = 0 + dest: MoneroDestination = MoneroDestination() + dest.address = receiver.get_subaddress(0, 85000).address + dest.amount = TxWalletUtils.MAX_FEE + tx_config.destinations.append(dest) + tx_config.relay = True + + wallet.create_tx(tx_config) + + # observe unconfirmed funds + GenUtils.wait_for(1000) + receiver.sync() + assert receiver.get_balance() > 0 + finally: + if receiver is not None: + self._close_wallet(receiver) + + # Can get the wallet's version + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_version(self, wallet: MoneroWallet) -> None: + version: MoneroVersion = wallet.get_version() + assert version.number is not None + assert version.number > 0 + assert version.is_release is not None + + # Can get the wallet's path + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_path(self) -> None: + # create random wallet + config: MoneroWalletConfig = MoneroWalletConfig() + wallet: MoneroWallet = self._create_wallet(config) + + # set a random attribute + #String uuid = UUID.randomUUID().toString() + uuid: str = StringUtils.get_random_string() + wallet.set_attribute("uuid", uuid) + + # record the wallet's path then save and close + path: str = wallet.get_path() + self._close_wallet(wallet, True) + + # re-open the wallet using its path + wallet = self._open_wallet_from_path(path, None) + + # test the attribute + assert uuid == wallet.get_attribute("uuid") + self._close_wallet(wallet) + + # Can change the wallet password + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_change_password(self) -> None: + # create random wallet + config: MoneroWalletConfig = MoneroWalletConfig() + config.password = TestUtils.WALLET_PASSWORD + wallet: MoneroWallet = self._create_wallet(config) + path: str = wallet.get_path() + + # change password + new_password: str = "" + wallet.change_password(TestUtils.WALLET_PASSWORD, new_password) + + # close wallet without saving + self._close_wallet(wallet) + + # old password does not work (password change is auto saved) + config = MoneroWalletConfig() + config.path = path + config.password = TestUtils.WALLET_PASSWORD + with pytest.raises(Exception) as exc_info: + self._open_wallet(config) + # TODO: different errors from rpc and wallet2 + e_str = str(exc_info.value).lower() + assert "failed to open wallet" in e_str or "invalid password" in e_str + + # open wallet with new password + config = MoneroWalletConfig() + config.path = path + config.password = new_password + wallet = self._open_wallet(config) + + # change password with incorrect password + with pytest.raises(Exception) as exc_info: + wallet.change_password("badpassword", new_password) + assert "Invalid original password." == str(exc_info.value) + # save and close + self._close_wallet(wallet, True) + + # open wallet + config = MoneroWalletConfig() + config.path = path + config.password = new_password + wallet = self._open_wallet(config) + + # close wallet + self._close_wallet(wallet) + + # Can save and close the wallet in a single call + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_save_and_close(self) -> None: + # create random wallet + password: str = "" + config: MoneroWalletConfig = MoneroWalletConfig() + config.password = password + wallet: MoneroWallet = self._create_wallet(config) + path: str = wallet.get_path() + + # set an attribute + uuid: str = StringUtils.get_random_string() + wallet.set_attribute("id", uuid) + + # close the wallet without saving + self._close_wallet(wallet) + + # re-open the wallet and ensure attribute was not saved + config = MoneroWalletConfig() + config.path = path + config.password = password + wallet = self._open_wallet(config) + assert wallet.get_attribute("id") == "" + + # set the attribute and close with saving + wallet.set_attribute("id", uuid) + self._close_wallet(wallet, True) + + # re-open the wallet and ensure attribute was saved + wallet = self._open_wallet(config) + assert uuid == wallet.get_attribute("id") + self._close_wallet(wallet) + + # Supports view-only and offline wallets to create, sign and submit transactions + @pytest.mark.skipif(TestUtils.LITE_MODE, reason="LITE_MODE enabled") + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False and TestUtils.TEST_RELAYS is False, reason="TEST_NON_RELAYS and TEST_RELAYS disabled") + def test_view_only_and_offline_wallets(self, wallet: MoneroWallet) -> None: + # create view-only and offline wallets + config: MoneroWalletConfig = MoneroWalletConfig() + config.primary_address = wallet.get_primary_address() + config.private_view_key = wallet.get_private_view_key() + config.restore_height = TestUtils.FIRST_RECEIVE_HEIGHT + view_only_wallet: MoneroWallet = self._create_wallet(config) + + config = MoneroWalletConfig() + config.primary_address = wallet.get_primary_address() + config.private_view_key = wallet.get_private_view_key() + config.private_spend_key = wallet.get_private_spend_key() + config.server = MoneroRpcConnection(TestUtils.OFFLINE_SERVER_URI) + config.restore_height = 0 + offline_wallet: MoneroWallet = self._create_wallet(config) + assert offline_wallet.is_connected_to_daemon() is False + view_only_wallet.sync() + + # test tx signing with wallets + try: + tester: ViewOnlyAndOfflineWalletTester = ViewOnlyAndOfflineWalletTester(wallet, view_only_wallet, offline_wallet) + tester.test() + finally: + self._close_wallet(view_only_wallet) + self._close_wallet(offline_wallet) + + # Can get and set arbitrary key/value attributes + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_set_attributes(self, wallet: MoneroWallet) -> None: + # set attributes + attrs: dict[str, str] = {} + for i in range(5): + key: str = f"attr{i}" + val: str = StringUtils.get_random_string() + attrs[key] = val + wallet.set_attribute(key, val) + + # test attributes + for key in attrs: + val = attrs[key] + assert val == wallet.get_attribute(key) + + # get an undefined attribute + assert wallet.get_attribute("unset_key") == "" + + +@pytest.mark.integration +class TestMoneroWalletFullCreation(FullWalletSupport, BaseTestMoneroWalletCreation): + """Full wallet creation integration tests.""" + + # Can create a random full wallet + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_create_wallet_random_full(self, daemon: MoneroDaemonRpc) -> None: + # create random wallet with defaults + path: str = Utils.get_random_wallet_path() + config: MoneroWalletConfig = MoneroWalletConfig() + config.path = path + config.network_type = MoneroNetworkType.MAINNET + config.server = MoneroRpcConnection(Utils.OFFLINE_SERVER_URI) + wallet: MoneroWalletFull = self._create_wallet(config) + MoneroUtils.validate_mnemonic(wallet.get_seed()) + MoneroUtils.validate_address(wallet.get_primary_address(), MoneroNetworkType.MAINNET) + assert wallet.get_network_type() == MoneroNetworkType.MAINNET + AssertUtils.assert_equals(wallet.get_daemon_connection(), MoneroRpcConnection(Utils.OFFLINE_SERVER_URI)) + assert wallet.is_connected_to_daemon() is False + assert wallet.get_seed_language() == "English" + assert wallet.get_path() == path + assert wallet.is_synced() is False + # TODO monero-project: why does height of new unsynced wallet start at 1? + assert wallet.get_height() == 1 + assert wallet.get_restore_height() >= 0 + + # cannot get daemon chain height: wallet2 masks errors from untrusted daemons + with pytest.raises(Exception) as exc_info: + wallet.get_daemon_height() + assert str(exc_info.value) == "daemon error" + + # set daemon and check chain height + wallet.set_daemon_connection(daemon.get_rpc_connection()) + assert daemon.get_height() == wallet.get_daemon_height() + + # close wallet which releases resources + wallet.close() + + # create random wallet with non defaults + path = Utils.get_random_wallet_path() + config = MoneroWalletConfig() + config.path = path + config.network_type = MoneroNetworkType.TESTNET + config.language = "Spanish" + wallet = self._create_wallet(config, False) + MoneroUtils.validate_mnemonic(wallet.get_seed()) + MoneroUtils.validate_address(wallet.get_primary_address(), MoneroNetworkType.TESTNET) + assert wallet.get_network_type() == MoneroNetworkType.TESTNET + assert wallet.get_daemon_connection() is not None + assert wallet.get_daemon_connection() != daemon.get_rpc_connection() + AssertUtils.assert_equals(wallet.get_daemon_connection(), daemon.get_rpc_connection()) + assert wallet.is_connected_to_daemon() + assert wallet.get_seed_language() == "Spanish" + assert path == wallet.get_path() + assert wallet.is_synced() is False + # TODO monero-project: why is height of unsynced wallet 1? + assert wallet.get_height() == 1 + if daemon.is_connected(): + assert daemon.get_height() == wallet.get_restore_height() + else: + assert wallet.get_restore_height() >= 0 + + wallet.close() + + # Can create a full wallet from seed + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_create_wallet_from_seed_full(self, daemon: MoneroDaemonRpc) -> None: + # create unconnected wallet with seed + path: str = Utils.get_random_wallet_path() + config: MoneroWalletConfig = MoneroWalletConfig() + config.path = path + config.seed = Utils.SEED + config.server = MoneroRpcConnection(Utils.OFFLINE_SERVER_URI) + wallet: MoneroWalletFull = self._create_wallet(config) + assert wallet.get_seed() == Utils.SEED + assert wallet.get_primary_address() == Utils.ADDRESS + assert wallet.get_network_type() == Utils.NETWORK_TYPE + AssertUtils.assert_equals(MoneroRpcConnection(Utils.OFFLINE_SERVER_URI), wallet.get_daemon_connection()) + assert wallet.is_connected_to_daemon() is False + assert wallet.get_seed_language() == "English" + assert wallet.get_path() == path + assert wallet.is_synced() is False + assert wallet.get_height() == 1 + assert wallet.get_restore_height() == 0 + wallet.start_syncing() # succeeds while offline, syncing when a daemon becomes reachable + + wallet.close() + + # create wallet without restore height + path = Utils.get_random_wallet_path() + config = MoneroWalletConfig() + config.path = path + config.seed = Utils.SEED + wallet = self._create_wallet(config, False) + assert wallet.get_seed() == Utils.SEED + assert wallet.get_primary_address() == Utils.ADDRESS + assert wallet.get_network_type() == Utils.NETWORK_TYPE + assert wallet.get_daemon_connection() is not None + assert wallet.get_daemon_connection() != daemon.get_rpc_connection() + AssertUtils.assert_equals(wallet.get_daemon_connection(), daemon.get_rpc_connection()) + assert wallet.is_connected_to_daemon() + assert wallet.get_seed_language() == "English" + assert wallet.get_path() == path + assert wallet.is_synced() is False + assert wallet.get_height() == 1 + # TODO (java annotation) restore height is lost after closing only in JNI + assert wallet.get_restore_height() == 0 + wallet.close() + + # create wallet with seed, no connection, and restore height + restore_height: int = 10000 + path = Utils.get_random_wallet_path() + config = MoneroWalletConfig() + config.path = path + config.seed = Utils.SEED + config.restore_height = restore_height + config.server = MoneroRpcConnection(Utils.OFFLINE_SERVER_URI) + wallet = self._create_wallet(config) + assert wallet.get_seed() == Utils.SEED + assert wallet.get_primary_address() == Utils.ADDRESS + assert wallet.get_network_type() == Utils.NETWORK_TYPE + AssertUtils.assert_equals(MoneroRpcConnection(Utils.OFFLINE_SERVER_URI), wallet.get_daemon_connection()) + assert wallet.is_connected_to_daemon() is False + assert wallet.get_seed_language() == "English" + # TODO monero-project: why does height of new unsynced wallet start at 1? + assert wallet.get_height() == 1 + assert wallet.get_restore_height() == restore_height + assert wallet.get_path() == path + wallet.close(True) + config = MoneroWalletConfig() + config.path = path + config.server = MoneroRpcConnection(Utils.OFFLINE_SERVER_URI) + wallet = self._open_wallet(config) + assert wallet.is_connected_to_daemon() is False + assert wallet.is_synced() is False + assert wallet.get_height() == 1 + assert wallet.get_restore_height() == restore_height + wallet.close() + + # create wallet with seed, connection, and restore height + path = Utils.get_random_wallet_path() + config = MoneroWalletConfig() + config.path = path + config.seed = Utils.SEED + config.restore_height = restore_height + wallet = self._create_wallet(config, False) + assert wallet.get_seed() == Utils.SEED + assert wallet.get_primary_address() == Utils.ADDRESS + assert wallet.get_network_type() == Utils.NETWORK_TYPE + assert wallet.get_daemon_connection() is not None + assert wallet.get_daemon_connection() != daemon.get_rpc_connection() + AssertUtils.assert_equals(wallet.get_daemon_connection(), daemon.get_rpc_connection()) + assert wallet.is_connected_to_daemon() + assert wallet.get_seed_language() == "English" + assert wallet.get_path() == path + assert wallet.is_synced() is False + # TODO monero-project: why does height of new unsynced wallet start at 1? + assert wallet.get_height() == 1 + assert wallet.get_restore_height() == restore_height + wallet.close() + + # Can create a full wallet from keys + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_create_wallet_from_keys_pybind(self, wallet: MoneroWalletFull) -> None: + # recreate test wallet from keys + path: str = Utils.get_random_wallet_path() + config: MoneroWalletConfig = MoneroWalletConfig() + config.path = path + config.primary_address = wallet.get_primary_address() + config.private_view_key = wallet.get_private_view_key() + config.private_spend_key = wallet.get_private_spend_key() + config.restore_height = Utils.FIRST_RECEIVE_HEIGHT + wallet_keys: MoneroWalletFull = self._create_wallet(config) + + try: + # test wallet keys equality + assert wallet.get_seed() == wallet_keys.get_seed() + assert wallet.get_primary_address() == wallet_keys.get_primary_address() + assert wallet.get_private_view_key() == wallet_keys.get_private_view_key() + assert wallet.get_public_view_key() == wallet_keys.get_public_view_key() + assert wallet.get_private_spend_key() == wallet_keys.get_private_spend_key() + assert wallet.get_public_spend_key() == wallet_keys.get_public_spend_key() + assert Utils.FIRST_RECEIVE_HEIGHT == wallet_keys.get_restore_height() + assert wallet_keys.is_connected_to_daemon() + assert wallet_keys.is_synced() is False + finally: + wallet_keys.close() + + # Does not interfere with other wallet notifications + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + @pytest.mark.skipif(Utils.LITE_MODE, reason="LITE_MODE enabled") + def test_wallets_do_not_interfere(self, daemon: MoneroDaemonRpc) -> None: + # create 2 wallets with a recent restore height + height: int = daemon.get_height() + restore_height: int = height - 5 + config: MoneroWalletConfig = MoneroWalletConfig() + config.seed = Utils.SEED + config.restore_height = restore_height + wallet1: MoneroWalletFull = self._create_wallet(config, False) + + config = MoneroWalletConfig() + config.seed = Utils.SEED + config.restore_height = restore_height + wallet2: MoneroWalletFull = self._create_wallet(config, False) + + # track notifications of each wallet + tester1: SyncProgressTester = SyncProgressTester(wallet1, restore_height, height) + tester2: SyncProgressTester = SyncProgressTester(wallet2, restore_height, height) + wallet1.add_listener(tester1) + wallet2.add_listener(tester2) + + # sync first wallet and test that 2nd is not notified + wallet1.sync() + assert tester1.is_notified + assert not tester2.is_notified + + # sync 2nd wallet and test that 1st is not notified + tester3: SyncProgressTester = SyncProgressTester(wallet1, restore_height, height) + wallet1.add_listener(tester3) + wallet2.sync() + assert tester2.is_notified + assert not tester3.is_notified + + # Can be closed + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_close(self) -> None: + # create test wallet + path: str = Utils.get_random_wallet_path() + config: MoneroWalletConfig = MoneroWalletConfig() + config.path = path + wallet: MoneroWalletFull = self._create_wallet(config) + wallet.sync() + assert wallet.get_height() > 1, "Wallet height is still 1" + assert wallet.is_synced(), "Wallet is not synced" + assert wallet.is_closed() is False + + # close wallet + wallet.close() + + assert wallet.is_closed() + + # attempt to interact with the wallet + with pytest.raises(Exception) as exc_info: + wallet.get_height() + WalletErrorUtils.test_wallet_is_closed_error(exc_info.value) + + with pytest.raises(Exception) as exc_info: + wallet.get_seed() + WalletErrorUtils.test_wallet_is_closed_error(exc_info.value) + + with pytest.raises(Exception) as exc_info: + wallet.sync() + WalletErrorUtils.test_wallet_is_closed_error(exc_info.value) + + with pytest.raises(Exception) as exc_info: + wallet.start_syncing() + WalletErrorUtils.test_wallet_is_closed_error(exc_info.value) + + with pytest.raises(Exception) as exc_info: + wallet.stop_syncing() + WalletErrorUtils.test_wallet_is_closed_error(exc_info.value) + + # re-open the wallet + config = MoneroWalletConfig() + config.path = path + + wallet = self._open_wallet(config) + assert wallet.is_closed() is False + wallet.sync() + assert wallet.get_daemon_height() == wallet.get_height() + assert wallet.is_closed() is False + + # close the wallet + wallet.close() + assert wallet.is_closed() + + +@pytest.mark.integration +class TestMoneroWalletRpcCreation(RpcWalletSupport, BaseTestMoneroWalletCreation): + """Rpc wallet creation integration tests.""" + + # Can create a wallet with a randomly generated seed + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_create_wallet_random_rpc(self) -> None: + # create random wallet with defaults + path: str = StringUtils.get_random_string() + config: MoneroWalletConfig = MoneroWalletConfig() + config.path = path + wallet: MoneroWalletRpc = self._create_wallet(config) + seed: str = wallet.get_seed() + MoneroUtils.validate_mnemonic(seed) + assert Utils.SEED != seed + MoneroUtils.validate_address(wallet.get_primary_address(), Utils.NETWORK_TYPE) + # very quick because restore height is chain height + wallet.sync() + self._close_wallet(wallet) + + # create random wallet non defaults + path = StringUtils.get_random_string() + config = MoneroWalletConfig() + config.path = path + config.language = "Spanish" + wallet = self._create_wallet(config) + MoneroUtils.validate_mnemonic(wallet.get_seed()) + assert seed != wallet.get_seed() + seed = wallet.get_seed() + MoneroUtils.validate_address(wallet.get_primary_address(), Utils.NETWORK_TYPE) + + # attempt to create wallet which already exists + with pytest.raises(MoneroError) as exc_info: + wallet.create_wallet(config) + assert str(exc_info.value) == f"Wallet already exists: {path}" + assert seed == wallet.get_seed() + + self._close_wallet(wallet) + + # Can create a RPC wallet from a seed + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_create_wallet_from_seed_rpc(self, daemon: MoneroDaemonRpc) -> None: + # create wallet with seed and defaults + path: str = StringUtils.get_random_string() + config: MoneroWalletConfig = MoneroWalletConfig() + config.path = path + config.seed = Utils.SEED + config.restore_height = Utils.FIRST_RECEIVE_HEIGHT + wallet: MoneroWalletRpc = self._create_wallet(config) + + # validate wallet + assert Utils.SEED == wallet.get_seed() + assert Utils.ADDRESS == wallet.get_primary_address() + wallet.sync() + assert daemon.get_height() == wallet.get_height() + txs: list[MoneroTxWallet] = wallet.get_txs() + # expect used wallet + assert len(txs) > 0, "Wallet is not used" + assert Utils.FIRST_RECEIVE_HEIGHT == txs[0].get_height() + # TODO: monero-wallet-rpc: if wallet is not closed, primary address will not change + self._close_wallet(wallet) + + # create wallet with non-defaults + path = StringUtils.get_random_string() + config = MoneroWalletConfig() + config.path = path + config.seed = Utils.SEED + config.restore_height = Utils.FIRST_RECEIVE_HEIGHT + config.language = "German" + config.seed_offset = "my offset!" + config.save_current = False + wallet = self._create_wallet(config) + + # validate wallet + MoneroUtils.validate_mnemonic(wallet.get_seed()) + assert wallet.get_seed() != Utils.SEED + assert wallet.get_primary_address() != Utils.ADDRESS + assert not wallet.is_view_only() + wallet.sync() + assert daemon.get_height() == wallet.get_height() + txs = wallet.get_txs() + # expect non used wallet + assert len(txs) == 0, "Wallet is used" + self._close_wallet(wallet) + + # Can open wallets + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_open_wallet(self)-> None: + # create names of tests wallets + num_test_wallets: int = 1 + names: list[str] = [ ] + for i in range(num_test_wallets): + logger.debug(f"Creating test wallet {i + 1}") + names.append(StringUtils.get_random_string()) + + # create test wallets + seeds: list[str] = [] + for name in names: + config: MoneroWalletConfig = MoneroWalletConfig() + config.path = name + wallet: MoneroWalletRpc = self._create_wallet(config) + seeds.append(wallet.get_seed()) + self._close_wallet(wallet, True) + + # open test wallets + wallets: list[MoneroWalletRpc] = [] + for i in range(num_test_wallets): + config: MoneroWalletConfig = MoneroWalletConfig() + config.path = names[i] + config.password = Utils.WALLET_PASSWORD + wallet: MoneroWalletRpc = self._open_wallet(config) + assert seeds[i] == wallet.get_seed() + wallets.append(wallet) + + # attempt to open non-existent + config: MoneroWalletConfig = MoneroWalletConfig() + config.path = "btc_integrity" + config.password = Utils.WALLET_PASSWORD + with pytest.raises(Exception): + self._open_wallet(config) + + # close wallets: + for wallet in wallets: + self._close_wallet(wallet) + + # Can save the wallet + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_save(self, wallet: MoneroWallet) -> None: + wallet.save() + + # Can close a wallet + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_close(self, daemon: MoneroDaemonRpc) -> None: + # create a test wallet + path: str = StringUtils.get_random_string() + config: MoneroWalletConfig = MoneroWalletConfig() + config.path = path + wallet: MoneroWalletRpc = self._create_wallet(config) + wallet.sync() + + # close the wallet + wallet.close() + Utils.free_wallet_rpc_resource(wallet) + + # attempt to interact with the wallet + with pytest.raises(Exception) as exc_info: + wallet.get_height() + WalletErrorUtils.test_no_wallet_file_error(exc_info.value) + + with pytest.raises(Exception) as exc_info: + wallet.get_seed() + WalletErrorUtils.test_no_wallet_file_error(exc_info.value) + + with pytest.raises(Exception) as exc_info: + wallet.sync() + WalletErrorUtils.test_no_wallet_file_error(exc_info.value) + + # re-open the wallet + wallet.open_wallet(path, Utils.WALLET_PASSWORD) + wallet.sync() + assert daemon.get_height() == wallet.get_height() + + # close the wallet + self._close_wallet(wallet, True) + + # Can stop the RPC server + @pytest.mark.skip(reason="Disabled so server not actually stopped") + def test_stop(self, wallet: MoneroWalletRpc) -> None: + wallet.stop() + + @pytest.mark.not_supported + @override + def test_subaddress_lookahead(self, wallet: MoneroWallet) -> None: + return super().test_subaddress_lookahead(wallet) + + +@pytest.mark.unit +class TestMoneroWalletKeysCreation(KeysWalletSupport, BaseTestMoneroWalletCreation): + """Keys-only wallet creation unit tests.""" + + @pytest.mark.not_supported + @override + def test_get_path(self) -> None: + return super().test_get_path() + + @pytest.mark.not_supported + @override + def test_subaddress_lookahead(self, wallet: MoneroWallet) -> None: + return super().test_subaddress_lookahead(wallet) + + @pytest.mark.not_supported + @override + def test_set_attributes(self, wallet: MoneroWallet) -> None: + return super().test_set_attributes(wallet) + + @pytest.mark.not_supported + @override + def test_change_password(self) -> None: + return super().test_change_password() + + @pytest.mark.not_supported + @override + def test_save_and_close(self) -> None: + return super().test_save_and_close() + + @pytest.mark.not_supported + @override + def test_view_only_and_offline_wallets(self, wallet: MoneroWallet) -> None: + return super().test_view_only_and_offline_wallets(wallet) + + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + @override + def test_create_wallet_random(self) -> None: + """ + Can create a random wallet. + """ + config: MoneroWalletConfig = MoneroWalletConfig() + wallet: MoneroWalletKeys = self._create_wallet(config) + + # validate wallet + MoneroUtils.validate_address(wallet.get_primary_address(), Utils.NETWORK_TYPE) + MoneroUtils.validate_private_view_key(wallet.get_private_view_key()) + MoneroUtils.validate_private_spend_key(wallet.get_private_spend_key()) + MoneroUtils.validate_mnemonic(wallet.get_seed()) + # TODO monero-wallet-rpc: get seed language + assert MoneroWallet.DEFAULT_LANGUAGE == wallet.get_seed_language() + + # attempt to create wallet with unknown language + config = MoneroWalletConfig() + config.language = "english" + with pytest.raises(Exception, match="Unknown language: english"): + self._create_wallet(config) + + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + @override + def test_create_wallet_from_seed(self, wallet: MoneroWallet, test_config: BaseTestMoneroWallet.Config) -> None: + # save for comparison + primary_address: str = wallet.get_primary_address() + private_view_key: str = wallet.get_private_view_key() + private_spend_key: str = wallet.get_private_spend_key() + + # recreate test wallet from seed + config: MoneroWalletConfig = MoneroWalletConfig() + config.seed = Utils.SEED + w: MoneroWallet = self._create_wallet(config) + + assert primary_address == w.get_primary_address() + assert private_view_key == w.get_private_view_key() + assert private_spend_key == w.get_private_spend_key() + assert Utils.SEED == w.get_seed() + assert MoneroWallet.DEFAULT_LANGUAGE == w.get_seed_language() + + # attempt to create wallet with two missing words + config = MoneroWalletConfig() + config.seed = test_config.seed + with pytest.raises(Exception) as exc_info: + self._create_wallet(config) + assert str(exc_info.value) == "Invalid mnemonic" + + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + @override + def test_create_wallet_from_seed_with_offset(self) -> None: + # create test wallet with offset + config: MoneroWalletConfig = MoneroWalletConfig() + config.seed = Utils.SEED + config.seed_offset = "my secret offset!" + wallet: MoneroWallet = self._create_wallet(config) + + MoneroUtils.validate_mnemonic(wallet.get_seed()) + assert Utils.SEED != wallet.get_seed() + MoneroUtils.validate_address(wallet.get_primary_address(), Utils.NETWORK_TYPE) + assert Utils.ADDRESS != wallet.get_primary_address() + assert MoneroWallet.DEFAULT_LANGUAGE == wallet.get_seed_language() + + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + @override + def test_create_wallet_from_keys(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: + # save for comparison + primary_address: str = wallet.get_primary_address() + private_view_key: str = wallet.get_private_view_key() + private_spend_key: str = wallet.get_private_spend_key() + + # recreate test wallet from keys + config: MoneroWalletConfig = MoneroWalletConfig() + config.primary_address = primary_address + config.private_view_key = private_view_key + config.private_spend_key = private_spend_key + w: MoneroWallet = self._create_wallet(config) + WalletUtils.test_wallet_keys(primary_address, private_view_key, private_spend_key, w) + assert w.get_network_type() == Utils.NETWORK_TYPE + assert not w.is_closed() + w.close() + + # recreate test wallet from spend key + config = MoneroWalletConfig() + config.primary_address = primary_address + config.private_spend_key = private_spend_key + w = self._create_wallet(config) + WalletUtils.test_wallet_keys(primary_address, private_view_key, private_spend_key, w) + assert w.get_network_type() == Utils.NETWORK_TYPE + assert not w.is_closed() + w.close() + + # recreate test wallet from view keys + config = MoneroWalletConfig() + config.primary_address = primary_address + config.private_view_key = private_view_key + w = self._create_wallet(config) + logger.info(f"Created wallet with config: {config.serialize()}") + assert primary_address == w.get_primary_address() + assert private_view_key == w.get_private_view_key() + assert w.get_network_type() == Utils.NETWORK_TYPE + assert w.is_view_only() + # a view-only keys wallet has no seed + with pytest.raises(RuntimeError, match="watch-only"): + w.get_seed() + assert not w.is_closed() + w.close() + + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_create_wallet_from_keys_no_keys(self) -> None: + """ + create_wallet_from_keys() must require at least one of the private spend/view keys. + """ + config: MoneroWalletConfig = MoneroWalletConfig() + config.network_type = Utils.NETWORK_TYPE + with pytest.raises(RuntimeError, match="Neither spend key nor view key supplied"): + MoneroWalletKeys.create_wallet_from_keys(config) + + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_create_wallet_from_keys_invalid_spend_key(self) -> None: + """ + create_wallet_from_keys() must fail to parse a malformed private spend key. + """ + config: MoneroWalletConfig = MoneroWalletConfig() + config.network_type = Utils.NETWORK_TYPE + config.private_spend_key = "not-a-valid-hex-secret-key" + with pytest.raises(RuntimeError, match="failed to parse secret spend key"): + MoneroWalletKeys.create_wallet_from_keys(config) + + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_create_wallet_from_keys_invalid_view_key(self) -> None: + """ + create_wallet_from_keys() must fail to parse a malformed private view key. + """ + config: MoneroWalletConfig = MoneroWalletConfig() + config.network_type = Utils.NETWORK_TYPE + config.primary_address = Utils.ADDRESS + config.private_view_key = "not-a-valid-hex-secret-key" + with pytest.raises(RuntimeError, match="failed to parse secret view key"): + MoneroWalletKeys.create_wallet_from_keys(config) + + # Test invalid wallet configuration + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_create_wallet_from_keys_view_key_without_address(self) -> None: + """ + create_wallet_from_keys() must require a primary address when a private view key is given. + """ + config: MoneroWalletConfig = MoneroWalletConfig() + config.network_type = Utils.NETWORK_TYPE + config.private_view_key = "a" * 64 + + with pytest.raises(RuntimeError, match="must provide address if providing private view key"): + MoneroWalletKeys.create_wallet_from_keys(config) + + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_is_closed(self) -> None: + """A keys-only wallet reports its open/closed state and rejects use once closed.""" + config: MoneroWalletConfig = MoneroWalletConfig() + config.network_type = Utils.NETWORK_TYPE + w: MoneroWalletKeys = MoneroWalletKeys.create_wallet_random(config) + + # a freshly created wallet is open + assert w.is_closed() is False + primary_address: str = w.get_primary_address() + + # closing it (without saving) marks it closed + w.close() + assert w.is_closed() is True + + # any accessor now raises "Wallet is closed" + with pytest.raises(RuntimeError, match="Wallet is closed"): + w.get_primary_address() + with pytest.raises(RuntimeError, match="Wallet is closed"): + w.get_private_view_key() + + # closing an already-closed wallet is a no-op (and does not re-raise) + w.close() + assert w.is_closed() is True + + # sanity: the address read before closing is unaffected + MoneroUtils.validate_address(primary_address, Utils.NETWORK_TYPE) + + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_close_with_save_not_supported(self) -> None: + """`close(save=True)` is rejected because a keys-only wallet has nothing to persist.""" + config: MoneroWalletConfig = MoneroWalletConfig() + config.network_type = Utils.NETWORK_TYPE + w: MoneroWalletKeys = MoneroWalletKeys.create_wallet_random(config) + + with pytest.raises(RuntimeError, match="does not support saving"): + w.close(True) + + # the failed save-and-close left the wallet open + assert w.is_closed() is False + w.close() diff --git a/tests/wallet/test_equality.py b/tests/wallet/test_equality.py new file mode 100644 index 00000000..2b3555ec --- /dev/null +++ b/tests/wallet/test_equality.py @@ -0,0 +1,147 @@ +from __future__ import annotations + +import logging + +import pytest +from monero import ( + MoneroAccount, + MoneroOutputQuery, + MoneroOutputWallet, + MoneroTxWallet, + MoneroWallet, + MoneroWalletFull, +) +from typing_extensions import override + +from utils import GenUtils, TestUtils, WalletEqualityUtils, WalletUtils +from .base_test_monero_wallet import BaseTestMoneroWallet +from .wallet_support import FullWalletSupport, RpcWalletSupport, KeysWalletSupport + +logger: logging.Logger = logging.getLogger("TestMoneroWalletEquality") + + +class BaseTestMoneroWalletEquality(BaseTestMoneroWallet): + """Common wallet equality tests.""" + + # Is equal to a ground truth wallet accoring to on-chain data + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_wallet_equality_ground_truth(self, wallet: MoneroWallet) -> None: + TestUtils.WALLET_TX_TRACKER.wait_for_txs_to_clear_pool([wallet]) + wallet_gt: MoneroWalletFull = TestUtils.create_wallet_ground_truth( + TestUtils.NETWORK_TYPE, TestUtils.SEED, None, TestUtils.FIRST_RECEIVE_HEIGHT + ) + try: + WalletEqualityUtils.test_wallet_equality_on_chain(wallet_gt, wallet) + finally: + wallet_gt.close() + + # Has correct accounting across accounts, subaddresses, txs, transfers and outputs + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_accounting(self, wallet: MoneroWallet) -> None: + # pre-fetch wallet balances, accounts, subaddresses and txs + wallet_balance: int = wallet.get_balance() + wallet_unlocked_balance: int = wallet.get_unlocked_balance() + # includes subaddresses + accounts: list[MoneroAccount] = wallet.get_accounts(True) + + # test wallet balance + GenUtils.test_unsigned_big_integer(wallet_balance) + GenUtils.test_unsigned_big_integer(wallet_unlocked_balance) + assert wallet_balance >= wallet_unlocked_balance + + # test that wallet balance equals sum of account balances + accounts_balance: int = 0 + accounts_unlocked_balance: int = 0 + for account in accounts: + # test that account balance equals sum of subaddress balances + WalletUtils.test_account(account, TestUtils.NETWORK_TYPE) + assert account.balance is not None + assert account.unlocked_balance is not None + accounts_balance += account.balance + accounts_unlocked_balance += account.unlocked_balance + + assert wallet_balance == accounts_balance + assert wallet_unlocked_balance == accounts_unlocked_balance + + # TODO test that wallet balance equals net of wallet's incoming and outgoing tx amounts + + # balance may not equal sum of unspent outputs if unconfirmed txs + # TODO monero-wallet-rpc: reason not to return unspent outputs on unconfirmed txs? then this isn't necessary + txs: list[MoneroTxWallet] = wallet.get_txs() + has_unconfirmed_tx: bool = False + for tx in txs: + if tx.in_tx_pool: + has_unconfirmed_tx = True + + # wallet balance is sum of all unspent outputs + wallet_sum: int = 0 + output_query: MoneroOutputQuery = MoneroOutputQuery() + output_query.is_spent = False + for output in wallet.get_outputs(output_query): + assert output.amount is not None + wallet_sum += output.amount + + if wallet_balance != wallet_sum: + # txs may have changed in between calls to retry test + wallet_sum = 0 + for output in wallet.get_outputs(output_query): + assert output.amount is not None + wallet_sum += output.amount + + if wallet_balance != wallet_sum: + assert has_unconfirmed_tx, "Wallet balance must equal sum of unspent outputs if no unconfirmed txs" + + # account balances are sum of their unspent outputs + for account in accounts: + account_sum: int = 0 + output_query = MoneroOutputQuery() + output_query.account_index = account.index + output_query.is_spent = False + account_outputs: list[MoneroOutputWallet] = wallet.get_outputs(output_query) + for output in account_outputs: + assert output.amount is not None + account_sum += output.amount + + assert account.balance is not None + if account.balance != account_sum: + assert has_unconfirmed_tx, "Account balance must equal sum of its unspent outputs if no unconfirmed txs" + + # subaddress balances are sum of their unspent outputs + for subaddress in account.subaddresses: + subaddress_sum: int = 0 + output_query = MoneroOutputQuery() + output_query.account_index = account.index + output_query.subaddress_index = subaddress.index + output_query.is_spent = False + subaddress_outputs: list[MoneroOutputWallet] = wallet.get_outputs(output_query) + for output in subaddress_outputs: + assert output.amount is not None + subaddress_sum += output.amount + + if subaddress_sum != subaddress.balance: + assert has_unconfirmed_tx, "Subaddress balance must equal sum of its unspent outputs if no unconfirmed txs" + + +@pytest.mark.integration +class TestMoneroWalletFullEquality(FullWalletSupport, BaseTestMoneroWalletEquality): + """Full wallet equality integration tests.""" + + +@pytest.mark.integration +class TestMoneroWalletRpcEquality(RpcWalletSupport, BaseTestMoneroWalletEquality): + """Rpc wallet equality integration tests.""" + + +@pytest.mark.unit +class TestMoneroWalletKeysEquality(KeysWalletSupport, BaseTestMoneroWalletEquality): + """Keys-only wallet equality unit tests.""" + + @pytest.mark.not_supported + @override + def test_accounting(self, wallet: MoneroWallet) -> None: + return super().test_accounting(wallet) + + @pytest.mark.not_supported + @override + def test_wallet_equality_ground_truth(self, wallet: MoneroWallet) -> None: + return super().test_wallet_equality_ground_truth(wallet) diff --git a/tests/wallet/test_full_offline.py b/tests/wallet/test_full_offline.py new file mode 100644 index 00000000..50e746be --- /dev/null +++ b/tests/wallet/test_full_offline.py @@ -0,0 +1,120 @@ +from __future__ import annotations + +import logging +import os + +import pytest +from monero import MoneroKeyImage, MoneroNetworkType, MoneroWalletConfig, MoneroWalletFull + +from utils import BaseTestClass, TestUtils as Utils + +logger: logging.Logger = logging.getLogger("TestMoneroWalletFullOffline") + + +@pytest.mark.unit +class TestMoneroWalletFullOffline(BaseTestClass): + """Full wallet unit tests that run against a disconnected wallet, no daemon needed.""" + + @pytest.fixture(scope="class") + @classmethod + def wallet(cls) -> MoneroWalletFull: + """Shared disconnected full wallet.""" + return Utils.get_wallet_full_offline() + + def test_get_default_ringdb_path_mainnet(self) -> None: + path: str = MoneroWalletFull.get_default_ringdb_path(MoneroNetworkType.MAINNET) + assert path.endswith(".shared-ringdb") + assert not path.endswith("testnet") + assert not path.endswith("stagenet") + + def test_get_default_ringdb_path_testnet(self) -> None: + path: str = MoneroWalletFull.get_default_ringdb_path(MoneroNetworkType.TESTNET) + assert path.endswith(os.path.join(".shared-ringdb", "testnet")) + + def test_get_default_ringdb_path_stagenet(self) -> None: + path: str = MoneroWalletFull.get_default_ringdb_path(MoneroNetworkType.STAGENET) + assert path.endswith(os.path.join(".shared-ringdb", "stagenet")) + + # import_key_images guards unset key image fields + def test_import_key_images_hex_not_defined(self, wallet: MoneroWalletFull) -> None: + with pytest.raises(RuntimeError) as exc_info: + wallet.import_key_images([MoneroKeyImage()]) + assert str(exc_info.value) == "key image hex is not defined" + + def test_import_key_images_signature_not_defined(self, wallet: MoneroWalletFull) -> None: + key_image: MoneroKeyImage = MoneroKeyImage() + key_image.hex = "a" * 64 + with pytest.raises(RuntimeError) as exc_info: + wallet.import_key_images([key_image]) + assert str(exc_info.value) == "key image signature is not defined" + + # Can be moved + def test_move_to(self) -> None: + config: MoneroWalletConfig = MoneroWalletConfig() + config.path = "" + config.password = Utils.WALLET_PASSWORD + config.network_type = MoneroNetworkType.MAINNET + wallet: MoneroWalletFull = MoneroWalletFull.create_wallet(config) + try: + seed: str = wallet.get_seed() + wallet.set_attribute("mykey", "myval1") + + # move the in-memory wallet to disk + path1: str = Utils.get_random_wallet_path() + assert MoneroWalletFull.wallet_exists(path1) is False + wallet.move_to(path1, Utils.WALLET_PASSWORD) + assert MoneroWalletFull.wallet_exists(path1) is True + assert wallet.get_seed() == seed + assert wallet.get_attribute("mykey") == "myval1" + + # moving to the same path saves in place + wallet.set_attribute("mykey", "myval2") + wallet.move_to(path1, Utils.WALLET_PASSWORD) + wallet.close() + wallet = MoneroWalletFull.open_wallet(path1, Utils.WALLET_PASSWORD, MoneroNetworkType.MAINNET) + assert wallet.get_seed() == seed + assert wallet.get_attribute("mykey") == "myval2" + + # move to a new path + path2: str = Utils.get_random_wallet_path() + wallet.set_attribute("mykey", "myval3") + wallet.move_to(path2, Utils.WALLET_PASSWORD) + assert MoneroWalletFull.wallet_exists(path1) is False + assert MoneroWalletFull.wallet_exists(path2) is True + wallet.close() + wallet = MoneroWalletFull.open_wallet(path2, Utils.WALLET_PASSWORD, MoneroNetworkType.MAINNET) + assert wallet.get_seed() == seed + assert wallet.get_attribute("mykey") == "myval3" + finally: + wallet.close() + + # Can export and import wallet files + def test_export_and_import_wallet_files(self) -> None: + config: MoneroWalletConfig = MoneroWalletConfig() + config.path = "" + config.password = Utils.WALLET_PASSWORD + config.network_type = MoneroNetworkType.MAINNET + wallet: MoneroWalletFull = MoneroWalletFull.create_wallet(config) + from_keys: MoneroWalletFull | None = None + from_both: MoneroWalletFull | None = None + try: + keys_data: bytes = wallet.get_keys_file_buffer(Utils.WALLET_PASSWORD, False) + cache_data: bytes = wallet.get_cache_file_buffer() + assert len(keys_data) > 0 + assert len(cache_data) > 0 + + # open from the keys buffer alone, then from keys + cache + from_keys = MoneroWalletFull.open_wallet_data(Utils.WALLET_PASSWORD, MoneroNetworkType.MAINNET, keys_data, b"", None, Utils.REGTEST) + from_both = MoneroWalletFull.open_wallet_data(Utils.WALLET_PASSWORD, MoneroNetworkType.MAINNET, keys_data, cache_data, None, Utils.REGTEST) + + for restored in (from_keys, from_both): + assert restored.get_seed() == wallet.get_seed() + assert restored.get_primary_address() == wallet.get_primary_address() + assert restored.get_private_view_key() == wallet.get_private_view_key() + assert restored.get_private_spend_key() == wallet.get_private_spend_key() + finally: + wallet.close() + if from_keys is not None: + from_keys.close() + if from_both is not None: + from_both.close() diff --git a/tests/test_monero_wallet_interface.py b/tests/wallet/test_interface.py similarity index 100% rename from tests/test_monero_wallet_interface.py rename to tests/wallet/test_interface.py diff --git a/tests/wallet/test_keys_and_addresses.py b/tests/wallet/test_keys_and_addresses.py new file mode 100644 index 00000000..1ecb084b --- /dev/null +++ b/tests/wallet/test_keys_and_addresses.py @@ -0,0 +1,445 @@ +from __future__ import annotations + +import logging + +import pytest +from monero import ( + MoneroAccount, + MoneroDestination, + MoneroIntegratedAddress, + MoneroMessageSignatureResult, + MoneroMessageSignatureType, + MoneroSubaddress, + MoneroTxConfig, + MoneroUtils, + MoneroWallet, + MoneroWalletConfig, + MoneroWalletKeys, +) +from typing_extensions import override + +from utils import AssertUtils, TestUtils, TestUtils as Utils, WalletErrorUtils, WalletTestUtils, WalletUtils +from .base_test_monero_wallet import BaseTestMoneroWallet +from .wallet_support import FullWalletSupport, RpcWalletSupport, KeysWalletSupport + +logger: logging.Logger = logging.getLogger("TestMoneroWalletKeysAndAddresses") + + +class BaseTestMoneroWalletKeysAndAddresses(BaseTestMoneroWallet): + """Common wallet keys and addresses tests.""" + + # Can get the seed + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_seed(self, wallet: MoneroWallet) -> None: + seed: str = wallet.get_seed() + MoneroUtils.validate_mnemonic(seed) + assert TestUtils.SEED == seed + + # Can get the language of the seed + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_seed_language(self, wallet: MoneroWallet) -> None: + language: str = wallet.get_seed_language() + assert MoneroWallet.DEFAULT_LANGUAGE == language + + # Can get a list of supported languages for the seed + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_seed_languages(self) -> None: + languages: list[str] = self._get_seed_languages() + assert len(languages) > 0 + for language in languages: + assert len(language) > 0 + + # Can get the private view key + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_private_view_key(self, wallet: MoneroWallet) -> None: + private_view_key: str = wallet.get_private_view_key() + MoneroUtils.validate_private_view_key(private_view_key) + + # Can get the private spend key + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_private_spend_key(self, wallet: MoneroWallet) -> None: + private_spend_key: str = wallet.get_private_spend_key() + MoneroUtils.validate_private_spend_key(private_spend_key) + + # Can get the public view key + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_public_view_key(self, wallet: MoneroWallet) -> None: + public_view_key: str = wallet.get_public_view_key() + MoneroUtils.validate_private_spend_key(public_view_key) + + # Can get the public spend key + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_public_spend_key(self, wallet: MoneroWallet) -> None: + public_spend_key: str = wallet.get_public_spend_key() + MoneroUtils.validate_private_spend_key(public_spend_key) + + # Can get the primary address + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_primary_address(self, wallet: MoneroWallet) -> None: + primary_address: str = wallet.get_primary_address() + MoneroUtils.validate_address(primary_address, TestUtils.NETWORK_TYPE) + assert wallet.get_address(0, 0) == primary_address + + # Can get the address of a subaddress at a specified account and subaddress index + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_subaddress_address(self, wallet: MoneroWallet) -> None: + assert wallet.get_primary_address() == wallet.get_address(0, 0) + for account in wallet.get_accounts(True): + for subaddress in account.subaddresses: + assert account.index is not None + assert subaddress.index is not None + assert subaddress.address == wallet.get_address(account.index, subaddress.index) + + # Can get addresses out of range of used accounts and subaddresses + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_subaddress_address_out_of_range(self, wallet: MoneroWallet) -> None: + accounts: list[MoneroAccount] = wallet.get_accounts(True) + account_idx: int = len(accounts) - 1 + subaddress_idx: int = len(accounts[account_idx].subaddresses) + address: str = wallet.get_address(account_idx, subaddress_idx) + assert address is not None + assert len(address) > 0 + + # Can get the account and subaddress indices of an address + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_address_indices(self, wallet: MoneroWallet) -> None: + # get last subaddress to test + accounts: list[MoneroAccount] = wallet.get_accounts(True) + account_idx: int = len(accounts) - 1 + subaddress_idx: int = len(accounts[account_idx].subaddresses) - 1 + address: str = wallet.get_address(account_idx, subaddress_idx) + assert address is not None + assert len(address) > 0 + + # get address index + subaddress: MoneroSubaddress = wallet.get_address_index(address) + assert account_idx == subaddress.account_index + assert subaddress_idx == subaddress.index + + # test valid but unfound address + non_wallet_address: str = WalletTestUtils.get_external_wallet_address() + with pytest.raises(Exception) as exc_info: + wallet.get_address_index(non_wallet_address) + assert str(exc_info.value) == "Address doesn't belong to the wallet" + + # test invalid address + with pytest.raises(Exception) as exc_info: + wallet.get_address_index("this is definitely not an address") + WalletErrorUtils.test_invalid_address_error(exc_info.value) + + # Can decode an integrated address + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_decode_integrated_address(self, wallet: MoneroWallet) -> None: + integrated_address: MoneroIntegratedAddress = wallet.get_integrated_address('', "03284e41c342f036") + decoded_address: MoneroIntegratedAddress = wallet.decode_integrated_address(integrated_address.integrated_address) + AssertUtils.assert_equals(integrated_address, decoded_address) + + # decode invalid address + with pytest.raises(Exception) as exc_info: + wallet.decode_integrated_address("bad address") + WalletErrorUtils.test_invalid_address_error(exc_info.value) + + # decode invalid payment id + with pytest.raises(Exception) as exc_info: + wallet.get_integrated_address(wallet.get_primary_address(), "invalid payment id") + assert str(exc_info.value) == "Invalid payment ID: invalid payment id" + + # Can sign and verify messages + # TODO test with view-only wallet + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_sign_and_verify_messages(self, wallet: MoneroWallet) -> None: + msg: str = "This is a super important message which needs to be signed and verified." + subaddress1: MoneroSubaddress = MoneroSubaddress() + subaddress1.account_index = 0 + subaddress1.index = 0 + subaddress2: MoneroSubaddress = MoneroSubaddress() + subaddress2.account_index = 0 + subaddress2.index = 1 + subaddress3: MoneroSubaddress = MoneroSubaddress() + subaddress3.account_index = 1 + subaddress3.index = 0 + subaddresses: list[MoneroSubaddress] = [subaddress1, subaddress2, subaddress3] + + # test signing message with subaddresses + for subaddress in subaddresses: + assert subaddress.account_index is not None + assert subaddress.index is not None + account_idx: int = subaddress.account_index + idx: int = subaddress.index + + # sign and verify message with spend key + signature: str = wallet.sign_message(msg, MoneroMessageSignatureType.SIGN_WITH_SPEND_KEY, account_idx, idx) + result: MoneroMessageSignatureResult = wallet.verify_message(msg, wallet.get_address(account_idx, idx), signature) + WalletUtils.test_message_signature_result(result, True) + assert result.signature_type == MoneroMessageSignatureType.SIGN_WITH_SPEND_KEY + + # verify message with incorrect address + result = wallet.verify_message(msg, wallet.get_address(0, 2), signature) + WalletUtils.test_message_signature_result(result, False) + + # verify message with invalid address + result = wallet.verify_message(msg, "invalid address", signature) + WalletUtils.test_message_signature_result(result, False) + + # verify message with external address + result = wallet.verify_message(msg, WalletTestUtils.get_external_wallet_address(), signature) + WalletUtils.test_message_signature_result(result, False) + + # sign and verify message with view key + signature = wallet.sign_message(msg, MoneroMessageSignatureType.SIGN_WITH_VIEW_KEY, account_idx, idx) + result = wallet.verify_message(msg, wallet.get_address(account_idx, idx), signature) + WalletUtils.test_message_signature_result(result, True) + assert result.signature_type == MoneroMessageSignatureType.SIGN_WITH_VIEW_KEY + + # verify message with incorrect address + result = wallet.verify_message(msg, wallet.get_address(0, 2), signature) + WalletUtils.test_message_signature_result(result, False) + + # verify message with invalid address + result = wallet.verify_message(msg, "invalid address", signature) + WalletUtils.test_message_signature_result(result, False) + + # verify message with external address + result = wallet.verify_message(msg, WalletTestUtils.get_external_wallet_address(), signature) + WalletUtils.test_message_signature_result(result, False) + + # Can convert between a tx config and payment URI + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_payment_uri(self, wallet: MoneroWallet) -> None: + # test with address and amount + config1: MoneroTxConfig = MoneroTxConfig() + dest: MoneroDestination = MoneroDestination() + dest.address = wallet.get_address(0, 0) + dest.amount = 0 + config1.destinations.append(dest) + uri: str = wallet.get_payment_uri(config1) + config2: MoneroTxConfig = wallet.parse_payment_uri(uri) + AssertUtils.assert_equals(config1, config2) + + # test with subaddress and all fields + subaddress: MoneroSubaddress = wallet.get_subaddress(0, 1) + assert subaddress.address is not None + config1.destinations[0].address = subaddress.address + config1.destinations[0].amount = 425000000000 + config1.recipient_name = "John Doe" + config1.note = "OMZG XMR FTW" + uri = wallet.get_payment_uri(config1) + config2 = wallet.parse_payment_uri(uri) + AssertUtils.assert_equals(config1, config2) + + # test with undefined address + address: str | None = config1.destinations[0].address + config1.destinations[0].address = None + with pytest.raises(Exception, match="Cannot make URI from supplied parameters"): + wallet.get_payment_uri(config1) + + config1.destinations[0].address = address + + # test with standalone payment id + config1.payment_id = "03284e41c342f03603284e41c342f03603284e41c342f03603284e41c342f036" + with pytest.raises(Exception, match="Cannot make URI from supplied parameters"): + wallet.get_payment_uri(config1) + + +@pytest.mark.integration +class TestMoneroWalletFullKeysAndAddresses(FullWalletSupport, BaseTestMoneroWalletKeysAndAddresses): + """Full wallet keys and addresses integration tests.""" + + +@pytest.mark.integration +class TestMoneroWalletRpcKeysAndAddresses(RpcWalletSupport, BaseTestMoneroWalletKeysAndAddresses): + """Rpc wallet keys and addresses integration tests.""" + + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + @override + def test_get_subaddress_address_out_of_range(self, wallet: MoneroWallet) -> None: + accounts: list[MoneroAccount] = wallet.get_accounts(True) + account_idx: int = len(accounts) - 1 + subaddress_idx: int = len(accounts[account_idx].subaddresses) + address: str = wallet.get_address(account_idx, subaddress_idx) + assert address is None or len(address) == 0 + + @pytest.mark.not_supported + @override + def test_get_seed_language(self, wallet: MoneroWallet) -> None: + return super().test_get_seed_language(wallet) + + @pytest.mark.xfail(reason="TODO monero-project") + @override + def test_get_public_view_key(self, wallet: MoneroWallet) -> None: + return super().test_get_public_view_key(wallet) + + @pytest.mark.xfail(reason="TODO monero-project") + @override + def test_get_public_spend_key(self, wallet: MoneroWallet) -> None: + return super().test_get_public_spend_key(wallet) + + +@pytest.mark.unit +class TestMoneroWalletKeysKeysAndAddresses(KeysWalletSupport, BaseTestMoneroWalletKeysAndAddresses): + """Keys-only wallet keys and addresses unit tests.""" + + @pytest.mark.not_supported + @override + def test_get_address_indices(self, wallet: MoneroWallet) -> None: + return super().test_get_address_indices(wallet) + + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + @override + def test_get_subaddress_address(self, wallet: MoneroWallet) -> None: + assert wallet.get_primary_address() == (wallet.get_address(0, 0)) + accounts: list[MoneroAccount] = self._get_test_accounts(wallet, True) + + for account in accounts: + assert account is not None + assert account.index is not None + assert account.primary_address is not None + MoneroUtils.validate_address(account.primary_address, Utils.NETWORK_TYPE) + + for subaddress in account.subaddresses: + assert subaddress is not None + assert subaddress.index is not None + assert subaddress.address == wallet.get_address(account.index, subaddress.index) + + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + @override + def test_get_subaddress_address_out_of_range(self, wallet: MoneroWallet) -> None: + accounts: list[MoneroAccount] = self._get_test_accounts(wallet, True) + account_idx: int = len(accounts) - 1 + subaddress_idx: int = len(accounts[account_idx].subaddresses) + address: str = wallet.get_address(account_idx, subaddress_idx) + assert address is not None + assert len(address) > 0 + + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_integrated_address_with_empty_standard_address(self) -> None: + """An empty standard_address uses the wallet's own primary address (account 0, subaddress 0).""" + config: MoneroWalletConfig = MoneroWalletConfig() + config.network_type = Utils.NETWORK_TYPE + w: MoneroWalletKeys = MoneroWalletKeys.create_wallet_random(config) + try: + integrated: MoneroIntegratedAddress = w.get_integrated_address("", "a" * 16) + assert integrated.standard_address == w.get_primary_address() + assert integrated.payment_id == "a" * 16 + finally: + w.close() + + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_integrated_address_with_standard_address(self) -> None: + config: MoneroWalletConfig = MoneroWalletConfig() + config.network_type = Utils.NETWORK_TYPE + w: MoneroWalletKeys = MoneroWalletKeys.create_wallet_random(config) + try: + address: str = w.get_primary_address() + integrated: MoneroIntegratedAddress = w.get_integrated_address(address, "b" * 16) + assert integrated.standard_address == address + assert integrated.payment_id == "b" * 16 + finally: + w.close() + + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_integrated_address_invalid_address_raises(self) -> None: + config: MoneroWalletConfig = MoneroWalletConfig() + config.network_type = Utils.NETWORK_TYPE + w: MoneroWalletKeys = MoneroWalletKeys.create_wallet_random(config) + try: + with pytest.raises(RuntimeError, match="Invalid address"): + w.get_integrated_address("notanaddress", "a" * 16) + finally: + w.close() + + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_integrated_address_subaddress_raises(self) -> None: + config: MoneroWalletConfig = MoneroWalletConfig() + config.network_type = Utils.NETWORK_TYPE + w: MoneroWalletKeys = MoneroWalletKeys.create_wallet_random(config) + try: + subaddress: str = w.get_address(1, 1) + with pytest.raises(RuntimeError, match="Subaddress shouldn't be used"): + w.get_integrated_address(subaddress, "a" * 16) + finally: + w.close() + + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_integrated_address_already_integrated_raises(self) -> None: + config: MoneroWalletConfig = MoneroWalletConfig() + config.network_type = Utils.NETWORK_TYPE + w: MoneroWalletKeys = MoneroWalletKeys.create_wallet_random(config) + try: + integrated: str = w.get_integrated_address("", "a" * 16).integrated_address + with pytest.raises(RuntimeError, match="Already integrated address"): + w.get_integrated_address(integrated, "a" * 16) + finally: + w.close() + + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_integrated_address_missing_payment_id_raises(self) -> None: + config: MoneroWalletConfig = MoneroWalletConfig() + config.network_type = Utils.NETWORK_TYPE + w: MoneroWalletKeys = MoneroWalletKeys.create_wallet_random(config) + try: + with pytest.raises(RuntimeError, match="Payment ID shouldn't be left unspecified"): + w.get_integrated_address(w.get_primary_address(), "") + finally: + w.close() + + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_sign_message_invalid_signature_type_base_address_raises(self) -> None: + config: MoneroWalletConfig = MoneroWalletConfig() + config.network_type = Utils.NETWORK_TYPE + w: MoneroWalletKeys = MoneroWalletKeys.create_wallet_random(config) + try: + invalid_type: MoneroMessageSignatureType = MoneroMessageSignatureType(99) # type: ignore + with pytest.raises(RuntimeError, match="Invalid signature type requested"): + w.sign_message("hello", invalid_type, 0, 0) + finally: + w.close() + + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_sign_message_invalid_signature_type_subaddress_raises(self) -> None: + config: MoneroWalletConfig = MoneroWalletConfig() + config.network_type = Utils.NETWORK_TYPE + w: MoneroWalletKeys = MoneroWalletKeys.create_wallet_random(config) + try: + invalid_type: MoneroMessageSignatureType = MoneroMessageSignatureType(99) # type: ignore + with pytest.raises(RuntimeError, match="Invalid signature type requested"): + w.sign_message("hello", invalid_type, 1, 1) + finally: + w.close() + + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_verify_message_no_signature_header(self) -> None: + config: MoneroWalletConfig = MoneroWalletConfig() + config.network_type = Utils.NETWORK_TYPE + w: MoneroWalletKeys = MoneroWalletKeys.create_wallet_random(config) + try: + result: MoneroMessageSignatureResult = w.verify_message("hello", w.get_primary_address(), "not-a-signature") + WalletUtils.test_message_signature_result(result, False) + finally: + w.close() + + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_verify_message_invalid_base58(self) -> None: + config: MoneroWalletConfig = MoneroWalletConfig() + config.network_type = Utils.NETWORK_TYPE + w: MoneroWalletKeys = MoneroWalletKeys.create_wallet_random(config) + try: + result: MoneroMessageSignatureResult = w.verify_message("hello", w.get_primary_address(), "SigV2!!!not-base58!!!") + WalletUtils.test_message_signature_result(result, False) + finally: + w.close() + + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_verify_message_wrong_decoded_size(self) -> None: + config: MoneroWalletConfig = MoneroWalletConfig() + config.network_type = Utils.NETWORK_TYPE + w: MoneroWalletKeys = MoneroWalletKeys.create_wallet_random(config) + try: + address: str = w.get_primary_address() + signature: str = w.sign_message("hello", MoneroMessageSignatureType.SIGN_WITH_SPEND_KEY, 0, 0) + # truncate the base58 payload so it decodes to fewer bytes than crypto::signature expects + truncated: str = signature[:5] + signature[5:-10] + result: MoneroMessageSignatureResult = w.verify_message("hello", address, truncated) + WalletUtils.test_message_signature_result(result, False) + finally: + w.close() diff --git a/tests/wallet/test_listener_lifetime.py b/tests/wallet/test_listener_lifetime.py new file mode 100644 index 00000000..c5a28151 --- /dev/null +++ b/tests/wallet/test_listener_lifetime.py @@ -0,0 +1,35 @@ +from __future__ import annotations + +import gc +import weakref + +import pytest +from monero import MoneroWalletFull, MoneroWalletListener + +from utils import BaseTestClass, TestUtils as Utils + + +@pytest.mark.unit +class TestMoneroWalletListenerLifetime(BaseTestClass): + """A listener that Python does not reference any more must stay alive while the wallet has it, as the threads of the wallet call it.""" + + #region Tests + + # The wallet keeps its listener alive + def test_wallet_keeps_its_listener_alive(self) -> None: + wallet: MoneroWalletFull = Utils.get_wallet_full_offline() + listener: MoneroWalletListener = MoneroWalletListener() + listener_ref: weakref.ref[MoneroWalletListener] = weakref.ref(listener) + wallet.add_listener(listener) + try: + del listener + gc.collect() + assert listener_ref() is not None, "The wallet does not keep alive its listener" + assert len(wallet.get_listeners()) == 1 + finally: + listener_back: MoneroWalletListener | None = listener_ref() + if listener_back is not None: + wallet.remove_listener(listener_back) + assert len(wallet.get_listeners()) == 0 + + #endregion diff --git a/tests/wallet/test_listeners.py b/tests/wallet/test_listeners.py new file mode 100644 index 00000000..e60297d8 --- /dev/null +++ b/tests/wallet/test_listeners.py @@ -0,0 +1,110 @@ +from __future__ import annotations + +import logging +from time import monotonic, sleep + +import pytest +from monero import MoneroDaemonRpc, MoneroTxConfig, MoneroTxWallet, MoneroWallet, MoneroWalletConfig +from typing_extensions import override + +from utils import MiningUtils, TestUtils, TxWalletUtils, WalletNotificationCollector +from .base_test_monero_wallet import BaseTestMoneroWallet +from .wallet_support import FullWalletSupport, RpcWalletSupport, KeysWalletSupport + +logger: logging.Logger = logging.getLogger("TestMoneroWalletListeners") + + +class BaseTestMoneroWalletListeners(BaseTestMoneroWallet): + """Common wallet listeners tests.""" + + # Can stop listening + @pytest.mark.skipif(TestUtils.TEST_NOTIFICATIONS is False, reason="TEST_NOTIFICATIONS disabled") + def test_stop_listening(self) -> None: + # create wallet and start background synchronizing + wallet: MoneroWallet = self._create_wallet(MoneroWalletConfig()) + + # add listener + listener: WalletNotificationCollector = WalletNotificationCollector() + wallet.add_listener(listener) + assert len(wallet.get_listeners()) == 1 + sleep(1) + + # remove listener and close + wallet.remove_listener(listener) + assert len(wallet.get_listeners()) == 0 + self._close_wallet(wallet) + + # Can be created and receive funds + # TODO this test is flaky on monero-wallet-rpc because of mining speed + @pytest.mark.skipif(TestUtils.TEST_NOTIFICATIONS is False, reason="TEST_NOTIFICATIONS disabled") + @pytest.mark.flaky(reruns=5, reruns_delay=10, only_rerun=[]) + def test_create_and_receive(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: + # create random wallet + receiver: MoneroWallet = self._create_wallet(MoneroWalletConfig()) + try: + # listen for received funds + my_listener: WalletNotificationCollector = WalletNotificationCollector() + receiver.add_listener(my_listener) + assert len(receiver.get_listeners()) > 0 + + # wait for txs to confirm and for sufficient unlocked balance + TestUtils.WALLET_TX_TRACKER.wait_for_txs_to_clear_pool(wallet) + TestUtils.WALLET_TX_TRACKER.wait_for_unlocked_balance(wallet, 0, None, TxWalletUtils.MAX_FEE) + + # send funds to the receiver + tx_config: MoneroTxConfig = MoneroTxConfig() + tx_config.account_index = 0 + tx_config.address = receiver.get_primary_address() + tx_config.amount = TxWalletUtils.MAX_FEE + tx_config.relay = True + sent_tx: MoneroTxWallet = wallet.create_tx(tx_config) + assert sent_tx.hash is not None + + # wait for funds to confirm + MiningUtils.try_start_mining() + while True: + tx: MoneroTxWallet | None = wallet.get_tx(sent_tx.hash) + assert tx is not None + assert tx.is_confirmed is not None + if tx.is_confirmed: + logger.debug(f"Confirmed tx at height {tx.get_height()}") + break + + assert tx.is_failed is False, f"Tx failed in mempool: {tx.hash}" + daemon.wait_for_next_block_header() + + # receiver should notify listeners of received outputs within a few rpc refresh / poll periods + deadline: float = monotonic() + TestUtils.SYNC_PERIOD_IN_MS * 10 / 1000 + while len(my_listener.outputs_received) == 0 and monotonic() < deadline: + sleep(1) + assert len(my_listener.outputs_received) > 0 + finally: + logger.debug(f"Closing receiver wallet...") + self._close_wallet(receiver) + logger.debug(f"Closed receiver wallet") + MiningUtils.try_stop_mining() + + +@pytest.mark.integration +class TestMoneroWalletFullListeners(FullWalletSupport, BaseTestMoneroWalletListeners): + """Full wallet listeners integration tests.""" + + +@pytest.mark.integration +class TestMoneroWalletRpcListeners(RpcWalletSupport, BaseTestMoneroWalletListeners): + """Rpc wallet listeners integration tests.""" + + +@pytest.mark.unit +class TestMoneroWalletKeysListeners(KeysWalletSupport, BaseTestMoneroWalletListeners): + """Keys-only wallet listeners unit tests.""" + + @pytest.mark.not_supported + @override + def test_stop_listening(self) -> None: + return super().test_stop_listening() + + @pytest.mark.not_supported + @override + def test_create_and_receive(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: + return super().test_create_and_receive(daemon, wallet) diff --git a/tests/wallet/test_mining.py b/tests/wallet/test_mining.py new file mode 100644 index 00000000..bb62db52 --- /dev/null +++ b/tests/wallet/test_mining.py @@ -0,0 +1,46 @@ +from __future__ import annotations + +import logging + +import pytest +from monero import MoneroDaemonRpc, MoneroMiningStatus, MoneroWallet +from typing_extensions import override + +from utils import TestUtils +from .base_test_monero_wallet import BaseTestMoneroWallet +from .wallet_support import FullWalletSupport, RpcWalletSupport, KeysWalletSupport + +logger: logging.Logger = logging.getLogger("TestMoneroWalletMining") + + +class BaseTestMoneroWalletMining(BaseTestMoneroWallet): + """Common wallet mining tests.""" + + # Can start and stop mining + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_mining(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: + status: MoneroMiningStatus = daemon.get_mining_status() + if status.is_active: + wallet.stop_mining() + wallet.start_mining(1, False, True) + wallet.stop_mining() + + +@pytest.mark.integration +class TestMoneroWalletFullMining(FullWalletSupport, BaseTestMoneroWalletMining): + """Full wallet mining integration tests.""" + + +@pytest.mark.integration +class TestMoneroWalletRpcMining(RpcWalletSupport, BaseTestMoneroWalletMining): + """Rpc wallet mining integration tests.""" + + +@pytest.mark.unit +class TestMoneroWalletKeysMining(KeysWalletSupport, BaseTestMoneroWalletMining): + """Keys-only wallet mining unit tests.""" + + @pytest.mark.not_supported + @override + def test_mining(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: + return super().test_mining(daemon, wallet) diff --git a/tests/wallet/test_multisig.py b/tests/wallet/test_multisig.py new file mode 100644 index 00000000..91cbc1b6 --- /dev/null +++ b/tests/wallet/test_multisig.py @@ -0,0 +1,59 @@ +from __future__ import annotations + +import logging + +import pytest +from monero import MoneroWallet +from typing_extensions import override + +from utils import TestUtils, TestUtils as Utils +from .base_test_monero_wallet import BaseTestMoneroWallet +from .wallet_support import FullWalletSupport, RpcWalletSupport, KeysWalletSupport + +logger: logging.Logger = logging.getLogger("TestMoneroWalletMultisig") + + +class BaseTestMoneroWalletMultisig(BaseTestMoneroWallet): + """Common wallet multisig tests.""" + + # Can indicate if multisig import is needed for correct balance information + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_is_multisig_needed(self, wallet: MoneroWallet) -> None: + # TODO test with multisig wallet + multisig_import_needed: bool = wallet.is_multisig_import_needed() + assert multisig_import_needed is False, "Expected non-multisig wallet" + + +@pytest.mark.integration +class TestMoneroWalletFullMultisig(FullWalletSupport, BaseTestMoneroWalletMultisig): + """Full wallet multisig integration tests.""" + + # Supports multisig sample code + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_multisig_sample(self) -> None: + self._test_multisig_sample(1, 2) + self._test_multisig_sample(1, 4) + self._test_multisig_sample(2, 2) + self._test_multisig_sample(2, 3) + self._test_multisig_sample(2, 4) + + +@pytest.mark.integration +class TestMoneroWalletRpcMultisig(RpcWalletSupport, BaseTestMoneroWalletMultisig): + """Rpc wallet multisig integration tests.""" + + # Supports multisig sample code + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_multisig_sample(self) -> None: + self._test_multisig_sample(1, 2) + self._test_multisig_sample(2, 2) + + +@pytest.mark.unit +class TestMoneroWalletKeysMultisig(KeysWalletSupport, BaseTestMoneroWalletMultisig): + """Keys-only wallet multisig unit tests.""" + + @pytest.mark.not_supported + @override + def test_is_multisig_needed(self, wallet: MoneroWallet) -> None: + return super().test_is_multisig_needed(wallet) diff --git a/tests/wallet/test_outputs.py b/tests/wallet/test_outputs.py new file mode 100644 index 00000000..007c22fd --- /dev/null +++ b/tests/wallet/test_outputs.py @@ -0,0 +1,600 @@ +from __future__ import annotations + +import logging +from typing import Optional + +import pytest +from monero import ( + MoneroAccount, + MoneroDestination, + MoneroKeyImage, + MoneroKeyImageExportResult, + MoneroKeyImageImportResult, + MoneroOutputQuery, + MoneroOutputWallet, + MoneroSubaddress, + MoneroTx, + MoneroTxConfig, + MoneroTxQuery, + MoneroTxWallet, + MoneroWallet, +) +from typing_extensions import override + +from utils import GenUtils, OutputUtils, TestUtils, TxWalletUtils, WalletTestUtils, WalletTxsUtils +from .base_test_monero_wallet import BaseTestMoneroWallet +from .wallet_support import FullWalletSupport, RpcWalletSupport, KeysWalletSupport + +logger: logging.Logger = logging.getLogger("TestMoneroWalletOutputs") + + +class BaseTestMoneroWalletOutputs(BaseTestMoneroWallet): + """Common wallet outputs tests.""" + + # Can get outputs in the wallet, accounts, and subaddresses + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_outputs(self, wallet: MoneroWallet) -> None: + # get all outputs + OutputUtils.get_and_test_outputs(wallet, None, True) + + # get outputs for each account + non_default_incoming: bool = False + accounts: list[MoneroAccount] = wallet.get_accounts(True) + for account in accounts: + # determine if account is used + is_used: bool = False + for subaddress in account.subaddresses: + if subaddress.is_used is True: + is_used = True + break + + # get outputs by account index + output_query: MoneroOutputQuery = MoneroOutputQuery() + output_query.account_index = account.index + account_outputs: list[MoneroOutputWallet] = OutputUtils.get_and_test_outputs(wallet, output_query, is_used) + for ouput in account_outputs: + assert ouput.account_index == account.index + + # get outputs by subaddress index + subaddress_outputs: list[MoneroOutputWallet] = [] + for subaddress in account.subaddresses: + subaddr_query: MoneroOutputQuery = MoneroOutputQuery() + subaddr_query.account_index = account.index + subaddr_query.subaddress_index = subaddress.index + outputs: list[MoneroOutputWallet] = OutputUtils.get_and_test_outputs(wallet, subaddr_query, subaddress.is_used) + for output in outputs: + assert subaddress.account_index == output.account_index + assert subaddress.index == output.subaddress_index + if output.account_index != 0 and output.subaddress_index != 0: + non_default_incoming = True + subaddress_outputs.append(output) + + assert len(subaddress_outputs) == len(account_outputs) + + # get outputs by subaddress indices + subaddress_indices: set[int] = set() + for output in subaddress_outputs: + assert output.subaddress_index is not None + subaddress_indices.add(output.subaddress_index) + + output_query = MoneroOutputQuery() + output_query.account_index = account.index + for sub_idx in subaddress_indices: + output_query.subaddress_indices.append(sub_idx) + + outputs = OutputUtils.get_and_test_outputs(wallet, output_query, is_used) + assert len(outputs) == len(subaddress_outputs) + + for output in outputs: + assert account.index == output.account_index + assert output.subaddress_index is not None + assert output.subaddress_index in subaddress_indices + + # ensure output found with non-zero account and subaddress indices + assert non_default_incoming, "No outputs found in non-default account and subaddress; run send-to-multiple tests" + + # Can get outputs with additional configuration + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_outputs_with_query(self, wallet: MoneroWallet) -> None: + # get unspent outputs to account 0 + output_query: MoneroOutputQuery = MoneroOutputQuery() + output_query.account_index = 0 + output_query.is_spent = False + outputs: list[MoneroOutputWallet] = OutputUtils.get_and_test_outputs(wallet, output_query, None) + + for output in outputs: + assert output.account_index == 0 + assert output.is_spent is False + + # get spent outputs to account 1 + output_query = MoneroOutputQuery() + output_query.account_index = 1 + output_query.is_spent = True + outputs = OutputUtils.get_and_test_outputs(wallet, output_query, True) + + for output in outputs: + assert output.account_index == 1 + assert output.is_spent is True + + # get random transactions + tx_query: MoneroTxQuery = MoneroTxQuery() + tx_query.is_confirmed = True + txs: list[MoneroTxWallet] = WalletTxsUtils.get_random_transactions(wallet, tx_query, 3, 5) + + # get outputs with a tx hash + tx_hashes: list[str] = [] + for tx in txs: + assert tx.hash is not None + tx_hashes.append(tx.hash) + output_query = MoneroOutputQuery() + output_query.set_tx_query(MoneroTxQuery(), True) + assert output_query.tx_query is not None + output_query.tx_query.hash = tx.hash + outputs = OutputUtils.get_and_test_outputs(wallet, output_query, True) + + for output in outputs: + assert output.tx is not None + assert output.tx.hash is not None + assert output.tx.hash in tx_hashes + + # get outputs with tx hashes + tx_query = MoneroTxQuery() + tx_query.hashes = tx_hashes + output_query = MoneroOutputQuery() + output_query.set_tx_query(tx_query, True) + outputs = OutputUtils.get_and_test_outputs(wallet, output_query, True) + + for output in outputs: + assert output.tx is not None + assert output.tx.hash is not None + assert output.tx.hash in tx_hashes + + # get confirmed outputs to specifi subaddress with pre-built query + account_idx: int = 0 + subaddress_idx: int = 1 + output_query = MoneroOutputQuery() + output_query.account_index = account_idx + output_query.subaddress_index = subaddress_idx + tx_query = MoneroTxQuery() + tx_query.is_confirmed = True + output_query.set_tx_query(tx_query, True) + output_query.min_amount = TxWalletUtils.MAX_FEE + outputs = OutputUtils.get_and_test_outputs(wallet, output_query, True) + + for output in outputs: + assert output.account_index == account_idx + assert output.subaddress_index == subaddress_idx + assert output.tx is not None + assert output.tx.is_confirmed is True + assert output.amount is not None + assert output.amount >= TxWalletUtils.MAX_FEE + + # get output by key image + output: MoneroOutputWallet = outputs[0] + assert output.key_image is not None + assert output.key_image.hex is not None + output_query = MoneroOutputQuery() + output_query.key_image = MoneroKeyImage() + output_query.key_image.hex = output.key_image.hex + outputs = wallet.get_outputs(output_query) + assert len(outputs) == 1 + output_result: MoneroOutputWallet = outputs[0] + assert output_result.key_image is not None + assert output.key_image.hex == output_result.key_image.hex + + # get outputs whose transaction is confirmed and has incoming and outgoing transfers + output_query = MoneroOutputQuery() + tx_query = MoneroTxQuery() + tx_query.is_confirmed = True + tx_query.is_incoming = True + tx_query.is_outgoing = True + tx_query.include_outputs = True + output_query.set_tx_query(tx_query, True) + outputs = wallet.get_outputs(output_query) + assert len(outputs) > 0 + + for output in outputs: + assert output.tx is not None + assert isinstance(output.tx, MoneroTxWallet) + assert output.tx.is_incoming is True + assert output.tx.is_outgoing is True + assert output.tx.is_confirmed is True + outputs_wallet: list[MoneroOutputWallet] = output.tx.get_outputs_wallet() + assert len(outputs_wallet) > 0 + assert output in outputs_wallet + + # Validates inputs when getting wallet outputs + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False or TestUtils.LITE_MODE, reason="TEST_NON_RELAYS disabled or LITE_MODE enabled") + def test_validate_inputs_get_outputs(self, wallet: MoneroWallet) -> None: + # test with invalid hash + output_query: MoneroOutputQuery = MoneroOutputQuery() + output_query.set_tx_query(MoneroTxQuery(), True) + assert output_query.tx_query is not None + output_query.tx_query.hash = "invalid_id" + + outputs: list[MoneroOutputWallet] = wallet.get_outputs(output_query) + assert len(outputs) == 0 + + # test invalid hash in list + tx_query: MoneroTxQuery = MoneroTxQuery() + tx_query.is_confirmed = True + tx_query.include_outputs = True + random_txs: list[MoneroTxWallet] = WalletTxsUtils.get_random_transactions(wallet, tx_query, 3, 5) + + for random_tx in random_txs: + assert len(random_tx.outputs) > 0 + + output_query = MoneroOutputQuery() + output_query.set_tx_query(MoneroTxQuery(), False) + assert output_query.tx_query is not None + random_hash: str | None = random_txs[0].hash + assert random_hash is not None and len(random_hash) > 0 + output_query.tx_query.hashes = [random_hash, "invalid_id"] + + outputs = wallet.get_outputs(output_query) + assert len(outputs) > 0 + assert len(outputs) == len(random_txs[0].outputs) + + tx: MoneroTx = outputs[0].tx + assert isinstance(tx, MoneroTxWallet) + + for output in outputs: + assert output.tx == tx + + # Can export outputs in hex format + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False or TestUtils.LITE_MODE, reason="TEST_NON_RELAYS disabled") + def test_export_outputs(self, wallet: MoneroWallet) -> None: + outputs_hex: str = wallet.export_outputs() + logger.debug(f"Exported outputs hex: {outputs_hex}") + # TODO: this will fail if wallet has no outputs; run these tests on new wallet + assert outputs_hex is not None and len(outputs_hex) > 0 + + # wallet exports outputs since last export by default + outputs_hex = wallet.export_outputs() + outputs_hex_all: str = wallet.export_outputs(True) + assert len(outputs_hex_all) > len(outputs_hex) + + # Can import outputs in hex format + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False or TestUtils.LITE_MODE, reason="TEST_NON_RELAYS disabled") + def test_import_outputs(self, wallet: MoneroWallet) -> None: + # export outputs hex + outputs_hex: str = wallet.export_outputs() + logger.debug(f"Exported outputs hex {outputs_hex}") + # import outputs hex + if len(outputs_hex) > 0: + num_imported: int = wallet.import_outputs(outputs_hex) + assert num_imported >= 0 + + # Can freeze and thaw outputs + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_freeze_outputs(self, wallet: MoneroWallet) -> None: + # get an available output + output_query: MoneroOutputQuery = MoneroOutputQuery() + output_query.is_spent = False + output_query.is_frozen = False + output_query.set_tx_query(MoneroTxQuery(), True) + assert output_query.tx_query is not None + output_query.tx_query.is_locked = False + outputs: list[MoneroOutputWallet] = wallet.get_outputs(output_query) + assert len(outputs) > 0 + for output in outputs: + assert output.is_frozen is False + + output: MoneroOutputWallet = outputs[0] + assert output.tx is not None + assert isinstance(output.tx, MoneroTxWallet) + assert output.tx.is_locked is False + assert output.is_spent is False + assert output.is_frozen is False + assert output.key_image is not None + assert output.key_image.hex is not None + assert wallet.is_output_frozen(output.key_image.hex) is False + + # freeze output by key image + output_query = MoneroOutputQuery() + output_query.is_frozen = True + num_frozen_before: int = len(wallet.get_outputs(output_query)) + wallet.freeze_output(output.key_image.hex) + is_frozen: bool = wallet.is_output_frozen(output.key_image.hex) + assert is_frozen + + # test querying + frozen_outputs: list[MoneroOutputWallet] = wallet.get_outputs(output_query) + num_frozen: int = len(frozen_outputs) + assert num_frozen == num_frozen_before + 1 + output_query = MoneroOutputQuery() + output_query.key_image = MoneroKeyImage() + output_query.key_image.hex = output.key_image.hex + output_query.is_frozen = True + outputs = wallet.get_outputs(output_query) + assert len(outputs) == 1 + output_frozen: MoneroOutputWallet = outputs[0] + assert output_frozen.is_frozen is True + assert output_frozen.key_image is not None + assert output.key_image.hex == output_frozen.key_image.hex + + # try to sweep frozen output + tx_config: MoneroTxConfig = MoneroTxConfig() + tx_config.address = wallet.get_primary_address() + tx_config.key_image = output.key_image.hex + with pytest.raises(Exception) as exc_info: + wallet.sweep_output(tx_config) + assert str(exc_info.value) == "No outputs found" + + # try to freeze empty key image + with pytest.raises(Exception) as exc_info: + wallet.freeze_output("") + assert str(exc_info.value) == "Must specify key image to freeze" + + # try to freeze bad key image + with pytest.raises(Exception) as exc_info: + wallet.freeze_output("123") + assert str(exc_info.value) == "failed to parse key image" + + # thaw output by key image + wallet.thaw_output(output.key_image.hex) + is_frozen = wallet.is_output_frozen(output.key_image.hex) + assert is_frozen is False + + # test querying + output_query = MoneroOutputQuery() + output_query.is_frozen = True + assert num_frozen_before == len(wallet.get_outputs(output_query)) + + output_query = MoneroOutputQuery() + output_query.key_image = MoneroKeyImage() + output_query.key_image.hex = output.key_image.hex + output_query.is_frozen = True + outputs = wallet.get_outputs(output_query) + assert len(outputs) == 0 + + output_query.is_frozen = False + outputs = wallet.get_outputs(output_query) + assert len(outputs) == 1 + + output_thawed: MoneroOutputWallet = outputs[0] + assert output_thawed.is_frozen is False + assert output_thawed.key_image is not None + assert output_thawed.key_image.hex == output.key_image.hex + + # Provides key images of spent outputs + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_input_key_images(self, wallet: MoneroWallet) -> None: + # get subaddress to test input key images + subaddress: Optional[MoneroSubaddress] = WalletTestUtils.select_subaddress_with_min_balance(wallet, TxWalletUtils.MAX_FEE) + assert subaddress is not None, "No subaddress with outputs found for test input key images; fund wallet" + assert subaddress.account_index is not None + assert subaddress.index is not None + account_index: int = subaddress.account_index + subaddress_index: int = subaddress.index + + # test unrelayed single transaction + tx_config: MoneroTxConfig = MoneroTxConfig() + tx_config.account_index = account_index + tx_config.destinations.append(MoneroDestination(wallet.get_primary_address(), TxWalletUtils.MAX_FEE)) + spend_tx: MoneroTxWallet = wallet.create_tx(tx_config) + TxWalletUtils.test_spend_tx(spend_tx) + + # test unrelayed split transactions + txs: list[MoneroTxWallet] = wallet.create_txs(tx_config) + for tx in txs: + TxWalletUtils.test_spend_tx(tx) + + # test unrelayed sweep dust + dust_key_images: list[str] = [] + txs = wallet.sweep_dust(False) + for tx in txs: + TxWalletUtils.test_spend_tx(tx) + for tx_input in tx.inputs: + assert tx_input.key_image is not None + assert tx_input.key_image.hex is not None + dust_key_images.append(tx_input.key_image.hex) + + # get available outputs above min amount + output_query: MoneroOutputQuery = MoneroOutputQuery() + output_query.account_index = account_index + output_query.subaddress_index = subaddress_index + output_query.is_spent = False + output_query.is_frozen = False + output_query.min_amount = TxWalletUtils.MAX_FEE + output_query.set_tx_query(MoneroTxQuery(), True) + assert output_query.tx_query is not None + output_query.tx_query.is_locked = False + outputs: list[MoneroOutputWallet] = wallet.get_outputs(output_query) + + assert len(outputs) > 0, "No outputs found" + logger.debug(f"Found {len(outputs)} outputs") + + # filter dust outputs + dust_outputs: list[MoneroOutputWallet] = [] + for output in outputs: + assert output.key_image is not None + assert output.key_image.hex is not None + if output.key_image.hex in dust_key_images: + dust_outputs.append(output) + + logger.debug(f"Found {len(dust_outputs)} dust outputs") + + # remove dust outputs from outputs + outputs = list(filter(lambda output: output not in dust_outputs, outputs)) + + assert len(outputs) > 0, "No available outputs found" + logger.debug(f"Using {len(outputs)} available outputs") + + # test unrelayed sweep output + tx_config = MoneroTxConfig() + tx_config.address = wallet.get_primary_address() + output_key_image: MoneroKeyImage | None = outputs[0].key_image + assert output_key_image is not None + tx_config.key_image = output_key_image.hex + spend_tx = wallet.sweep_output(tx_config) + TxWalletUtils.test_spend_tx(spend_tx) + + # test unrelayed sweep wallet ensuring all non-dust outputs are spent + available_key_images: set[str] = set() + for output in outputs: + assert output.key_image is not None + assert output.key_image.hex is not None + available_key_images.add(output.key_image.hex) + swept_key_images: set[str] = set() + tx_config = MoneroTxConfig() + tx_config.account_index = account_index + tx_config.subaddress_indices.append(subaddress_index) + tx_config.address = wallet.get_primary_address() + txs = wallet.sweep_unlocked(tx_config) + + for tx in txs: + TxWalletUtils.test_spend_tx(tx) + for input_wallet in tx.inputs: + assert input_wallet.key_image is not None + assert input_wallet.key_image.hex is not None + swept_key_images.add(input_wallet.key_image.hex) + + assert len(swept_key_images) > 0 + + # max skipped output is less than max fee amount + max_skipped_output: Optional[MoneroOutputWallet] = None + for output in outputs: + assert output.key_image is not None + assert output.key_image.hex is not None + assert output.amount is not None + if output.key_image.hex not in swept_key_images: + if max_skipped_output is None or max_skipped_output.amount < output.amount: # type: ignore + max_skipped_output = output + + if max_skipped_output is not None: + assert max_skipped_output.amount is not None + assert max_skipped_output.amount < TxWalletUtils.MAX_FEE + + # Can export signed key images + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_export_key_images(self, wallet: MoneroWallet) -> None: + result: MoneroKeyImageExportResult = wallet.export_key_images(True) + assert len(result.key_images) > 0, "No signed key images in wallet" + + for image in result.key_images: + assert isinstance(image, MoneroKeyImage) + assert image.hex is not None and len(image.hex) > 0 + assert image.signature is not None and len(image.signature) > 0 + + # wallet exports key images since last export by default + images: MoneroKeyImageExportResult = wallet.export_key_images() + images_all: MoneroKeyImageExportResult = wallet.export_key_images(True) + assert len(images_all.key_images) > len(images.key_images) + + # Can get new key images from the last import + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_new_key_images_from_last_import(self, wallet: MoneroWallet) -> None: + # get outputs hex + outputs_hex: str = wallet.export_outputs() + + # import outputs hex + if outputs_hex != "": + num_imported: int = wallet.import_outputs(outputs_hex) + assert num_imported >= 0 + + # get and test new key images from last import + export_result: MoneroKeyImageExportResult = wallet.get_new_key_images_from_last_import() + if len(export_result.key_images) == 0: + pytest.skip("wallet already knows every output's key image; run after tests that generate new ones") + for image in export_result.key_images: + assert image.hex is not None and len(image.hex) > 0 + assert image.signature is not None and len(image.signature) > 0 + + # Can import key images + # TODO monero-project: importing key images can cause erasure of incoming transfers per wallet2.cpp:11957 + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_import_key_images(self, wallet: MoneroWallet) -> None: + export_result: MoneroKeyImageExportResult = wallet.export_key_images() + assert len(export_result.key_images) > 0, "Wallet does not have any key images run send tests" + result: MoneroKeyImageImportResult = wallet.import_key_images(export_result.key_images) + assert result.height is not None and result.height > 0 + + # determine if non-zero spent and unspent amounts are expected + query: MoneroTxQuery = MoneroTxQuery() + query.is_outgoing = True + query.is_confirmed = True + txs: list[MoneroTxWallet] = wallet.get_txs(query) + balance: int = wallet.get_balance() + has_spent: bool = len(txs) > 0 + has_unspent: bool = balance > 0 + + # test amounts + GenUtils.test_unsigned_big_integer(result.spent_amount, has_spent) + GenUtils.test_unsigned_big_integer(result.unspent_amount, has_unspent) + + +@pytest.mark.integration +class TestMoneroWalletFullOutputs(FullWalletSupport, BaseTestMoneroWalletOutputs): + """Full wallet outputs integration tests.""" + + @pytest.mark.skip(reason="TODO disabled because importing key images deletes corresponding incoming transfers: #5812") + @override + def test_import_key_images(self, wallet: MoneroWallet) -> None: + return super().test_import_key_images(wallet) + + +@pytest.mark.integration +class TestMoneroWalletRpcOutputs(RpcWalletSupport, BaseTestMoneroWalletOutputs): + """Rpc wallet outputs integration tests.""" + + @pytest.mark.skip(reason="TODO https://github.com/monero-project/monero/issues/5812") + @override + def test_import_key_images(self, wallet: MoneroWallet) -> None: + return super().test_import_key_images(wallet) + + +@pytest.mark.unit +class TestMoneroWalletKeysOutputs(KeysWalletSupport, BaseTestMoneroWalletOutputs): + """Keys-only wallet outputs unit tests.""" + + @pytest.mark.not_supported + @override + def test_get_outputs(self, wallet: MoneroWallet) -> None: + return super().test_get_outputs(wallet) + + @pytest.mark.not_supported + @override + def test_validate_inputs_get_outputs(self, wallet: MoneroWallet) -> None: + return super().test_validate_inputs_get_outputs(wallet) + + @pytest.mark.not_supported + @override + def test_export_key_images(self, wallet: MoneroWallet) -> None: + return super().test_export_key_images(wallet) + + @pytest.mark.not_supported + @override + def test_get_new_key_images_from_last_import(self, wallet: MoneroWallet) -> None: + return super().test_get_new_key_images_from_last_import(wallet) + + @pytest.mark.not_supported + @override + def test_import_key_images(self, wallet: MoneroWallet) -> None: + return super().test_import_key_images(wallet) + + @pytest.mark.not_supported + @override + def test_export_outputs(self, wallet: MoneroWallet) -> None: + return super().test_export_outputs(wallet) + + @pytest.mark.not_supported + @override + def test_import_outputs(self, wallet: MoneroWallet) -> None: + return super().test_import_outputs(wallet) + + @pytest.mark.not_supported + @override + def test_freeze_outputs(self, wallet: MoneroWallet) -> None: + return super().test_freeze_outputs(wallet) + + @pytest.mark.not_supported + @override + def test_get_outputs_with_query(self, wallet: MoneroWallet) -> None: + return super().test_get_outputs_with_query(wallet) + + @override + def test_input_key_images(self, wallet: MoneroWallet) -> None: + # a keys-only wallet cannot enumerate accounts/subaddresses, which this test needs + with pytest.raises(RuntimeError, match=r"get_accounts\(\) not supported"): + super().test_input_key_images(wallet) diff --git a/tests/wallet/test_pool.py b/tests/wallet/test_pool.py new file mode 100644 index 00000000..4c132ec1 --- /dev/null +++ b/tests/wallet/test_pool.py @@ -0,0 +1,182 @@ +from __future__ import annotations + +import logging + +import pytest +from monero import MoneroDaemonRpc, MoneroSubmitTxResult, MoneroTxConfig, MoneroTxWallet, MoneroWallet +from typing_extensions import override + +from utils import TestUtils, TxWalletUtils, WalletSendUtils +from .base_test_monero_wallet import BaseTestMoneroWallet +from .wallet_support import FullWalletSupport, RpcWalletSupport, KeysWalletSupport + +logger: logging.Logger = logging.getLogger("TestMoneroWalletPool") + + +class BaseTestMoneroWalletPool(BaseTestMoneroWallet): + """Common wallet pool tests.""" + + # Can sync with txs in the pool sent from/to the same account + # TODO this test fails because wallet does not recognize pool tx sent from/to same account + @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") + def test_sync_with_pool_same_accounts(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: + config: MoneroTxConfig = MoneroTxConfig() + config.account_index = 0 + config.address = wallet.get_primary_address() + config.amount = TxWalletUtils.MAX_FEE * 5 + config.relay = True + WalletSendUtils.test_sync_with_pool_submit(daemon, wallet, config) + + # Can sync with txs submitted and flushed from the pool + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_RELAYS disabled") + @pytest.mark.skipif(TestUtils.LITE_MODE, reason="LITE_MODE enabled") + @pytest.mark.skipif(TestUtils.CI, reason="CI is too slow to catchup failed txs (see wallet2::process_unconfirmed_transfer)") + def test_sync_with_pool_submit_and_flush(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: + logger.warning("This test takes at least 500 seconds (~8 minutes) to catchup failed txs (see wallet2::process_unconfirmed_transfer).") + config: MoneroTxConfig = MoneroTxConfig() + config.account_index = 2 + config.address = wallet.get_primary_address() + config.amount = TxWalletUtils.MAX_FEE * 5 + config.relay = False + WalletSendUtils.test_sync_with_pool_submit(daemon, wallet, config) + + # Can sync with txs submitted and relayed from the pool + @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") + @pytest.mark.skipif(TestUtils.LITE_MODE, reason="LITE_MODE enabled") + def test_sync_with_pool_submit_and_relay(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: + config: MoneroTxConfig = MoneroTxConfig() + config.account_index = 2 + config.address = wallet.get_primary_address() + config.amount = TxWalletUtils.MAX_FEE * 5 + config.relay = True + WalletSendUtils.test_sync_with_pool_submit(daemon, wallet, config) + + # can sync with txs relayed to the pool + @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") + @pytest.mark.skipif(TestUtils.LITE_MODE, reason="LITE_MODE enabled") + def test_sync_with_pool_relay(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: + # wait one time for wallet txs in the pool to clear + TestUtils.WALLET_TX_TRACKER.wait_for_txs_to_clear_pool(wallet) + + # record wallet balances before submitting tx to pool + balance_before: int = wallet.get_balance() + unlocked_balance_before: int = wallet.get_unlocked_balance() + + # create config + config: MoneroTxConfig = MoneroTxConfig() + config.account_index = 2 + config.address = wallet.get_primary_address() + config.amount = TxWalletUtils.MAX_FEE * 5 + + # create tx to relay + tx: MoneroTxWallet = wallet.create_tx(config) + assert tx.hash is not None + assert tx.full_hex is not None + assert tx.fee is not None + + # create another tx using same config which would be double spend + tx_double_spend: MoneroTxWallet = wallet.create_tx(config) + assert tx_double_spend.hash is not None + assert tx_double_spend.full_hex is not None + + # relay first tx directly to daemon + result: MoneroSubmitTxResult = daemon.submit_tx_hex(tx.full_hex) + assert result.is_good, "Transaction could not be submitted to the pool" + + # sync wallet which updates from pool + wallet.sync() + + # collect issues to report at end of test + issues: list[str] = [] + + # wallet should be aware of tx + fetched: MoneroTxWallet | None = wallet.get_tx(tx.hash) + assert fetched is not None, "Wallet should be aware of its tx in pool after syncing" + + # test wallet balances + if unlocked_balance_before == wallet.get_unlocked_balance(): + issues.append("unlocked balance should have decreased after relaying tx directly to the daemon") + + if balance_before == wallet.get_balance(): + issues.append("balance should have decreased after relaying tx directly to the daemon") + + expected_balance: int = balance_before - tx.fee + if expected_balance != wallet.get_balance(): + issues.append(f"expected balance after relaying tx directly to the daemon to be {expected_balance} but was {wallet.get_balance()}") + + # submit double spend tx + result_double_spend: MoneroSubmitTxResult = daemon.submit_tx_hex(tx_double_spend.full_hex) + if result_double_spend.is_good: + daemon.flush_tx_pool(tx_double_spend.hash) + issues.append("Tx submit result should have been double spend") + + # sync wallet which updates from pool + wallet.sync() + + # create tx using same config which is no longer double spend + tx2: MoneroTxWallet | None = None + try: + config_copy: MoneroTxConfig = config.copy() + config_copy.relay = True + tx2 = wallet.create_tx(config_copy) + except Exception as e: + logger.warning(e) + # TODO monero-project: this fails meaning wallet did not recognize tx relayed directly to pool + issues.append("creating and sending tx through wallet should succeed after syncing wallet with pool but creates a double spend") + + # submit the transaction to the pool and test + if tx2 is not None: + assert tx2.hash is not None + assert tx2.full_hex is not None + result2: MoneroSubmitTxResult = daemon.submit_tx_hex(tx2.full_hex, True) + if result2.is_double_spend: + issues.append("creating and submitting tx to daemon should succeed after syncing wallet with pool but was a double spend") + else: + assert result2.is_good + + wallet.sync() + if wallet.get_tx(tx2.hash) is None: + issues.append("wallet should be aware of tx created and relayed through it after syncing with pool") + + daemon.flush_tx_pool(tx2.hash) + + # should be no issues + for issue in issues: + logger.warning(issue) + + assert len(issues) == 0, f"test_sync_with_pool_relay has {len(issues)} issues" + + +@pytest.mark.integration +class TestMoneroWalletFullPool(FullWalletSupport, BaseTestMoneroWalletPool): + """Full wallet pool integration tests.""" + + +@pytest.mark.integration +class TestMoneroWalletRpcPool(RpcWalletSupport, BaseTestMoneroWalletPool): + """Rpc wallet pool integration tests.""" + + +@pytest.mark.unit +class TestMoneroWalletKeysPool(KeysWalletSupport, BaseTestMoneroWalletPool): + """Keys-only wallet pool unit tests.""" + + @pytest.mark.not_supported + @override + def test_sync_with_pool_same_accounts(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: + return super().test_sync_with_pool_same_accounts(daemon, wallet) + + @pytest.mark.not_supported + @override + def test_sync_with_pool_submit_and_flush(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: + return super().test_sync_with_pool_submit_and_flush(daemon, wallet) + + @pytest.mark.not_supported + @override + def test_sync_with_pool_submit_and_relay(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: + return super().test_sync_with_pool_submit_and_relay(daemon, wallet) + + @pytest.mark.not_supported + @override + def test_sync_with_pool_relay(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: + return super().test_sync_with_pool_relay(daemon, wallet) diff --git a/tests/wallet/test_proofs.py b/tests/wallet/test_proofs.py new file mode 100644 index 00000000..0a268fad --- /dev/null +++ b/tests/wallet/test_proofs.py @@ -0,0 +1,439 @@ +from __future__ import annotations + +import logging +from typing import Optional + +import pytest +from monero import ( + MoneroAccount, + MoneroCheckReserve, + MoneroCheckTx, + MoneroDaemonRpc, + MoneroDestination, + MoneroSubmitTxResult, + MoneroTransferQuery, + MoneroTx, + MoneroTxConfig, + MoneroTxQuery, + MoneroTxWallet, + MoneroWallet, + MoneroWalletConfig, +) +from typing_extensions import override + +from utils import TestUtils, TxWalletUtils, WalletErrorUtils, WalletTestUtils, WalletTxsUtils, WalletUtils +from .base_test_monero_wallet import BaseTestMoneroWallet +from .wallet_support import FullWalletSupport, RpcWalletSupport, KeysWalletSupport + +logger: logging.Logger = logging.getLogger("TestMoneroWalletProofs") + + +class BaseTestMoneroWalletProofs(BaseTestMoneroWallet): + """Common wallet proofs tests.""" + + # Can check a transfer using the transaction's secret key and the destination + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_check_tx_key(self, wallet: MoneroWallet) -> None: + # get random txs that are confirmed and have outgoing destinations + txs: list[MoneroTxWallet] = [] + try: + query: MoneroTxQuery = MoneroTxQuery() + query.is_confirmed = True + query.transfer_query = MoneroTransferQuery() + query.transfer_query.has_destinations = True + txs = WalletTxsUtils.get_random_transactions(wallet, query, 1, WalletUtils.MAX_TX_PROOFS) + except AssertionError as e: + if "found with" in str(e): + raise Exception("No txs with outgoing destinations found; run send tests") + raise + + # test good checks + assert len(txs) > 0, "No transactions found with outgoing destinations" + for tx in txs: + assert tx.hash is not None + key: str = wallet.get_tx_key(tx.hash) + assert tx.outgoing_transfer is not None + assert len(tx.outgoing_transfer.destinations) > 0 + for destination in tx.outgoing_transfer.destinations: + assert destination.address is not None + check: MoneroCheckTx = wallet.check_tx_key(tx.hash, key, destination.address) + assert destination.amount is not None + if destination.amount > 0: + # TODO monero-wallet-rpc: indicates amount received amount is 0 despite transaction with transfer to this address + # TODO monero-wallet-rpc: returns 0-4 errors, not consistent + assert check.received_amount is not None + if check.received_amount == 0: + msg: str = f"WARNING: key proof indicates no funds received despite transfer (txid={tx.hash}, key={key}, address={destination.address} amount={destination.amount})" + logger.warning(msg) + else: + assert check.received_amount == 0 + TxWalletUtils.test_check_tx(tx, check) + + # test get tx key with invalid hash + with pytest.raises(Exception) as exc_info: + wallet.get_tx_key("invalid_tx_id") + WalletErrorUtils.test_invalid_tx_hash_error(exc_info.value) + # test check with invalid tx hash + tx: MoneroTxWallet = txs[0] + assert tx.hash is not None + key: str = wallet.get_tx_key(tx.hash) + assert tx.outgoing_transfer is not None + destination: MoneroDestination = tx.outgoing_transfer.destinations[0] + assert destination.address is not None + with pytest.raises(Exception) as exc_info: + wallet.check_tx_key("invalid_tx_id", key, destination.address) + WalletErrorUtils.test_invalid_tx_hash_error(exc_info.value) + # test check with invalid key + with pytest.raises(Exception) as exc_info: + wallet.check_tx_key(tx.hash, "invalid_tx_key", destination.address) + WalletErrorUtils.test_invalid_tx_key_error(exc_info.value) + # test check with invalid address + with pytest.raises(Exception) as exc_info: + wallet.check_tx_key(tx.hash, key, "invalid_tx_address") + WalletErrorUtils.test_invalid_address_error(exc_info.value) + # test check with different address + different_address: Optional[str] = None + for a_tx in wallet.get_txs(): + if a_tx.outgoing_transfer is None or len(a_tx.outgoing_transfer.destinations) == 0: + continue + for a_destination in a_tx.outgoing_transfer.destinations: + assert a_destination.address is not None + if a_destination.address != destination.address: + different_address = a_destination.address + break + + assert different_address is not None, "Could not get a different outgoing address to test; run send tests" + check: MoneroCheckTx = wallet.check_tx_key(tx.hash, key, different_address) + assert check.is_good is True + assert check.received_amount is not None + assert check.received_amount >= 0 + TxWalletUtils.test_check_tx(tx, check) + + # Can prove a transaction by getting its signature + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_check_tx_proof(self, wallet: MoneroWallet) -> None: + # get random txs with outgoing destinations + txs: list[MoneroTxWallet] = [] + try: + query: MoneroTxQuery = MoneroTxQuery() + query.transfer_query = MoneroTransferQuery() + query.transfer_query.has_destinations = True + txs = WalletTxsUtils.get_random_transactions(wallet, query, 2, WalletUtils.MAX_TX_PROOFS) + except Exception as e: + if "found with" in str(e): + raise Exception("No txs with outgoing destinations found; run send tests") + raise + + # test good checks with messages + for tx in txs: + assert tx.hash is not None + assert tx.outgoing_transfer is not None + for destination in tx.outgoing_transfer.destinations: + assert destination.address is not None + signature: str = wallet.get_tx_proof(tx.hash, destination.address, "This transaction definitely happened.") + check: MoneroCheckTx = wallet.check_tx_proof(tx.hash, destination.address, "This transaction definitely happened.", signature) + TxWalletUtils.test_check_tx(tx, check) + + # test good check without message + tx: MoneroTx = txs[0] + assert tx.hash is not None + assert tx.outgoing_transfer is not None + assert len(tx.outgoing_transfer.destinations) > 0 + destination: MoneroDestination = tx.outgoing_transfer.destinations[0] + assert destination.address is not None + signature: str = wallet.get_tx_proof(tx.hash, destination.address) + check: MoneroCheckTx = wallet.check_tx_proof(tx.hash, destination.address, '', signature) + TxWalletUtils.test_check_tx(tx, check) + + # test get proof with invalid hash + with pytest.raises(Exception) as exc_info: + wallet.get_tx_proof("invalid_tx_id", destination.address) + WalletErrorUtils.test_invalid_tx_hash_error(exc_info.value) + # test check tx proof with invalid tx hash + with pytest.raises(Exception) as exc_info: + wallet.check_tx_proof("invalid_tx_id", destination.address, '', signature) + WalletErrorUtils.test_invalid_tx_hash_error(exc_info.value) + # test check with invalid address + with pytest.raises(Exception) as exc_info: + wallet.check_tx_proof(tx.hash, "invalid_tx_address", '', signature) + WalletErrorUtils.test_invalid_address_error(exc_info.value) + # test check with wrong message + signature = wallet.get_tx_proof(tx.hash, destination.address, "This is the right message") + check = wallet.check_tx_proof(tx.hash, destination.address, "This is the wrong message", signature) + assert check.is_good is False + TxWalletUtils.test_check_tx(tx, check) + + # test check with wrong signature + other_tx: MoneroTxWallet = txs[1] + assert other_tx.hash is not None + assert other_tx.outgoing_transfer is not None + assert len(other_tx.outgoing_transfer.destinations) > 0 + address: Optional[str] = other_tx.outgoing_transfer.destinations[0].address + assert address is not None + wrong_signature: str = wallet.get_tx_proof(other_tx.hash, address, "This is the right message") + try: + check = wallet.check_tx_proof(tx.hash, destination.address, "This is the right message", wrong_signature) + assert check.is_good is False + except Exception as e: + WalletErrorUtils.test_invalid_signature_error(e) + + # test check with empty signature + try: + check = wallet.check_tx_proof(tx.hash, destination.address, "This is the right message", "") + assert check.is_good is False + except Exception as e: + assert str(e) == "Must provide signature to check tx proof" + + # Can prove a spend using a generated signature and no destination public address + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disablde") + def test_check_spend_proof(self, wallet: MoneroWallet) -> None: + # get random confirmed outgoing txs + query: MoneroTxQuery = MoneroTxQuery() + query.is_incoming = False + query.in_tx_pool = False + query.is_failed = False + txs: list[MoneroTxWallet] = WalletTxsUtils.get_random_transactions(wallet, query, 2, WalletUtils.MAX_TX_PROOFS) + for tx in txs: + assert tx.is_confirmed is True + assert len(tx.incoming_transfers) == 0 + assert tx.outgoing_transfer is not None + + # test good checks with messages + for tx in txs: + assert tx.hash is not None + logger.debug(f"Getting tx hash {tx.hash} proof") + signature: str = wallet.get_spend_proof(tx.hash, "I am a message.") + logger.debug(f"Checking tx hash {tx.hash} proof") + result: bool = wallet.check_spend_proof(tx.hash, "I am a message.", signature) + assert result is True + + # test good check without message + tx: MoneroTxWallet = txs[0] + assert tx.hash is not None + signature: str = wallet.get_spend_proof(tx.hash) + result: bool = wallet.check_spend_proof(tx.hash, '', signature) + assert result is True + + # test get proof with invalid hash + with pytest.raises(Exception) as exc_info: + wallet.get_spend_proof("invalid_tx_id") + WalletErrorUtils.test_invalid_tx_hash_error(exc_info.value) + # test check with invalid tx hash + with pytest.raises(Exception) as exc_info: + wallet.check_spend_proof("invalid_tx_id", '', signature) + WalletErrorUtils.test_invalid_tx_hash_error(exc_info.value) + # test check with invalid message + signature = wallet.get_spend_proof(tx.hash, "This is the right message") + result = wallet.check_spend_proof(tx.hash, "This is the wrong message", signature) + assert result is False + + # test check with wrong signature + other_tx: MoneroTxWallet = txs[1] + assert other_tx.hash is not None + signature = wallet.get_spend_proof(other_tx.hash, "This is the right message") + result = wallet.check_spend_proof(tx.hash, "This is the right message", signature) + assert result is False + + # Can prove reserves in the wallet + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disablde") + def test_get_reserve_proof_wallet(self, wallet: MoneroWallet) -> None: + # get proof of entire wallet + signature: str = wallet.get_reserve_proof_wallet("Test message") + + # check proof of entire wallet + check: MoneroCheckReserve = wallet.check_reserve_proof(wallet.get_primary_address(), "Test message", signature) + assert check.is_good is True + TxWalletUtils.test_check_reserve(check) + balance: int = wallet.get_balance() + if balance != check.total_amount: + # TODO monero-wallet-rpc: this check fails with unconfirmed txs + query: MoneroTxQuery = MoneroTxQuery() + query.in_tx_pool = True + unconfirmed_txs: list[MoneroTxWallet] = wallet.get_txs(query) + assert len(unconfirmed_txs) > 0, "Reserve amount must equal balance unless wallet has unconfirmed txs" + + # test different wallet address + different_address: str = WalletTestUtils.get_external_wallet_address() + with pytest.raises(Exception) as exc_info: + wallet.check_reserve_proof(different_address, "Test message", signature) + WalletErrorUtils.test_no_subaddress_error(exc_info.value) + # test subaddress + with pytest.raises(Exception) as exc_info: + address: Optional[str] = wallet.get_subaddress(0, 1).address + assert address is not None + wallet.check_reserve_proof(address, "Test message", signature) + WalletErrorUtils.test_no_subaddress_error(exc_info.value) + # test wrong message + check = wallet.check_reserve_proof(wallet.get_primary_address(), "Wrong message", signature) + # TODO: specifically test reserve checks, probably separate objects + assert check.is_good is False + TxWalletUtils.test_check_reserve(check) + + # test wrong signature + with pytest.raises(Exception) as exc_info: + wallet.check_reserve_proof(wallet.get_primary_address(), "Test message", "wrong signature") + WalletErrorUtils.test_signature_header_error(exc_info.value) + + # Can prove reserves in an account + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disablde") + def test_get_reserve_proof_account(self, wallet: MoneroWallet) -> None: + # test proofs of accounts + num_non_zero_tests: int = 0 + msg: str = "Test message" + accounts: list[MoneroAccount] = wallet.get_accounts() + signature: str = '' + for account in accounts: + assert account.balance is not None + assert account.index is not None + if account.balance > 0: + check_amount: int = int(account.balance/2) + signature = wallet.get_reserve_proof_account(account.index, check_amount, msg) + check: MoneroCheckReserve = wallet.check_reserve_proof(wallet.get_primary_address(), msg, signature) + assert check.is_good is True + TxWalletUtils.test_check_reserve(check) + assert check.total_amount is not None + assert check.total_amount >= 0 + num_non_zero_tests += 1 + else: + with pytest.raises(Exception) as exc_info: + wallet.get_reserve_proof_account(account.index, account.balance, msg) + logger.debug(str(exc_info.value)) + + with pytest.raises(Exception) as exc_info: + wallet.get_reserve_proof_account(account.index, TxWalletUtils.MAX_FEE, msg) + logger.debug(str(exc_info.value)) + + assert num_non_zero_tests > 1, "Must have more than one account with non-zero balance; run send-to-multiple tests" + + # test error when not enough balance for requested minimum reserve amount + # TODO monero-project#6595: an over-balance reserve proof should be rejected but isn't + account: MoneroAccount = accounts[0] + assert account.balance is not None + amount: int = account.balance + TxWalletUtils.MAX_FEE + try: + proof: str = wallet.get_reserve_proof_account(0, amount, "Test message") + reserve: MoneroCheckReserve = wallet.check_reserve_proof(wallet.get_primary_address(), "Test message", proof) + logger.warning(f"Got reserve proof despite insufficient balance: {reserve.serialize()}") + except Exception as e: + logger.debug(str(e)) + + # test different wallet address + different_address: str = WalletTestUtils.get_external_wallet_address() + with pytest.raises(Exception) as exc_info: + wallet.check_reserve_proof(different_address, "Test message", signature) + logger.debug(str(exc_info.value)) + + # test subaddress + address: Optional[str] = wallet.get_subaddress(0, 1).address + assert address is not None + with pytest.raises(Exception) as exc_info: + wallet.check_reserve_proof(address, "Test message", signature) + logger.debug(str(exc_info.value)) + + # test wrong message + check: MoneroCheckReserve = wallet.check_reserve_proof(wallet.get_primary_address(), "Wrong message", signature) + # TODO: specifically test reserve checks, probably separate objects + assert check.is_good is False + TxWalletUtils.test_check_reserve(check) + + # test wrong signature + with pytest.raises(Exception) as exc_info: + wallet.check_reserve_proof(wallet.get_primary_address(), "Test message", "wrong signature") + logger.debug(str(exc_info.value)) + + # Can prove unrelayed txs + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_prove_unrelayed_txs(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: + # create unrelayed tx to verify + address1: str = WalletTestUtils.get_external_wallet_address() + address2: str = wallet.get_address(0, 0) + address3: str = wallet.get_address(1, 0) + tx_config: MoneroTxConfig = MoneroTxConfig() + tx_config.account_index = 0 + tx_config.destinations.append(MoneroDestination(address1, TxWalletUtils.MAX_FEE)) + tx_config.destinations.append(MoneroDestination(address2, TxWalletUtils.MAX_FEE * 2)) + tx_config.destinations.append(MoneroDestination(address3, TxWalletUtils.MAX_FEE * 3)) + tx: MoneroTxWallet = wallet.create_tx(tx_config) + assert tx.full_hex is not None + assert tx.hash is not None + assert tx.key is not None + + # submit tx to daemon but do not relay + result: MoneroSubmitTxResult = daemon.submit_tx_hex(tx.full_hex, True) + assert result.is_good + + # create random wallet to verify transfers + verifying_wallet: MoneroWallet = self._create_wallet(MoneroWalletConfig()) + + try: + # verify transfer 1 + check: MoneroCheckTx = verifying_wallet.check_tx_key(tx.hash, tx.key, address1) + assert check.is_good + assert check.in_tx_pool is True + assert check.num_confirmations == 0 + assert check.received_amount == TxWalletUtils.MAX_FEE + + # verify transfer 2 + check = verifying_wallet.check_tx_key(tx.hash, tx.key, address2) + assert check.is_good + assert check.in_tx_pool is True + assert check.num_confirmations == 0 + # + change amount + assert check.received_amount is not None + assert check.received_amount >= TxWalletUtils.MAX_FEE * 2 + + # verify transfer 3 + check = verifying_wallet.check_tx_key(tx.hash, tx.key, address3) + assert check.is_good + assert check.in_tx_pool is True + assert check.num_confirmations == 0 + assert TxWalletUtils.MAX_FEE * 3 == check.received_amount + finally: + # cleanup, otherwise it permanently ties up the dest outputs for entire session + daemon.flush_tx_pool(tx.hash) + self._close_wallet(verifying_wallet) + + +@pytest.mark.integration +class TestMoneroWalletFullProofs(FullWalletSupport, BaseTestMoneroWalletProofs): + """Full wallet proofs integration tests.""" + + +@pytest.mark.integration +class TestMoneroWalletRpcProofs(RpcWalletSupport, BaseTestMoneroWalletProofs): + """Rpc wallet proofs integration tests.""" + + +@pytest.mark.unit +class TestMoneroWalletKeysProofs(KeysWalletSupport, BaseTestMoneroWalletProofs): + """Keys-only wallet proofs unit tests.""" + + @pytest.mark.not_supported + @override + def test_check_tx_key(self, wallet: MoneroWallet) -> None: + return super().test_check_tx_key(wallet) + + @pytest.mark.not_supported + @override + def test_check_tx_proof(self, wallet: MoneroWallet) -> None: + return super().test_check_tx_proof(wallet) + + @pytest.mark.not_supported + @override + def test_check_spend_proof(self, wallet: MoneroWallet) -> None: + return super().test_check_spend_proof(wallet) + + @pytest.mark.not_supported + @override + def test_get_reserve_proof_wallet(self, wallet: MoneroWallet) -> None: + return super().test_get_reserve_proof_wallet(wallet) + + @pytest.mark.not_supported + @override + def test_get_reserve_proof_account(self, wallet: MoneroWallet) -> None: + return super().test_get_reserve_proof_account(wallet) + + @pytest.mark.not_supported + @override + def test_prove_unrelayed_txs(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: + return super().test_prove_unrelayed_txs(daemon, wallet) diff --git a/tests/wallet/test_send.py b/tests/wallet/test_send.py new file mode 100644 index 00000000..b94d1015 --- /dev/null +++ b/tests/wallet/test_send.py @@ -0,0 +1,307 @@ +from __future__ import annotations + +import logging +from typing import Optional + +import pytest +from monero import ( + MoneroDaemonRpc, + MoneroFeeEstimate, + MoneroIntegratedAddress, + MoneroSubaddress, + MoneroTxConfig, + MoneroTxPriority, + MoneroTxQuery, + MoneroTxWallet, + MoneroUtils, + MoneroWallet, + MoneroWalletConfig, +) +from typing_extensions import override + +from utils import TestUtils, TxWalletUtils, WalletSendUtils +from .base_test_monero_wallet import BaseTestMoneroWallet +from .wallet_support import FullWalletSupport, RpcWalletSupport, KeysWalletSupport + +logger: logging.Logger = logging.getLogger("TestMoneroWalletSend") + + +class BaseTestMoneroWalletSend(BaseTestMoneroWallet): + """Common wallet send tests.""" + + # Validates inputs when sending funds + @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") + @pytest.mark.flaky(reruns=5, reruns_delay=5, only_rerun=[]) + def test_validate_inputs_sending_funds(self, wallet: MoneroWallet) -> None: + # try sending with invalid address + tx_config: MoneroTxConfig = MoneroTxConfig() + tx_config.address = "my invalid address" + tx_config.account_index = 0 + tx_config.amount = TxWalletUtils.MAX_FEE + with pytest.raises(Exception) as exc_info: + wallet.create_tx(tx_config) + assert str(exc_info.value) == "Invalid destination address" + + # Can send to self + @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") + def test_send_to_self(self, wallet: MoneroWallet) -> None: + # wait for txs to confirm and for sufficient unlocked balance + TestUtils.WALLET_TX_TRACKER.wait_for_txs_to_clear_pool(wallet) + amount: int = TxWalletUtils.MAX_FEE * 3 + TestUtils.WALLET_TX_TRACKER.wait_for_unlocked_balance(wallet, 0, None, amount) + + # collect sender balances before + balance1: int = wallet.get_balance() + unlocked_balance1: int = wallet.get_unlocked_balance() + + # test error sending funds to self with integrated subaddress + # TODO (monero-project): sending funds to self + # with integrated subaddress throws error: https://github.com/monero-project/monero/issues/8380 + + tx_config: MoneroTxConfig = MoneroTxConfig() + tx_config.account_index = 0 + subaddress: MoneroSubaddress = wallet.get_subaddress(0, 1) + assert subaddress.address is not None + address: str = subaddress.address + tx_config.address = MoneroUtils.get_integrated_address(TestUtils.NETWORK_TYPE, address, '').integrated_address + tx_config.amount = amount + tx_config.relay = True + with pytest.raises(Exception, match="Total received by"): + wallet.create_tx(tx_config) + + # send funds to self + tx_config = MoneroTxConfig() + tx_config.account_index = 0 + tx_config.address = wallet.get_integrated_address().integrated_address + tx_config.amount = amount + tx_config.relay = True + + tx: MoneroTxWallet = wallet.create_tx(tx_config) + + # test balances after + balance2: int = wallet.get_balance() + unlocked_balance2: int = wallet.get_unlocked_balance() + + # unlocked balance should decrease + assert unlocked_balance2 < unlocked_balance1 + assert tx.fee is not None + expected_balance: int = balance1 - tx.fee + assert expected_balance == balance2, "Balance after send was not balance before - fee" + + # Can send to external address + @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") + def test_send_to_external(self, wallet: MoneroWallet) -> None: + recipient: Optional[MoneroWallet] = None + try: + # wait for txs to confirm and for sufficient unlocked balance + TestUtils.WALLET_TX_TRACKER.wait_for_txs_to_clear_pool(wallet) + amount: int = TxWalletUtils.MAX_FEE * 3 + TestUtils.WALLET_TX_TRACKER.wait_for_unlocked_balance(wallet, 0, None, amount) + + # create recipient wallet + recipient = self._create_wallet(MoneroWalletConfig()) + + balance1: int = wallet.get_balance() + unlocked_balance1: int = wallet.get_unlocked_balance() + + # send funds to recipient + tx_config: MoneroTxConfig = MoneroTxConfig() + tx_config.account_index = 0 + tx_config.address = wallet.get_integrated_address(recipient.get_primary_address(), "54491f3bb3572a37").integrated_address + tx_config.amount = amount + tx_config.relay = True + tx: MoneroTxWallet = wallet.create_tx(tx_config) + + # test sender balances after + balance2: int = wallet.get_balance() + unlocked_balance2: int = wallet.get_unlocked_balance() + + # unlocked balance should decrease + assert unlocked_balance2 < unlocked_balance1 + assert tx.fee is not None + expected_balance: int = balance1 - tx.get_outgoing_amount() - tx.fee + assert expected_balance == balance2, "Balance after send was not balance before - net tx amount - fee (5 - 1 != 4 test)" + + tx_query: MoneroTxQuery = MoneroTxQuery() + tx_query.is_confirmed = False + txs: list[MoneroTxWallet] = wallet.get_txs(tx_query) + assert len(txs) > 0 + + # test recipient balance after + recipient.sync() + assert amount == recipient.get_balance() + + finally: + if recipient is not None: + self._close_wallet(recipient) + + # Can send to multiple subaddresses in a single transaction + @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") + def test_send_to_multiple(self, wallet: MoneroWallet) -> None: + WalletSendUtils.test_send_to_multiple(wallet, 5, 3, False) + + # Can send to multiple addresses in split transactions + @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") + def test_send_to_multiple_split(self, wallet: MoneroWallet) -> None: + WalletSendUtils.test_send_to_multiple(wallet, 3, 15, True) + + # Can send dust to multiple addresses in split transactions + @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") + def test_send_dust_to_multiple_split(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: + estimate: MoneroFeeEstimate = daemon.get_fee_estimate() + assert estimate.fee is not None + dust_amount: int = int(estimate.fee / 2) + WalletSendUtils.test_send_to_multiple(wallet, 5, 3, True, dust_amount) + + # Can subtract fees from destinations + @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") + def test_subtract_fee_from(self, wallet: MoneroWallet) -> None: + WalletSendUtils.test_send_to_multiple(wallet, 5, 3, False, None, True) + + # Cannot subtract fees from destinations in split transactions + @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") + def test_subtract_fee_from_split(self, wallet: MoneroWallet) -> None: + WalletSendUtils.test_send_to_multiple(wallet, 3, 15, True, None, True) + + # Can send from multiple subaddresses in a single transaction + @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") + def test_send_from_subaddresses(self, wallet: MoneroWallet) -> None: + WalletSendUtils.test_send_from_multiple(wallet, None) + + # Can send from multiple subaddresses in split transactions + @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") + def test_send_from_subaddresses_split(self, wallet: MoneroWallet) -> None: + WalletSendUtils.test_send_from_multiple(wallet, True) + + # Can send to an address in a single transaction + @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") + def test_send(self, wallet: MoneroWallet) -> None: + WalletSendUtils.test_send_to_single(wallet, False) + + # Can send to an address in a single transaction with a payment id + # NOTE this test will be invalid when payment hashes are fully removed + @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") + def test_send_with_payment_id(self, wallet: MoneroWallet) -> None: + integrated_address: MoneroIntegratedAddress = wallet.get_integrated_address() + assert integrated_address.payment_id is not None + payment_id: str = integrated_address.payment_id + msg = "Standalone payment IDs are obsolete. Use subaddresses or integrated addresses instead" + with pytest.raises(Exception) as exc_info: + WalletSendUtils.test_send_to_single(wallet, False, None, f"{payment_id}{payment_id}{payment_id}") + assert str(exc_info.value) == msg + + # Can send to an address with split transactions + @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") + def test_send_split(self, wallet: MoneroWallet) -> None: + WalletSendUtils.test_send_to_single(wallet, True) + + # Can create then relay a transaction to send to a single address + @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") + def test_create_then_relay(self, wallet: MoneroWallet) -> None: + WalletSendUtils.test_send_to_single(wallet, False, False) + + # Can create then relay split transactions to send to a single address + @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") + def test_create_then_relay_split(self, wallet: MoneroWallet) -> None: + WalletSendUtils.test_send_to_single(wallet, True, False) + + # Can get the default fee priority + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_default_fee_priority(self, wallet: MoneroWallet) -> None: + default_priority: MoneroTxPriority = wallet.get_default_fee_priority() + assert int(default_priority) > 0 + + +@pytest.mark.integration +class TestMoneroWalletFullSend(FullWalletSupport, BaseTestMoneroWalletSend): + """Full wallet send integration tests.""" + + +@pytest.mark.integration +class TestMoneroWalletRpcSend(RpcWalletSupport, BaseTestMoneroWalletSend): + """Rpc wallet send integration tests.""" + + +@pytest.mark.unit +class TestMoneroWalletKeysSend(KeysWalletSupport, BaseTestMoneroWalletSend): + """Keys-only wallet send unit tests.""" + + @pytest.mark.not_supported + @override + def test_send(self, wallet: MoneroWallet) -> None: + return super().test_send(wallet) + + @pytest.mark.not_implemented + @override + def test_send_with_payment_id(self, wallet: MoneroWallet) -> None: + return super().test_send_with_payment_id(wallet) + + @pytest.mark.not_supported + @override + def test_send_split(self, wallet: MoneroWallet) -> None: + return super().test_send_split(wallet) + + @pytest.mark.not_supported + @override + def test_create_then_relay(self, wallet: MoneroWallet) -> None: + return super().test_create_then_relay(wallet) + + @pytest.mark.not_supported + @override + def test_create_then_relay_split(self, wallet: MoneroWallet) -> None: + return super().test_create_then_relay_split(wallet) + + @pytest.mark.not_supported + @override + def test_validate_inputs_sending_funds(self, wallet: MoneroWallet) -> None: + return super().test_validate_inputs_sending_funds(wallet) + + @pytest.mark.not_supported + @override + def test_send_to_self(self, wallet: MoneroWallet) -> None: + return super().test_send_to_self(wallet) + + @pytest.mark.not_supported + @override + def test_send_to_external(self, wallet: MoneroWallet) -> None: + return super().test_send_to_external(wallet) + + @pytest.mark.not_supported + @override + def test_get_default_fee_priority(self, wallet: MoneroWallet) -> None: + return super().test_get_default_fee_priority(wallet) + + @pytest.mark.not_supported + @override + def test_send_from_subaddresses(self, wallet: MoneroWallet) -> None: + return super().test_send_from_subaddresses(wallet) + + @pytest.mark.not_supported + @override + def test_send_from_subaddresses_split(self, wallet: MoneroWallet) -> None: + return super().test_send_from_subaddresses_split(wallet) + + @pytest.mark.not_supported + @override + def test_send_to_multiple(self, wallet: MoneroWallet) -> None: + return super().test_send_to_multiple(wallet) + + @pytest.mark.not_supported + @override + def test_send_to_multiple_split(self, wallet: MoneroWallet) -> None: + return super().test_send_to_multiple_split(wallet) + + @pytest.mark.not_supported + @override + def test_send_dust_to_multiple_split(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: + return super().test_send_dust_to_multiple_split(daemon, wallet) + + @pytest.mark.not_supported + @override + def test_subtract_fee_from(self, wallet: MoneroWallet) -> None: + return super().test_subtract_fee_from(wallet) + + @pytest.mark.not_supported + @override + def test_subtract_fee_from_split(self, wallet: MoneroWallet) -> None: + return super().test_subtract_fee_from_split(wallet) diff --git a/tests/wallet/test_sweep.py b/tests/wallet/test_sweep.py new file mode 100644 index 00000000..29c551b7 --- /dev/null +++ b/tests/wallet/test_sweep.py @@ -0,0 +1,377 @@ +from __future__ import annotations + +import logging + +import pytest +from monero import ( + MoneroAccount, + MoneroOutputQuery, + MoneroOutputWallet, + MoneroSubaddress, + MoneroTxConfig, + MoneroTxQuery, + MoneroTxWallet, + MoneroWallet, +) +from typing_extensions import override + +from utils import IntegrationTestUtils, OutputUtils, TestUtils, TxContext, TxWalletUtils, WalletSendUtils +from .base_test_monero_wallet import BaseTestMoneroWallet +from .wallet_support import FullWalletSupport, RpcWalletSupport, KeysWalletSupport + +logger: logging.Logger = logging.getLogger("TestMoneroWalletSweep") + + +class BaseTestMoneroWalletSweep(BaseTestMoneroWallet): + """Common wallet sweep tests.""" + + # Can sweep individual outputs identified by their key images + @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") + def test_sweep_outputs(self, wallet: MoneroWallet) -> None: + TestUtils.WALLET_TX_TRACKER.wait_for_txs_to_clear_pool(wallet) + + # test config + num_outputs: int = 3 + + # get outputs to sweep (not spent, unlocked, and amount >= fee) + query: MoneroOutputQuery = MoneroOutputQuery() + query.is_spent = False + tx_query: MoneroTxQuery = MoneroTxQuery() + tx_query.is_locked = False + query.set_tx_query(tx_query, True) + spendable_unlocked_outputs: list[MoneroOutputWallet] = wallet.get_outputs(query) + outputs_to_sweep: list[MoneroOutputWallet] = [] + for spendable_output in spendable_unlocked_outputs: + if len(outputs_to_sweep) >= num_outputs: + break + assert spendable_output.amount is not None + if spendable_output.amount > TxWalletUtils.MAX_FEE: + outputs_to_sweep.append(spendable_output) + + assert len(outputs_to_sweep) >= num_outputs, "Wallet does not have enough sweepable outputs; run send tests" + + # sweep each output by key image + for output in outputs_to_sweep: + OutputUtils.test_output_wallet(output) + assert output.is_spent is False + assert output.tx is not None + assert isinstance(output.tx, MoneroTxWallet) + assert output.tx.is_locked is False + assert output.amount is not None + + if output.amount <= TxWalletUtils.MAX_FEE: + continue + + # sweep output to address + assert output.account_index is not None + assert output.subaddress_index is not None + assert output.key_image is not None + assert output.key_image.hex is not None + address: str = wallet.get_address(output.account_index, output.subaddress_index) + config: MoneroTxConfig = MoneroTxConfig() + config.address = address + config.key_image = output.key_image.hex + config.relay = True + tx: MoneroTxWallet = wallet.sweep_output(config) + + # test result tx + ctx: TxContext = TxContext() + ctx.wallet = wallet + ctx.config = config + ctx.config.can_split = False + ctx.is_send_response = True + ctx.is_sweep_response = True + ctx.is_sweep_output_response = True + TxWalletUtils.test_tx_wallet(tx, ctx) + + # get outputs after sweeping + after_outputs: list[MoneroOutputWallet] = wallet.get_outputs() + + # swept outputs are now spent + for after_output in after_outputs: + assert after_output.key_image is not None + + for output in outputs_to_sweep: + assert output.key_image is not None + if output.key_image.hex == after_output.key_image.hex: + assert after_output.is_spent is True, "Output should be spent" + + # Can sweep individual outputs identified by their key images + @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") + def test_sweep_dust_no_relay(self, wallet: MoneroWallet) -> None: + TestUtils.WALLET_TX_TRACKER.wait_for_txs_to_clear_pool(wallet) + + # sweep dust which returns empty list if no dust to sweep (dust does not exist after rct) + txs: list[MoneroTxWallet] = wallet.sweep_dust(False) + if len(txs) == 0: + return + + # test txs + ctx: TxContext = TxContext() + ctx.is_send_response = True + ctx.config = MoneroTxConfig() + ctx.config.relay = False + ctx.is_sweep_response = True + for tx in txs: + TxWalletUtils.test_tx_wallet(tx, ctx) + + # relay txs + metadatas: list[str] = [] + for tx in txs: + assert tx.metadata is not None + metadatas.append(tx.metadata) + + tx_hashes: list[str] = wallet.relay_txs(metadatas) + assert len(tx_hashes) == len(txs) + for tx_hash in tx_hashes: + assert len(tx_hash) == 64 + + # fetch and test txs + tx_query: MoneroTxQuery = MoneroTxQuery() + tx_query.hashes = tx_hashes + txs = wallet.get_txs(tx_query) + ctx.config.relay = True + for tx in txs: + TxWalletUtils.test_tx_wallet(tx, ctx) + + # Can sweep dust + @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") + def test_sweep_dust(self, wallet: MoneroWallet) -> None: + TestUtils.WALLET_TX_TRACKER.wait_for_txs_to_clear_pool(wallet) + + # sweep dust which returns empty list if no dust to sweep (dust does not exist after rct) + txs: list[MoneroTxWallet] = wallet.sweep_dust(True) + + # test any txs + ctx: TxContext = TxContext() + ctx.wallet = wallet + ctx.config = None + ctx.is_send_response = True + ctx.is_sweep_response = True + for tx in txs: + TxWalletUtils.test_tx_wallet(tx, ctx) + + # Can sweep subaddresses + @pytest.mark.skipif(TestUtils.TEST_RESETS is False, reason="TEST_RESETS disabled") + def test_sweep_subaddresses(self, wallet: MoneroWallet) -> None: + TestUtils.WALLET_TX_TRACKER.wait_for_txs_to_clear_pool(wallet) + NUM_SUBADDRESSES_TO_SWEEP: int = 2 + + # collect subaddresses with balance and unlocked balance + subaddresses: list[MoneroSubaddress] = [] + subaddresses_balance: list[MoneroSubaddress] = [] + subaddresses_unlocked: list[MoneroSubaddress] = [] + for account in wallet.get_accounts(True): + if account.index == 0: + # skip default account + continue + for subaddress in account.subaddresses: + subaddresses.append(subaddress) + assert subaddress.balance is not None + if subaddress.balance > TxWalletUtils.MAX_FEE: + subaddresses_balance.append(subaddress) + assert subaddress.unlocked_balance is not None + if subaddress.unlocked_balance > TxWalletUtils.MAX_FEE: + subaddresses_unlocked.append(subaddress) + + # test requires at least one more subaddresses than the number being swept to verify it does not change + msg: str = f"Test requires balance in at least {NUM_SUBADDRESSES_TO_SWEEP + 1} subaddresses from non-default acccount; run send-to-multiple tests" + assert len(subaddresses_balance) >= NUM_SUBADDRESSES_TO_SWEEP + 1, msg + assert len(subaddresses_unlocked) >= NUM_SUBADDRESSES_TO_SWEEP + 1, "Wallet is waiting on unlocked funds" + + # sweep from first unlocked subaddresses + for i in range(NUM_SUBADDRESSES_TO_SWEEP): + # sweep unlocked account + unlocked_subaddress: MoneroSubaddress = subaddresses_unlocked[i] + config: MoneroTxConfig = MoneroTxConfig() + config.address = wallet.get_primary_address() + assert unlocked_subaddress.account_index is not None + assert unlocked_subaddress.index is not None + config.account_index = unlocked_subaddress.account_index + config.subaddress_indices.append(unlocked_subaddress.index) + config.relay = True + txs: list[MoneroTxWallet] = wallet.sweep_unlocked(config) + + # test transactions + assert len(txs) > 0 + for tx in txs: + assert tx.tx_set is not None + assert tx in tx.tx_set.txs + ctx: TxContext = TxContext() + ctx.wallet = wallet + ctx.config = config + ctx.is_send_response = True + ctx.is_sweep_response = True + TxWalletUtils.test_tx_wallet(tx, ctx) + + # assert unlocked balance is less than max fee + subaddress: MoneroSubaddress = wallet.get_subaddress(unlocked_subaddress.account_index, unlocked_subaddress.index) + assert subaddress.unlocked_balance is not None + assert subaddress.unlocked_balance < TxWalletUtils.MAX_FEE + + # test subaddresses after sweeping + subaddresses_after: list[MoneroSubaddress] = [] + for account in wallet.get_accounts(True): + if account.index == 0: + # skip default account + continue + for subaddress in account.subaddresses: + subaddresses_after.append(subaddress) + + assert len(subaddresses) == len(subaddresses_after) + for i, subaddress_before in enumerate(subaddresses): + subaddress_after: MoneroSubaddress = subaddresses_after[i] + assert subaddress_after.unlocked_balance is not None + + # determine if subaddress was swept + swept: bool = False + for j in range(NUM_SUBADDRESSES_TO_SWEEP): + subaddress_unlocked: MoneroSubaddress = subaddresses_unlocked[j] + account_eq: bool = subaddress_unlocked.account_index == subaddress_before.account_index + subaddr_eq: bool = subaddress_unlocked.index == subaddress_before.index + if account_eq and subaddr_eq: + swept = True + break + + # assert unlocked balance is less than max fee if swept, unchanged otherwise + if swept: + assert subaddress_after.unlocked_balance < TxWalletUtils.MAX_FEE + else: + assert subaddress_before.unlocked_balance == subaddress_after.unlocked_balance + + # Can sweep accounts + @pytest.mark.skipif(TestUtils.TEST_RESETS is False, reason="TEST_RESETS disabled") + def test_sweep_accounts(self, wallet: MoneroWallet) -> None: + TestUtils.WALLET_TX_TRACKER.wait_for_txs_to_clear_pool(wallet) + NUM_ACCOUNTS_TO_SWEEP: int = 1 + + # collect accounts with sufficient balance and unlocked balance to cover the fee + accounts: list[MoneroAccount] = wallet.get_accounts(True) + accounts_balance: list[MoneroAccount] = [] + accounts_unlocked: list[MoneroAccount] = [] + for account in accounts: + if account.index == 0: + # skip default account + continue + assert account.balance is not None + assert account.unlocked_balance is not None + if account.balance > TxWalletUtils.MAX_FEE: + accounts_balance.append(account) + if account.unlocked_balance > TxWalletUtils.MAX_FEE: + accounts_unlocked.append(account) + + # test requires at least one more accounts than the number being swept to verify it does not change + + msg: str = f"Test requires balance greater than the fee in at least {NUM_ACCOUNTS_TO_SWEEP + 1} non-default accounts; run send-to-multiple tests" + assert len(accounts_balance) >= NUM_ACCOUNTS_TO_SWEEP + 1, msg + assert len(accounts_unlocked) >= NUM_ACCOUNTS_TO_SWEEP + 1, "Wallet is waiting on unlocked funds" + + # sweep from first unlocked accounts + for i in range(NUM_ACCOUNTS_TO_SWEEP): + # sweep unlocked account + unlocked_account: MoneroAccount = accounts_unlocked[i] + assert unlocked_account.index is not None + config: MoneroTxConfig = MoneroTxConfig() + config.address = wallet.get_primary_address() + config.account_index = unlocked_account.index + config.relay = True + txs: list[MoneroTxWallet] = wallet.sweep_unlocked(config) + + # test transactions + assert len(txs) > 0 + for tx in txs: + ctx: TxContext = TxContext() + ctx.wallet = wallet + ctx.config = config + ctx.is_send_response = True + ctx.is_sweep_response = True + TxWalletUtils.test_tx_wallet(tx, ctx) + assert tx.tx_set is not None + assert tx in tx.tx_set.txs + + # assert unlocked account balance less than max fee + account: MoneroAccount = wallet.get_account(unlocked_account.index) + + # test accounts after sweeping + accounts_after: list[MoneroAccount] = wallet.get_accounts(True) + assert len(accounts) == len(accounts_after) + for i, account_before in enumerate(accounts): + account_after: MoneroAccount = accounts_after[i] + assert account_after.unlocked_balance is not None + + # determine if account was swept + swept: bool = False + for j in range(NUM_ACCOUNTS_TO_SWEEP): + account_unlocked: MoneroAccount = accounts_unlocked[j] + if account_unlocked.index == account_before.index: + swept = True + break + + # assert unlocked balance is less than max fee if swept, unchanged otherwise + if swept: + assert account_after.unlocked_balance < TxWalletUtils.MAX_FEE + else: + assert account_after.unlocked_balance == account_after.unlocked_balance + + # Can sweep the whole wallet by accounts + @pytest.mark.skipif(TestUtils.TEST_RESETS is False, reason="TEST_RESETS disabled") + def test_sweep_wallet_by_accounts(self, wallet: MoneroWallet) -> None: + IntegrationTestUtils.fund_wallet_and_wait_for_unlocked(wallet) + WalletSendUtils.test_sweep_wallet(wallet, None) + + # Can sweep the whole wallet by subaddresses + @pytest.mark.skipif(TestUtils.TEST_RESETS is False, reason="TEST_RESETS disabled") + @pytest.mark.xfail(reason="TODO wallet2 error: No unlocked balance in the specified subaddress(es)") + def test_sweep_wallet_by_subaddresses(self, wallet: MoneroWallet) -> None: + IntegrationTestUtils.fund_wallet_and_wait_for_unlocked(wallet) + WalletSendUtils.test_sweep_wallet(wallet, True) + + +@pytest.mark.integration +class TestMoneroWalletFullSweep(FullWalletSupport, BaseTestMoneroWalletSweep): + """Full wallet sweep integration tests.""" + + +@pytest.mark.integration +class TestMoneroWalletRpcSweep(RpcWalletSupport, BaseTestMoneroWalletSweep): + """Rpc wallet sweep integration tests.""" + + +@pytest.mark.unit +class TestMoneroWalletKeysSweep(KeysWalletSupport, BaseTestMoneroWalletSweep): + """Keys-only wallet sweep unit tests.""" + + @pytest.mark.not_supported + @override + def test_sweep_outputs(self, wallet: MoneroWallet) -> None: + return super().test_sweep_outputs(wallet) + + @pytest.mark.not_supported + @override + def test_sweep_dust_no_relay(self, wallet: MoneroWallet) -> None: + return super().test_sweep_dust_no_relay(wallet) + + @pytest.mark.not_supported + @override + def test_sweep_dust(self, wallet: MoneroWallet) -> None: + return super().test_sweep_dust(wallet) + + @pytest.mark.not_supported + @override + def test_sweep_subaddresses(self, wallet: MoneroWallet) -> None: + return super().test_sweep_subaddresses(wallet) + + @pytest.mark.not_supported + @override + def test_sweep_accounts(self, wallet: MoneroWallet) -> None: + return super().test_sweep_accounts(wallet) + + @pytest.mark.not_supported + @override + def test_sweep_wallet_by_accounts(self, wallet: MoneroWallet) -> None: + return super().test_sweep_wallet_by_accounts(wallet) + + @pytest.mark.not_supported + @override + def test_sweep_wallet_by_subaddresses(self, wallet: MoneroWallet) -> None: + return super().test_sweep_wallet_by_subaddresses(wallet) diff --git a/tests/wallet/test_sync.py b/tests/wallet/test_sync.py new file mode 100644 index 00000000..0aa01dd5 --- /dev/null +++ b/tests/wallet/test_sync.py @@ -0,0 +1,444 @@ +from __future__ import annotations + +import logging +from datetime import datetime +from time import sleep +from typing import Optional + +import pytest +from monero import ( + MoneroDaemonRpc, + MoneroError, + MoneroRpcConnection, + MoneroSyncResult, + MoneroTxWallet, + MoneroWallet, + MoneroWalletConfig, + MoneroWalletFull, + MoneroWalletRpc, +) +from typing_extensions import override + +from utils import ( + AssertUtils, + GenUtils, + MiningUtils, + SyncProgressTester, + SyncSeedTester, + TestUtils, + TestUtils as Utils, + TxWalletUtils, + WalletEqualityUtils, + WalletNotificationCollector, + WalletTxsUtils, +) +from .base_test_monero_wallet import BaseTestMoneroWallet +from .wallet_support import FullWalletSupport, RpcWalletSupport, KeysWalletSupport + +logger: logging.Logger = logging.getLogger("TestMoneroWalletSync") + + +class BaseTestMoneroWalletSync(BaseTestMoneroWallet): + """Common wallet sync tests.""" + + # Can sync (without progress) + # TODO test syncing from start height + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_sync_without_progress(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: + num_blocks: int = 100 + chain_height: int = daemon.get_height() + assert chain_height >= num_blocks + result: MoneroSyncResult = wallet.sync(chain_height - num_blocks) # sync end of chain + assert result.num_blocks_fetched >= 0 + assert result.received_money is not None + + # Can get the current height that the wallet is synchronized to + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_height(self, wallet: MoneroWallet) -> None: + height: int = wallet.get_height() + assert height >= 0 + + # Can get a blockchain height by date + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_height_by_date(self, wallet: MoneroWallet) -> None: + # collect dates to test starting 100 days ago + day_ms: int = 24 * 60 * 60 * 1000 + # TODO monero-project: today's date can throw exception as "in future" so we test up to yesterday + yesterday: int = GenUtils.current_timestamp() - day_ms + dates: list[datetime] = [] + date_range: list[int] = list(range(99)) + date_range.reverse() + + for i in date_range: + # subtract i days + dates.append(datetime.fromtimestamp((yesterday - day_ms * i) / 1000)) + + # test heights by date + last_height: Optional[int] = None + for date in dates: + height: int = wallet.get_height_by_date(date.year + 1900, date.month + 1, date.day) + assert (height >= 0) + if last_height is not None: + assert (height >= last_height) + last_height = height + + assert last_height is not None + assert (last_height >= 0) + height = wallet.get_height() + assert (height >= 0) + + # test future date + tomorrow: datetime = datetime.fromtimestamp((yesterday + day_ms * 2) / 1000) + with pytest.raises(MoneroError, match="specified date is in the future"): + wallet.get_height_by_date(tomorrow.year + 1900, tomorrow.month + 1, tomorrow.day) + + # Can scan transactions by id + @pytest.mark.skipif(TestUtils.TEST_RESETS is False, reason="TEST_RESETS disabled") + def test_scan_txs(self, wallet: MoneroWallet) -> None: + config: MoneroWalletConfig = MoneroWalletConfig() + config.seed = wallet.get_seed() + config.restore_height = 0 + scan_wallet: MoneroWallet = self._create_wallet(config) + logger.debug("Created scan wallet") + WalletTxsUtils.test_scan_txs(wallet, scan_wallet) + + # Can rescan spent + @pytest.mark.skipif(TestUtils.TEST_RESETS is False, reason="TEST_RESETS disabled") + def test_rescan_spent(self, wallet: MoneroWallet) -> None: + wallet.rescan_spent() + + # Can rescan the blockchain + @pytest.mark.skipif(TestUtils.TEST_RESETS is False, reason="TEST_RELAYS disabled") + @pytest.mark.skip(reason="Disabled so tests don't delete local cache") + def test_rescan_blockchain(self, wallet: MoneroWallet) -> None: + wallet.rescan_blockchain() + for tx in wallet.get_txs(): + TxWalletUtils.test_tx_wallet(tx) + + +@pytest.mark.integration +class TestMoneroWalletFullSync(FullWalletSupport, BaseTestMoneroWalletSync): + """Full wallet sync integration tests.""" + + def _test_sync_seed( + self, + daemon: MoneroDaemonRpc, + wallet: MoneroWalletFull, + start_height: Optional[int], + restore_height: Optional[int], + skip_gt_comparison: bool = False, + test_post_sync_notifications: bool = False + ) -> None: + tester: SyncSeedTester = SyncSeedTester( + daemon, wallet, self._create_wallet, + start_height, restore_height, + skip_gt_comparison, test_post_sync_notifications + ) + tester.test() + + # Can sync a wallet with a randomly generated seed + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_sync_random(self, daemon: MoneroDaemonRpc) -> None: + assert daemon.is_connected(), "Not connected to daemon" + + # create test wallet + wallet: MoneroWalletFull = self._create_wallet(MoneroWalletConfig(), False) + restore_height: int = daemon.get_height() + + # test wallet's height before syncing + AssertUtils.assert_equals(Utils.get_daemon_rpc_connection(), wallet.get_daemon_connection()) + assert restore_height == wallet.get_daemon_height() + assert wallet.is_connected_to_daemon() + assert wallet.is_synced() is False + assert wallet.get_height() == 1 + assert wallet.get_restore_height() == restore_height + assert wallet.get_daemon_height() == daemon.get_height() + + # sync the wallet + progress_tester: SyncProgressTester = SyncProgressTester(wallet, wallet.get_restore_height(), wallet.get_daemon_height()) + result: MoneroSyncResult = wallet.sync(progress_tester) + progress_tester.on_done(wallet.get_daemon_height()) + + # test result after syncing + wallet_gt: MoneroWalletFull = Utils.create_wallet_ground_truth(Utils.NETWORK_TYPE, wallet.get_seed(), None, restore_height) + wallet_gt.sync() + + try: + assert wallet.is_connected_to_daemon() + assert wallet.is_synced() + assert result.num_blocks_fetched == 0 + assert result.received_money is False + assert wallet.get_height() == daemon.get_height() + + # sync the wallet with default params + wallet.sync() + assert wallet.is_synced() + assert wallet.get_height() == daemon.get_height() + + # compare wallet to ground truth + WalletEqualityUtils.test_wallet_full_equality_on_chain(wallet_gt, wallet) + finally: + wallet_gt.close(True) + wallet.close() + + # attempt to sync unconnected wallet + config: MoneroWalletConfig = MoneroWalletConfig() + config.server = MoneroRpcConnection(Utils.OFFLINE_SERVER_URI) + wallet = self._create_wallet(config) + try: + with pytest.raises(Exception) as exc_info: + wallet.sync() + assert str(exc_info.value) == "Wallet is not connected to daemon" + finally: + wallet.close() + + # Can sync a wallet created from seed from the genesis + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + @pytest.mark.skipif(Utils.LITE_MODE, reason="LITE_MODE enabled") + def test_sync_seed_from_genesis(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletFull) -> None: + self._test_sync_seed(daemon, wallet, None, None, True, False) + + # Can sync a wallet created from seed from a restore height + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + @pytest.mark.skipif(Utils.LITE_MODE, reason="LITE_MODE enabled") + def test_sync_seed_from_restore_height(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletFull) -> None: + self._test_sync_seed(daemon, wallet, None, Utils.FIRST_RECEIVE_HEIGHT) + + # Can sync a wallet created from seed from a start height + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + @pytest.mark.skipif(Utils.LITE_MODE, reason="LITE_MODE enabled") + def test_sync_seed_from_start_height(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletFull) -> None: + self._test_sync_seed(daemon, wallet, Utils.FIRST_RECEIVE_HEIGHT, None, False, True) + + # Can sync a wallet created from seed from a start height less than the restore height + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + @pytest.mark.skipif(Utils.LITE_MODE, reason="LITE_MODE enabled") + def test_sync_seed_start_height_lt_restore_height(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletFull) -> None: + self._test_sync_seed(daemon, wallet, Utils.FIRST_RECEIVE_HEIGHT, Utils.FIRST_RECEIVE_HEIGHT + 3) + + # Can sync a wallet created from seed from a start height greater than the restore height + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + @pytest.mark.skipif(Utils.LITE_MODE, reason="LITE_MODE enabled") + def test_sync_seed_start_height_gt_restore_height(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletFull) -> None: + self._test_sync_seed(daemon, wallet, Utils.FIRST_RECEIVE_HEIGHT + 3, Utils.FIRST_RECEIVE_HEIGHT) + + # Can sync a wallet created from keys + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + @pytest.mark.skipif(Utils.LITE_MODE, reason="LITE_MODE enabled") + def test_sync_wallet_from_keys(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletFull) -> None: + # recreate test wallet from keys + path: str = Utils.get_random_wallet_path() + config: MoneroWalletConfig = MoneroWalletConfig() + config.path = path + config.primary_address = wallet.get_primary_address() + config.private_view_key = wallet.get_private_view_key() + config.private_spend_key = wallet.get_private_spend_key() + config.restore_height = Utils.FIRST_RECEIVE_HEIGHT + wallet_keys: MoneroWalletFull = self._create_wallet(config, False) + + # create ground truth wallet for comparison + wallet_gt: MoneroWalletFull = Utils.create_wallet_ground_truth(Utils.NETWORK_TYPE, Utils.SEED, None, Utils.FIRST_RECEIVE_HEIGHT) + + # test wallet and close as final step + try: + assert wallet_keys.get_seed() == wallet_gt.get_seed() + assert wallet_keys.get_primary_address() == wallet_gt.get_primary_address() + assert wallet_keys.get_private_view_key() == wallet_gt.get_private_view_key() + assert wallet_keys.get_public_view_key() == wallet_gt.get_public_view_key() + assert wallet_keys.get_private_spend_key() == wallet_gt.get_private_spend_key() + assert wallet_keys.get_public_spend_key() == wallet_gt.get_public_spend_key() + assert Utils.FIRST_RECEIVE_HEIGHT == wallet_gt.get_restore_height() + assert wallet_keys.is_connected_to_daemon() + assert wallet_keys.is_synced() is False + + # sync the wallet + progress_tester: SyncProgressTester = SyncProgressTester(wallet_keys, Utils.FIRST_RECEIVE_HEIGHT, wallet_keys.get_daemon_max_peer_height()) + result: MoneroSyncResult = wallet_keys.sync(progress_tester) + progress_tester.on_done(wallet_keys.get_daemon_height()) + + # test result after syncing + assert wallet_keys.is_synced() + assert wallet_keys.get_daemon_height() - Utils.FIRST_RECEIVE_HEIGHT == result.num_blocks_fetched + assert result.received_money is True + assert wallet_keys.get_height() == daemon.get_height() + assert wallet_keys.get_daemon_height() == daemon.get_height() + + # wallet should be fully synced so first tx happens on true restore height + txs: list[MoneroTxWallet] = wallet.get_txs() + assert len(txs) > 0 + tx: MoneroTxWallet = txs[0] + tx_height: int | None = tx.get_height() + assert tx_height is not None + assert Utils.FIRST_RECEIVE_HEIGHT == tx_height + + # compare with ground truth + WalletEqualityUtils.test_wallet_full_equality_on_chain(wallet_gt, wallet_keys) + finally: + wallet_gt.close(True) + wallet_keys.close() + + # Can start and stop syncing + # TODO test start syncing, notification of syncs happening, stop syncing, no notifications, etc + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + @pytest.mark.skipif(Utils.LITE_MODE, reason="LITE_MODE enabled") + def test_start_stop_syncing(self, daemon: MoneroDaemonRpc) -> None: + # test unconnected wallet + config: MoneroWalletConfig = MoneroWalletConfig() + config.server = MoneroRpcConnection(Utils.OFFLINE_SERVER_URI) + config.path = Utils.get_random_wallet_path() + wallet: MoneroWalletFull = self._create_wallet(config) + try: + assert len(wallet.get_seed()) > 0 + assert wallet.get_height() == 1 + assert wallet.get_balance() == 0 + wallet.start_syncing() # succeeds while offline, syncing when a daemon becomes reachable + finally: + wallet.close() + + # test connecting wallet + config = MoneroWalletConfig() + config.path = Utils.get_random_wallet_path() + config.server = MoneroRpcConnection(Utils.OFFLINE_SERVER_URI) + wallet = self._create_wallet(config) + try: + assert len(wallet.get_seed()) > 0 + wallet.set_daemon_connection(daemon.get_rpc_connection()) + assert wallet.get_height() == 1 + assert wallet.is_synced() is False + assert wallet.get_balance() == 0 + chain_height: int = wallet.get_daemon_height() + wallet.set_restore_height(chain_height - 3) + wallet.start_syncing() + assert chain_height - 3 == wallet.get_restore_height() + AssertUtils.assert_equals(daemon.get_rpc_connection(), wallet.get_daemon_connection()) + wallet.stop_syncing() + wallet.sync() + wallet.stop_syncing() + wallet.stop_syncing() + finally: + wallet.close() + + # test that sync starts automatically + restore_height: int = daemon.get_height() - 100 + config = MoneroWalletConfig() + config.path = Utils.get_random_wallet_path() + config.seed = Utils.SEED + config.restore_height = restore_height + wallet = self._create_wallet(config, False) + try: + # start syncing + assert wallet.get_height() == 1 + assert wallet.get_restore_height() == restore_height + assert wallet.is_synced() is False + assert wallet.get_balance() == 0 + wallet.start_syncing(Utils.SYNC_PERIOD_IN_MS) + + # pause for sync to start + sleep(1 + (Utils.SYNC_PERIOD_IN_MS / 1000)) + + # test that wallet has started syncing + assert wallet.get_height() > 1 + + # stop syncing + wallet.stop_syncing() + + # TODO monero-project: wallet.cpp m_synchronized only ever set to true, never false + finally: + wallet.close() + + @pytest.mark.skipif(Utils.REGTEST, reason="Cannot retrieve accurate height by date from regtest fakechain") + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + @override + def test_get_height_by_date(self, wallet: MoneroWallet) -> None: + return super().test_get_height_by_date(wallet) + + @pytest.mark.skipif(Utils.REGTEST is False, reason="REGTEST disabled") + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_height_by_date_regtest(self, wallet: MoneroWallet) -> None: + # the base test's fixed dates fall outside a short regtest chain + with pytest.raises(RuntimeError): + super().test_get_height_by_date(wallet) + + # Can wait for the next block to be added and be notified of its height + @pytest.mark.skipif(Utils.TEST_NOTIFICATIONS is False, reason="TEST_NOTIFICATIONS disabled") + @pytest.mark.flaky(reruns=5, reruns_delay=10, only_rerun=[]) + def test_wait_for_next_block(self, wallet: MoneroWalletFull) -> None: + height_before: int = wallet.get_height() + MiningUtils.try_start_mining() + try: + height: int = wallet.wait_for_next_block() + # the notification carries the height of the new block, which is the chain + # length the wallet knew before it was added, so it is only greater when the wallet lagged behind + assert height >= height_before + finally: + MiningUtils.try_stop_mining() + + +@pytest.mark.integration +class TestMoneroWalletRpcSync(RpcWalletSupport, BaseTestMoneroWalletSync): + """Rpc wallet sync integration tests.""" + + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_sync_progress(self, wallet: MoneroWalletRpc) -> None: + listener: WalletNotificationCollector = WalletNotificationCollector() + # expected error message + ERR_MSG: str = "Monero Wallet RPC does not support reporting sync progress" + + # sync with listener + with pytest.raises(Exception) as exc_info: + wallet.sync(listener) + assert str(exc_info.value) == ERR_MSG + + # sync with listener from start height + with pytest.raises(Exception) as exc_info: + wallet.sync(0, listener) + assert str(exc_info.value) == ERR_MSG + + # Can set the poll period for wallet notifications + @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_set_poll_period_in_ms(self, wallet: MoneroWalletRpc) -> None: + try: + wallet.set_poll_period_in_ms(1000) + finally: + # restore the configured period so later tests poll at the expected rate + wallet.set_poll_period_in_ms(Utils.SYNC_PERIOD_IN_MS) + + @pytest.mark.not_supported + @override + def test_get_height_by_date(self, wallet: MoneroWallet) -> None: + return super().test_get_height_by_date(wallet) + + +@pytest.mark.unit +class TestMoneroWalletKeysSync(KeysWalletSupport, BaseTestMoneroWalletSync): + """Keys-only wallet sync unit tests.""" + + @pytest.mark.not_supported + @override + def test_sync_without_progress(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: + return super().test_sync_without_progress(daemon, wallet) + + @pytest.mark.not_supported + @override + def test_get_height(self, wallet: MoneroWallet) -> None: + return super().test_get_height(wallet) + + @pytest.mark.not_supported + @override + def test_get_height_by_date(self, wallet: MoneroWallet) -> None: + return super().test_get_height_by_date(wallet) + + @pytest.mark.not_supported + @override + def test_scan_txs(self, wallet: MoneroWallet) -> None: + return super().test_scan_txs(wallet) + + @pytest.mark.not_supported + @override + def test_rescan_blockchain(self, wallet: MoneroWallet) -> None: + return super().test_rescan_blockchain(wallet) + + @pytest.mark.not_supported + @override + def test_rescan_spent(self, wallet: MoneroWallet) -> None: + return super().test_rescan_spent(wallet) diff --git a/tests/wallet/test_transfers.py b/tests/wallet/test_transfers.py new file mode 100644 index 00000000..2b30bc06 --- /dev/null +++ b/tests/wallet/test_transfers.py @@ -0,0 +1,313 @@ +from __future__ import annotations + +import logging + +import pytest +from monero import ( + MoneroIncomingTransfer, + MoneroOutgoingTransfer, + MoneroTransfer, + MoneroTransferQuery, + MoneroTxQuery, + MoneroTxWallet, + MoneroWallet, +) +from typing_extensions import override + +from utils import TestUtils, WalletTransfersUtils, WalletTxsUtils +from .base_test_monero_wallet import BaseTestMoneroWallet +from .wallet_support import FullWalletSupport, RpcWalletSupport, KeysWalletSupport + +logger: logging.Logger = logging.getLogger("TestMoneroWalletTransfers") + + +class BaseTestMoneroWalletTransfers(BaseTestMoneroWallet): + """Common wallet transfers tests.""" + + # Can get transfers in the wallet, accounts, and subaddresses + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_transfers(self, wallet: MoneroWallet) -> None: + # get all transfers + WalletTransfersUtils.get_and_test_transfers(wallet, None, None, True) + + # get transfers by account index + non_default_incoming: bool = False + for account in wallet.get_accounts(True): + transfer_query: MoneroTransferQuery = MoneroTransferQuery() + transfer_query.account_index = account.index + account_transfers: list[MoneroTransfer] = WalletTransfersUtils.get_and_test_transfers(wallet, transfer_query, None, None) + for transfer in account_transfers: + assert transfer.account_index == account.index + + # get transfers by subaddress index + subaddress_transfers: list[MoneroTransfer] = [] + for subaddress in account.subaddresses: + subaddress_query: MoneroTransferQuery = MoneroTransferQuery() + subaddress_query.account_index = subaddress.account_index + subaddress_query.subaddress_index = subaddress.index + transfers: list[MoneroTransfer] = WalletTransfersUtils.get_and_test_transfers(wallet, subaddress_query, None, None) + + for transfer in transfers: + # test account and subaddress indices + assert subaddress.account_index == transfer.account_index + if transfer.is_incoming() is True: + assert isinstance(transfer, MoneroIncomingTransfer) + assert subaddress.index == transfer.subaddress_index + if transfer.account_index != 0 and transfer.subaddress_index != 0: + non_default_incoming = True + else: + assert isinstance(transfer, MoneroOutgoingTransfer) + assert subaddress.index in transfer.subaddress_indices + if transfer.account_index != 0: + for subaddr_idx in transfer.subaddress_indices: + if subaddr_idx > 0: + non_default_incoming = True + break + + # don't add duplicates + # TODO monero-wallet-rpc: duplicate outgoing transfers returned for different + # subaddress indices, way to return outgoing subaddress indices? + + found: bool = False + for subaddress_transfer in subaddress_transfers: + eq_hash: bool = transfer.tx.hash == subaddress_transfer.tx.hash + if transfer.serialize() == subaddress_transfer.serialize() and eq_hash: + found = True + break + + if not found: + subaddress_transfers.append(transfer) + + assert len(account_transfers) == len(subaddress_transfers) + + # collect unique subaddress indices + subaddress_indices: set[int] = set() + for transfer in subaddress_transfers: + if transfer.is_incoming(): + assert isinstance(transfer, MoneroIncomingTransfer) + assert transfer.subaddress_index is not None + subaddress_indices.add(transfer.subaddress_index) + else: + assert isinstance(transfer, MoneroOutgoingTransfer) + for idx in transfer.subaddress_indices: + subaddress_indices.add(idx) + + # get and test transfers by subaddress indices + transfer_query = MoneroTransferQuery() + transfer_query.account_index = account.index + for idx in subaddress_indices: + transfer_query.subaddress_indices.append(idx) + + transfers = WalletTransfersUtils.get_and_test_transfers(wallet, transfer_query, None, None) + # TODO monero-wallet-rpc: these may not be equal because outgoing transfers are always from subaddress 0 (#5171) + # and/or incoming transfers from/to same account are occluded (#4500) + assert len(subaddress_transfers) == len(transfers) + for transfer in transfers: + assert transfer.account_index == account.index + if transfer.is_incoming(): + assert isinstance(transfer, MoneroIncomingTransfer) + assert transfer.subaddress_index in subaddress_indices + else: + assert isinstance(transfer, MoneroOutgoingTransfer) + intersections: set[int] = set(subaddress_indices) + overlap: set[int] = intersections.intersection(transfer.subaddress_indices) + assert overlap is not None and len(overlap) > 0, "Subaddresses must overlap" + + # ensure transfer found with non-zero account and subaddress indices + assert non_default_incoming, "No transfers found in non-default account and subaddress; run send-to-multiple tests" + + # Can get transfers with additional configuration + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_transfers_with_query(self, wallet: MoneroWallet) -> None: + # get incoming transfers + query: MoneroTransferQuery = MoneroTransferQuery() + query.incoming = True + transfers: list[MoneroTransfer] = WalletTransfersUtils.get_and_test_transfers(wallet, query, None, True) + for transfer in transfers: + assert transfer.is_incoming() + + # get outgoing transfers + query = MoneroTransferQuery() + query.outgoing = True + transfers = WalletTransfersUtils.get_and_test_transfers(wallet, query, None, True) + for transfer in transfers: + assert transfer.is_outgoing() + + # get confirmed transfers to account 0 + query = MoneroTransferQuery() + query.account_index = 0 + query.tx_query = MoneroTxQuery() + query.tx_query.is_confirmed = True + transfers = WalletTransfersUtils.get_and_test_transfers(wallet, query, None, True) + for transfer in transfers: + assert transfer.account_index == 0 + assert transfer.tx is not None + assert transfer.tx.is_confirmed is True + + # get confirmed transfers to (1, 2) + query = MoneroTransferQuery() + query.account_index = 1 + query.subaddress_index = 2 + query.tx_query = MoneroTxQuery() + query.tx_query.is_confirmed = True + transfers = WalletTransfersUtils.get_and_test_transfers(wallet, query, None, True) + for transfer in transfers: + assert transfer.account_index == 1 + if transfer.is_incoming(): + assert isinstance(transfer, MoneroIncomingTransfer) + assert transfer.subaddress_index == 2 + else: + assert isinstance(transfer, MoneroOutgoingTransfer) + assert 2 in transfer.subaddress_indices + + assert transfer.tx is not None + assert transfer.tx.is_confirmed is True + + # get transfers in the tx pool + query = MoneroTransferQuery() + query.tx_query = MoneroTxQuery() + query.tx_query.in_tx_pool = True + transfers = WalletTransfersUtils.get_and_test_transfers(wallet, query, None, None) + for transfer in transfers: + assert transfer.tx is not None + assert transfer.tx.in_tx_pool is True + + # get random transactions + txs: list[MoneroTxWallet] = WalletTxsUtils.get_random_transactions(wallet, None, 3, 5) + + # get transfers with a tx hash + tx_hashes: list[str] = [] + for tx in txs: + assert tx.hash is not None + tx_hashes.append(tx.hash) + query = MoneroTransferQuery() + query.tx_query = MoneroTxQuery() + query.tx_query.hash = tx.hash + transfers = WalletTransfersUtils.get_and_test_transfers(wallet, query, None, True) + for transfer in transfers: + assert transfer.tx is not None + assert tx.hash == transfer.tx.hash + + # get transfers with tx hashes + query = MoneroTransferQuery() + query.tx_query = MoneroTxQuery() + query.tx_query.hashes = tx_hashes + transfers = WalletTransfersUtils.get_and_test_transfers(wallet, query, None, True) + for transfer in transfers: + assert transfer.tx is not None + assert transfer.tx.hash is not None + assert transfer.tx.hash in tx_hashes + + # TODO test that transfers with the same tx_hash have same tx reference + # TODO test transfers destinations + + # get transfers with pre-built query that are confirmed and have outgoing destinations + transfer_query: MoneroTransferQuery = MoneroTransferQuery() + transfer_query.outgoing = True + transfer_query.has_destinations = True + transfer_query.tx_query = MoneroTxQuery() + transfer_query.tx_query.is_confirmed = True + transfers = WalletTransfersUtils.get_and_test_transfers(wallet, transfer_query, None, None) + for transfer in transfers: + assert transfer.is_outgoing() is True + assert isinstance(transfer, MoneroOutgoingTransfer) + assert len(transfer.destinations) > 0 + assert transfer.tx is not None + assert transfer.tx.is_confirmed is True + + # get incoming transfers to account 0 which has outgoing transfers (i.e. originated from the same wallet) + query = MoneroTransferQuery() + query.account_index = 1 + query.incoming = True + query.tx_query = MoneroTxQuery() + query.tx_query.is_outgoing = True + transfers = wallet.get_transfers(query) + assert len(transfers) > 0 + for transfer in transfers: + assert transfer.is_incoming() is True + assert transfer.account_index == 1 + assert transfer.tx is not None + assert transfer.tx.is_outgoing is True + assert transfer.tx.outgoing_transfer is None + + # get incoming transfers to a spefici address + subaddress: str = wallet.get_address(1, 0) + query = MoneroTransferQuery() + query.incoming = True + query.address = subaddress + transfers = wallet.get_transfers(query) + assert len(transfers) > 0 + for transfer in transfers: + assert isinstance(transfer, MoneroIncomingTransfer) + assert transfer.account_index == 1 + assert transfer.subaddress_index == 0 + assert transfer.address == subaddress + + # Validates inputs when getting transfers + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False or TestUtils.LITE_MODE, reason="TEST_NON_RELAYS disabled or LITE_MODE enabled") + def test_validate_inputs_get_transfers(self, wallet: MoneroWallet) -> None: + # test with invalid hash + transfer_query: MoneroTransferQuery = MoneroTransferQuery() + transfer_query.tx_query = MoneroTxQuery() + transfer_query.tx_query.hash = "invalid_id" + + transfers: list[MoneroTransfer] = wallet.get_transfers(transfer_query) + assert len(transfers) == 0 + + # test invalid hash in list + random_txs: list[MoneroTxWallet] = WalletTxsUtils.get_random_transactions(wallet, None, 3, 5) + transfer_query.tx_query = MoneroTxQuery() + random_hash: str | None = random_txs[0].hash + assert random_hash is not None + transfer_query.tx_query.hashes.append(random_hash) + transfer_query.tx_query.hashes.append("invalid_id") + + transfers = wallet.get_transfers(transfer_query) + assert len(transfers) > 0 + + tx: MoneroTxWallet = transfers[0].tx + for transfer in transfers: + assert transfer.tx == tx + + # test unused subaddress indices + transfer_query = MoneroTransferQuery() + transfer_query.account_index = 0 + transfer_query.subaddress_indices.append(1234907) + transfers = wallet.get_transfers(transfer_query) + + # test invalid subaddress index + transfer_query = MoneroTransferQuery() + transfer_query.account_index = 0 + with pytest.raises(Exception): + transfer_query.subaddress_index = -1 + wallet.get_transfers(transfer_query) + + +@pytest.mark.integration +class TestMoneroWalletFullTransfers(FullWalletSupport, BaseTestMoneroWalletTransfers): + """Full wallet transfers integration tests.""" + + +@pytest.mark.integration +class TestMoneroWalletRpcTransfers(RpcWalletSupport, BaseTestMoneroWalletTransfers): + """Rpc wallet transfers integration tests.""" + + +@pytest.mark.unit +class TestMoneroWalletKeysTransfers(KeysWalletSupport, BaseTestMoneroWalletTransfers): + """Keys-only wallet transfers unit tests.""" + + @pytest.mark.not_supported + @override + def test_get_transfers(self, wallet: MoneroWallet) -> None: + return super().test_get_transfers(wallet) + + @pytest.mark.not_supported + @override + def test_validate_inputs_get_transfers(self, wallet: MoneroWallet) -> None: + return super().test_validate_inputs_get_transfers(wallet) + + @pytest.mark.not_supported + @override + def test_get_transfers_with_query(self, wallet: MoneroWallet) -> None: + return super().test_get_transfers_with_query(wallet) diff --git a/tests/wallet/test_txs.py b/tests/wallet/test_txs.py new file mode 100644 index 00000000..cdca28a2 --- /dev/null +++ b/tests/wallet/test_txs.py @@ -0,0 +1,645 @@ +from __future__ import annotations + +import logging +from random import shuffle +from typing import Optional + +import pytest +from monero import ( + MoneroBlock, + MoneroOutputQuery, + MoneroTransferQuery, + MoneroTxQuery, + MoneroTxWallet, + MoneroUtils, + MoneroWallet, +) +from typing_extensions import override + +from utils import ( + AssertUtils, + GenUtils, + StringUtils, + TestUtils, + TransferUtils, + TxContext, + TxWalletUtils, + WalletTxsUtils, +) +from .base_test_monero_wallet import BaseTestMoneroWallet +from .wallet_support import FullWalletSupport, RpcWalletSupport, KeysWalletSupport + +logger: logging.Logger = logging.getLogger("TestMoneroWalletTxs") + + +class BaseTestMoneroWalletTxs(BaseTestMoneroWallet): + """Common wallet txs tests.""" + + # Can get transactions in the wallet + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_txs_wallet(self, wallet: MoneroWallet) -> None: + #non_default_incoming: bool = False + txs: list[MoneroTxWallet] = WalletTxsUtils.get_and_test_txs(wallet, None, None, True, TestUtils.REGTEST) + assert len(txs) > 0, "Wallet has no txs to test" + # TODO make consistent with test funded wallet + # assert TestUtils.FIRST_RECEIVE_HEIGHT == txs[0].get_height(), "First tx's restore height must match the restore height in TestUtils" + + # build test context + ctx: TxContext = TxContext() + ctx.wallet = wallet + + # test each transaction + block_per_height: dict[int, MoneroBlock] = {} + for i, tx in enumerate(txs): + TxWalletUtils.test_tx_wallet(tx, ctx) + + # test merging equivalent txs + it: MoneroTxWallet = txs[i] # is the same as tx + copy1: MoneroTxWallet = it.copy() + copy2: MoneroTxWallet = it.copy() + + if copy1.is_confirmed: + assert it.block is not None + copy1.block = it.block.copy() + copy1.block.txs = [copy1] + + if copy2.is_confirmed: + assert it.block is not None + copy2.block = it.block.copy() + copy2.block.txs = [copy2] + + copy1.merge(copy2) + TxWalletUtils.test_tx_wallet(copy1, ctx) + + # find non-default incoming + for transfer in it.incoming_transfers: + assert transfer.account_index is not None + assert transfer.subaddress_index is not None + #if transfer.account_index != 0 and transfer.subaddress_index != 0: + # non_default_incoming = True + + # ensure unique block reference per height + if it.is_confirmed: + h: int | None = it.get_height() + assert h is not None + block: MoneroBlock | None = block_per_height.get(h) + if block is None: + assert it.block is not None + block_per_height[i] = it.block + else: + AssertUtils.assert_equals(block, it.block) + assert block == it.block, "Block references for same height must be same" + + # Can get transactions by hash + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_txs_by_hash(self, wallet: MoneroWallet) -> None: + # max number of txs to test + max_num_txs: int = 10 + + # fetch all txs for testing + txs: list[MoneroTxWallet] = wallet.get_txs() + num_txs: int = len(txs) + assert num_txs > 1, f"Test requires at least 2 txs to fetch by hash, got {num_txs}" + + # randomly pick a few for fetching by hash + shuffle(txs) + txs = txs[0:min(max_num_txs, num_txs)] + + # test fetching by hash + tx_hash: str | None = txs[0].hash + assert tx_hash is not None + fetched_tx: MoneroTxWallet | None = wallet.get_tx(tx_hash) + assert fetched_tx is not None + assert tx_hash == fetched_tx.hash + TxWalletUtils.test_tx_wallet(fetched_tx) + + # test fetching by hashes + tx_id1: str | None = txs[0].hash + tx_id2: str | None = txs[1].hash + assert tx_id1 is not None + assert tx_id2 is not None + fetched_txs: list[MoneroTxWallet] = wallet.get_txs([tx_id1, tx_id2]) + num_fetched_txs: int = len(fetched_txs) + assert num_fetched_txs == 2, f"Expected 2 txs, got {num_fetched_txs}" + + # test fetching by hashes as collection + tx_hashes: list[str] = [] + for tx in txs: + assert tx.hash is not None + tx_hashes.append(tx.hash) + + fetched_txs = wallet.get_txs(tx_hashes) + assert len(txs) == len(fetched_txs) + for i, tx in enumerate(txs): + fetched_tx = fetched_txs[i] + assert tx.hash == fetched_tx.hash + TxWalletUtils.test_tx_wallet(fetched_tx) + + # test fetching with missing tx hashes + missing_hash: str = "d01ede9cde813b2a693069b640c4b99c5adbdb49fbbd8da2c16c8087d0c3e320" + tx_hashes.append(missing_hash) + fetched_txs = wallet.get_txs(tx_hashes) + assert len(txs) == len(fetched_txs) + for i, tx in enumerate(txs): + fetched_tx = fetched_txs[i] + assert tx.hash == fetched_tx.hash + TxWalletUtils.test_tx_wallet(fetched_tx) + + # Can get transactions with additional configuration + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_txs_with_query(self, wallet: MoneroWallet) -> None: + # get random transactions for testing + random_txs: list[MoneroTxWallet] = WalletTxsUtils.get_random_transactions(wallet, None, 3, 5) + for random_tx in random_txs: + TxWalletUtils.test_tx_wallet(random_tx, None) + + # get transactions by hash + tx_hashes: list[str] = [] + for random_tx in random_txs: + assert random_tx.hash is not None + tx_hashes.append(random_tx.hash) + query: MoneroTxQuery = MoneroTxQuery() + query.hash = random_tx.hash + txs: list[MoneroTxWallet] = WalletTxsUtils.get_and_test_txs(wallet, query, None, True, TestUtils.REGTEST) + assert len(txs) == 1 + # txs change with chain so check mergeability + merged: MoneroTxWallet = txs[0] + merged.merge(random_tx.copy()) + TxWalletUtils.test_tx_wallet(merged) + + # get transactions by hashes + query = MoneroTxQuery() + query.hashes = tx_hashes + txs = WalletTxsUtils.get_and_test_txs(wallet, query, None, None, TestUtils.REGTEST) + assert len(txs) == len(random_txs) + for tx in txs: + assert tx.hash in tx_hashes + + # get transactions with an outgoing transfer + ctx: TxContext = TxContext() + ctx.has_outgoing_transfer = True + query = MoneroTxQuery() + query.is_outgoing = True + txs = WalletTxsUtils.get_and_test_txs(wallet, query, ctx, True, TestUtils.REGTEST) + for tx in txs: + assert tx.is_outgoing is True + assert tx.outgoing_transfer is not None + TransferUtils.test_transfer(tx.outgoing_transfer, None) + + # get transactions without an outgoing transfer + ctx.has_outgoing_transfer = False + query = MoneroTxQuery() + query.is_outgoing = False + txs = WalletTxsUtils.get_and_test_txs(wallet, query, ctx, True, TestUtils.REGTEST) + for tx in txs: + assert tx.outgoing_transfer is None + + # get transactions with incoming transfers + ctx = TxContext() + ctx.has_incoming_transfers = True + query = MoneroTxQuery() + query.is_incoming = True + txs = WalletTxsUtils.get_and_test_txs(wallet, query, ctx, True, TestUtils.REGTEST) + for tx in txs: + assert tx.is_incoming is True + assert len(tx.incoming_transfers) > 0 + for transfer in tx.incoming_transfers: + TransferUtils.test_transfer(transfer, None) + + # get transactions without incoming transfers + ctx.has_incoming_transfers = False + query = MoneroTxQuery() + query.is_incoming = False + txs = WalletTxsUtils.get_and_test_txs(wallet, query, ctx, True, TestUtils.REGTEST) + for tx in txs: + assert tx.is_incoming is False + assert len(tx.incoming_transfers) == 0 + + # get transactions associated with an account + account_idx: int = 1 + query = MoneroTxQuery() + query.transfer_query = MoneroTransferQuery() + query.transfer_query.account_index = account_idx + txs = wallet.get_txs(query) + + for tx in txs: + found: bool = False + if tx.is_outgoing and tx.outgoing_transfer.account_index == account_idx: # type: ignore + found = True + elif len(tx.incoming_transfers) > 0: + for transfer in tx.incoming_transfers: + if transfer.account_index == account_idx: + found = True + break + + assert found, f"Transaction is not associated with account {account_idx}: \n{tx.serialize()}" + + # get txs with manually built query that are confirmed and have an outgoing transfer from account 0 + ctx = TxContext() + ctx.has_outgoing_transfer = True + tx_query: MoneroTxQuery = MoneroTxQuery() + tx_query.is_confirmed = True + tx_query.transfer_query = MoneroTransferQuery() + tx_query.transfer_query.account_index = 0 + tx_query.transfer_query.outgoing = True + txs = WalletTxsUtils.get_and_test_txs(wallet, tx_query, ctx, True, TestUtils.REGTEST) + for tx in txs: + if tx.is_confirmed is not True: + logger.warning(f"{tx.serialize()}") + assert tx.is_confirmed is True + assert tx.is_outgoing is True + assert tx.outgoing_transfer is not None + assert tx.outgoing_transfer.account_index == 0 + + # get txs with outgoing transfers that have destinations to account 1 + tx_query = MoneroTxQuery() + tx_query.is_confirmed = True + tx_query.transfer_query = MoneroTransferQuery() + tx_query.transfer_query.account_index = 0 + tx_query.transfer_query.has_destinations = True + + txs = WalletTxsUtils.get_and_test_txs(wallet, tx_query, None, None, TestUtils.REGTEST) + for tx in txs: + assert tx.is_outgoing is True + assert tx.outgoing_transfer is not None + assert len(tx.outgoing_transfer.destinations) > 0 + + # include outputs with transactions + ctx = TxContext() + ctx.include_outputs = True + tx_query = MoneroTxQuery() + tx_query.include_outputs = True + txs = WalletTxsUtils.get_and_test_txs(wallet, tx_query, ctx, True, TestUtils.REGTEST) + found: bool = False + for tx in txs: + if len(tx.outputs) > 0: + found = True + else: + # TODO: monero-wallet-rpc: return outputs for unconfirmed txs + assert tx.is_outgoing or (tx.is_incoming and tx.is_confirmed is False) + + assert found, "No outputs found in txs" + + # get txs with input query + # TODO no inputs returned to filter + + # get txs with output query + tx_query = MoneroTxQuery() + tx_query.output_query = MoneroOutputQuery() + tx_query.output_query.is_spent = False + tx_query.output_query.account_index = 1 + tx_query.output_query.subaddress_index = 2 + txs = wallet.get_txs(tx_query) + assert len(txs) > 0 + for tx in txs: + assert len(tx.outputs) > 0 + found = False + for output in tx.get_outputs_wallet(): + if output.is_spent is False and output.account_index == 1 and output.subaddress_index == 2: + found = True + break + + if not found: + raise Exception("Tx does not contain specified output") + + # get unlocked txs + tx_query = MoneroTxQuery() + tx_query.is_locked = False + txs = wallet.get_txs(tx_query) + assert len(txs) > 0 + for tx in txs: + assert tx.is_locked is False + + # get confirmed transactions sent from/to same wallet with a transfer with destinations + + tx_query = MoneroTxQuery() + tx_query.is_incoming = True + tx_query.is_outgoing = True + tx_query.include_outputs = True + tx_query.is_confirmed = True + tx_query.transfer_query = MoneroTransferQuery() + tx_query.transfer_query.has_destinations = True + + txs = wallet.get_txs(tx_query) + assert len(txs) > 0, "Wallet has no incoming/outgoing txs to test; run send from/to tests" + for tx in txs: + assert tx.is_incoming is True + assert tx.is_outgoing is True + assert tx.is_confirmed is True + assert len(tx.get_outputs_wallet()) > 0 + assert tx.outgoing_transfer is not None + assert len(tx.outgoing_transfer.destinations) > 0 + + # Can get transactions by height + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_txs_by_height(self, wallet: MoneroWallet) -> None: + # get all confirmed txs for testing + query: MoneroTxQuery = MoneroTxQuery() + query.is_confirmed = True + txs: list[MoneroTxWallet] = wallet.get_txs(query) + + # collect all tx heights + tx_heights: list[int] = [] + for tx in txs: + tx_height: Optional[int] = tx.get_height() + assert tx_height is not None + tx_heights.append(tx_height) + + # get height that most txs occur at + height_counts: dict[int, int] = GenUtils.count_num_instances(tx_heights) + assert len(height_counts) > 0, "Wallet has no confirmed txs; run send tests" + height_modes: set[int] = GenUtils.get_modes(height_counts) + mode_height: int = next(iter(height_modes)) + + # fetch txs at mode height + query = MoneroTxQuery() + query.height = mode_height + logger.debug(f"Getting mode txs by height; mode height {mode_height}") + mode_txs: list[MoneroTxWallet] = wallet.get_txs(query) + assert height_counts[mode_height] == len(mode_txs) + for tx in mode_txs: + assert mode_height == tx.get_height() + + # fetch txs at mode height by range + query = MoneroTxQuery() + query.min_height = mode_height + query.max_height = mode_height + logger.debug(f"Getting mode txs by range; mode height {mode_height}") + mode_txs_by_range: list[MoneroTxWallet] = wallet.get_txs(query) + # TODO test txs order is failing + TxWalletUtils.assert_list_txs_equals(mode_txs, mode_txs_by_range) + + # fetch all txs by range + query = MoneroTxQuery() + query.min_height = txs[0].get_height() + query.max_height = txs[-1].get_height() + all_txs: list[MoneroTxWallet] = wallet.get_txs(query) + # TODO test txs order is failing + TxWalletUtils.assert_list_txs_equals(txs, all_txs) + + # test some filtered by range + try: + query = MoneroTxQuery() + query.is_confirmed = True + txs = wallet.get_txs(query) + assert len(txs) > 0, "No transactions; run send to multiple test" + + # get and sort block heights in ascending order + heights: list[int] = [] + for tx in txs: + assert tx.block is not None + assert tx.block.height is not None + heights.append(tx.block.height) + + heights.sort() + + # pick minimum and maximum heights for filtering + min_height: int = -1 + max_height: int = -1 + if len(heights) == 1: + min_height = 0 + max_height = heights[0] - 1 + else: + min_height = heights[0] + 1 + max_height = heights[-1] - 1 + + # assert some transactions filtered + unfiltered_count: int = len(txs) + query = MoneroTxQuery() + query.min_height = min_height + query.max_height = max_height + txs = WalletTxsUtils.get_and_test_txs(wallet, query, None, True, TestUtils.REGTEST) + assert len(txs) < unfiltered_count + for tx in txs: + assert tx.block is not None + assert tx.block.height is not None + height: int = tx.block.height + assert height >= min_height and height <= max_height + + except Exception as e: + logger.debug(str(e)) + + # Can get transactions with payment id + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False or TestUtils.LITE_MODE, reason="TEST_NON_RELAYS disabled or LITE_MODE enabled") + def test_get_txs_with_payment_ids(self, wallet: MoneroWallet) -> None: + # get random transactions with payment ids for testing + tx_query: MoneroTxQuery = MoneroTxQuery() + tx_query.has_payment_id = True + random_txs: list[MoneroTxWallet] = WalletTxsUtils.get_random_transactions(wallet, tx_query, 2, 5) + assert len(random_txs) > 0, "No txs with payment ids to test" + for random_tx in random_txs: + assert random_tx.payment_id is not None and len(random_tx.payment_id) > 0 + + # get transactions by payment id + payment_ids: list[str] = [] + for tx in random_txs: + assert tx.payment_id is not None + payment_ids.append(tx.payment_id) + + assert len(payment_ids) > 1 + for payment_id in payment_ids: + tx_query = MoneroTxQuery() + tx_query.payment_id = payment_id + txs: list[MoneroTxWallet] = WalletTxsUtils.get_and_test_txs(wallet, tx_query, None, None, TestUtils.REGTEST) + assert len(txs) > 0 + first_payment_id: Optional[str] = txs[0].payment_id + assert first_payment_id is not None + MoneroUtils.validate_payment_id(first_payment_id) + + # get transactions by payment hashes + tx_query = MoneroTxQuery() + tx_query.payment_ids = payment_ids + txs: list[MoneroTxWallet] = WalletTxsUtils.get_and_test_txs(wallet, tx_query, None, None, TestUtils.REGTEST) + for tx in txs: + assert tx.payment_id is not None + assert tx.payment_id in payment_ids + + # Returns all known fields of txs regardless of filtering + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_get_txs_fields_with_filtering(self, wallet: MoneroWallet) -> None: + # fetch wallet txs + tx_query: MoneroTxQuery = MoneroTxQuery() + tx_query.is_confirmed = True + txs: list[MoneroTxWallet] = wallet.get_txs(tx_query) + + for tx in txs: + # find tx sent to same wallet with incoming transfer in different account than src account + if tx.outgoing_transfer is None or len(tx.incoming_transfers) == 0: + continue + for transfer in tx.incoming_transfers: + if transfer.account_index == tx.outgoing_transfer.account_index: + continue + + # fetch tx with filtering + tx_query = MoneroTxQuery() + tx_query.transfer_query = MoneroTransferQuery() + tx_query.transfer_query.incoming = True + tx_query.transfer_query.account_index = transfer.account_index + filtered_txs: list[MoneroTxWallet] = wallet.get_txs(tx_query) + + for filtered_tx in filtered_txs: + assert filtered_tx.hash is not None + if filtered_tx.hash == tx.hash: + tx.merge(filtered_tx) + # test is done + return + + raise Exception("Test requires tx sent from/to different accounts of same wallet but none found; run send tests") + + # Validates inputs when getting transactions + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False or TestUtils.LITE_MODE, reason="TEST_NON_RELAYS disabled or LITE_MODE enabled") + def test_validate_inputs_get_txs(self, wallet: MoneroWallet) -> None: + # fetch random txs for testing + random_txs: list[MoneroTxWallet] = WalletTxsUtils.get_random_transactions(wallet, None, 3, 5) + + # valid, invalid, and unknown tx hashes for tests + tx_hash: str | None = random_txs[0].hash + invalid_hash: str = "invalid_id" + unknown_hash1: str = "6c4982f2499ece80e10b627083c4f9b992a00155e98bcba72a9588ccb91d0a61" + unknown_hash2: str = "ff397104dd875882f5e7c66e4f852ee134f8cf45e21f0c40777c9188bc92e943" + assert tx_hash is not None and len(tx_hash) > 0 + + # fetch unknown tx hash + fetched_tx: MoneroTxWallet | None = wallet.get_tx(unknown_hash1) + assert fetched_tx is None + + # fetch unknown tx hash using query + tx_query: MoneroTxQuery = MoneroTxQuery() + tx_query.hash = unknown_hash1 + fetched_txs: list[MoneroTxWallet] = wallet.get_txs(tx_query) + assert len(fetched_txs) == 0 + + # fetch unknwon tx hash in list + txs: list[MoneroTxWallet] = wallet.get_txs([tx_hash, unknown_hash1]) + assert len(txs) == 1 + assert txs[0].hash == tx_hash + + # fetch unknwon tx hashes in list + txs = wallet.get_txs([tx_hash, unknown_hash1, unknown_hash2]) + assert len(txs) == 1 + assert txs[0].hash == tx_hash + + # fetch invalid hash + fetched_tx = wallet.get_tx(invalid_hash) + assert fetched_tx is None + + # fetch invalid hash list + txs = wallet.get_txs([tx_hash, invalid_hash]) + assert len(txs) == 1 + assert txs[0].hash == tx_hash + + # fetch invalid hashes in list + txs = wallet.get_txs([tx_hash, invalid_hash, "invalid_hash_2"]) + assert len(txs) == 1 + assert txs[0].hash == tx_hash + + # test collection of invalid hashes + tx_query = MoneroTxQuery() + tx_query.hashes = [tx_hash, invalid_hash, "invalid_hash_2"] + txs = wallet.get_txs(tx_query) + assert len(txs) == 1 + + # test txs + for tx in txs: + TxWalletUtils.test_tx_wallet(tx) + + # Can get and set a transaction note + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_set_tx_note(self, wallet: MoneroWallet) -> None: + txs: list[MoneroTxWallet] = WalletTxsUtils.get_random_transactions(wallet, None, 1, 5) + + # set notes + uuid: str = StringUtils.get_random_string() + + for i, tx in enumerate(txs): + tx_hash: str | None = tx.hash + assert tx_hash is not None + wallet.set_tx_note(tx_hash, f"{uuid}{i}") + + # get notes + for i, tx in enumerate(txs): + tx_hash: str | None = tx.hash + assert tx_hash is not None + assert wallet.get_tx_note(tx_hash) == f"{uuid}{i}" + + # Can get and set multiple transaction notes + # TODO why does getting cached txs take 2 seconds when should already be cached? + @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") + def test_set_tx_notes(self, wallet: MoneroWallet) -> None: + # set tx notes + uuid: str = StringUtils.get_random_string() + txs: list[MoneroTxWallet] = wallet.get_txs() + assert len(txs) >= 3, "Test requires 3 or more wallet transactions run send tests" + tx_hashes: list[str] = [] + tx_notes: list[str] = [] + for i, tx_hash in enumerate(tx_hashes): + assert tx_hash is not None + tx_hashes.append(tx_hash) + tx_notes.append(f"{uuid}{i}") + + wallet.set_tx_notes(tx_hashes, tx_notes) + + # get tx notes + tx_notes: list[str] = wallet.get_tx_notes(tx_hashes) + for i, tx_note in enumerate(tx_notes): + assert f"{uuid}{i}" == tx_note + + +@pytest.mark.integration +class TestMoneroWalletFullTxs(FullWalletSupport, BaseTestMoneroWalletTxs): + """Full wallet txs integration tests.""" + + +@pytest.mark.integration +class TestMoneroWalletRpcTxs(RpcWalletSupport, BaseTestMoneroWalletTxs): + """Rpc wallet txs integration tests.""" + + +@pytest.mark.unit +class TestMoneroWalletKeysTxs(KeysWalletSupport, BaseTestMoneroWalletTxs): + """Keys-only wallet txs unit tests.""" + + @pytest.mark.not_supported + @override + def test_get_txs_wallet(self, wallet: MoneroWallet) -> None: + return super().test_get_txs_wallet(wallet) + + @pytest.mark.not_supported + @override + def test_get_txs_by_hash(self, wallet: MoneroWallet) -> None: + return super().test_get_txs_by_hash(wallet) + + @pytest.mark.not_supported + @override + def test_get_txs_with_query(self, wallet: MoneroWallet) -> None: + return super().test_get_txs_with_query(wallet) + + @pytest.mark.not_supported + @override + def test_validate_inputs_get_txs(self, wallet: MoneroWallet) -> None: + return super().test_validate_inputs_get_txs(wallet) + + @pytest.mark.not_supported + @override + def test_set_tx_note(self, wallet: MoneroWallet) -> None: + return super().test_set_tx_note(wallet) + + @pytest.mark.not_supported + @override + def test_set_tx_notes(self, wallet: MoneroWallet) -> None: + return super().test_set_tx_notes(wallet) + + @pytest.mark.not_supported + @override + def test_get_txs_by_height(self, wallet: MoneroWallet) -> None: + return super().test_get_txs_by_height(wallet) + + @pytest.mark.not_supported + @override + def test_get_txs_with_payment_ids(self, wallet: MoneroWallet) -> None: + return super().test_get_txs_with_payment_ids(wallet) + + @pytest.mark.not_supported + @override + def test_get_txs_fields_with_filtering(self, wallet: MoneroWallet) -> None: + return super().test_get_txs_fields_with_filtering(wallet) diff --git a/tests/wallet/test_update_locked.py b/tests/wallet/test_update_locked.py new file mode 100644 index 00000000..28050e99 --- /dev/null +++ b/tests/wallet/test_update_locked.py @@ -0,0 +1,109 @@ +from __future__ import annotations + +import logging + +import pytest +from monero import MoneroDaemonRpc, MoneroTxConfig, MoneroWallet +from typing_extensions import override + +from utils import TestUtils, TxWalletUtils, WalletSendUtils +from .base_test_monero_wallet import BaseTestMoneroWallet +from .wallet_support import FullWalletSupport, RpcWalletSupport, KeysWalletSupport + +logger: logging.Logger = logging.getLogger("TestMoneroWalletUpdateLocked") + + +class BaseTestMoneroWalletUpdateLocked(BaseTestMoneroWallet): + """Common wallet update locked tests.""" + + # TODO: test sending to multiple accounts + # Can update a locked tx sent from/to the same account as blocks are added to the chain + @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") + @pytest.mark.skipif(TestUtils.TEST_NOTIFICATIONS is False, reason="TEST_NOTIFICATIONS disabled") + @pytest.mark.flaky(reruns=5, reruns_delay=10, only_rerun=["Daemon is busy", r"Cannot reconcile integrals:.*m_is_incoming"]) + def test_update_locked_same_account(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: + config: MoneroTxConfig = MoneroTxConfig() + config.address = wallet.get_primary_address() + config.amount = TxWalletUtils.MAX_FEE + config.account_index = 0 + config.can_split = False + config.relay = True + WalletSendUtils.test_send_and_update_txs(daemon, wallet, config) + + # Can update split locked txs sent from/to the same account as blocks are added to the chain + @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") + @pytest.mark.skipif(TestUtils.TEST_NOTIFICATIONS is False, reason="TEST_NOTIFICATIONS disabled") + @pytest.mark.skipif(TestUtils.LITE_MODE, reason="LITE_MODE enabled") + @pytest.mark.flaky(reruns=5, reruns_delay=10, only_rerun=["Daemon is busy", r"Cannot reconcile integrals:.*m_is_incoming"]) + def test_update_locked_same_account_split(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: + config: MoneroTxConfig = MoneroTxConfig() + config.address = wallet.get_primary_address() + config.amount = TxWalletUtils.MAX_FEE + config.account_index = 0 + config.can_split = True + config.relay = True + WalletSendUtils.test_send_and_update_txs(daemon, wallet, config) + + # TODO on wallet full is flaky due to `Cannot reconcile integrals: 0 vs 1. tx wallet m_is_incoming` error + # Can update a locked tx sent from/to different accounts as blocks are added to the chain + @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") + @pytest.mark.skipif(TestUtils.TEST_NOTIFICATIONS is False, reason="TEST_NOTIFICATIONS disabled") + @pytest.mark.skipif(TestUtils.LITE_MODE, reason="LITE_MODE enabled") + @pytest.mark.flaky(reruns=5, reruns_delay=10, only_rerun=["Daemon is busy", r"Cannot reconcile integrals:.*m_is_incoming"]) + def test_update_locked_different_accounts(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: + config: MoneroTxConfig = MoneroTxConfig() + config.address = wallet.get_subaddress(1, 0).address + config.amount = TxWalletUtils.MAX_FEE + config.account_index = 0 + config.can_split = False + config.relay = True + WalletSendUtils.test_send_and_update_txs(daemon, wallet, config) + + # Can update locked, split txs sent from/to different accounts as blocks are added to the chain + @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") + @pytest.mark.skipif(TestUtils.TEST_NOTIFICATIONS is False, reason="TEST_NOTIFICATIONS disabled") + @pytest.mark.skipif(TestUtils.LITE_MODE, reason="LITE_MODE enabled") + @pytest.mark.flaky(reruns=5, reruns_delay=10, only_rerun=["Daemon is busy", r"Cannot reconcile integrals:.*m_is_incoming"]) + def test_update_locked_different_accounts_split(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: + config: MoneroTxConfig = MoneroTxConfig() + config.address = wallet.get_subaddress(1, 0).address + config.amount = TxWalletUtils.MAX_FEE + config.account_index = 0 + config.can_split = True + config.relay = True + WalletSendUtils.test_send_and_update_txs(daemon, wallet, config) + + +@pytest.mark.integration +class TestMoneroWalletFullUpdateLocked(FullWalletSupport, BaseTestMoneroWalletUpdateLocked): + """Full wallet update locked integration tests.""" + + +@pytest.mark.integration +class TestMoneroWalletRpcUpdateLocked(RpcWalletSupport, BaseTestMoneroWalletUpdateLocked): + """Rpc wallet update locked integration tests.""" + + +@pytest.mark.unit +class TestMoneroWalletKeysUpdateLocked(KeysWalletSupport, BaseTestMoneroWalletUpdateLocked): + """Keys-only wallet update locked unit tests.""" + + @pytest.mark.not_supported + @override + def test_update_locked_same_account(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: + return super().test_update_locked_same_account(daemon, wallet) + + @pytest.mark.not_supported + @override + def test_update_locked_same_account_split(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: + return super().test_update_locked_same_account_split(daemon, wallet) + + @pytest.mark.not_supported + @override + def test_update_locked_different_accounts(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: + return super().test_update_locked_different_accounts(daemon, wallet) + + @pytest.mark.not_supported + @override + def test_update_locked_different_accounts_split(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: + return super().test_update_locked_different_accounts_split(daemon, wallet) diff --git a/tests/wallet/wallet_support.py b/tests/wallet/wallet_support.py new file mode 100644 index 00000000..430ce973 --- /dev/null +++ b/tests/wallet/wallet_support.py @@ -0,0 +1,262 @@ +from __future__ import annotations + +import logging +from typing import Optional + +import pytest +from monero import ( + MoneroAccount, + MoneroDaemon, + MoneroDaemonRpc, + MoneroNetworkType, + MoneroWallet, + MoneroWalletConfig, + MoneroWalletFull, + MoneroWalletKeys, + MoneroWalletRpc, +) +from typing_extensions import override + +from utils import StringUtils, TestUtils as Utils, WalletType +from .base_test_monero_wallet import BaseTestMoneroWallet + +logger: logging.Logger = logging.getLogger("TestMoneroWallet") + + +class FullWalletSupport(BaseTestMoneroWallet): + """What the full wallet tests do differently from the common ones.""" + + @classmethod + @override + def get_wallet_type(cls) -> WalletType: + return WalletType.FULL + + @pytest.fixture(scope="class") + @classmethod + @override + def wallet(cls) -> MoneroWalletFull: + """Test rpc wallet instance""" + return Utils.get_wallet_full() + + @override + def after_all(self) -> None: + super().after_all() + Utils.WALLET_FULL_TESTS_RUN = True + + @override + def _create_wallet(self, config: Optional[MoneroWalletConfig], start_syncing: bool = True) -> MoneroWalletFull: + # assign defaults + if config is None: + config = MoneroWalletConfig() + random: bool = self.is_random_wallet_config(config) + if config.path is None: + config.path = Utils.TEST_WALLETS_DIR + "/" + StringUtils.get_random_string() + if config.password is None: + config.password = Utils.WALLET_PASSWORD + if config.network_type is None: + config.network_type = Utils.NETWORK_TYPE + if config.server is None: + config.server = Utils.get_daemon_rpc_connection() + if config.restore_height is None and not random: + config.restore_height = 0 + + config.regtest = config.network_type == MoneroNetworkType.MAINNET and Utils.REGTEST + + # create wallet + wallet: MoneroWalletFull = MoneroWalletFull.create_wallet(config) + if not random: + assert config.restore_height == wallet.get_restore_height() + if start_syncing is not False and wallet.is_connected_to_daemon(): + wallet.start_syncing(Utils.SYNC_PERIOD_IN_MS) + return wallet + + @override + def _open_wallet(self, config: Optional[MoneroWalletConfig], start_syncing: bool = True) -> MoneroWalletFull: + # assign defaults + if config is None: + config = MoneroWalletConfig() + if config.password is None: + config.password = Utils.WALLET_PASSWORD + if config.network_type is None: + config.network_type = Utils.NETWORK_TYPE + if config.server is None: + config.server = Utils.get_daemon_rpc_connection() + + # open wallet + assert config.network_type is not None + assert config.path is not None + + wallet: MoneroWalletFull = MoneroWalletFull.open_wallet(config.path, config.password, config.network_type) + wallet.set_daemon_connection(config.server) + if start_syncing is not False and wallet.is_connected_to_daemon(): + wallet.start_syncing(Utils.SYNC_PERIOD_IN_MS) + return wallet + + @override + def _close_wallet(self, wallet: MoneroWallet, save: bool = False) -> None: + wallet.close(save) + + @override + def _get_seed_languages(self) -> list[str]: + return self.get_test_wallet().get_seed_languages() + + @override + @classmethod + def get_test_wallet(cls) -> MoneroWalletFull: + return super().get_test_wallet() # type: ignore + + +class RpcWalletSupport(BaseTestMoneroWallet): + """What the rpc wallet tests do differently from the common ones.""" + + @classmethod + @override + def get_wallet_type(cls) -> WalletType: + return WalletType.RPC + + @pytest.fixture(scope="class") + @classmethod + @override + def wallet(cls) -> MoneroWalletRpc: + """Test rpc wallet instance.""" + return cls.get_test_wallet() + + @classmethod + @override + def get_test_wallet(cls) -> MoneroWalletRpc: + return super().get_test_wallet() # type: ignore + + @override + def _open_wallet(self, config: MoneroWalletConfig | None) -> MoneroWalletRpc: + return Utils.open_wallet_rpc(config) + + @override + def _create_wallet(self, config: MoneroWalletConfig) -> MoneroWalletRpc: + return Utils.create_wallet_rpc(config) + + @override + def _close_wallet(self, wallet: MoneroWallet, save: bool = False) -> None: + wallet.close(save) + Utils.free_wallet_rpc_resource(wallet) + + @override + def _get_seed_languages(self) -> list[str]: + return self.get_test_wallet().get_seed_languages() + + @override + def before_all(self) -> None: + super().before_all() + + @override + def after_all(self) -> None: + super().after_all() + Utils.free_wallet_rpc_resources() + + @override + def after_each(self, request: pytest.FixtureRequest) -> None: + super().after_each(request) + Utils.free_wallet_rpc_resources() + + @override + def get_daemon_rpc_uri(self) -> str: + return Utils.DAEMON_RPC_URI if not Utils.IN_CONTAINER else Utils.CONTAINER_DAEMON_RPC_URI + + +class KeysWalletSupport(BaseTestMoneroWallet): + """What the keys-only wallet tests do differently from the common ones.""" + + _account_indices: list[int] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + + _subaddress_indices: list[int] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + + @pytest.fixture(scope="class") + @classmethod + @override + def wallet(cls) -> MoneroWalletKeys: + """Test keys wallet instance""" + return Utils.get_wallet_keys() + + @pytest.fixture(scope="class") + @classmethod + @override + def daemon(cls) -> MoneroDaemonRpc: + return MoneroDaemon() # type: ignore + + @classmethod + @override + def get_wallet_type(cls) -> WalletType: + return WalletType.KEYS + + @override + def after_all(self) -> None: + logger.info(f"Teardown test class {type(self).__name__}") + + @override + def before_each(self, request: pytest.FixtureRequest) -> None: + logger.info(f"Before {request.node.name}") # type: ignore + + @override + def after_each(self, request: pytest.FixtureRequest) -> None: + logger.info(f"After {request.node.name}") # type: ignore + + @classmethod + @override + def is_random_wallet_config(cls, config: Optional[MoneroWalletConfig]) -> bool: + assert config is not None + return super().is_random_wallet_config(config) and config.private_spend_key is None + + @override + def _create_wallet(self, config: Optional[MoneroWalletConfig]) -> MoneroWalletKeys: + # assign defaults + if config is None: + config = MoneroWalletConfig() + + random: bool = self.is_random_wallet_config(config) + if config.network_type is None: + config.network_type = Utils.NETWORK_TYPE + + # create wallet + if random: + wallet: MoneroWalletKeys = MoneroWalletKeys.create_wallet_random(config) + elif config.seed is not None and config.seed != "": + wallet = MoneroWalletKeys.create_wallet_from_seed(config) + elif config.primary_address is not None and config.private_view_key is not None: + wallet = MoneroWalletKeys.create_wallet_from_keys(config) + elif config.primary_address is not None and config.private_spend_key is not None: + wallet = MoneroWalletKeys.create_wallet_from_keys(config) + else: + raise Exception("Invalid configuration") + + return wallet + + @override + def _open_wallet(self, config: Optional[MoneroWalletConfig]) -> MoneroWallet: + raise NotImplementedError("TestMoneroWalletKeys._open_wallet(): not supported") + + @override + def _close_wallet(self, wallet: MoneroWallet, save: bool = False) -> None: + # a keys-only wallet has nothing to persist, so `save` is ignored + wallet.close() + + @override + def _get_seed_languages(self) -> list[str]: + return self.get_test_wallet().get_seed_languages() + + @classmethod + @override + def get_test_wallet(cls) -> MoneroWalletKeys: + return super().get_test_wallet() # type: ignore + + def _get_test_accounts(self, wallet: MoneroWallet, include_subaddresses: bool = False) -> list[MoneroAccount]: + account_indices: list[int] = self._account_indices + subaddress_indices: list[int] = self._subaddress_indices + accounts: list[MoneroAccount] = [] + for account_idx in account_indices: + account: MoneroAccount = wallet.get_account(account_idx) + + if include_subaddresses: + account.subaddresses = wallet.get_subaddresses(account_idx, subaddress_indices) + + accounts.append(account) + + return accounts