Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 5 additions & 6 deletions .github/release-notes.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,11 @@

<!-- the ones of this release, since the one before: replace them for the next one, or remove the section -->

- **The objects of the data model compare by value.** `a == b` is true for two objects of the same class with the same JSON (`serialize()`), also in the lists of the model (`in`, `count`, `remove`). It was true only for the same object: use `is` for that. `MoneroRpcConnection` compares the uri, the username, the password, the proxy uri, the zmq uri and the ssl verify.
- **The objects of the data model are not hashable.** `hash()` of one, putting it in a `set` or using it as a key of a `dict` raises `TypeError`: key them by what identifies them, as the hash of a tx, or by `id()`.
- **The raw RPC responses keep the types of their JSON**, in `send_json_request()` and the other raw requests of `MoneroRpcConnection`. A text stays a `str`, also when it looks like a number or a boolean, a large integer stays an `int` instead of becoming a `float`, `null` is `None`, and an empty list or object stays one.
- **Python 3.10 or later** is required: 3.8 and 3.9 are not supported anymore.
- **The macOS wheels need macOS 15 or later**: there is no wheel for macOS 14.
- **Type annotations:** `MoneroOutput.tx`, `MoneroTransfer.tx` and `MoneroRpcConnection.timeout_ms` can be `None`, and `MoneroTxQuery.include_outputs` is a `bool`: a type checker can report new errors.
- **`verify_message()` raises the errors that say nothing about the signature**, as `MoneroError`: a closed wallet, a server that can not be reached, a wallet that does not support it. It returned a result that was not good for any error, and still does for a signature or an address that are not valid.
- **`MoneroWallet.get_attribute()` returns `None` for a key that the wallet does not have**, instead of an empty string, which is the value of an attribute set to it. An override of it in a subclass takes the key only and returns the value or `None`.
- **`MoneroWallet.get_transfers()` takes `account_idx` and `subaddress_idx`**, the names of the stubs and of the other methods, instead of `account_index` and `subaddress_index`.
- **`set_daemon_connection()` takes `proxy_uri`**, the name of the stubs, instead of `proxy`.
- **Type annotations:** `get_listeners()` of a wallet and of a daemon returns a `set`, `MoneroWallet.get_attribute()` can return `None`, and `merge()` of `MoneroBlock`, `MoneroTxWallet`, `MoneroOutputWallet` and of the transfers takes its own class only, as the module does: a type checker can report new errors.

## Which file to download

Expand Down
2 changes: 1 addition & 1 deletion docs/monero-spec.drawio
Original file line number Diff line number Diff line change
Expand Up @@ -1199,7 +1199,7 @@
<mxCell id="QYUe6zCbC_x82nWfNGpH-291" parent="sync-2" style="text;strokeColor=none;fillColor=none;align=left;verticalAlign=top;spacingLeft=4;spacingRight=4;overflow=hidden;rotatable=0;points=[[0,0.5],[1,0.5]];portConstraint=eastwest;fontFamily=Verdana;" value="parse_payment_uri(uri: str) -&gt; MoneroTxConfig" vertex="1">
<mxGeometry height="26" width="811" y="344" as="geometry" />
</mxCell>
<mxCell id="QYUe6zCbC_x82nWfNGpH-292" parent="sync-2" style="text;strokeColor=none;fillColor=none;align=left;verticalAlign=top;spacingLeft=4;spacingRight=4;overflow=hidden;rotatable=0;points=[[0,0.5],[1,0.5]];portConstraint=eastwest;fontFamily=Verdana;" value="get_attribute(key: str) -&gt; str" vertex="1">
<mxCell id="QYUe6zCbC_x82nWfNGpH-292" parent="sync-2" style="text;strokeColor=none;fillColor=none;align=left;verticalAlign=top;spacingLeft=4;spacingRight=4;overflow=hidden;rotatable=0;points=[[0,0.5],[1,0.5]];portConstraint=eastwest;fontFamily=Verdana;" value="get_attribute(key: str) -&gt; Optional[str]" vertex="1">
<mxGeometry height="26" width="811" y="370" as="geometry" />
</mxCell>
<mxCell id="QYUe6zCbC_x82nWfNGpH-293" parent="sync-2" style="text;strokeColor=none;fillColor=none;align=left;verticalAlign=top;spacingLeft=4;spacingRight=4;overflow=hidden;rotatable=0;points=[[0,0.5],[1,0.5]];portConstraint=eastwest;fontFamily=Verdana;" value="set_attribute(key: str, val: str) -&gt; None" vertex="1">
Expand Down
9 changes: 8 additions & 1 deletion src/cpp/wallet/py_monero_wallet.h
Original file line number Diff line number Diff line change
Expand Up @@ -594,8 +594,15 @@ class PyMoneroWallet : public monero_wallet {
PYBIND11_OVERRIDE(std::shared_ptr<monero_tx_config>, monero_wallet, parse_payment_uri, uri);
}

// python has no output parameters: an override of get_attribute(key) returns the value, or None for a missing key
bool get_attribute(const std::string& key, std::string& value) const override {
PYBIND11_OVERRIDE(bool, monero_wallet, get_attribute, key, value);
py::gil_scoped_acquire gil;
py::function override = py::get_override(static_cast<const monero_wallet*>(this), "get_attribute");
if (!override) return monero_wallet::get_attribute(key, value);
boost::optional<std::string> result = override(key).cast<boost::optional<std::string>>();
if (result == boost::none) return false;
value = result.get();
return true;
}

void set_attribute(const std::string& key, const std::string& val) override {
Expand Down
54 changes: 35 additions & 19 deletions src/cpp/wallet/py_monero_wallet_bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,22 @@ static std::vector<std::shared_ptr<monero_outgoing_transfer>> get_outgoing_trans
return transfers;
}

// the errors of the full and keys wallets for an address that they can not verify a message with (monero_wallet_full.cpp and
// monero_wallet_keys.cpp verify_message()), which the rpc wallet answers with a bad signature
static bool is_invalid_address_error(const std::string& message) {
return message == "Invalid address" || message.rfind("Invalid DNSSEC for ", 0) == 0 || message.rfind("No Monero address found at ", 0) == 0;
}

static monero_message_signature_result verify_message(const monero_wallet& wallet, const std::string& msg, const std::string& address, const std::string& signature) {
try {
return wallet.verify_message(msg, address, signature);
} catch (const std::runtime_error& e) {
if (!is_invalid_address_error(e.what())) throw;
// value initialized: not good
return monero_message_signature_result();
}
}

static std::shared_ptr<monero_tx_wallet> get_tx(const monero_wallet& wallet, const std::string& tx_hash) {
monero_tx_query query;
query.m_hashes.push_back(tx_hash);
Expand All @@ -96,9 +112,15 @@ static void def_set_daemon_connection(PyClass& cls) {
.def("set_daemon_connection", [](monero_wallet& self, const std::shared_ptr<monero_rpc_connection>& connection, const boost::optional<bool>& is_trusted) {
MONERO_CATCH_AND_RETHROW(self.set_daemon_connection(connection, is_trusted));
}, py::arg("connection"), py::arg("is_trusted") = py::none(), py::call_guard<py::gil_scoped_release>())
.def("set_daemon_connection", [](monero_wallet& self, const std::string& uri, const std::string& username, const std::string& password, const std::string& proxy, const boost::optional<bool>& is_trusted) {
MONERO_CATCH_AND_RETHROW(self.set_daemon_connection(uri, username, password, proxy, is_trusted));
}, py::arg("uri"), py::arg("username") = "", py::arg("password") = "", py::arg("proxy") = "", py::arg("is_trusted") = py::none(), py::call_guard<py::gil_scoped_release>());
.def("set_daemon_connection", [](monero_wallet& self, const std::string& uri, const std::string& username, const std::string& password, const std::string& proxy_uri, const boost::optional<bool>& is_trusted) {
MONERO_CATCH_AND_RETHROW(self.set_daemon_connection(uri, username, password, proxy_uri, is_trusted));
}, py::arg("uri"), py::arg("username") = "", py::arg("password") = "", py::arg("proxy_uri") = "", py::arg("is_trusted") = py::none(), py::call_guard<py::gil_scoped_release>());
}

static boost::optional<std::string> get_attribute(const monero_wallet& wallet, const std::string& key) {
std::string value;
if (!wallet.get_attribute(key, value)) return boost::none;
return value;
}

// runs a call without the GIL, which is taken again before the caller makes a python object of the result
Expand Down Expand Up @@ -854,17 +876,17 @@ void py_monero_bind_wallet(py::module_& m, PyMoneroTypes& t) {
monero_transfer_query query;
MONERO_CATCH_AND_RETHROW(self.get_transfers(query));
}, py::call_guard<py::gil_scoped_release>())
.def("get_transfers", [](monero_wallet& self, uint32_t account_index) {
.def("get_transfers", [](monero_wallet& self, uint32_t account_idx) {
monero_transfer_query query;
query.m_account_index = account_index;
query.m_account_index = account_idx;
MONERO_CATCH_AND_RETHROW(self.get_transfers(query));
}, py::arg("account_index"), py::call_guard<py::gil_scoped_release>())
.def("get_transfers", [](monero_wallet& self, uint32_t account_index, uint32_t subaddress_index) {
}, py::arg("account_idx"), py::call_guard<py::gil_scoped_release>())
.def("get_transfers", [](monero_wallet& self, uint32_t account_idx, uint32_t subaddress_idx) {
monero_transfer_query query;
query.m_account_index = account_index;
query.m_subaddress_index = subaddress_index;
query.m_account_index = account_idx;
query.m_subaddress_index = subaddress_idx;
MONERO_CATCH_AND_RETHROW(self.get_transfers(query));
}, py::arg("account_index"), py::arg("subaddress_index"), py::call_guard<py::gil_scoped_release>())
}, py::arg("account_idx"), py::arg("subaddress_idx"), py::call_guard<py::gil_scoped_release>())
.def("get_incoming_transfers", [](monero_wallet& self, const monero_transfer_query& query) {
MONERO_CATCH_AND_RETHROW(get_incoming_transfers(self, query));
}, py::arg("query"), py::call_guard<py::gil_scoped_release>())
Expand Down Expand Up @@ -961,12 +983,7 @@ void py_monero_bind_wallet(py::module_& m, PyMoneroTypes& t) {
MONERO_CATCH_AND_RETHROW(self.sign_message(msg, signature_type, account_idx, subaddress_idx));
}, py::arg("msg"), py::arg("signature_type"), py::arg("account_idx") = 0, py::arg("subaddress_idx") = 0, py::call_guard<py::gil_scoped_release>())
.def("verify_message", [](monero_wallet& self, const std::string& msg, const std::string& address, const std::string& signature) {
try {
return self.verify_message(msg, address, signature);
} catch (...) {
// TODO wallet full can differentiate incorrect from invalid address, but rpc returns -2 for both, so returning bad result for consistency
return monero_message_signature_result();
}
MONERO_CATCH_AND_RETHROW(verify_message(self, msg, address, signature));
}, py::arg("msg"), py::arg("address"), py::arg("signature"), py::call_guard<py::gil_scoped_release>())
.def("get_tx_key", [](monero_wallet& self, const std::string& tx_hash) {
MONERO_CATCH_AND_RETHROW(self.get_tx_key(tx_hash));
Expand Down Expand Up @@ -1044,9 +1061,8 @@ void py_monero_bind_wallet(py::module_& m, PyMoneroTypes& t) {
.def("parse_payment_uri", [](monero_wallet& self, const std::string& uri) {
MONERO_CATCH_AND_RETHROW(self.parse_payment_uri(uri));
}, py::arg("uri"), py::call_guard<py::gil_scoped_release>())
.def("get_attribute", [](monero_wallet& self, const std::string& key) -> std::string {
std::string val;
MONERO_CATCH_AND_RETHROW((self.get_attribute(key, val), val));
.def("get_attribute", [](monero_wallet& self, const std::string& key) {
MONERO_CATCH_AND_RETHROW(get_attribute(self, key));
}, py::arg("key"), py::call_guard<py::gil_scoped_release>())
.def("set_attribute", [](monero_wallet& self, const std::string& key, const std::string& val) {
MONERO_CATCH_AND_RETHROW(self.set_attribute(key, val));
Expand Down
4 changes: 2 additions & 2 deletions src/monero/monero_wallet.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -345,12 +345,12 @@ class MoneroWallet:
:raises MoneroError: exception if address is not a wallet address.
"""
...
def get_attribute(self, key: str) -> str:
def get_attribute(self, key: str) -> str | None:
"""
Get an attribute.

:param str key: is the attribute to get the value of.
:returns str: attribute's value.
:returns str | None: attribute's value, or `None` if the wallet has no attribute with that key.
"""
...
@typing.overload
Expand Down
2 changes: 1 addition & 1 deletion tests/utils/wallet_calls.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ def _tx_with_metadata() -> MoneroTxWallet:

# messages and payment uris
WalletCall("sign_message", "msg,signature_type", lambda w: w.sign_message("", MoneroMessageSignatureType.SIGN_WITH_VIEW_KEY)),
WalletCall("verify_message", "msg,address,signature", lambda w: w.verify_message("", "", ""), in_base=True),
WalletCall("verify_message", "msg,address,signature", lambda w: w.verify_message("", "", "")),
WalletCall("get_payment_uri", "config", lambda w: w.get_payment_uri(MoneroTxConfig())),
WalletCall("parse_payment_uri", "uri", lambda w: w.parse_payment_uri("")),

Expand Down
4 changes: 2 additions & 2 deletions tests/wallet/test_creation.py
Original file line number Diff line number Diff line change
Expand Up @@ -329,7 +329,7 @@ def test_save_and_close(self) -> None:
config.path = path
config.password = password
wallet = self._open_wallet(config)
assert wallet.get_attribute("id") == ""
assert wallet.get_attribute("id") is None

# set the attribute and close with saving
wallet.set_attribute("id", uuid)
Expand Down Expand Up @@ -386,7 +386,7 @@ def test_set_attributes(self, wallet: MoneroWallet) -> None:
assert val == wallet.get_attribute(key)

# get an undefined attribute
assert wallet.get_attribute("unset_key") == ""
assert wallet.get_attribute("unset_key") is None


@pytest.mark.integration
Expand Down
6 changes: 6 additions & 0 deletions tests/wallet/test_full_offline.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,12 @@ 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"))

# An attribute that is not set is None, and one that is set to an empty value is empty
def test_get_attribute_missing_or_empty(self, wallet: MoneroWalletFull) -> None:
assert wallet.get_attribute("unset_key") is None
wallet.set_attribute("empty_key", "")
assert wallet.get_attribute("empty_key") == ""

# 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:
Expand Down
77 changes: 71 additions & 6 deletions tests/wallet/test_interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@
from typing_extensions import override

from monero import (
MoneroAccountTag, MoneroError, MoneroMessageSignatureResult, MoneroSubaddress, MoneroSyncResult,
MoneroTxWallet, MoneroWallet
MoneroAccountTag, MoneroError, MoneroMessageSignatureResult, MoneroSubaddress, MoneroSyncResult, MoneroTransfer,
MoneroTransferQuery, MoneroTxWallet, MoneroWallet, MoneroWalletConfig, MoneroWalletKeys, MoneroWalletRpc
)

from utils import WalletUtils, BaseTestClass, WalletCall, WALLET_CALLS
from utils import TestUtils, WalletUtils, BaseTestClass, WalletCall, WALLET_CALLS

logger: logging.Logger = logging.getLogger("TestMoneroWalletInterface")

Expand Down Expand Up @@ -61,16 +61,75 @@
with pytest.raises(MoneroError, match="not supported"):
wallet.get_tx("")

def test_verify_message(self, wallet: MoneroWallet) -> None:
result: MoneroMessageSignatureResult = wallet.verify_message("", "", "")
WalletUtils.test_message_signature_result(result, False)
# verify_message answers an invalid address with a bad signature
def test_verify_message_invalid_address(self) -> None:
wallet: MoneroWalletKeys = self._create_wallet_keys()
try:
result: MoneroMessageSignatureResult = wallet.verify_message("message", "invalid address", "signature")
WalletUtils.test_message_signature_result(result, False)
finally:
wallet.close()

# verify_message raises the other errors, which do not say anything about the signature
def test_verify_message_raises_other_errors(self) -> None:
wallet: MoneroWalletKeys = self._create_wallet_keys()
address: str = wallet.get_primary_address()
wallet.close()

with pytest.raises(MoneroError, match="Wallet is closed"):
wallet.verify_message("message", address, "signature")

# The number of fetched blocks of a sync result is not limited to 16 bits
def test_sync_result_num_blocks_fetched(self) -> None:
result: MoneroSyncResult = MoneroSyncResult(100000, True)
assert result.num_blocks_fetched == 100000
assert result.received_money is True

# The binding gets the value of an attribute, or None for a missing key, from the python override of get_attribute
def test_get_attribute_override(self) -> None:
class AttributeWallet(MoneroWallet):
@override
def get_attribute(self, key: str) -> str | None:
return {"key": "value", "empty": ""}.get(key)

wallet: MoneroWallet = AttributeWallet()

assert MoneroWallet.get_attribute(wallet, "key") == "value"
assert MoneroWallet.get_attribute(wallet, "empty") == ""
assert MoneroWallet.get_attribute(wallet, "missing") is None

# get_transfers takes the account and the subaddress by the names that the other methods use
def test_get_transfers_by_account_and_subaddress(self) -> None:
queries: list[tuple[Optional[int], Optional[int]]] = []

class TransfersWallet(MoneroWallet):
@override
def get_transfers(self, query: Optional[MoneroTransferQuery] = None) -> list[MoneroTransfer]:
assert query is not None
queries.append((query.account_index, query.subaddress_index))
return []

wallet: MoneroWallet = TransfersWallet()

MoneroWallet.get_transfers(wallet, account_idx=1)
MoneroWallet.get_transfers(wallet, account_idx=2, subaddress_idx=3)

assert queries == [(1, None), (2, 3)]

# set_daemon_connection takes the proxy as proxy_uri, also on the rpc wallet, which adds an overload of its own
def test_set_daemon_connection_proxy_uri(self) -> None:
proxies: list[str] = []

class ConnectingWallet(MoneroWallet):
@override
def set_daemon_connection(self, uri: str, username: str = "", password: str = "", proxy_uri: str = "", is_trusted: Optional[bool] = None) -> None: # type: ignore

Check warning on line 125 in tests/wallet/test_interface.py

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

tests/wallet/test_interface.py#L125

Possible hardcoded password: ''
proxies.append(proxy_uri)

MoneroWallet.set_daemon_connection(ConnectingWallet(), uri="uri", proxy_uri="proxy")

assert proxies == ["proxy"]
assert "proxy_uri: str" in str(MoneroWalletRpc.set_daemon_connection.__doc__)

# A python override of import_multisig_hex gets the refresh flag of the caller
def test_import_multisig_hex_forwards_refresh_after_import(self) -> None:
forwarded: list[bool] = []
Expand Down Expand Up @@ -159,3 +218,9 @@
wallet.get_subaddress(2, 1)

#endregion

@staticmethod
def _create_wallet_keys() -> MoneroWalletKeys:
config: MoneroWalletConfig = MoneroWalletConfig()
config.network_type = TestUtils.NETWORK_TYPE
return MoneroWalletKeys.create_wallet_random(config)
Loading