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
2 changes: 2 additions & 0 deletions docs/mkdocs/docs/en/api/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ The model is the one of monero-cpp and monero-java, with the names of Python. It
[`MoneroTransfer`][monero.MoneroTransfer], [`MoneroOutputQuery`][monero.MoneroOutputQuery] extends
[`MoneroOutputWallet`][monero.MoneroOutputWallet].
- The classes of the model extend [`SerializableStruct`][monero.SerializableStruct], whose `serialize()` turns them into JSON.
- Two objects of the model are equal if they hold the same values, and the same object only with `is`
([Equality and Identity](equality.md)).

## Listeners

Expand Down
123 changes: 123 additions & 0 deletions docs/mkdocs/docs/en/api/equality.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
---
title: Equality and Identity
---
# Equality and Identity

The objects of the [data model](architecture.md#the-data-model) are compared like in monero-java, with the operators of Python:
`==` tells whether two objects hold the same values, `is` whether they are the same object. A test ported from monero-java has to
pick the right one, since Java writes them the other way around.

## Equality

Two objects are equal if they have the same class and the same JSON, the one of [`serialize`][monero.SerializableStruct.serialize]:

```python
tx1: MoneroTxWallet = wallet.get_tx(tx_hash)
tx2: MoneroTxWallet = wallet.get_tx(tx_hash)
assert tx1 == tx2 # the same values
assert tx1 is not tx2 # two objects
```

- **The children are compared, the back references are not.** A block compares its txs and a tx its outputs, but a tx does not
compare its block and an output its tx, as with `equals` in monero-java. Two txs with the same values in two different blocks are
equal.
- **The class has to be the same.** A [`MoneroTx`][monero.MoneroTx] does not equal a [`MoneroTxWallet`][monero.MoneroTxWallet], and a
[`MoneroTxQuery`][monero.MoneroTxQuery] does not equal the tx that it selects, even with the same JSON.
- **What is not serialized is not compared**, and what is serialized is: the `server` of a
[`MoneroWalletConfig`][monero.MoneroWalletConfig] is compared by its JSON, with its priority and its state, unlike two
[`MoneroRpcConnection`][monero.MoneroRpcConnection] on their own.

[`MoneroRpcConnection`][monero.MoneroRpcConnection] is compared as in monero-java, by uri, username, password, proxy uri, zmq uri and
ssl verify. Its JSON also has the priority, the timeout and the state of the connection (`responseTime`, `isOnline`), which are not
compared: a connection equals the one that a wallet returns for it.

## Hashing

The objects can be changed, so they are not hashable: they can not be keys of a `dict` or go in a `set`, and `hash(tx)` raises
`TypeError`. Key them by what identifies them:

```python
txs_by_hash: dict[str, MoneroTxWallet] = {tx.hash: tx for tx in txs}
```

or, to tell the objects apart rather than their values, by their `id()` while a reference keeps them alive (see below).

## Identity

An object of the model is a Python object around a C++ object. The bindings give the same Python object for the same C++ object as long
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
```

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
next. Keep a reference before taking it:

```python
block: MoneroBlock | None = tx.block
if block is not None and id(block) not in seen_blocks:
seen_blocks.add(id(block))
blocks.append(block) # keeps it alive, so its id is not used again
```

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

```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
```

## Representation

The `repr` of an object is its class with its JSON, `MoneroTxWallet({"hash":"...",...})`, which is what pytest shows when an `==`
fails. [`MoneroRpcConnection`][monero.MoneroRpcConnection] shows `***` for its password, and
[`MoneroWalletConfig`][monero.MoneroWalletConfig] for its password, seed, seed offset, private keys and the password of its server, so
that they do not end up in a log. `serialize()` keeps them.

## Differences from monero-java

| monero-java | monero-python | |
| --- | --- | --- |
| `a == b`, `a != b` | `a is b`, `a is not b` | the same object |
| `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<MoneroBlock>`, `Map<MoneroTx, ...>` | 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 |
| `toString()`, an indented text | `repr()`, the JSON on one line | with the secrets hidden |

## Porting a test from monero-java

monero-java checks a copy with a pair of asserts, one for each meaning:

```java
MoneroTxConfig configCopy = config.copy();
// ...
assertTrue(configCopy != config); // another object
assertEquals(configCopy, config); // with the same values
```

In Python, the first is `is not`, not `!=`: `configCopy != config` would fail, since the copy has the same values.

```python
config_copy: MoneroTxConfig = config.copy()
# ...
assert config_copy is not config
assert config_copy == config
```

The same goes for the back references, which monero-java checks with `==`: `assertTrue(tx == output.getTx())` is
`assert output.tx is tx`. A `==` there would also pass with a copy of the tx, which is not what the test checks.
4 changes: 4 additions & 0 deletions docs/mkdocs/docs/en/api/serializable_struct.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,8 @@ def carry(result: MoneroKeyImageExportResult) -> MoneroKeyImageExportResult:

It is how an object goes from a process or a machine to another ([Signing Offline with a Cold Wallet](../examples/scenarios/cold_signing.md)).

Two objects of the same class are equal if they serialize the same, without their back references, and they are not hashable. Their
`repr` is their class with their JSON. [Equality and Identity](equality.md) says how `==` and `is` work on the model, and how they
differ from monero-java.

::: monero.SerializableStruct
1 change: 1 addition & 0 deletions docs/mkdocs/docs/en/tests/files/common.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +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_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 |
Expand Down
3 changes: 3 additions & 0 deletions docs/mkdocs/docs/en/tests/writing/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ How the tests are made, and what a new one needs.
| [A New Wallet Method](new_wallet_method.md) | the call and the row of the support matrix that a new method of `MoneroWallet` needs |
| [Helpers](helpers.md) | the helpers of `tests/utils` |

A test ported from monero-java turns its `==` between objects into `is`, and its `assertEquals` into `==`: see
[Porting a test from monero-java](../../api/equality.md#porting-a-test-from-monero-java).

## Where a test goes

| What it tests | Where |
Expand Down
1 change: 1 addition & 0 deletions docs/mkdocs/mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ nav:
- Logging: 'api/utils/logging.md'
- Binary RPC: 'api/utils/binary.md'
- Test Helpers: 'api/utils/helpers.md'
- Equality and Identity: 'api/equality.md'
- Glossary: 'api/glossary.md'
- Security: 'api/security.md'
- Troubleshooting: 'api/troubleshooting.md'
Expand Down
30 changes: 30 additions & 0 deletions src/cpp/common/py_monero_common.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@
* Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers
*/
#include "py_monero_common.h"
#include "utils/gen_utils.h"
#include <algorithm>

// --------------------------- GEN UTILS ---------------------------

Expand Down Expand Up @@ -131,6 +133,34 @@ py::object PyGenUtils::parse_rpc_response(const std::string& body, const std::st
return response_dict.contains("jsonrpc") ? py::none() : response;
}

// replaces the non-empty strings of the keys with ***, at any depth, like the password of the server of a wallet config
static void redact(rapidjson::Value& val, const std::vector<std::string>& keys) {
// iterators rather than GetObject(), which windows.h renames to GetObjectA
if (val.IsArray()) {
for (auto it = val.Begin(); it != val.End(); ++it) redact(*it, keys);
return;
}
if (!val.IsObject()) return;
for (auto it = val.MemberBegin(); it != val.MemberEnd(); ++it) {
bool secret = std::find(keys.begin(), keys.end(), it->name.GetString()) != keys.end();
if (secret && it->value.IsString() && it->value.GetStringLength() > 0) it->value.SetString("***");
else redact(it->value, keys);
}
}

std::string PyGenUtils::serialize_redacted(const serializable_struct& s, const std::vector<std::string>& keys) {
rapidjson::Document doc;
doc.SetObject();
rapidjson::Value val = s.to_rapidjson_val(doc.GetAllocator());
val.Swap(doc);
redact(doc, keys);
return gen_utils::serialize(doc);
}

py::str PyGenUtils::repr(const py::object& self, const std::string& json) {
return py::str("{}({})").format(py::type::of(self).attr("__name__"), json);
}

// --------------------------- MONERO REQUEST PARAMS ---------------------------

PyMoneroRequestParams::PyMoneroRequestParams(const boost::optional<py::object>& py_params) {
Expand Down
18 changes: 18 additions & 0 deletions src/cpp/common/py_monero_common.h
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,24 @@ class PyGenUtils {
* @return the result of a JSON-RPC response, or the whole response of a path request
*/
static py::object parse_rpc_response(const std::string& body, const std::string& method, const std::string& uri, bool json_rpc);

/**
* Serialize a struct with the non-empty strings of the given keys replaced by ***, at any depth.
*
* @param s is the struct to serialize
* @param keys are the json keys of the secrets to hide, like "password"
* @return the json of the struct without its secrets
*/
static std::string serialize_redacted(const serializable_struct& s, const std::vector<std::string>& keys);

/**
* Represent a struct as the name of its python type with its json.
*
* @param self is the struct
* @param json is the json to show
* @return the representation, like MoneroTx({...})
*/
static py::str repr(const py::object& self, const std::string& json);
};

/**
Expand Down
17 changes: 17 additions & 0 deletions src/cpp/common/py_monero_common_bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,14 @@ void py_monero_bind_common(py::module_& m, PyMoneroTypes& t) {
t.py_serializable_struct
.def("serialize", [](serializable_struct& self) {
MONERO_CATCH_AND_RETHROW(self.serialize());
})
.def("__eq__", [](const py::object& self, const py::object& other) -> py::object {
// structs of the same type are equal if they serialize the same, without their back references like monero-java
if (!py::type::of(self).is(py::type::of(other))) return py::reinterpret_borrow<py::object>(Py_NotImplemented);
MONERO_CATCH_AND_RETHROW(py::bool_(self.cast<const serializable_struct&>().serialize() == other.cast<const serializable_struct&>().serialize()));
}, py::arg("other"), py::is_operator())
.def("__repr__", [](const py::object& self) {
MONERO_CATCH_AND_RETHROW(PyGenUtils::repr(self, self.cast<const serializable_struct&>().serialize()));
});

// monero_rpc_payment_info
Expand Down Expand Up @@ -263,6 +271,15 @@ void py_monero_bind_common(py::module_& m, PyMoneroTypes& t) {
.def_static("deserialize", [](const std::string& json) {
MONERO_CATCH_AND_RETHROW(monero_rpc_connection::deserialize(json));
}, py::arg("json"))
.def("__eq__", [](const monero_rpc_connection& self, const py::object& other) -> py::object {
// compare the config of the connections like monero-java, not their state
if (!py::isinstance<monero_rpc_connection>(other)) return py::reinterpret_borrow<py::object>(Py_NotImplemented);
const monero_rpc_connection& connection = other.cast<const monero_rpc_connection&>();
return py::bool_(self.m_uri == connection.m_uri && self.m_username == connection.m_username && self.m_password == connection.m_password && self.m_proxy_uri == connection.m_proxy_uri && self.m_zmq_uri == connection.m_zmq_uri && self.m_ssl_verify == connection.m_ssl_verify);
}, py::arg("other"), py::is_operator())
.def("__repr__", [](const py::object& self) {
MONERO_CATCH_AND_RETHROW(PyGenUtils::repr(self, PyGenUtils::serialize_redacted(self.cast<const monero_rpc_connection&>(), {"password"})));
})
.def_property("uri",
[](const monero_rpc_connection& self) { return self.m_uri; },
[](monero_rpc_connection& self, const boost::optional<std::string>& val) {
Expand Down
3 changes: 3 additions & 0 deletions src/cpp/wallet/py_monero_wallet_bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,9 @@ void py_monero_bind_wallet(py::module_& m, PyMoneroTypes& t) {
.def_readwrite("regtest", &monero_wallet_config::m_regtest)
.def("copy", [](monero_wallet_config& self) {
MONERO_CATCH_AND_RETHROW(self.copy());
})
.def("__repr__", [](const py::object& self) {
MONERO_CATCH_AND_RETHROW(PyGenUtils::repr(self, PyGenUtils::serialize_redacted(self.cast<const monero_wallet_config&>(), {"password", "seed", "seedOffset", "privateViewKey", "privateSpendKey"})));
});

// monero_subaddress
Expand Down
21 changes: 21 additions & 0 deletions src/monero/monero_rpc_connection.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,27 @@ class MoneroRpcConnection(SerializableStruct):
"""Connection response time in milliseconds."""
...

@typing.override
def __eq__(self, other: object) -> bool:
"""
Compare this connection to another like monero-java: by uri, username, password, proxy uri, zmq uri and ssl verify.
The priority, the timeout and the state of the connections, like the response time, are not compared.

:param object other: connection to compare against.

:returns bool: `True` if `other` is a connection with the same config.
"""
...

@typing.override
def __repr__(self) -> str:
"""
Represent this connection as its json, with the password hidden.

:returns str: e.g. `MoneroRpcConnection({"uri":"http://localhost:28081","username":"rpc_user","password":"***",...})`.
"""
...

@staticmethod
def compare(p1: int, p2: int) -> bool:
"""
Expand Down
10 changes: 10 additions & 0 deletions src/monero/monero_wallet_config.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -76,3 +76,13 @@ class MoneroWalletConfig(SerializableStruct):
:returns MoneroWalletConfig: Copy of the wallet config.
"""
...

@typing.override
def __repr__(self) -> str:
"""
Represent this config as its json, with the password, the seed, its offset, the private keys and the password of its
server hidden.

:returns str: e.g. `MoneroWalletConfig({"networkType":2,"path":"wallets/main","password":"***",...})`.
"""
...
30 changes: 29 additions & 1 deletion src/monero/serializable_struct.pyi
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
import typing

from abc import ABC


class SerializableStruct(ABC):
"""Base struct which can be serialized."""
"""Base struct which can be serialized.

Structs of the same type are equal if they serialize the same: the back references, like the block of a tx or the tx
of an output, are not compared. Structs are mutable, so they are not hashable.
"""

__hash__: typing.ClassVar[None] # type: ignore[assignment]

def serialize(self) -> str:
"""
Expand All @@ -11,3 +19,23 @@ class SerializableStruct(ABC):
:returns str: the struct serialized to a json string.
"""
...

@typing.override
def __eq__(self, other: object) -> bool:
"""
Compare this struct to another by their serialization.

:param object other: struct to compare against.

:returns bool: `True` if `other` has the same type and serializes the same.
"""
...

@typing.override
def __repr__(self) -> str:
"""
Represent this struct as its type with its json.

:returns str: e.g. `MoneroSubaddress({"accountIndex":0,"index":1})`.
"""
...
Loading
Loading