From fb6f0ce20834a352324dc92a337615ecf07eef06 Mon Sep 17 00:00:00 2001 From: everoddandeven Date: Sat, 28 Nov 2026 23:47:27 +0100 Subject: [PATCH 1/6] bindings: lint the stubs against the signatures of the module --- bin/lint_bindings.py | 142 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 142 insertions(+) diff --git a/bin/lint_bindings.py b/bin/lint_bindings.py index 53f6f5c7..66b1f94f 100755 --- a/bin/lint_bindings.py +++ b/bin/lint_bindings.py @@ -11,6 +11,11 @@ nothing about the parameter. The special methods are left out, pybind11 names those of the containers it binds itself, and so are the setters of the properties. +The stubs of the package, in src/, are written by hand: they give the docs and the types that the module can not. +This also fails where they differ from the signatures of the module: a class or a member that only one of them has, other +names of parameters, or another return type. A type of the stubs can be None when the one of the module can not say it, +as the one of a shared pointer. + pip install pybind11-stubgen bin/lint_bindings.py [module] # monero, which has to be installed or on the path """ @@ -45,6 +50,131 @@ def visit(node: ast.AST, owner: str) -> None: return sorted(set(found)) +# the names that python gives to the containers bound by the module, which the stubs write as the types of python +ELEMENT_TYPES = {'String': 'str', 'Int': 'int', 'Uint8': 'int', 'Uint32': 'int', 'Uint64': 'int'} + +# the members that a stub has and the module does not declare: the attributes that a class of python sets in its __init__ +INSTANCE_ATTRIBUTES = {('MoneroRpcError', 'code')} + +Signature = tuple[tuple[str, ...], int] +"""The names of the parameters of a function, and how many of them are required""" + + +class Member: + """A function, a property or a constant of a class, with all of its overloads""" + + def __init__(self) -> None: + self.signatures: list[Signature] = [] + self.types: set[str] = set() + + def calls(self) -> set[tuple[str, ...]]: + """The parameters that a call can give: the required ones and any number of the optional ones that follow them""" + return {names[:count] for names, required in self.signatures for count in range(required, len(names) + 1)} + + +def type_members(node: ast.expr) -> set[str]: + """The types of an annotation, written the same way for the stubs and the module: Optional[VectorX] -> {'list[X]', 'None'}""" + if isinstance(node, ast.Constant): + return {'None'} if node.value is None else type_members(ast.parse(str(node.value), mode='eval').body) + if isinstance(node, ast.BinOp) and isinstance(node.op, ast.BitOr): + return type_members(node.left) | type_members(node.right) + if isinstance(node, ast.Subscript): + outer = ast.unparse(node.value).split('.')[-1] + if outer == 'Optional': + return type_members(node.slice) | {'None'} + if outer == 'ClassVar': + return type_members(node.slice) + args = node.slice.elts if isinstance(node.slice, ast.Tuple) else [node.slice] + inner = [' | '.join(sorted(type_members(a))) for a in args] + if outer == 'dict' and inner == ['object', 'object']: + return {'dict'} + return {'%s[%s]' % (outer.lower() if outer in ('List', 'Set', 'Dict') else outer, ', '.join(inner))} + name = ast.unparse(node).split('.')[-1] + if name == 'Any': + return {'object'} + if name.startswith('Vector'): + element = name[len('Vector'):] + if element.endswith('Ptr'): + element = element[:-len('Ptr')] + return {'list[%s]' % ELEMENT_TYPES.get(element, element)} + # the name that pybind11 gives to the element of a vector of shared pointers + if name.endswith('Ptr'): + name = name[:-len('Ptr')] + return {ELEMENT_TYPES.get(name, name)} + + +def read_classes(files: list[Path]) -> dict[str, dict[str, Member]]: + """The public members of the classes of the stubs, by class and name""" + classes: dict[str, dict[str, Member]] = {} + for file in files: + for node in ast.parse(file.read_text()).body: + if not isinstance(node, ast.ClassDef): + continue + members = classes.setdefault(node.name, {}) + is_enum = any('Enum' in ast.unparse(base) for base in node.bases) + for child in node.body: + if isinstance(child, ast.AnnAssign) and isinstance(child.target, ast.Name): + name = child.target.id + member = members.setdefault(name, Member()) + if not is_enum: + member.types |= type_members(child.annotation) + elif isinstance(child, ast.Assign) and isinstance(child.targets[0], ast.Name): + name = child.targets[0].id + members.setdefault(name, Member()) + elif isinstance(child, ast.FunctionDef): + name = child.name + decorators = [ast.unparse(d).split('.')[-1] for d in child.decorator_list] + if name.startswith('_') or 'setter' in decorators: + continue + member = members.setdefault(name, Member()) + if child.returns is not None: + member.types |= type_members(child.returns) + if 'property' not in decorators: + args = child.args.posonlyargs + child.args.args + if 'staticmethod' not in decorators: + args = args[1:] + names = tuple(a.arg for a in args) + member.signatures.append((names, len(names) - len(child.args.defaults))) + for name in [n for n in members if n.startswith('_')]: + del members[name] + return classes + + +def stub_differences(module_files: list[Path], stub_files: list[Path]) -> list[str]: + """Where the stubs written by hand differ from the ones that stubgen writes from the module""" + module = read_classes(module_files) + stubs = read_classes(stub_files) + # the vectors and the maps that the module binds are the lists and the dicts of the stubs + module = {name: members for name, members in module.items() if not name.startswith('Vector') and not name.endswith('Map')} + + found = ['%s is not in the stubs' % name for name in sorted(set(module) - set(stubs))] + found += ['%s is not in the module' % name for name in sorted(set(stubs) - set(module))] + for owner in sorted(set(module) & set(stubs)): + bound, written = module[owner], stubs[owner] + # the members of an enum of the stubs come from its base + is_enum = 'value' in bound and 'value' not in written and '__int__' not in written and owner.endswith(('Type', 'Status', 'Priority')) + for name in sorted(set(bound) | set(written)): + member = '%s.%s' % (owner, name) + if (owner, name) in INSTANCE_ATTRIBUTES or (is_enum and name in ('name', 'value')): + continue + if name not in written: + found.append('%s is not in the stubs' % member) + elif name not in bound: + found.append('%s is not in the module' % member) + else: + module_calls, stub_calls = bound[name].calls(), written[name].calls() + if module_calls != stub_calls: + found.append('%s takes %s in the module and %s in the stubs' % (member, sorted(module_calls - stub_calls), + sorted(stub_calls - module_calls))) + module_types, stub_types = bound[name].types, set(written[name].types) + # "X | None" can be the "X" of the module, "None" alone is another type + if 'None' not in module_types and len(stub_types) > 1: + stub_types.discard('None') + if module_types and stub_types and module_types != stub_types: + found.append('%s returns %s in the module and %s in the stubs' % (member, sorted(module_types), sorted(stub_types))) + return found + + def main() -> int: module = sys.argv[1] if len(sys.argv) > 1 else 'monero' ok = True @@ -73,6 +203,18 @@ def main() -> int: ok = False elif stubs: print('%d stub files generated, no unnamed parameters' % len(stubs)) + + written = sorted((Path(__file__).resolve().parent.parent / 'src' / module).glob('*.pyi')) + if stubs and written: + differences = stub_differences(stubs, written) + if differences: + print('Stubs that differ from the module:') + for d in differences: + print(' ' + d) + print('::error::%d differences between the stubs and the bindings of %s' % (len(differences), module)) + ok = False + else: + print('%d stubs of the package match the module' % len(written)) return 0 if ok else 1 From 6643eeb0b95c5fb7652832feeecc58bb1609ba56 Mon Sep 17 00:00:00 2001 From: everoddandeven Date: Sun, 29 Nov 2026 01:16:20 +0100 Subject: [PATCH 2/6] tests: ignore only the pyright rules that the lines break --- conftest.py | 2 +- tests/common/test_block_generation.py | 4 ++-- tests/common/test_rpc_connection.py | 4 ++-- tests/common/test_wallet_tx_tracker.py | 8 ++++---- tests/daemon/model/test_outputs.py | 2 +- tests/daemon/model/test_txs.py | 6 +++--- tests/utils/assert_utils.py | 4 ++-- tests/utils/fake_raw_rpc_server.py | 2 +- tests/utils/fake_rpc_server.py | 2 +- tests/utils/rpc_connection_utils.py | 2 +- tests/wallet/model/test_output_query.py | 4 ++-- tests/wallet/model/test_transfer_query.py | 2 +- tests/wallet/model/test_tx_query.py | 2 +- tests/wallet/model/test_txs.py | 2 +- tests/wallet/test_accounts.py | 2 +- tests/wallet/test_interface.py | 8 ++++---- tests/wallet/test_outputs.py | 2 +- tests/wallet/test_txs.py | 2 +- tests/wallet/wallet_support.py | 8 ++++---- 19 files changed, 34 insertions(+), 34 deletions(-) diff --git a/conftest.py b/conftest.py index 8e5cae70..a0848493 100644 --- a/conftest.py +++ b/conftest.py @@ -59,7 +59,7 @@ def pytest_runtest_logstart(nodeid: str) -> None: def pytest_runtest_logreport(report: pytest.TestReport) -> None: - if report.outcome == "rerun": # type: ignore # set by pytest-rerunfailures + if report.outcome == "rerun": # pyright: ignore[reportUnnecessaryComparison] # set by pytest-rerunfailures logger.error(f"EXPECTED FAILURE: {_crash_message(report)}") logger.warning(f"RERUN {report.nodeid}") return diff --git a/tests/common/test_block_generation.py b/tests/common/test_block_generation.py index c17e9c82..cf3f86e4 100644 --- a/tests/common/test_block_generation.py +++ b/tests/common/test_block_generation.py @@ -34,12 +34,12 @@ class TestBlockGeneration(BaseTestClass): # 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] + assert is_generation_fast(_Daemon(difficulty)) is True # pyright: ignore[reportArgumentType] # 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] + assert is_generation_fast(_Daemon(difficulty)) is False # pyright: ignore[reportArgumentType] # 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)]) diff --git a/tests/common/test_rpc_connection.py b/tests/common/test_rpc_connection.py index 99200133..7dceb7ff 100644 --- a/tests/common/test_rpc_connection.py +++ b/tests/common/test_rpc_connection.py @@ -213,10 +213,10 @@ def test_set_invalid_credentials(self) -> None: # username / password are read-only properties (set via set_credentials()) with pytest.raises(AttributeError, match="object has no setter"): - connection.username = "user" # type: ignore + connection.username = "user" # pyright: ignore[reportAttributeAccessIssue] with pytest.raises(AttributeError, match="object has no setter"): - connection.password = "abc123" # type: ignore + connection.password = "abc123" # pyright: ignore[reportAttributeAccessIssue] # set invalid username with pytest.raises(RuntimeError, match="username cannot be empty because password is not empty"): diff --git a/tests/common/test_wallet_tx_tracker.py b/tests/common/test_wallet_tx_tracker.py index 844be4aa..e9e0b5b1 100644 --- a/tests/common/test_wallet_tx_tracker.py +++ b/tests/common/test_wallet_tx_tracker.py @@ -52,7 +52,7 @@ class TestWalletTxTracker(BaseTestClass): def test_rpc_wallet_rescans_spent_outputs_after_the_pool_is_clear(self) -> None: # the server of a wallet rpc sets back as unspent the inputs of a tx that it saw in the pool and that left it, 500 s after, and # the next tx used them: the daemon rejected it as a double spend (test_subtract_fee_from, in CI) - tracker: WalletTxTracker = WalletTxTracker(_Daemon(), 10, "") # type: ignore[arg-type] + tracker: WalletTxTracker = WalletTxTracker(_Daemon(), 10, "") # pyright: ignore[reportArgumentType] with FakeWalletRpcServer() as server: wallet: MoneroWalletRpc = MoneroWalletRpc(server.uri) tracker.wait_for_txs_to_clear_pool([wallet]) @@ -63,7 +63,7 @@ def test_rpc_wallet_rescans_spent_outputs_after_the_pool_is_clear(self) -> None: # Every wallet rpc of a list is asked, not only the first one def test_each_rpc_wallet_rescans_spent_outputs(self) -> None: - tracker: WalletTxTracker = WalletTxTracker(_Daemon(), 10, "") # type: ignore[arg-type] + tracker: WalletTxTracker = WalletTxTracker(_Daemon(), 10, "") # pyright: ignore[reportArgumentType] with FakeWalletRpcServer() as server1, FakeWalletRpcServer() as server2: wallets: list[Any] = [MoneroWalletRpc(server1.uri), MoneroWalletRpc(server2.uri)] tracker.wait_for_txs_to_clear_pool(wallets) @@ -72,9 +72,9 @@ def test_each_rpc_wallet_rescans_spent_outputs(self) -> None: # The other wallets are not asked: the full wallet follows its own outputs, and a wallet that is not a wallet rpc may not have it def test_other_wallets_do_not_rescan_spent_outputs(self) -> None: - tracker: WalletTxTracker = WalletTxTracker(_Daemon(), 10, "") # type: ignore[arg-type] + tracker: WalletTxTracker = WalletTxTracker(_Daemon(), 10, "") # pyright: ignore[reportArgumentType] wallet: _Wallet = _Wallet() - tracker.wait_for_txs_to_clear_pool([wallet]) # type: ignore[list-item] + tracker.wait_for_txs_to_clear_pool([wallet]) # pyright: ignore[reportArgumentType] assert wallet.num_rescans == 0 #endregion diff --git a/tests/daemon/model/test_outputs.py b/tests/daemon/model/test_outputs.py index 7801f77a..ca5ae2a0 100644 --- a/tests/daemon/model/test_outputs.py +++ b/tests/daemon/model/test_outputs.py @@ -36,7 +36,7 @@ def test_output_is_locked(self) -> None: # it is read from the tx, so it cannot be set with pytest.raises(AttributeError): - output.is_locked = True # type: ignore[misc] + output.is_locked = True # pyright: ignore[reportAttributeAccessIssue] # it comes from the tx, which the output does not serialize assert "isLocked" not in output.serialize() diff --git a/tests/daemon/model/test_txs.py b/tests/daemon/model/test_txs.py index 3886731a..b82e4a4e 100644 --- a/tests/daemon/model/test_txs.py +++ b/tests/daemon/model/test_txs.py @@ -178,7 +178,7 @@ def test_tx_copy_deep_copies_inputs(self) -> None: 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].key_image.hex == "1" * 64 # pyright: ignore[reportOptionalMemberAccess] assert copy.inputs[0].amount == 1234 assert copy.inputs[0].tx is copy @@ -284,9 +284,9 @@ def make_input(tx: MoneroTx, key_image_hex: str) -> MoneroOutput: a.merge(b) assert len(a.inputs) == 2 - assert a.inputs[0].key_image.hex == "1" * 64 # type: ignore + assert a.inputs[0].key_image.hex == "1" * 64 # pyright: ignore[reportOptionalMemberAccess] 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].key_image.hex == "2" * 64 # pyright: ignore[reportOptionalMemberAccess] assert a.inputs[1].tx is a # appended input is repointed at a def test_tx_lt_height_comparator(self) -> None: diff --git a/tests/utils/assert_utils.py b/tests/utils/assert_utils.py index 033e9451..8f552413 100644 --- a/tests/utils/assert_utils.py +++ b/tests/utils/assert_utils.py @@ -63,7 +63,7 @@ def assert_serialization_integrity[T: SerializableStruct](cls, obj: T) -> T: cls = type(obj) json_str: str = obj.serialize() logger.debug(f"Serialized {cls.__name__}: {json_str}") - restored: Any = cls.deserialize(json_str) # type: ignore + restored: Any = cls.deserialize(json_str) # pyright: ignore[reportUnknownVariableType, reportUnknownMemberType, reportAttributeAccessIssue] AssertUtils.assert_equals(obj, restored) - return restored # type: ignore + return restored # pyright: ignore[reportUnknownVariableType] diff --git a/tests/utils/fake_raw_rpc_server.py b/tests/utils/fake_raw_rpc_server.py index 87c0282f..22214f07 100644 --- a/tests/utils/fake_raw_rpc_server.py +++ b/tests/utils/fake_raw_rpc_server.py @@ -11,7 +11,7 @@ class FakeRawRpcHandler(BaseHTTPRequestHandler): """Answers a request with the body that the test set for its path, after the delay of the server.""" - server: "FakeRawRpcServer" # type: ignore[assignment] + server: "FakeRawRpcServer" # pyright: ignore[reportIncompatibleVariableOverride] def do_POST(self) -> None: """Answer a request with the response of its path, 404 if it has none.""" diff --git a/tests/utils/fake_rpc_server.py b/tests/utils/fake_rpc_server.py index 6ba058e2..2ae9b36d 100644 --- a/tests/utils/fake_rpc_server.py +++ b/tests/utils/fake_rpc_server.py @@ -14,7 +14,7 @@ class FakeRpcHandler(BaseHTTPRequestHandler): """Answers the json rpc requests of a poller. A subclass gives the result of the response.""" - server: "FakeRpcServer" # type: ignore[assignment] + server: "FakeRpcServer" # pyright: ignore[reportIncompatibleVariableOverride] def build_result(self, height: int, method: str) -> dict[str, Any]: """Build the result of a response. diff --git a/tests/utils/rpc_connection_utils.py b/tests/utils/rpc_connection_utils.py index ba4eb481..c768eb42 100644 --- a/tests/utils/rpc_connection_utils.py +++ b/tests/utils/rpc_connection_utils.py @@ -74,7 +74,7 @@ def test_rpc_connection( # response_time is a read-only property with pytest.raises(Exception): - connection.response_time = 0 # type: ignore + connection.response_time = 0 # pyright: ignore[reportAttributeAccessIssue] # test connection type if connection_type == MoneroConnectionType.I2P: diff --git a/tests/wallet/model/test_output_query.py b/tests/wallet/model/test_output_query.py index 78b16aaa..efc9339d 100644 --- a/tests/wallet/model/test_output_query.py +++ b/tests/wallet/model/test_output_query.py @@ -21,7 +21,7 @@ def test_output_query(self) -> None: # test tx query property assign try: - output_query.tx_query = tx_query # type: ignore + output_query.tx_query = tx_query # pyright: ignore[reportAttributeAccessIssue] except AttributeError as e: err_msg: str = str(e) assert "object has no setter" in err_msg @@ -196,7 +196,7 @@ def test_output_query_meets_criteria_query_parent_links_tx_query(self) -> None: 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 + MoneroOutputQuery().meets_criteria(None, False) # pyright: ignore[reportArgumentType] assert str(exc_info.value) == "nullptr given to monero_output_query::meets_criteria()" def test_output_query_deserialize(self) -> None: diff --git a/tests/wallet/model/test_transfer_query.py b/tests/wallet/model/test_transfer_query.py index 3e4ea517..5f84c66c 100644 --- a/tests/wallet/model/test_transfer_query.py +++ b/tests/wallet/model/test_transfer_query.py @@ -238,7 +238,7 @@ def test_transfer_query_meets_criteria_query_parent_links_tx_query(self) -> None 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 + MoneroTransferQuery().meets_criteria(None, False) # pyright: ignore[reportArgumentType] assert str(exc_info.value) == "nullptr given to monero_transfer_query::meets_criteria()" def test_transfer_query_deserialize(self) -> None: diff --git a/tests/wallet/model/test_tx_query.py b/tests/wallet/model/test_tx_query.py index a4f52a11..d6049d41 100644 --- a/tests/wallet/model/test_tx_query.py +++ b/tests/wallet/model/test_tx_query.py @@ -265,7 +265,7 @@ def test_tx_query_meets_criteria_output_query(self) -> None: def test_tx_query_meets_criteria_none_tx_raises(self) -> None: with pytest.raises(RuntimeError) as exc_info: - MoneroTxQuery().meets_criteria(None) # type: ignore + MoneroTxQuery().meets_criteria(None) # pyright: ignore[reportArgumentType] assert str(exc_info.value) == "nullptr given to monero_tx_query::meets_criteria()" def test_tx_query_deserialize(self) -> None: diff --git a/tests/wallet/model/test_txs.py b/tests/wallet/model/test_txs.py index 4699bebe..ce87ac95 100644 --- a/tests/wallet/model/test_txs.py +++ b/tests/wallet/model/test_txs.py @@ -153,7 +153,7 @@ def test_tx_wallet_copy_re_copies_inputs_as_output_wallet(self) -> None: 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].key_image.hex == "1" * 64 # pyright: ignore[reportOptionalMemberAccess] assert copy.inputs[0].tx is copy def test_tx_wallet_merge(self) -> None: diff --git a/tests/wallet/test_accounts.py b/tests/wallet/test_accounts.py index dc8f8295..afce9b98 100644 --- a/tests/wallet/test_accounts.py +++ b/tests/wallet/test_accounts.py @@ -435,7 +435,7 @@ class TestMoneroWalletFullAccounts(FullWalletSupport, BaseTestMoneroWalletAccoun # 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 + def test_create_subaddress(self, wallet: MoneroWalletFull) -> None: # pyright: ignore[reportIncompatibleMethodOverride] # create subaddresses across accounts accounts: list[MoneroAccount] = wallet.get_accounts() if len(accounts) < 2: diff --git a/tests/wallet/test_interface.py b/tests/wallet/test_interface.py index f6238253..0dd4b6a3 100644 --- a/tests/wallet/test_interface.py +++ b/tests/wallet/test_interface.py @@ -40,7 +40,7 @@ def test_call(self, wallet: MoneroWallet, call: WalletCall) -> None: def test_relay_txs_none_tx_raises(self, wallet: MoneroWallet) -> None: with pytest.raises(RuntimeError) as exc_info: - wallet.relay_txs([None]) # type: ignore + wallet.relay_txs([None]) # pyright: ignore[reportCallIssue, reportArgumentType] assert str(exc_info.value) == "Tx metadata is not initialized" def test_relay_txs_uninitialized_metadata_raises(self, wallet: MoneroWallet) -> None: @@ -103,9 +103,9 @@ def test_get_transfers_by_account_and_subaddress(self) -> None: queries: list[tuple[Optional[int], Optional[int]]] = [] class TransfersWallet(MoneroWallet): + # the binding calls the override only with a query @override - def get_transfers(self, query: Optional[MoneroTransferQuery] = None) -> list[MoneroTransfer]: - assert query is not None + def get_transfers(self, query: MoneroTransferQuery) -> list[MoneroTransfer]: # pyright: ignore[reportIncompatibleMethodOverride] queries.append((query.account_index, query.subaddress_index)) return [] @@ -122,7 +122,7 @@ def test_set_daemon_connection_proxy_uri(self) -> None: 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 + def set_daemon_connection(self, uri: str, username: str = "", password: str = "", proxy_uri: str = "", is_trusted: Optional[bool] = None) -> None: # pyright: ignore[reportIncompatibleMethodOverride] proxies.append(proxy_uri) MoneroWallet.set_daemon_connection(ConnectingWallet(), uri="uri", proxy_uri="proxy") diff --git a/tests/wallet/test_outputs.py b/tests/wallet/test_outputs.py index 444e291f..129ec5f8 100644 --- a/tests/wallet/test_outputs.py +++ b/tests/wallet/test_outputs.py @@ -459,7 +459,7 @@ def test_input_key_images(self, wallet: MoneroWallet) -> 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 + if max_skipped_output is None or max_skipped_output.amount < output.amount: # pyright: ignore[reportOptionalOperand] max_skipped_output = output if max_skipped_output is not None: diff --git a/tests/wallet/test_txs.py b/tests/wallet/test_txs.py index cfe5e370..9dfafd1b 100644 --- a/tests/wallet/test_txs.py +++ b/tests/wallet/test_txs.py @@ -224,7 +224,7 @@ def test_get_txs_with_query(self, wallet: MoneroWallet) -> None: for tx in txs: found: bool = False - if tx.is_outgoing and tx.outgoing_transfer.account_index == account_idx: # type: ignore + if tx.is_outgoing and tx.outgoing_transfer.account_index == account_idx: # pyright: ignore[reportOptionalMemberAccess] found = True elif len(tx.incoming_transfers) > 0: for transfer in tx.incoming_transfers: diff --git a/tests/wallet/wallet_support.py b/tests/wallet/wallet_support.py index 516515b3..5eaa924e 100644 --- a/tests/wallet/wallet_support.py +++ b/tests/wallet/wallet_support.py @@ -103,7 +103,7 @@ def _get_seed_languages(self) -> list[str]: @override @classmethod def get_test_wallet(cls) -> MoneroWalletFull: - return super().get_test_wallet() # type: ignore + return super().get_test_wallet() # pyright: ignore[reportReturnType] class RpcWalletSupport(BaseTestMoneroWallet): @@ -124,7 +124,7 @@ def wallet(cls) -> MoneroWalletRpc: @classmethod @override def get_test_wallet(cls) -> MoneroWalletRpc: - return super().get_test_wallet() # type: ignore + return super().get_test_wallet() # pyright: ignore[reportReturnType] @override def _open_wallet(self, config: MoneroWalletConfig | None) -> MoneroWalletRpc: @@ -190,7 +190,7 @@ def wallet(cls) -> MoneroWalletKeys: @classmethod @override def daemon(cls) -> MoneroDaemonRpc: - return MoneroDaemon() # type: ignore + return MoneroDaemon() # pyright: ignore[reportReturnType] @classmethod @override @@ -255,7 +255,7 @@ def _get_seed_languages(self) -> list[str]: @classmethod @override def get_test_wallet(cls) -> MoneroWalletKeys: - return super().get_test_wallet() # type: ignore + return super().get_test_wallet() # pyright: ignore[reportReturnType] def _get_test_accounts(self, wallet: MoneroWallet, include_subaddresses: bool = False) -> list[MoneroAccount]: account_indices: list[int] = self._account_indices From b76b9ff0006a7229a2070d412b1c06839b741c25 Mon Sep 17 00:00:00 2001 From: everoddandeven Date: Sun, 29 Nov 2026 01:34:18 +0100 Subject: [PATCH 3/6] bindings: lint the types of the parameters of the stubs --- bin/lint_bindings.py | 38 +++++++++++++++++++++++++++++++------- 1 file changed, 31 insertions(+), 7 deletions(-) diff --git a/bin/lint_bindings.py b/bin/lint_bindings.py index 66b1f94f..8b612c4d 100755 --- a/bin/lint_bindings.py +++ b/bin/lint_bindings.py @@ -13,8 +13,9 @@ The stubs of the package, in src/, are written by hand: they give the docs and the types that the module can not. This also fails where they differ from the signatures of the module: a class or a member that only one of them has, other -names of parameters, or another return type. A type of the stubs can be None when the one of the module can not say it, -as the one of a shared pointer. +names or types of parameters, or another return type. A type of the stubs can be None when the one of the module can not +say it, as the one of a shared pointer, and a parameter can be the type that the binding converts: a sequence for a vector +and bytes for a string. pip install pybind11-stubgen bin/lint_bindings.py [module] # monero, which has to be installed or on the path @@ -66,6 +67,8 @@ class Member: def __init__(self) -> None: self.signatures: list[Signature] = [] self.types: set[str] = set() + # the types of each parameter, of all the overloads that have it + self.params: dict[str, set[str]] = {} def calls(self) -> set[tuple[str, ...]]: """The parameters that a call can give: the required ones and any number of the optional ones that follow them""" @@ -133,6 +136,9 @@ def read_classes(files: list[Path]) -> dict[str, dict[str, Member]]: args = child.args.posonlyargs + child.args.args if 'staticmethod' not in decorators: args = args[1:] + for a in args: + if a.annotation is not None: + member.params.setdefault(a.arg, set()).update(type_members(a.annotation)) names = tuple(a.arg for a in args) member.signatures.append((names, len(names) - len(child.args.defaults))) for name in [n for n in members if n.startswith('_')]: @@ -140,6 +146,21 @@ def read_classes(files: list[Path]) -> dict[str, dict[str, Member]]: return classes +def same_types(module_types: set[str], stub_types: set[str]) -> bool: + """Whether the types of the stubs are the ones of the module: "X | None" can be the "X" of the module, "None" alone is + another type""" + if 'None' not in module_types and len(stub_types) > 1: + stub_types = stub_types - {'None'} + return module_types == stub_types + + +def converted_type(stub_type: str, module_types: set[str]) -> str: + """The type of the module that takes an argument of a type of the stubs""" + if stub_type == 'bytes' and 'str' in module_types: + return 'str' + return re.sub(r'^Sequence\[', 'list[', stub_type) + + def stub_differences(module_files: list[Path], stub_files: list[Path]) -> list[str]: """Where the stubs written by hand differ from the ones that stubgen writes from the module""" module = read_classes(module_files) @@ -166,12 +187,15 @@ def stub_differences(module_files: list[Path], stub_files: list[Path]) -> list[s if module_calls != stub_calls: found.append('%s takes %s in the module and %s in the stubs' % (member, sorted(module_calls - stub_calls), sorted(stub_calls - module_calls))) - module_types, stub_types = bound[name].types, set(written[name].types) - # "X | None" can be the "X" of the module, "None" alone is another type - if 'None' not in module_types and len(stub_types) > 1: - stub_types.discard('None') - if module_types and stub_types and module_types != stub_types: + module_types, stub_types = bound[name].types, written[name].types + if module_types and stub_types and not same_types(module_types, stub_types): found.append('%s returns %s in the module and %s in the stubs' % (member, sorted(module_types), sorted(stub_types))) + for param in sorted(set(bound[name].params) & set(written[name].params)): + module_types = bound[name].params[param] + stub_types = {converted_type(t, module_types) for t in written[name].params[param]} + if not same_types(module_types, stub_types): + found.append('%s(%s) is %s in the module and %s in the stubs' % (member, param, sorted(module_types), + sorted(stub_types))) return found From 1bcbf817ac9cbca7376f363a78ed07fb68f1177c Mon Sep 17 00:00:00 2001 From: everoddandeven Date: Sun, 29 Nov 2026 01:46:28 +0100 Subject: [PATCH 4/6] ci: check the types of the python code with pyright --- .github/workflows/ci.yml | 1 + .github/workflows/types.yml | 47 ++++++++++ .vscode/extensions/status-bar-buttons/lint.js | 9 +- .vscode/tasks.json | 19 ++++ bin/check_types.py | 91 +++++++++++++++++++ bin/check_types.sh | 20 ++++ docs/mkdocs/docs/en/contributing/changes.md | 2 +- docs/mkdocs/docs/en/contributing/ci.md | 1 + docs/mkdocs/docs/en/contributing/commits.md | 1 + docs/mkdocs/docs/en/tests/vscode/checks.md | 3 + docs/mkdocs/docs/en/tests/vscode/index.md | 3 +- 11 files changed, 194 insertions(+), 3 deletions(-) create mode 100644 .github/workflows/types.yml create mode 100755 bin/check_types.py create mode 100755 bin/check_types.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ee090c5b..292d18f1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,6 +23,7 @@ on: - '.github/workflows/codacy.yml' - '.github/workflows/release.yml' - '.github/workflows/lint-workflows.yml' + - '.github/workflows/types.yml' - '.github/zizmor.yml' - '.github/dependabot.yml' diff --git a/.github/workflows/types.yml b/.github/workflows/types.yml new file mode 100644 index 00000000..fc2d9a8b --- /dev/null +++ b/.github/workflows/types.yml @@ -0,0 +1,47 @@ +name: Types + +# pyright on the Python code: the tests, the scripts and the stubs, in strict mode with the rules of .vscode/settings.json, as Pylance shows +# in VS Code. An error or a warning fails the run. ./bin/check_types.sh runs the same, with the same versions. +on: + push: + branches: [ main ] + pull_request: + branches: [ main ] + workflow_dispatch: + +# A new push to a pull request cancels the previous run. Other events get their own +# group so they are never cancelled or replaced. +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +permissions: + contents: read + +jobs: + pyright: + name: pyright + runs-on: ubuntu-24.04 + timeout-minutes: 10 + + steps: + - name: Checkout repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Setup Python + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: '3.12' + cache: pip + cache-dependency-path: | + tests/requirements.txt + docs/mkdocs/requirements.in + + # pyright is the one of the requirements of the docs, with griffe, which a script of the docs imports + - name: Install the packages that the code imports + run: pip install -r tests/requirements.txt -r docs/mkdocs/requirements.in + + - name: Check the types + run: python bin/check_types.py diff --git a/.vscode/extensions/status-bar-buttons/lint.js b/.vscode/extensions/status-bar-buttons/lint.js index 51f2f390..07f66b5f 100644 --- a/.vscode/extensions/status-bar-buttons/lint.js +++ b/.vscode/extensions/status-bar-buttons/lint.js @@ -31,6 +31,13 @@ const LINTS = [ description: 'actionlint and zizmor on .github', sources: ['actionlint', 'zizmor'], }, + { + task: 'lint: types', + name: 'Types', + icon: 'symbol-class', + description: 'pyright on the tests, the scripts and the stubs', + sources: ['check_types'], + }, { task: 'lint: examples', name: 'Examples', @@ -150,7 +157,7 @@ function createLintButton(context) { const busy = LINTS.find(lint => running.isRunning(lint.task)); show({ text: busy ? `$(sync~spin) Lint ${busy.name}` : '$(checklist) Lint', - tooltip: busy ? busy.description : 'check the links, the spelling, the workflows or the examples', + tooltip: busy ? busy.description : 'check the links, the spelling, the workflows, the types or the examples', // while one runs, as the other buttons: VS Code asks whether to stop it command: busy ? { title: 'Lint', command: 'workbench.action.tasks.runTask', arguments: [busy.task] } : COMMAND, waitsFor: busy ? undefined : running.blocker(LINTS.map(lint => lint.task)), diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 014b2247..2d0f076d 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -172,6 +172,25 @@ "pattern": { "regexp": "^(.+):(\\d+): (.+)$", "file": 1, "line": 2, "message": 3 } } }, + { + // pyright on the whole code, as .github/workflows/types.yml does: Pylance checks the same while it is edited + "label": "lint: types", + "type": "shell", + "command": "./bin/check_types.sh", + "problemMatcher": { + "owner": "check_types", + "source": "check_types", + "fileLocation": ["relative", "${workspaceFolder}"], + "pattern": { + "regexp": "^(.+\\.pyi?):(\\d+):(\\d+): (error|warning): (.+)$", + "file": 1, + "line": 2, + "column": 3, + "severity": 4, + "message": 5 + } + } + }, { // the code of the docs and of README.md against the stubs, the first step of "docs: build" "label": "lint: examples", diff --git a/bin/check_types.py b/bin/check_types.py new file mode 100755 index 00000000..84b7dd08 --- /dev/null +++ b/bin/check_types.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python3 +"""Checks the types of the Python code of the repository with pyright, as Pylance does in VS Code: the tests, the scripts and the +stubs, with the rules of .vscode/settings.json, which are declared only there. An error or a warning fails it. The module is not +needed, the stubs of src/monero say what it has. + + ./bin/check_types.sh # installs what it needs and runs this + python3 bin/check_types.py # with tests/requirements.txt and docs/mkdocs/requirements.in installed, as CI does + +CI runs it in .github/workflows/types.yml, with the pyright of docs/mkdocs/requirements.in. +""" + +from __future__ import annotations + +import json +import os +import re +import subprocess +import sys +import tempfile +from pathlib import Path +from typing import Any + +ROOT: Path = Path(__file__).resolve().parent.parent +SETTINGS: Path = ROOT / ".vscode" / "settings.json" +PREFIX: str = "python.analysis." + + +def read_settings() -> dict[str, Any]: + """The settings of VS Code, whose JSON has comments on their own lines and can have trailing commas.""" + text: str = re.sub(r"^\s*//.*$", "", SETTINGS.read_text(encoding="utf-8"), flags=re.MULTILINE) + return json.loads(re.sub(r",(\s*[\]}])", r"\1", text)) + + +def get_config(folder: str) -> dict[str, Any]: + """The configuration of pyright that matches the settings of Pylance, for a file in the given folder: it is written in a + temporary one, as one in the repository would replace the settings in VS Code.""" + settings: dict[str, Any] = read_settings() + + def path(value: str) -> str: + return str(ROOT / value.replace("${workspaceFolder}/", "")) + + # pyright ignores the absolute paths of "include" and "exclude" + def relative(value: str) -> str: + return os.path.relpath(path(value), os.path.realpath(folder)) + + config: dict[str, Any] = { + "include": [relative(".")], + "exclude": [relative(p) for p in settings[PREFIX + "exclude"]] + ["**/__pycache__", "**/node_modules"], + # and the root of the repository, which Pylance searches too: conftest.py imports tests.utils + "extraPaths": [path(p) for p in settings[PREFIX + "extraPaths"]] + [str(ROOT)], + "stubPath": path(settings[PREFIX + "stubPath"]), + "typeCheckingMode": settings[PREFIX + "typeCheckingMode"], + # the module is compiled, and it is not built to check the types + "reportMissingModuleSource": "none", + } + config.update(settings[PREFIX + "diagnosticSeverityOverrides"]) + return config + + +def main() -> int: + with tempfile.TemporaryDirectory() as folder: + (Path(folder) / "pyrightconfig.json").write_text(json.dumps(get_config(folder)), encoding="utf-8") + command: list[str] = [sys.executable, "-m", "pyright", "--pythonpath", sys.executable, "--outputjson"] + run = subprocess.run(command, cwd=folder, capture_output=True, text=True) + try: + report: dict[str, Any] = json.loads(run.stdout[run.stdout.index("{"):]) + except ValueError: + print(run.stdout + run.stderr, file=sys.stderr) + return 2 + + found: int = 0 + for diagnostic in report.get("generalDiagnostics", []): + if diagnostic["severity"] == "information": + continue + start: dict[str, int] = diagnostic["range"]["start"] + file: Path = Path(diagnostic["file"]) + name: Path = file.relative_to(ROOT) if file.is_relative_to(ROOT) else file + message: str = " ".join(line.strip() for line in diagnostic["message"].splitlines()) + rule: str = f" ({diagnostic['rule']})" if "rule" in diagnostic else "" + print(f"{name}:{start['line'] + 1}:{start['character'] + 1}: {diagnostic['severity']}: {message}{rule}") + found += 1 + files: int = report.get("summary", {}).get("filesAnalyzed", 0) + print(f"{files} files checked, {found} errors and warnings") + # pyright did not check anything: a wrong configuration, which would pass otherwise + if files == 0: + return 2 + return 1 if found else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/bin/check_types.sh b/bin/check_types.sh new file mode 100755 index 00000000..6ccb3328 --- /dev/null +++ b/bin/check_types.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Checks the types of the Python code as .github/workflows/types.yml does, with bin/check_types.py. The versions of +# tests/requirements.txt and of docs/mkdocs/requirements.in, which has pyright, are installed in .cache, again when they change. +# +# ./bin/check_types.sh +set -euo pipefail + +root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) +tests="$root/tests/requirements.txt" +docs="$root/docs/mkdocs/requirements.in" + +# in a folder of its own, not in a virtual environment: Debian and Ubuntu need python3-venv for one +packages="$root/.cache/types-$(cat "$tests" "$docs" | sha256sum | cut -c1-12)" +if [ ! -f "$packages/.installed" ]; then + rm -rf "$packages" + python3 -m pip install --quiet --disable-pip-version-check --target "$packages" -r "$tests" -r "$docs" + touch "$packages/.installed" +fi + +PYTHONPATH="$packages" exec python3 "$root/bin/check_types.py" diff --git a/docs/mkdocs/docs/en/contributing/changes.md b/docs/mkdocs/docs/en/contributing/changes.md index 3b328c5a..b806d9c2 100644 --- a/docs/mkdocs/docs/en/contributing/changes.md +++ b/docs/mkdocs/docs/en/contributing/changes.md @@ -38,7 +38,7 @@ A change of the library has its parts in more than one place: the C++ of the bin | --- | --- | --- | | `pytest -m unit` | the unit tests | always | | `pytest -m integration` | the integration tests, on the network of `tests/docker-compose.yml` | a change of what talks to a daemon or a wallet ([Running the Tests](../tests/running/index.md)) | -| the **Problems** of VS Code | the types of the tests and of the scripts, with Pylance in strict mode | a change of Python | +| `./bin/check_types.sh` | the types of the tests, the scripts and the stubs, with the pyright of CI in strict mode; Pylance shows the same in **Problems** of VS Code | a change of Python or of a stub | | `python3 bin/lint_bindings.py` | the bindings, against what stubgen makes of them | a change of `src/cpp` | | `./bin/docs.sh build` | the code of the docs and of `README.md` against the stubs, and the site, strict as in CI: a reference or a link that does not resolve fails it | a change of the docs, of a stub or of `README.md` | | `./bin/lint_workflows.sh` | the workflows, with the actionlint and zizmor of CI | a change of `.github` | diff --git a/docs/mkdocs/docs/en/contributing/ci.md b/docs/mkdocs/docs/en/contributing/ci.md index e1ccbd58..b49658d4 100644 --- a/docs/mkdocs/docs/en/contributing/ci.md +++ b/docs/mkdocs/docs/en/contributing/ci.md @@ -16,6 +16,7 @@ in its comments, what it does and why. | Build Debian Packages (`build-deb.yml`) | every push to `main`, the pull requests that change the packaging; called by Release | the deb packages, in a container of each release of Debian and Ubuntu, on amd64, arm64 and armhf | | Lint workflows (`lint-workflows.yml`) | the pushes and pull requests that change `.github` | actionlint and zizmor on the workflows | | Spelling (`spelling.yml`) | every push to `main` and every pull request | codespell on the files of git | +| Types (`types.yml`) | every push to `main` and every pull request | pyright in strict mode on the tests, the scripts and the stubs | | Links (`links.yml`) | every Monday, and the pull requests that change `lychee.toml` or `bin/check_links.sh` | `./bin/check_links.sh`: lychee on the links to the web of the docs, the stubs and the README; a page that moved or went away fails the run (`lychee.toml`) | | Codacy Coverage Reporter (`codacy.yml`) | the end of each run of CI | sends the coverage of the run to Codacy | | Release (`release.yml`) | a tag `v*` | the draft of a release, with its packages ([Releases](releases.md)) | diff --git a/docs/mkdocs/docs/en/contributing/commits.md b/docs/mkdocs/docs/en/contributing/commits.md index ae475580..af61fd13 100644 --- a/docs/mkdocs/docs/en/contributing/commits.md +++ b/docs/mkdocs/docs/en/contributing/commits.md @@ -46,6 +46,7 @@ evident from what it does. | Build Debian Packages (`build-deb.yml`) | `debian/`, the build of monero-cpp, `CMakeLists.txt`, `pyproject.toml` | builds the deb packages of noble, jammy and trixie, on amd64, arm64 and armhf | | Lint workflows (`lint-workflows.yml`) | `.github/` | actionlint and zizmor | | Spelling (`spelling.yml`) | anything | codespell on the files of git; the words that are not typos are in `.codespellrc` | +| Types (`types.yml`) | anything | pyright on the tests, the scripts and the stubs, with the rules of `.vscode/settings.json` | The checks are not required by GitHub: a maintainer merges a pull request once they pass. [Continuous Integration](ci.md) has all the workflows. diff --git a/docs/mkdocs/docs/en/tests/vscode/checks.md b/docs/mkdocs/docs/en/tests/vscode/checks.md index eef836d8..0e17c5ee 100644 --- a/docs/mkdocs/docs/en/tests/vscode/checks.md +++ b/docs/mkdocs/docs/en/tests/vscode/checks.md @@ -11,6 +11,9 @@ Pylance checks the tests in strict mode, with more rules than strict (`.vscode/s **Problems**, not only of the open ones. It reads the types of the module from its stubs in `src/monero`, and the helpers of the tests from `tests/`. An error in Problems is one that the change brings: the code of the repository has none. +CI checks the same with pyright (`types.yml`), which reads the rules from `.vscode/settings.json`. The task `lint: types`, or +`./bin/check_types.sh` in a terminal, runs it on your machine. + ## Coverage in the editor The task `tests: unit (coverage)` writes `coverage.xml`. With Coverage Gutters, **Coverage Gutters: Display Coverage** (or diff --git a/docs/mkdocs/docs/en/tests/vscode/index.md b/docs/mkdocs/docs/en/tests/vscode/index.md index 5fd42847..6db70d70 100644 --- a/docs/mkdocs/docs/en/tests/vscode/index.md +++ b/docs/mkdocs/docs/en/tests/vscode/index.md @@ -33,7 +33,7 @@ The buttons of the status bar are of an extension of the repository, `.vscode/ex | Build | runs `build: monero-python` | | Docker | **Setup Docker** when the network of the integration tests is down and **Stop Docker** when it is up, also when `docker compose` is run from a terminal; a warning icon, with their names in the tooltip, when some of its services do not run | | Docs | **Build Docs**, which runs `docs: serve`; a spinning icon while the site is built and **Stop Docs** once it is served | -| Lint | a menu that runs `lint: links`, `lint: spelling`, `lint: workflows` or `lint: examples` | +| Lint | a menu that runs `lint: links`, `lint: spelling`, `lint: workflows`, `lint: types` or `lint: examples` | While a task of `.vscode/tasks.json` runs, the buttons of the other tasks are gray and do nothing, so that two of them do not work at once; their tooltip says what they wait for. The server of the docs makes them wait only while it builds the site. A task run @@ -77,6 +77,7 @@ From **Terminal → Run Task**: | `lint: links` | lychee on the links to the web of the docs, the stubs and the README, with the version of CI | | `lint: examples` | the code of the docs and of the README against the stubs: the errors show in **Problems** | | `lint: spelling` | codespell on the files of git, with the version of CI: the typos show in **Problems** | +| `lint: types` | pyright on the tests, the scripts and the stubs, with the rules of the editor and the version of CI: the errors show in **Problems** | | `docs: serve` | the docs at `http://127.0.0.1:8000`, built again at every change | | `docs: build` | the docs, strict as in CI | From 7ee67b869f0c55acda375efb4ed32de0ca2ff16c Mon Sep 17 00:00:00 2001 From: everoddandeven Date: Sun, 29 Nov 2026 02:06:57 +0100 Subject: [PATCH 5/6] style: clean up imports and add spacing in type hint files --- .../monero_add_auxiliary_pow_result.pyi | 1 + src/monero/monero_block.pyi | 1 + src/monero/monero_check_reserve.pyi | 1 + src/monero/monero_check_tx.pyi | 1 + src/monero/monero_daemon_info.pyi | 1 + src/monero/monero_daemon_network_stats.pyi | 1 + src/monero/monero_daemon_sync_info.pyi | 1 + .../monero_daemon_update_download_result.pyi | 1 + src/monero/monero_destination.pyi | 1 + src/monero/monero_hard_fork_info.pyi | 1 + src/monero/monero_miner_data.pyi | 1 + src/monero/monero_multisig_sign_result.pyi | 1 - src/monero/monero_prune_result.pyi | 2 +- src/monero/monero_submit_tx_result.pyi | 2 ++ src/monero/monero_tx.pyi | 5 +++ src/monero/monero_tx_config.pyi | 9 +++++- src/monero/monero_tx_priority.pyi | 1 + src/monero/monero_tx_query.pyi | 31 +++++++++++-------- src/monero/monero_tx_set.pyi | 3 ++ src/monero/monero_tx_wallet.pyi | 13 ++++++++ src/monero/monero_utils.pyi | 8 ++--- src/monero/monero_wallet.pyi | 4 +-- 22 files changed, 68 insertions(+), 22 deletions(-) diff --git a/src/monero/monero_add_auxiliary_pow_result.pyi b/src/monero/monero_add_auxiliary_pow_result.pyi index df82d1ae..3151573d 100644 --- a/src/monero/monero_add_auxiliary_pow_result.pyi +++ b/src/monero/monero_add_auxiliary_pow_result.pyi @@ -1,4 +1,5 @@ import typing + from .monero_rpc_payment_info import MoneroRpcPaymentInfo from .monero_auxiliary_pow import MoneroAuxiliaryPow diff --git a/src/monero/monero_block.pyi b/src/monero/monero_block.pyi index 20d5085f..d2c2cbe7 100644 --- a/src/monero/monero_block.pyi +++ b/src/monero/monero_block.pyi @@ -3,6 +3,7 @@ import typing from .monero_block_header import MoneroBlockHeader from .monero_tx import MoneroTx + class MoneroBlock(MoneroBlockHeader): """Models a Monero block in the blockchain.""" diff --git a/src/monero/monero_check_reserve.pyi b/src/monero/monero_check_reserve.pyi index 6282f7e1..0d4e6aee 100644 --- a/src/monero/monero_check_reserve.pyi +++ b/src/monero/monero_check_reserve.pyi @@ -1,4 +1,5 @@ import typing + from .monero_check import MoneroCheck diff --git a/src/monero/monero_check_tx.pyi b/src/monero/monero_check_tx.pyi index 0dfcc35c..937a5f2f 100644 --- a/src/monero/monero_check_tx.pyi +++ b/src/monero/monero_check_tx.pyi @@ -1,4 +1,5 @@ import typing + from .monero_check import MoneroCheck diff --git a/src/monero/monero_daemon_info.pyi b/src/monero/monero_daemon_info.pyi index aba544c9..5c8c944b 100644 --- a/src/monero/monero_daemon_info.pyi +++ b/src/monero/monero_daemon_info.pyi @@ -1,4 +1,5 @@ import typing + from .monero_network_type import MoneroNetworkType from .monero_rpc_payment_info import MoneroRpcPaymentInfo diff --git a/src/monero/monero_daemon_network_stats.pyi b/src/monero/monero_daemon_network_stats.pyi index 5b17b99e..0b46f7de 100644 --- a/src/monero/monero_daemon_network_stats.pyi +++ b/src/monero/monero_daemon_network_stats.pyi @@ -1,4 +1,5 @@ import typing + from .monero_rpc_payment_info import MoneroRpcPaymentInfo diff --git a/src/monero/monero_daemon_sync_info.pyi b/src/monero/monero_daemon_sync_info.pyi index ba11935b..6a58f457 100644 --- a/src/monero/monero_daemon_sync_info.pyi +++ b/src/monero/monero_daemon_sync_info.pyi @@ -1,4 +1,5 @@ import typing + from .monero_peer import MoneroPeer from .monero_rpc_payment_info import MoneroRpcPaymentInfo from .monero_connection_span import MoneroConnectionSpan diff --git a/src/monero/monero_daemon_update_download_result.pyi b/src/monero/monero_daemon_update_download_result.pyi index 60b16198..6ed5b147 100644 --- a/src/monero/monero_daemon_update_download_result.pyi +++ b/src/monero/monero_daemon_update_download_result.pyi @@ -1,4 +1,5 @@ import typing + from .monero_daemon_update_check_result import MoneroDaemonUpdateCheckResult diff --git a/src/monero/monero_destination.pyi b/src/monero/monero_destination.pyi index 057c9f04..9f3ea429 100644 --- a/src/monero/monero_destination.pyi +++ b/src/monero/monero_destination.pyi @@ -1,4 +1,5 @@ import typing + from .serializable_struct import SerializableStruct diff --git a/src/monero/monero_hard_fork_info.pyi b/src/monero/monero_hard_fork_info.pyi index c537d9fc..b52627e2 100644 --- a/src/monero/monero_hard_fork_info.pyi +++ b/src/monero/monero_hard_fork_info.pyi @@ -1,4 +1,5 @@ import typing + from .monero_rpc_payment_info import MoneroRpcPaymentInfo diff --git a/src/monero/monero_miner_data.pyi b/src/monero/monero_miner_data.pyi index 2df36fea..f70ff238 100644 --- a/src/monero/monero_miner_data.pyi +++ b/src/monero/monero_miner_data.pyi @@ -1,4 +1,5 @@ import typing + from .monero_rpc_payment_info import MoneroRpcPaymentInfo from .monero_tx import MoneroTx diff --git a/src/monero/monero_multisig_sign_result.pyi b/src/monero/monero_multisig_sign_result.pyi index 86c04a0d..0868c318 100644 --- a/src/monero/monero_multisig_sign_result.pyi +++ b/src/monero/monero_multisig_sign_result.pyi @@ -6,7 +6,6 @@ class MoneroMultisigSignResult(SerializableStruct): signed_multisig_tx_hex: str | None """Multisig transaction in hex format.""" - tx_hashes: list[str] """List of transaction hash.""" diff --git a/src/monero/monero_prune_result.pyi b/src/monero/monero_prune_result.pyi index 4e8aa30a..549e0753 100644 --- a/src/monero/monero_prune_result.pyi +++ b/src/monero/monero_prune_result.pyi @@ -7,7 +7,7 @@ class MoneroPruneResult(SerializableStruct): is_pruned: bool | None """Indicates if blockchain is pruned.""" pruning_seed: int | None - """Blockheight at which pruning began.""" + """Block height at which pruning began.""" @staticmethod def deserialize(json: str) -> MoneroPruneResult: diff --git a/src/monero/monero_submit_tx_result.pyi b/src/monero/monero_submit_tx_result.pyi index 690cdae1..6f08c81b 100644 --- a/src/monero/monero_submit_tx_result.pyi +++ b/src/monero/monero_submit_tx_result.pyi @@ -1,6 +1,8 @@ import typing + from .monero_rpc_payment_info import MoneroRpcPaymentInfo + class MoneroSubmitTxResult(MoneroRpcPaymentInfo): """Models the result from submitting a tx to a daemon.""" diff --git a/src/monero/monero_tx.pyi b/src/monero/monero_tx.pyi index a27369c5..5a578406 100644 --- a/src/monero/monero_tx.pyi +++ b/src/monero/monero_tx.pyi @@ -86,6 +86,7 @@ class MoneroTx(SerializableStruct): """Transaction version.""" weight: int | None """The weight of this transaction in bytes.""" + @staticmethod def deserialize(json: str) -> MoneroTx: """ @@ -99,6 +100,7 @@ class MoneroTx(SerializableStruct): def __init__(self) -> None: """Initialize a new Monero transaction.""" ... + def copy(self) -> MoneroTx: """ Copy current tx. @@ -106,6 +108,7 @@ class MoneroTx(SerializableStruct): :returns MoneroTx: tx copy. """ ... + def get_height(self) -> int | None: """ Get the transaction height. @@ -113,6 +116,7 @@ class MoneroTx(SerializableStruct): :returns int | None: The height of the transaction, if known. """ ... + def merge(self, other: MoneroTx) -> None: """ Merge current tx with another one. @@ -120,6 +124,7 @@ class MoneroTx(SerializableStruct): :param MoneroTx other: other tx to merge with. """ ... + def __lt__(self, other: MoneroTx) -> bool: """ Compare this tx to another by height (see `TxHeightComparator`). diff --git a/src/monero/monero_tx_config.pyi b/src/monero/monero_tx_config.pyi index 703c3d83..777b16c3 100644 --- a/src/monero/monero_tx_config.pyi +++ b/src/monero/monero_tx_config.pyi @@ -7,6 +7,7 @@ from .monero_tx_priority import MoneroTxPriority class MoneroTxConfig(SerializableStruct): """Configures a transaction to send, sweep, or create a payment URI.""" + account_index: int | None """Account index to send funds from.""" address: str | None @@ -41,6 +42,7 @@ class MoneroTxConfig(SerializableStruct): """Subtract fee from outputs.""" sweep_each_subaddress: bool | None """Sweep each wallet subaddress.""" + @staticmethod def deserialize(config_json: str) -> MoneroTxConfig: """ @@ -50,10 +52,12 @@ class MoneroTxConfig(SerializableStruct): :returns MoneroTxConfig: deserialized tx config. """ ... + @typing.overload def __init__(self) -> None: """Initialize a new tx config.""" ... + @typing.overload def __init__(self, config: MoneroTxConfig) -> None: """ @@ -62,6 +66,7 @@ class MoneroTxConfig(SerializableStruct): :param MoneroTxConfig config: tx config to copy. """ ... + def copy(self) -> MoneroTxConfig: """ Copy current tx config. @@ -69,6 +74,7 @@ class MoneroTxConfig(SerializableStruct): :returns MoneroTxConfig: tx config copy. """ ... + def get_normalized_destinations(self) -> list[MoneroDestination]: """ Get all destinations set in current tx config. @@ -76,10 +82,11 @@ class MoneroTxConfig(SerializableStruct): :returns list[MoneroDestination]: normalized tx config destinations. """ ... + def set_address(self, address: str) -> None: """ Set the address of a single-destination configuration. :param str address: the address to set for the single destination. """ - ... \ No newline at end of file + ... diff --git a/src/monero/monero_tx_priority.pyi b/src/monero/monero_tx_priority.pyi index e24d7a46..60a0d289 100644 --- a/src/monero/monero_tx_priority.pyi +++ b/src/monero/monero_tx_priority.pyi @@ -3,6 +3,7 @@ from enum import IntEnum class MoneroTxPriority(IntEnum): """Enumerates Monero transaction priorities.""" + DEFAULT = 0 """`0` Default transaction priority.""" UNIMPORTANT = 1 diff --git a/src/monero/monero_tx_query.pyi b/src/monero/monero_tx_query.pyi index d9d81e08..785a5fe6 100644 --- a/src/monero/monero_tx_query.pyi +++ b/src/monero/monero_tx_query.pyi @@ -11,6 +11,7 @@ class MoneroTxQuery(MoneroTxWallet): All transactions are returned except those that do not meet the criteria defined in this query. """ + has_payment_id: bool | None """Get transactions that have a payment id.""" hashes: list[str] @@ -35,6 +36,20 @@ class MoneroTxQuery(MoneroTxWallet): """Get transactions with specific payment ids.""" transfer_query: MoneroTransferQuery | None """Query to apply on transaction wallet transfer.""" + + @staticmethod + def decontextualize(query: MoneroTxQuery) -> MoneroTxQuery: + """ + Remove query criteria which require looking up other transfers/outputs to fulfill the query. + + Clears `is_incoming`, `is_outgoing`, `transfer_query`, `input_query` and `output_query`. + Mutates `query` in place. + + :param MoneroTxQuery query: the query to decontextualize. + :returns MoneroTxQuery: a reference to `query`, for convenience. + """ + ... + @staticmethod def deserialize_from_block(tx_query_json: str) -> MoneroTxQuery: """ @@ -44,6 +59,7 @@ class MoneroTxQuery(MoneroTxWallet): :returns MoneroTxQuery: deserialized tx query. """ ... + @typing.override @staticmethod def deserialize(json: str) -> MoneroTxQuery: @@ -58,6 +74,7 @@ class MoneroTxQuery(MoneroTxWallet): def __init__(self) -> None: """Initialize a new Monero transaction query.""" ... + @typing.override def copy(self) -> MoneroTxQuery: """ @@ -66,6 +83,7 @@ class MoneroTxQuery(MoneroTxWallet): :returns MoneroTxQuery: tx query copy. """ ... + def meets_criteria(self, tx: MoneroTxWallet, query_children: bool = True) -> bool: """ Check if transaction wallet meets all criteria defined in this query. @@ -75,16 +93,3 @@ class MoneroTxQuery(MoneroTxWallet): :returns bool: `True` if `tx` meets all criteria defined in this query, `False` otherwise. """ ... - - @staticmethod - def decontextualize(query: MoneroTxQuery) -> MoneroTxQuery: - """ - Remove query criteria which require looking up other transfers/outputs to fulfill the query. - - Clears `is_incoming`, `is_outgoing`, `transfer_query`, `input_query` and `output_query`. - Mutates `query` in place. - - :param MoneroTxQuery query: the query to decontextualize. - :returns MoneroTxQuery: a reference to `query`, for convenience. - """ - ... diff --git a/src/monero/monero_tx_set.pyi b/src/monero/monero_tx_set.pyi index 2598b922..62988908 100644 --- a/src/monero/monero_tx_set.pyi +++ b/src/monero/monero_tx_set.pyi @@ -11,6 +11,7 @@ class MoneroTxSet(SerializableStruct): hex string which is needed in order to sign and submit the multisig transactions. """ + multisig_tx_hex: str | None """ Serialized multisig transaction data produced when a multisig wallet creates transactions; @@ -29,6 +30,7 @@ class MoneroTxSet(SerializableStruct): Serialized unsigned transaction data produced by a view-only wallet's `create_tx()` / `create_txs()`; transfer it to the offline spend wallet and call `MoneroWallet.sign_txs()`. """ + @staticmethod def deserialize(tx_set_json: str) -> MoneroTxSet: """ @@ -38,6 +40,7 @@ class MoneroTxSet(SerializableStruct): :returns MoneroTxSet: The deserialized transaction set. """ ... + def __init__(self) -> None: """Initialize a Monero transaction set.""" ... diff --git a/src/monero/monero_tx_wallet.pyi b/src/monero/monero_tx_wallet.pyi index 3d7f41d8..70eed72a 100644 --- a/src/monero/monero_tx_wallet.pyi +++ b/src/monero/monero_tx_wallet.pyi @@ -37,6 +37,7 @@ class MoneroTxWallet(MoneroTx): """The total output amount sum originated from this transaction.""" tx_set: MoneroTxSet | None """Set of transactions related to current tx.""" + @typing.override @staticmethod def deserialize(json: str) -> MoneroTxWallet: @@ -51,6 +52,7 @@ class MoneroTxWallet(MoneroTx): def __init__(self) -> None: """Initialize a new Monero tx wallet.""" ... + @typing.override def copy(self) -> MoneroTxWallet: """ @@ -59,6 +61,7 @@ class MoneroTxWallet(MoneroTx): :returns MoneroTxWallet: tx wallet copy. """ ... + def filter_inputs_wallet(self, query: MoneroOutputQuery) -> list[MoneroOutputWallet]: """ Filter this tx's inputs in place, keeping only those that meet the query. @@ -67,6 +70,7 @@ class MoneroTxWallet(MoneroTx): :returns list[MoneroOutputWallet]: inputs that meet all criteria defined in `query`. """ ... + def filter_outputs_wallet(self, query: MoneroOutputQuery) -> list[MoneroOutputWallet]: """ Get outputs filtered by query. @@ -75,6 +79,7 @@ class MoneroTxWallet(MoneroTx): :returns list[MoneroOutputWallet]: outputs that meets all criteria defined in `query`. """ ... + def filter_transfers(self, query: MoneroTransferQuery) -> list[MoneroTransfer]: """ Get transfers filtered by query. @@ -83,6 +88,7 @@ class MoneroTxWallet(MoneroTx): :returns list[MoneroTransfer]: transfers that meets all criteria defined in `query`. """ ... + @typing.overload def get_outputs_wallet(self) -> list[MoneroOutputWallet]: """ @@ -91,6 +97,7 @@ class MoneroTxWallet(MoneroTx): :returns list[MoneroOutputWallet]: wallet outputs defined in current tx. """ ... + @typing.overload def get_outputs_wallet(self, query: MoneroOutputQuery) -> list[MoneroOutputWallet]: """ @@ -108,6 +115,7 @@ class MoneroTxWallet(MoneroTx): :returns list[MoneroOutputWallet]: wallet inputs defined in current tx. """ ... + @typing.overload def get_inputs_wallet(self, query: MoneroOutputQuery) -> list[MoneroOutputWallet]: """ @@ -117,6 +125,7 @@ class MoneroTxWallet(MoneroTx): :returns list[MoneroOutputWallet]: wallet inputs filtered by query. """ ... + @typing.overload def get_transfers(self) -> list[MoneroTransfer]: """ @@ -125,6 +134,7 @@ class MoneroTxWallet(MoneroTx): :returns list[MoneroTransfer]: transfers from tx. """ ... + @typing.overload def get_transfers(self, query: MoneroTransferQuery) -> list[MoneroTransfer]: """ @@ -134,6 +144,7 @@ class MoneroTxWallet(MoneroTx): :returns list[MoneroTransfer]: wallet transfers filtered by query. """ ... + def get_incoming_amount(self) -> int: """ Get total amount received in current tx. @@ -141,6 +152,7 @@ class MoneroTxWallet(MoneroTx): :returns int: total amount received in current wallet tx. """ ... + def get_outgoing_amount(self) -> int: """ Get total amount spent in current tx. @@ -148,6 +160,7 @@ class MoneroTxWallet(MoneroTx): :returns int: total amount spent in current wallet tx. """ ... + def merge(self, tgt: MoneroTxWallet) -> None: # type: ignore[override] """ Merge current wallet tx with another one. diff --git a/src/monero/monero_utils.pyi b/src/monero/monero_utils.pyi index 63f71bb5..b9919b4d 100644 --- a/src/monero/monero_utils.pyi +++ b/src/monero/monero_utils.pyi @@ -1,6 +1,6 @@ import typing -from typing import Any +from abc import ABC from .monero_output_wallet import MoneroOutputWallet from .monero_block import MoneroBlock from .monero_transfer import MoneroTransfer @@ -11,7 +11,7 @@ from .monero_network_type import MoneroNetworkType from .monero_integrated_address import MoneroIntegratedAddress -class MoneroUtils: +class MoneroUtils(ABC): """Collection of Monero utilities.""" @staticmethod @@ -25,7 +25,7 @@ class MoneroUtils: ... @staticmethod - def binary_to_dict(bin: bytes) -> dict[Any, Any]: + def binary_to_dict(bin: bytes) -> dict[typing.Any, typing.Any]: """ Deserialize a dictionary from binary format. @@ -75,7 +75,7 @@ class MoneroUtils: ... @staticmethod - def dict_to_binary(dictionary: dict[Any, Any]) -> bytes: + def dict_to_binary(dictionary: dict[typing.Any, typing.Any]) -> bytes: """ Converts a dictionary into binary format. diff --git a/src/monero/monero_wallet.pyi b/src/monero/monero_wallet.pyi index 8f993a35..04ca510a 100644 --- a/src/monero/monero_wallet.pyi +++ b/src/monero/monero_wallet.pyi @@ -1,5 +1,6 @@ import typing +from abc import ABC from .monero_wallet_listener import MoneroWalletListener from .monero_check_reserve import MoneroCheckReserve from .monero_check_tx import MoneroCheckTx @@ -33,8 +34,7 @@ from .monero_sync_result import MoneroSyncResult from .monero_message_signature_result import MoneroMessageSignatureResult - -class MoneroWallet: +class MoneroWallet(ABC): """ Base wallet with default implementations. """ From 8703114f559a6cdb1bc4b176c26543069a0c4a61 Mon Sep 17 00:00:00 2001 From: everoddandeven Date: Sun, 29 Nov 2026 02:16:05 +0100 Subject: [PATCH 6/6] bindings: lint the constructors and the keyword arguments of the stubs --- bin/lint_bindings.py | 19 +++++++++++++------ src/monero/monero_daemon_rpc.pyi | 5 ----- src/monero/monero_generate_blocks_result.pyi | 4 ++++ src/monero/monero_rpc_payment_info.pyi | 4 ++++ 4 files changed, 21 insertions(+), 11 deletions(-) diff --git a/bin/lint_bindings.py b/bin/lint_bindings.py index 8b612c4d..a4a1a065 100755 --- a/bin/lint_bindings.py +++ b/bin/lint_bindings.py @@ -13,7 +13,7 @@ The stubs of the package, in src/, are written by hand: they give the docs and the types that the module can not. This also fails where they differ from the signatures of the module: a class or a member that only one of them has, other -names or types of parameters, or another return type. A type of the stubs can be None when the one of the module can not +names or types of parameters, also of the constructors, or another return type. A type of the stubs can be None when the one of the module can not say it, as the one of a shared pointer, and a parameter can be the type that the binding converts: a sequence for a vector and bytes for a string. @@ -69,6 +69,8 @@ def __init__(self) -> None: self.types: set[str] = set() # the types of each parameter, of all the overloads that have it self.params: dict[str, set[str]] = {} + # the parameters that a call can give only by name, of each overload that has some + self.keywords: set[tuple[str, ...]] = set() def calls(self) -> set[tuple[str, ...]]: """The parameters that a call can give: the required ones and any number of the optional ones that follow them""" @@ -127,21 +129,23 @@ def read_classes(files: list[Path]) -> dict[str, dict[str, Member]]: elif isinstance(child, ast.FunctionDef): name = child.name decorators = [ast.unparse(d).split('.')[-1] for d in child.decorator_list] - if name.startswith('_') or 'setter' in decorators: + if (name.startswith('_') and name != '__init__') or 'setter' in decorators: continue member = members.setdefault(name, Member()) - if child.returns is not None: + if child.returns is not None and name != '__init__': member.types |= type_members(child.returns) if 'property' not in decorators: args = child.args.posonlyargs + child.args.args if 'staticmethod' not in decorators: args = args[1:] - for a in args: + if child.args.kwonlyargs: + member.keywords.add(tuple(sorted(a.arg for a in child.args.kwonlyargs))) + for a in args + child.args.kwonlyargs: if a.annotation is not None: member.params.setdefault(a.arg, set()).update(type_members(a.annotation)) names = tuple(a.arg for a in args) member.signatures.append((names, len(names) - len(child.args.defaults))) - for name in [n for n in members if n.startswith('_')]: + for name in [n for n in members if n.startswith('_') and n != '__init__']: del members[name] return classes @@ -176,7 +180,7 @@ def stub_differences(module_files: list[Path], stub_files: list[Path]) -> list[s is_enum = 'value' in bound and 'value' not in written and '__int__' not in written and owner.endswith(('Type', 'Status', 'Priority')) for name in sorted(set(bound) | set(written)): member = '%s.%s' % (owner, name) - if (owner, name) in INSTANCE_ATTRIBUTES or (is_enum and name in ('name', 'value')): + if (owner, name) in INSTANCE_ATTRIBUTES or (is_enum and name in ('name', 'value', '__init__')): continue if name not in written: found.append('%s is not in the stubs' % member) @@ -187,6 +191,9 @@ def stub_differences(module_files: list[Path], stub_files: list[Path]) -> list[s if module_calls != stub_calls: found.append('%s takes %s in the module and %s in the stubs' % (member, sorted(module_calls - stub_calls), sorted(stub_calls - module_calls))) + if bound[name].keywords != written[name].keywords: + found.append('%s takes by name only %s in the module and %s in the stubs' % ( + member, sorted(bound[name].keywords - written[name].keywords), sorted(written[name].keywords - bound[name].keywords))) module_types, stub_types = bound[name].types, written[name].types if module_types and stub_types and not same_types(module_types, stub_types): found.append('%s returns %s in the module and %s in the stubs' % (member, sorted(module_types), sorted(stub_types))) diff --git a/src/monero/monero_daemon_rpc.pyi b/src/monero/monero_daemon_rpc.pyi index 4470729e..b15bd57f 100644 --- a/src/monero/monero_daemon_rpc.pyi +++ b/src/monero/monero_daemon_rpc.pyi @@ -10,11 +10,6 @@ class MoneroDaemonRpc(MoneroDaemon): .. _monerod-rpc: https://docs.getmonero.org/rpc-library/monerod-rpc/ """ - @typing.overload - def __init__(self) -> None: - """Initialize a Monero daemon RPC.""" - ... - @typing.overload def __init__(self, rpc: MoneroRpcConnection) -> None: """ diff --git a/src/monero/monero_generate_blocks_result.pyi b/src/monero/monero_generate_blocks_result.pyi index 7b424ba8..9a40c0e7 100644 --- a/src/monero/monero_generate_blocks_result.pyi +++ b/src/monero/monero_generate_blocks_result.pyi @@ -9,6 +9,10 @@ class MoneroGenerateBlocksResult(SerializableStruct): height: int | None """New chain height.""" + def __init__(self) -> None: + """Initialize a Monero generate blocks result.""" + ... + @staticmethod def deserialize(json: str) -> MoneroGenerateBlocksResult: """ diff --git a/src/monero/monero_rpc_payment_info.pyi b/src/monero/monero_rpc_payment_info.pyi index 1b331c8f..6cc964e8 100644 --- a/src/monero/monero_rpc_payment_info.pyi +++ b/src/monero/monero_rpc_payment_info.pyi @@ -10,6 +10,10 @@ class MoneroRpcPaymentInfo(SerializableStruct): top_block_hash: str | None """If payment for RPC is enabled, the hash of the highest block in the chain. Otherwise, `None`.""" + def __init__(self) -> None: + """Initialize a Monero RPC payment information.""" + ... + @staticmethod def deserialize(json: str) -> MoneroRpcPaymentInfo: """