diff --git a/README.md b/README.md index 0e4c86af..03d17b78 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ class MyWalletListener(MoneroWalletListener): assert tx is not None # the wallet gives the output with its transaction tx_hash: str | None = tx.hash is_confirmed: bool | None = tx.is_confirmed - is_locked: bool | None = tx.is_locked + is_locked: bool | None = output.is_locked # connect to daemon daemon: MoneroDaemon = MoneroDaemonRpc("http://localhost:38081", "superuser", "abctesting123") diff --git a/docs/mkdocs/docs/en/api/equality.md b/docs/mkdocs/docs/en/api/equality.md index 28286abf..7c9560cf 100644 --- a/docs/mkdocs/docs/en/api/equality.md +++ b/docs/mkdocs/docs/en/api/equality.md @@ -50,7 +50,7 @@ as one is alive, so the back references are the objects that they point to: ```python for output in tx.outputs: assert output.tx is tx -assert tx.block is None or tx in tx.block.txs +assert tx.block is None or any(block_tx is tx for block_tx in tx.block.txs) ``` When no Python object is alive, the next access makes a new one: the `id()` of a temporary object can change from an access to the @@ -66,19 +66,17 @@ if block is not None and id(block) not in seen_blocks: ## Lists of the model The fields that hold a list of objects of the model, as `block.txs`, `tx.inputs`, `tx.outputs`, `tx.incoming_transfers` or -`tx_set.txs`, are the vectors of C++ (`VectorMoneroTx`, `VectorMoneroOutput`...), and what the vector does compares its objects -**by identity**: `in`, `==`, `index`, `remove` and `count`. A `list` compares them by value: - -| | a vector, `tx.outputs` | a `list`, `list(tx.outputs)` | -| --- | --- | --- | -| `output in ...` | the same object is there | an equal object is there | -| `tx1.outputs == tx2.outputs` | the same objects, in the same order | equal objects, in the same order | +`tx_set.txs`, and the lists that the wallets return, as `get_account_tags()`, are the vectors of C++ (`VectorMoneroTx`, +`VectorMoneroOutput`...). They compare their objects **by value**, as a `list` does and as `contains` and `equals` of a `List` of +monero-java: `in`, `index`, `count` and `remove` look for an equal object, and a vector equals a vector or a `list` with equal objects in +the same order. An object is compared by its JSON, so `in` looks for the same object first, which costs nothing: `tx in tx.block.txs` +does not serialize the txs of the block. Their items are still the objects that they hold: ```python copy: MoneroOutputWallet = output.copy() assert copy == output -assert copy not in output.tx.outputs # not the same object -assert copy in list(output.tx.outputs) # an equal one +assert copy in output.tx.outputs # an equal one +assert any(tx_output is output for tx_output in output.tx.outputs) # the same object ``` ## Representation @@ -96,7 +94,7 @@ that they do not end up in a log. `serialize()` keeps them. | `a.equals(b)`, `assertEquals(a, b)` | `a == b` | the same values | | `equals` of each class, field by field | `serialize()` of the two objects | the fields that are not serialized are not compared | | `hashCode()`, `Set`, `Map` | not hashable | key by the hash, or by `id()` | -| `list.contains(x)`, with `equals` | `x in vector` by identity, `x in list(vector)` by value | the vectors of the model | +| `list.contains(x)`, with `equals` | `x in vector` | by value, as a `list` | | `toString()`, an indented text | `repr()`, the JSON on one line | with the secrets hidden | ## Porting a test from monero-java diff --git a/docs/mkdocs/docs/en/tests/files/common.md b/docs/mkdocs/docs/en/tests/files/common.md index b246e507..9719eb45 100644 --- a/docs/mkdocs/docs/en/tests/files/common.md +++ b/docs/mkdocs/docs/en/tests/files/common.md @@ -8,7 +8,7 @@ What is not about a wallet or a daemon. | File | Marker | What it tests | | --- | --- | --- | | `test_common.py` | unit | `MoneroError`, the serialization of the structs, the SSL options | -| `test_serializable_struct.py` | unit | the equality, the hash and the `repr` of the structs, of `MoneroRpcConnection` and of `MoneroWalletConfig` | +| `test_serializable_struct.py` | unit | the equality, the hash and the `repr` of the structs, the equality of their vectors, of `MoneroRpcConnection` and of `MoneroWalletConfig` | | `test_rpc_connection.py` | integration | `MoneroRpcConnection`: the validation of the uri, the copy and the serialization, the credentials, the priority, the connections to a node and to a wallet rpc server, the json, binary and path requests | | `test_gen_utils.py` | unit | the helpers of the tests: the uuids, the waits, and the reconciliation of the values of two models (the rules of `merge`) | | `test_block_generation.py` | unit | the choice of the tests between generating blocks (at a low difficulty) and mining them | diff --git a/external/monero-cpp b/external/monero-cpp index 5b0b3ca1..d04eaa63 160000 --- a/external/monero-cpp +++ b/external/monero-cpp @@ -1 +1 @@ -Subproject commit 5b0b3ca1c250c096f2ed389091dd24c16b84a003 +Subproject commit d04eaa63e53a4d9977902ce8ff741e45df7188a5 diff --git a/src/cpp/common/py_monero_common_bindings.cpp b/src/cpp/common/py_monero_common_bindings.cpp index f3e473ac..9124d5a4 100644 --- a/src/cpp/common/py_monero_common_bindings.cpp +++ b/src/cpp/common/py_monero_common_bindings.cpp @@ -53,6 +53,63 @@ */ #include "py_monero_types.h" +namespace { + + template struct is_shared_ptr : std::false_type {}; + template struct is_shared_ptr> : std::true_type {}; + + // the vectors of the objects of the model compare them by value with their __eq__, like a list and like contains() and equals() of + // monero-java: bind_vector compares their shared_ptr, so an object equal to one of the vector would not be in it. != is derived from + // __eq__ once bind_vector's is removed + template + void compare_by_value(Class_ cl) { + py::dict attrs = cl.attr("__dict__"); + for (const char* name : {"__contains__", "count", "remove", "__eq__", "__ne__"}) { + if (attrs.contains(name)) py::delattr(cl, name); // the vectors of a class without == do not have them + } + cl.def("__contains__", [](const Vector& v, const py::object& x) { + // the same object first, which does not serialize, as with the back references: tx in tx.block.txs. Only here: index() and + // remove() take the first equal object and count() all of them, which the same object found first would change + using Item = typename Vector::value_type; + if constexpr (is_shared_ptr::value) { + using Element = typename Item::element_type; + if (py::isinstance(x)) { + const Element* ptr = x.cast(); + for (const auto& item : v) if (item.get() == ptr) return true; + } + } + for (const auto& item : v) if (py::cast(item).equal(x)) return true; + return false; + }, py::arg("x"), "Return true the container contains an object equal to ``x``"); + cl.def("count", [](const Vector& v, const py::object& x) { + size_t count = 0; + for (const auto& item : v) if (py::cast(item).equal(x)) count++; + return count; + }, py::arg("x"), "Return the number of objects equal to ``x``"); + cl.def("index", [](const Vector& v, const py::object& x) { + for (size_t i = 0; i < v.size(); i++) if (py::cast(v[i]).equal(x)) return i; + throw py::value_error("x not in vector"); + }, py::arg("x"), "Return the index of the first object equal to ``x``"); + cl.def("remove", [](Vector& v, const py::object& x) { + for (auto it = v.begin(); it != v.end(); it++) { + if (py::cast(*it).equal(x)) { + v.erase(it); + return; + } + } + throw py::value_error("x not in vector"); + }, py::arg("x"), "Remove the first object equal to ``x``"); + cl.def("__eq__", [](const Vector& v, const py::object& other) -> py::object { + // equal to a vector of the same type or to a list with equal objects in the same order + if (!py::isinstance(other) && !py::isinstance(other)) return py::reinterpret_borrow(Py_NotImplemented); + py::sequence seq = py::reinterpret_borrow(other); + if (seq.size() != v.size()) return py::bool_(false); + for (size_t i = 0; i < v.size(); i++) if (!py::cast(v[i]).equal(seq[i])) return py::bool_(false); + return py::bool_(true); + }, py::arg("other"), py::is_operator()); + } +} + void py_monero_bind_vectors_and_maps(py::module_& m) { py::bind_vector(m, "VectorInt") @@ -75,67 +132,67 @@ void py_monero_bind_vectors_and_maps(py::module_& m) { .def("copy", [](const VectorString& v) { return VectorString(v); }); - py::bind_vector>>(m, "VectorMoneroAccountTagPtr") + compare_by_value>>(py::bind_vector>>(m, "VectorMoneroAccountTagPtr") .def("copy", [](const std::vector>& v) { return std::vector>(v); - }); - py::bind_vector>>(m, "VectorKeyImagePtr") + })); + compare_by_value>>(py::bind_vector>>(m, "VectorKeyImagePtr") .def("copy", [](const std::vector>& v) { return std::vector>(v); - }); - py::bind_vector>>(m, "VectorMoneroBlock") + })); + compare_by_value>>(py::bind_vector>>(m, "VectorMoneroBlock") .def("copy", [](const std::vector>& v) { return std::vector>(v); - }); - py::bind_vector>>(m, "VectorMoneroBlockHeader") + })); + compare_by_value>>(py::bind_vector>>(m, "VectorMoneroBlockHeader") .def("copy", [](const std::vector>& v) { return std::vector>(v); - }); - py::bind_vector(m, "VectorMoneroTx") + })); + compare_by_value(py::bind_vector(m, "VectorMoneroTx") .def("sort", [](VectorMoneroTx &v) { std::sort(v.begin(), v.end(), monero_tx_height_comparator()); }) .def("copy", [](const VectorMoneroTx& v) { return VectorMoneroTx(v); - }); - py::bind_vector(m, "VectorMoneroTxWallet") + })); + compare_by_value(py::bind_vector(m, "VectorMoneroTxWallet") .def("sort", [](VectorMoneroTxWallet &v) { std::sort(v.begin(), v.end(), monero_tx_height_comparator()); }) .def("copy", [](const VectorMoneroTxWallet& v) { return VectorMoneroTxWallet(v); - }); - py::bind_vector>>(m, "VectorMoneroOutput") + })); + compare_by_value>>(py::bind_vector>>(m, "VectorMoneroOutput") .def("copy", [](const std::vector>& v) { return std::vector>(v); - }); - py::bind_vector>>(m, "VectorMoneroOutputWallet") + })); + compare_by_value>>(py::bind_vector>>(m, "VectorMoneroOutputWallet") .def("copy", [](const std::vector>& v) { return std::vector>(v); - }); - py::bind_vector>>(m, "VectorMoneroTransfer") + })); + compare_by_value>>(py::bind_vector>>(m, "VectorMoneroTransfer") .def("copy", [](const std::vector>& v) { return std::vector>(v); - }); - py::bind_vector(m, "VectorMoneroIncomingTransfer") + })); + compare_by_value(py::bind_vector(m, "VectorMoneroIncomingTransfer") .def("sort", [](VectorMoneroIncomingTransfer &v) { std::sort(v.begin(), v.end(), monero_incoming_transfer_comparator()); }) .def("copy", [](const VectorMoneroIncomingTransfer& v) { return VectorMoneroIncomingTransfer(v); - }); - py::bind_vector(m, "VectorMoneroOutgoingTransfer") + })); + compare_by_value(py::bind_vector(m, "VectorMoneroOutgoingTransfer") .def("copy", [](const VectorMoneroOutgoingTransfer& v) { return VectorMoneroOutgoingTransfer(v); - }); - py::bind_vector(m, "VectorMoneroSubaddress") + })); + compare_by_value(py::bind_vector(m, "VectorMoneroSubaddress") .def("copy", [](const VectorMoneroSubaddress& v) { return VectorMoneroSubaddress(v); - }); - py::bind_vector(m, "VectorMoneroDestination") + })); + compare_by_value(py::bind_vector(m, "VectorMoneroDestination") .def("copy", [](const VectorMoneroDestination& v) { return VectorMoneroDestination(v); - }); + })); py::implicitly_convertible(); py::implicitly_convertible(); diff --git a/tests/common/monero_utils/test_serialization.py b/tests/common/monero_utils/test_serialization.py index 782109b7..6d3c084b 100644 --- a/tests/common/monero_utils/test_serialization.py +++ b/tests/common/monero_utils/test_serialization.py @@ -4,7 +4,7 @@ from typing import Any import pytest -from monero import MoneroUtils +from monero import MoneroError, MoneroUtils from .base_test_monero_utils import BaseTestMoneroUtils @@ -90,3 +90,31 @@ def test_serialize_text_long(self, config: BaseTestMoneroUtils.Config) -> None: json_map2: dict[Any, Any] = MoneroUtils.binary_to_dict(binary) assert json_map == json_map2 + + # Can reject invalid json and binary + def test_binary_conversion_invalid(self) -> None: + json_map: dict[Any, Any] = { + "heights": [[111], [222]] + } + with pytest.raises(MoneroError) as exc_info: + MoneroUtils.dict_to_binary(json_map) + assert str(exc_info.value) == "Invalid JSON" + + json_map["heights"] = [111, 222, 333] + binary: bytes = MoneroUtils.dict_to_binary(json_map) + for size in range(len(binary)): + with pytest.raises(MoneroError) as exc_info: + MoneroUtils.binary_to_dict(binary[:size]) + assert str(exc_info.value) == "Invalid binary" + assert json_map == MoneroUtils.binary_to_dict(binary) + + # a field name of 255 bytes is parsed but can not be serialized + with pytest.raises(MoneroError) as exc_info: + MoneroUtils.dict_to_binary({"k" * 255: 1}) + assert str(exc_info.value) == "Failed to serialize binary" + + # Can reject invalid binary blocks + def test_binary_blocks_invalid(self) -> None: + with pytest.raises(MoneroError) as exc_info: + MoneroUtils.binary_blocks_to_json(bytes([1, 2, 3])) + assert str(exc_info.value) == "failed to parse get_blocks_by_height.bin response" diff --git a/tests/common/test_serializable_struct.py b/tests/common/test_serializable_struct.py index 8d106ee5..3afee76a 100644 --- a/tests/common/test_serializable_struct.py +++ b/tests/common/test_serializable_struct.py @@ -2,7 +2,7 @@ import logging from monero import ( - MoneroBlock, MoneroOutput, MoneroOutputWallet, MoneroRpcConnection, MoneroSubaddress, MoneroTx, MoneroTxWallet, + MoneroAccount, MoneroBlock, MoneroOutput, MoneroOutputWallet, MoneroRpcConnection, MoneroSubaddress, MoneroTx, MoneroTxWallet, MoneroWalletConfig ) @@ -61,6 +61,45 @@ def test_equals_children(self) -> None: other_block.txs = [tx2] assert block == other_block + # Can compare the structs of a vector by value, like a list and like contains() and equals() of monero-java + def test_vector_equals(self) -> None: + tx: MoneroTx = self._get_tx() + output: MoneroOutput = tx.outputs[0] + copy: MoneroOutput = output.copy() + other: MoneroOutput = output.copy() + other.amount = 2 + + # an equal struct is in the vector, which keeps the same objects + assert output in tx.outputs + assert copy in tx.outputs + assert other not in tx.outputs + assert "my tx hash" not in tx.outputs + assert tx.outputs[0] is output + assert tx.outputs.count(copy) == 1 + assert tx.outputs.count(other) == 0 + assert tx.outputs.index(copy) == 0 + with pytest.raises(ValueError): + tx.outputs.index(other) + + # a vector equals a vector or a list with equal structs in the same order + assert tx.outputs == self._get_tx().outputs + assert tx.outputs == [copy] + assert tx.outputs != [other] + assert tx.outputs != [copy, copy] + assert tx.outputs != (copy,) + + # the vectors of structs without a shared_ptr too + account: MoneroAccount = MoneroAccount() + account.subaddresses = [self._get_subaddress()] + assert self._get_subaddress() in account.subaddresses + assert account.subaddresses == [self._get_subaddress()] + + # an equal struct is removed + with pytest.raises(ValueError): + tx.outputs.remove(other) + tx.outputs.remove(copy) + assert len(tx.outputs) == 0 + # Cannot hash the structs, which are mutable @pytest.mark.parametrize("struct", [MoneroSubaddress(), MoneroTxWallet(), MoneroRpcConnection(), MoneroWalletConfig()]) def test_not_hashable(self, struct: object) -> None: diff --git a/tests/wallet/test_accounts.py b/tests/wallet/test_accounts.py index bd18935f..8a14a39e 100644 --- a/tests/wallet/test_accounts.py +++ b/tests/wallet/test_accounts.py @@ -8,6 +8,7 @@ MoneroAccount, MoneroAccountTag, MoneroAddressBookEntry, + MoneroError, MoneroIntegratedAddress, MoneroSubaddress, MoneroWallet, @@ -284,6 +285,12 @@ def test_account_tags(self, wallet: MoneroWallet) -> None: assert tagged_accounts[1].index == 1 assert tagged_accounts[1].tag == tag.tag + # tag has no label until one is set + unlabeled_tag: MoneroAccountTag = MoneroAccountTag() + unlabeled_tag.tag = tag.tag + unlabeled_tag.account_indices = tag.account_indices + assert unlabeled_tag in wallet.get_account_tags() + # set tag label wallet.set_account_tag_label(tag.tag, tag.label) @@ -313,6 +320,16 @@ def test_account_tags(self, wallet: MoneroWallet) -> None: assert tagged_accounts[0].index == 0 assert tagged_accounts[0].tag == tag.tag + # test that tagging an account out of range fails + with pytest.raises(MoneroError) as exc_info: + wallet.tag_accounts(tag.tag, [len(accounts)]) + assert str(exc_info.value) == "Account index out of bound" + + # test that labeling an unregistered tag fails + with pytest.raises(MoneroError) as exc_info: + wallet.set_account_tag_label("non_existing_tag", "my label") + assert str(exc_info.value) == "Tag is unregistered" + # untag and query accounts wallet.untag_accounts([0, 1]) assert len(wallet.get_account_tags()) == 0