Coverage for tests/utils/test_utils.py: 95%
434 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 19:49 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 19:49 +0000
1import logging
3from time import time
4from typing import Optional
5from abc import ABC
6from os import getenv, makedirs
7from configparser import ConfigParser
8from monero import (
9 MoneroNetworkType, MoneroWalletFull, MoneroRpcConnection,
10 MoneroWalletConfig, MoneroDaemonRpc, MoneroWalletRpc,
11 MoneroWallet, MoneroRpcError, MoneroWalletKeys,
12 MoneroUtils
13)
15from .wallet_sync_printer import WalletSyncPrinter
16from .wallet_tx_tracker import WalletTxTracker
17from .gen_utils import GenUtils
18from .daemon_utils import DaemonUtils
19from .docker_wallet_rpc_manager import DockerWalletRpcManager
21logger: logging.Logger = logging.getLogger("TestUtils")
24class TestUtils(ABC):
25 """Test utilities and constants."""
27 __test__ = False
28 _LOADED: bool = False
29 """Indicates if test configuration is loaded."""
31 CI: bool = getenv("GITHUB_ACTIONS", "").lower() == "true"
32 """indicates if tests are running in the CI of GitHub. It is set when the class is defined, since the tests use it in skipif."""
33 IN_CONTAINER: bool = True
34 """indicates if tests are running in docker container."""
35 MIN_BLOCK_HEIGHT: int = 0
36 """min blockchain height for tests."""
37 WALLET_PORT_OFFSETS: dict[MoneroWalletRpc, int] = {}
39 # objects cache
40 _WALLET_FULL: Optional[MoneroWalletFull] = None
41 """Default wallet full used for tests."""
42 _WALLET_FULL_OFFLINE: Optional[MoneroWalletFull] = None
43 """Disconnected wallet full for tests that don't need a daemon."""
44 _WALLET_KEYS: Optional[MoneroWalletKeys] = None
45 """Default wallet keys used for tests."""
46 _WALLET_RPC: Optional[MoneroWalletRpc] = None
47 """Default wallet rpc used for tests."""
48 _WALLET_MINING: Optional[MoneroWalletFull] = None
49 """Mining wallet used for funding test wallets."""
50 _DAEMON_RPC: Optional[MoneroDaemonRpc] = None
51 """Default daemon rpc used for tests."""
52 _MINING_DAEMON: Optional[MoneroDaemonRpc] = None
53 """Internal daemon used for mining."""
54 _WALLET_RPC_2: Optional[MoneroWalletRpc] = None
55 """Additional wallet rpc instance."""
57 DAEMON_RPC_URI: str = ""
58 """Monero daemon rpc uri."""
59 CONTAINER_DAEMON_RPC_URI: str = ""
60 """Monero daemon rpc endpoint configuration (change per your configuration)."""
61 DAEMON_RPC_USERNAME: str = ""
62 """Monero daemon rpc username."""
63 DAEMON_RPC_PASSWORD: str = ""
64 """Monero daemon rpc password."""
65 DAEMON_RPC_ZMQ_URI: str = ""
66 """Monero daemon rpc zmq uri."""
67 DAEMON_RPC_ZMQ_PUB_URI: str = ""
68 """Monero daemon rpc zmq pub uri."""
69 TEST_NON_RELAYS: bool = True
70 """Indicates if non-relays tests are enabled."""
71 TEST_RELAYS: bool = True
72 """Indicates if relays tests are enabled."""
73 LITE_MODE: bool = False
74 """Indicates if running tests in light mode."""
75 TEST_NOTIFICATIONS: bool = True
76 """Indicates if notifications tests are enabled."""
77 TEST_RESETS: bool = True
78 """Indicates if reset tests are enabled."""
80 WALLET_TX_TRACKER: WalletTxTracker
81 """Test wallet tx tracker."""
83 # monero wallet rpc configuration (change per your configuration)
84 WALLET_RPC_PORT_START: int = 18082
85 """test wallet executables will bind to consecutive ports after these."""
86 WALLET_RPC_ZMQ_ENABLED: bool = False
87 """Indicates if test wallet rpc zmq is enabled."""
88 WALLET_RPC_ZMQ_PORT_START: int = 58083
89 WALLET_RPC_ZMQ_BIND_PORT_START: int = 48083 # TODO: zmq bind port necessary?
90 WALLET_RPC_USERNAME: str = ""
91 """Test wallet rpc username."""
92 WALLET_RPC_PASSWORD: str = ""
93 """Test wallet rpc password."""
94 WALLET_RPC_ZMQ_DOMAIN: str = ""
95 """Test wallet rpc zmq domain."""
96 WALLET_RPC_DOMAIN: str = ""
97 """Test wallet rpc domain."""
98 WALLET_RPC_URI: str = ""
99 """Test wallet rpc uri."""
100 WALLET_RPC_ZMQ_URI: str = ""
101 """Test wallet rpc zmq uri."""
102 WALLET_RPC_ACCESS_CONTROL_ORIGINS: str = ""
103 """cors access from web browser."""
104 WALLET_FULL_TESTS_RUN: bool = False
105 """Indicates if full tests run."""
107 # test wallet config
108 WALLET_NAME: str = ""
109 """Test wallet name."""
110 WALLET_PASSWORD: str = ""
111 """Test wallet password."""
112 TEST_WALLETS_DIR: str = ""
113 """Directory containing wallets used in tests."""
114 WALLET_FULL_PATH: str = ""
115 """Test wallet full path."""
116 # test wallet constants
117 NETWORK_TYPE: MoneroNetworkType = MoneroNetworkType.MAINNET
118 """Test network type."""
119 REGTEST: bool = False
120 """Indicates if running on fakechain."""
121 LANGUAGE: str = ""
122 """Test wallet language."""
123 SEED: str = ""
124 """Test wallet seed."""
125 ADDRESS: str = ""
126 """Test wallet primary address."""
127 PRIVATE_VIEW_KEY: str = ""
128 """Test wallet private view key."""
129 PRIVATE_SPEND_KEY: str = ""
130 """Test wallet private spend key."""
131 PUBLIC_SPEND_KEY: str = ""
132 """Test wallet public spend key."""
133 PUBLIC_VIEW_KEY: str = ""
134 """Test wallet public view key."""
135 FIRST_RECEIVE_HEIGHT: int = 0
136 """NOTE: this value must be the height of the wallet's first tx for tests."""
137 SYNC_PERIOD_IN_MS: int = 5000
138 """period between wallet syncs in milliseconds."""
139 OFFLINE_SERVER_URI: str = "offline_server_uri"
140 """dummy server uri to remain offline because wallet2 connects to default if not given."""
141 AUTO_CONNECT_TIMEOUT_MS: int = 3000
142 """Default connection timeout in milliseconds."""
144 # mining wallet config
145 MINING_WALLET_NAME: str = ""
146 """Mining wallet name."""
147 MINING_WALLET_PASSWORD: str = ""
148 """Mining wallet password."""
149 MINING_SEED: str = ""
150 """Mining wallet seed."""
151 MINING_ADDRESS: str = ""
152 """Mining wallet primary address."""
153 MINING_PRIVATE_VIEW_KEY: str = ""
154 """Mining wallet private view key."""
155 MINING_PRIVATE_SPEND_KEY: str = ""
156 """Mining wallet private spend key."""
157 MINING_PUBLIC_SPEND_KEY: str = ""
158 """Mining wallet public spend key."""
159 MINING_PUBLIC_VIEW_KEY: str = ""
160 """Mining wallet public view key."""
161 MINING_WALLET_FULL_PATH: str = ""
162 """Mining wallet full path."""
164 RPC_WALLET_MANAGER: DockerWalletRpcManager
166 LOG_LEVEL: int = 4
167 """Monero core internal log level."""
168 LOG_CATEGORIES: str = "*:WARNING,net:FATAL,net.http:FATAL,net.ssl:FATAL,net.p2p:FATAL,net.cn:FATAL,daemon.rpc:FATAL,global:INFO,verify:FATAL,serialization:FATAL,daemon.rpc.payment:ERROR,stacktrace:INFO,logging:INFO,msgwriter:INFO"
169 """Monero core internal log categories (monero-project's own default)."""
170 DAEMON_LOG_LEVEL: int = 3
171 """Daemon rpc log level."""
172 DAEMON_POLL_PERIOD_IN_MS: int = 10000
173 """period between daemon polls for block notifications in milliseconds."""
175 @classmethod
176 def load_config(cls) -> None:
177 """Load tests configuration from `tests/config/config.ini`."""
178 if cls._LOADED:
179 return
181 parser: ConfigParser = ConfigParser()
182 parser.read('tests/config/config.ini')
184 # validate config
185 assert parser.has_section("general")
186 assert parser.has_section("daemon")
187 assert parser.has_section("wallet")
189 # parse general config
190 nettype_str: str = parser.get('general', 'network_type')
191 cls.TEST_NON_RELAYS = parser.getboolean('general', 'test_non_relays')
192 cls.TEST_RELAYS = parser.getboolean('general', 'test_relays')
193 cls.TEST_NOTIFICATIONS = parser.getboolean('general', 'test_notifications')
194 cls.LITE_MODE = parser.getboolean('general', 'lite_mode')
195 cls.TEST_RESETS = parser.getboolean('general', 'test_resets')
196 cls.AUTO_CONNECT_TIMEOUT_MS = parser.getint('general', 'auto_connect_timeout_ms')
197 cls.LOG_LEVEL = parser.getint('general', 'log_level', fallback=cls.LOG_LEVEL)
198 cls.LOG_CATEGORIES = parser.get('general', 'log_categories', fallback=cls.LOG_CATEGORIES)
199 MoneroUtils.set_log_categories(cls.LOG_CATEGORIES)
200 cls.NETWORK_TYPE = DaemonUtils.parse_network_type(nettype_str)
201 cls.REGTEST = DaemonUtils.is_regtest(nettype_str)
203 if cls.REGTEST:
204 cls.MIN_BLOCK_HEIGHT = 100 # minimum block height for regtest environment
206 # parse daemon config
207 cls.DAEMON_LOG_LEVEL = parser.getint('daemon', 'log_level', fallback=cls.DAEMON_LOG_LEVEL)
208 cls.DAEMON_POLL_PERIOD_IN_MS = parser.getint('daemon', 'poll_period_in_ms', fallback=cls.DAEMON_POLL_PERIOD_IN_MS)
209 cls.DAEMON_RPC_URI = parser.get('daemon', 'rpc_uri')
210 cls.CONTAINER_DAEMON_RPC_URI = cls.DAEMON_RPC_URI.replace("127.0.0.1", "node_2")
211 cls.DAEMON_RPC_USERNAME = parser.get('daemon', 'rpc_username')
212 cls.DAEMON_RPC_PASSWORD = parser.get('daemon', 'rpc_password')
213 cls.DAEMON_RPC_ZMQ_URI = parser.get('daemon', 'zmq_uri')
214 cls.DAEMON_RPC_ZMQ_PUB_URI = parser.get('daemon', 'zmq_pub_uri')
216 # parse wallet config
217 cls.WALLET_NAME = parser.get('wallet', 'name')
218 cls.WALLET_PASSWORD = parser.get('wallet', 'password')
219 cls.ADDRESS = parser.get('wallet', 'address')
220 cls.PRIVATE_VIEW_KEY = parser.get('wallet', 'private_view_key')
221 cls.PRIVATE_SPEND_KEY = parser.get('wallet', 'private_spend_key')
222 cls.PUBLIC_VIEW_KEY = parser.get('wallet', 'public_view_key')
223 cls.PUBLIC_SPEND_KEY = parser.get('wallet', 'public_spend_key')
224 cls.SEED = parser.get('wallet', 'seed')
225 cls.FIRST_RECEIVE_HEIGHT = parser.getint('wallet', 'first_receive_height')
226 cls.TEST_WALLETS_DIR = parser.get('wallet', 'dir')
227 cls.WALLET_FULL_PATH = cls.TEST_WALLETS_DIR + "/" + cls.WALLET_NAME
228 cls.LANGUAGE = parser.get('wallet', 'language')
229 cls.WALLET_RPC_DOMAIN = parser.get('wallet', 'rpc_domain')
230 cls.WALLET_RPC_PORT_START = parser.getint('wallet', 'rpc_port_start')
231 cls.WALLET_RPC_USERNAME = parser.get('wallet', 'rpc_username')
232 cls.WALLET_RPC_PASSWORD = parser.get('wallet', 'rpc_password')
233 cls.WALLET_RPC_ACCESS_CONTROL_ORIGINS = parser.get('wallet', 'rpc_access_control_origins')
234 cls.WALLET_RPC_ZMQ_ENABLED = parser.getboolean('wallet', 'rpc_zmq_enabled')
235 cls.WALLET_RPC_ZMQ_PORT_START = parser.getint('wallet', 'rpc_zmq_port_start')
236 cls.WALLET_RPC_ZMQ_BIND_PORT_START = parser.getint('wallet', 'rpc_zmq_bind_port_start')
237 cls.WALLET_RPC_ZMQ_DOMAIN = parser.get('wallet', 'rpc_zmq_domain')
238 cls.WALLET_RPC_URI = cls.WALLET_RPC_DOMAIN + ":" + str(cls.WALLET_RPC_PORT_START)
239 cls.WALLET_RPC_ZMQ_URI = "tcp:#" + cls.WALLET_RPC_ZMQ_DOMAIN + ":" + str(cls.WALLET_RPC_ZMQ_PORT_START)
240 cls.SYNC_PERIOD_IN_MS = parser.getint('wallet', 'sync_period_in_ms')
241 in_container: str = getenv("IN_CONTAINER", "true")
242 cls.IN_CONTAINER = in_container.lower() == "true" or in_container == "1"
244 # parse mining wallet config
245 cls.MINING_WALLET_NAME = parser.get('mining_wallet', 'name')
246 cls.MINING_WALLET_FULL_PATH = cls.TEST_WALLETS_DIR + "/" + cls.MINING_WALLET_NAME
247 cls.MINING_WALLET_PASSWORD = parser.get('mining_wallet', 'password')
248 cls.MINING_ADDRESS = parser.get('mining_wallet', 'address')
249 cls.MINING_PRIVATE_VIEW_KEY = parser.get('mining_wallet', 'private_view_key')
250 cls.MINING_PRIVATE_SPEND_KEY = parser.get('mining_wallet', 'private_spend_key')
251 cls.MINING_PUBLIC_VIEW_KEY = parser.get('mining_wallet', 'public_view_key')
252 cls.MINING_PUBLIC_SPEND_KEY = parser.get('mining_wallet', 'public_spend_key')
253 cls.MINING_SEED = parser.get('mining_wallet', 'seed')
254 cls.WALLET_TX_TRACKER = WalletTxTracker(cls.get_daemon_rpc(), cls.SYNC_PERIOD_IN_MS, cls.MINING_ADDRESS)
256 cls._LOADED = True
258 @classmethod
259 def load(cls) -> None:
260 """Load configuration and wallet rpc manager."""
261 if cls._LOADED:
262 return
264 cls.load_config()
265 cls.RPC_WALLET_MANAGER = DockerWalletRpcManager(
266 cls.WALLET_RPC_DOMAIN,
267 cls.WALLET_RPC_PORT_START,
268 cls.get_daemon_rpc(),
269 cls.WALLET_PASSWORD,
270 cls.SYNC_PERIOD_IN_MS
271 )
272 cls.RPC_WALLET_MANAGER.set_connection_credentials(cls.WALLET_RPC_USERNAME, cls.WALLET_RPC_PASSWORD)
273 logger.debug("TestUtils configuration initialized")
275 @classmethod
276 def configure_logging(cls) -> None:
277 """Configure internal Monero core logging. conftest.py calls it when the tests run, not when they are only collected."""
278 # next to the log of the tests, log_file of pytest.ini
279 makedirs("test_logs", exist_ok=True)
280 MoneroUtils.configure_logging(f"test_logs/monero_tests_cpp_{GenUtils.current_date_time_str()}.log", False)
281 MoneroUtils.set_log_level(cls.LOG_LEVEL)
283 @classmethod
284 def initialize_test_wallet_dir(cls) -> None:
285 """Initialize test wallets directory. conftest.py calls it when the tests run, not when they are only collected."""
286 GenUtils.create_dir_if_not_exists(cls.TEST_WALLETS_DIR)
288 @classmethod
289 def get_random_wallet_path(cls) -> str:
290 """Get random test wallet path.
292 :returns str: random test wallet path.
293 """
294 return f"{cls.TEST_WALLETS_DIR}/test_wallet_{int(time() * 1000)}"
296 @classmethod
297 def get_daemon_rpc(cls) -> MoneroDaemonRpc:
298 """Get test daemon rpc.
300 :returns MoneroDaemonRpc: test daemon rpc instance.
301 """
303 if cls._DAEMON_RPC is None:
304 cls._DAEMON_RPC = MoneroDaemonRpc(cls.DAEMON_RPC_URI, cls.DAEMON_RPC_USERNAME, cls.DAEMON_RPC_PASSWORD)
306 return cls._DAEMON_RPC
308 @classmethod
309 def get_mining_daemon_rpc_connection(cls) -> MoneroRpcConnection:
310 """Get the rpc connection of the daemon used for internal mining.
312 :returns MoneroRpcConnection: rpc connection to internal mining daemon.
313 """
314 return MoneroRpcConnection("http://127.0.0.1:18089", cls.DAEMON_RPC_USERNAME, cls.DAEMON_RPC_PASSWORD)
316 @classmethod
317 def get_mining_daemon(cls) -> MoneroDaemonRpc:
318 """Get daemon used for mining.
320 :returns MoneroDaemonRpc: internal mining daemon.
321 """
323 if cls._MINING_DAEMON is None:
324 cls._MINING_DAEMON = MoneroDaemonRpc(cls.get_mining_daemon_rpc_connection())
326 return cls._MINING_DAEMON
328 @classmethod
329 def get_daemon_rpc_connection(cls) -> MoneroRpcConnection:
330 """Get test daemon rpc connection.
332 :returns MoneroRpcConnection: new test daemon rpc connection instance.
333 """
334 return MoneroRpcConnection(cls.DAEMON_RPC_URI, cls.DAEMON_RPC_USERNAME, cls.DAEMON_RPC_PASSWORD)
336 @classmethod
337 def close_wallets(cls) -> None:
338 """Close the test wallets that were opened, saving the full and the rpc one. The tests of a wallet type
339 share the wallet for the whole session, and this is called at its end."""
340 for wallet, save in ((cls._WALLET_FULL, True), (cls._WALLET_RPC, True), (cls._WALLET_KEYS, False)):
341 if wallet is None:
342 continue
343 closed: bool = not cls.is_wallet_rpc_open(wallet) if isinstance(wallet, MoneroWalletRpc) else wallet.is_closed()
344 if closed:
345 continue
346 try:
347 wallet.close(save)
348 except Exception as e:
349 # an rpc wallet that a test already closed
350 if "No wallet file" != str(e):
351 raise
353 @classmethod
354 def get_wallet_keys_config(cls) -> MoneroWalletConfig:
355 """Get test wallet keys configuration.
357 :returns MoneroWalletConfig: new test wallet keys configuration.
358 """
359 config: MoneroWalletConfig = MoneroWalletConfig()
360 config.network_type = cls.NETWORK_TYPE
361 config.seed = cls.SEED
362 return config
364 @classmethod
365 def get_wallet_keys(cls) -> MoneroWalletKeys:
366 """Get keys-only test wallet.
368 :returns MoneroWalletKeys: keys-only test wallet.
369 """
370 if cls._WALLET_KEYS is None:
371 config: MoneroWalletConfig = cls.get_wallet_keys_config()
372 cls._WALLET_KEYS = MoneroWalletKeys.create_wallet_from_seed(config)
374 return cls._WALLET_KEYS
376 @classmethod
377 def get_wallet_full_config(cls, daemon_connection: MoneroRpcConnection) -> MoneroWalletConfig:
378 """Get test wallet full configuration.
380 :param MoneroRpcConnection daemon_connection: rpc daemon connection.
381 :returns MoneroWalletConfig: full wallet test configuration.
382 """
383 config: MoneroWalletConfig = MoneroWalletConfig()
384 config.path = cls.WALLET_FULL_PATH
385 config.password = cls.WALLET_PASSWORD
386 config.network_type = cls.NETWORK_TYPE
387 config.seed = cls.SEED
388 config.server = daemon_connection
389 config.restore_height = cls.FIRST_RECEIVE_HEIGHT
390 config.regtest = cls.REGTEST
392 return config
394 @classmethod
395 def get_wallet_full(cls) -> MoneroWalletFull:
396 """Get test wallet full.
398 :returns MoneroWalletFull: full test wallet.
399 """
401 if cls._WALLET_FULL is None or cls._WALLET_FULL.is_closed():
402 # create wallet from seed if it doesn't exist
403 if not MoneroWalletFull.wallet_exists(cls.WALLET_FULL_PATH):
404 # create wallet with connection
405 daemon_connection: MoneroRpcConnection = MoneroRpcConnection(
406 cls.DAEMON_RPC_URI, cls.DAEMON_RPC_USERNAME, cls.DAEMON_RPC_PASSWORD
407 )
408 config: MoneroWalletConfig = cls.get_wallet_full_config(daemon_connection)
409 logger.debug("Creating full wallet...")
410 cls._WALLET_FULL = MoneroWalletFull.create_wallet(config)
411 logger.debug(f"Created full wallet at path '{cls.WALLET_FULL_PATH}'")
412 assert cls.FIRST_RECEIVE_HEIGHT == cls._WALLET_FULL.get_restore_height()
413 # TODO implement __eq__ method
414 #assert daemon_connection == cls._WALLET_FULL.get_daemon_connection()
416 # otherwise open existing wallet and update daemon connection
417 else:
418 logger.debug("Opening full wallet...")
419 cls._WALLET_FULL = MoneroWalletFull.open_wallet(
420 cls.WALLET_FULL_PATH, cls.WALLET_PASSWORD, cls.NETWORK_TYPE, cls.REGTEST
421 )
422 logger.debug(f"Opened full wallet at path '{cls.WALLET_FULL_PATH}")
423 cls._WALLET_FULL.set_daemon_connection(cls.get_daemon_rpc_connection())
425 # sync and save wallet
426 if cls._WALLET_FULL.is_connected_to_daemon():
427 logger.debug("Wallet full is connected to daemon")
428 listener: WalletSyncPrinter = WalletSyncPrinter(0.25)
429 cls._WALLET_FULL.sync(listener)
430 logger.debug("Synced full wallet")
431 cls._WALLET_FULL.save()
432 # start background synchronizing with sync period
433 cls._WALLET_FULL.start_syncing(cls.SYNC_PERIOD_IN_MS)
434 logger.debug("Started full wallet background synchronizing")
435 else:
436 logger.critical("Wallet full is not connected to daemon!")
438 # ensure we're testing the right wallet
439 assert cls.SEED == cls._WALLET_FULL.get_seed()
440 assert cls.ADDRESS == cls._WALLET_FULL.get_primary_address()
441 return cls._WALLET_FULL
443 @classmethod
444 def get_wallet_full_offline(cls) -> MoneroWalletFull:
445 """Get a shared in-memory full wallet with no daemon connection.
447 :returns MoneroWalletFull: disconnected full test wallet.
448 """
449 if cls._WALLET_FULL_OFFLINE is None or cls._WALLET_FULL_OFFLINE.is_closed():
450 config: MoneroWalletConfig = MoneroWalletConfig()
451 config.path = ""
452 config.password = cls.WALLET_PASSWORD
453 config.network_type = cls.NETWORK_TYPE
454 cls._WALLET_FULL_OFFLINE = MoneroWalletFull.create_wallet(config)
455 return cls._WALLET_FULL_OFFLINE
457 @classmethod
458 def get_mining_wallet_config(cls) -> MoneroWalletConfig:
459 """Get mining wallet configuration.
461 :returns MoneroWalletConfig: mining wallet configuration.
462 """
463 connection: MoneroRpcConnection = MoneroRpcConnection(
464 cls.DAEMON_RPC_URI,
465 cls.DAEMON_RPC_USERNAME,
466 cls.DAEMON_RPC_PASSWORD
467 )
468 config: MoneroWalletConfig = cls.get_wallet_full_config(connection)
469 config.path = cls.MINING_WALLET_FULL_PATH
470 config.password = cls.MINING_WALLET_PASSWORD
471 config.seed = cls.MINING_SEED
472 config.restore_height = 0
473 return config
475 @classmethod
476 def get_mining_wallet(cls) -> MoneroWalletFull:
477 """Get mining wallet.
479 :returns MoneroWalletFull: mining wallet.
480 """
481 listener: WalletSyncPrinter = WalletSyncPrinter(0.25)
483 if cls._WALLET_MINING is not None and not cls._WALLET_MINING.is_closed():
484 cls._WALLET_MINING.sync(listener)
485 cls._WALLET_MINING.save()
486 return cls._WALLET_MINING
488 if not MoneroWalletFull.wallet_exists(cls.MINING_WALLET_FULL_PATH):
489 logger.debug("Creating mining wallet...")
490 wallet: MoneroWalletFull = MoneroWalletFull.create_wallet(cls.get_mining_wallet_config())
491 logger.debug("Mining wallet created")
492 else:
493 logger.debug("Opening mining wallet...")
494 wallet = MoneroWalletFull.open_wallet(cls.MINING_WALLET_FULL_PATH, cls.MINING_WALLET_PASSWORD, cls.NETWORK_TYPE, cls.REGTEST)
495 logger.debug("Loaded mining wallet")
496 wallet.set_daemon_connection(cls.get_daemon_rpc_connection())
498 assert wallet.is_connected_to_daemon(), "Mining wallet is not connected to daemon"
499 wallet.sync(listener)
500 wallet.save()
502 assert cls.MINING_SEED == wallet.get_seed()
503 assert cls.MINING_ADDRESS == wallet.get_primary_address()
504 cls._WALLET_MINING = wallet
505 return wallet
507 @classmethod
508 def get_wallet_rpc_connection(cls) -> MoneroRpcConnection:
509 """Get test wallet rpc connection.
511 :returns MoneroRpcConnection: test wallet rpc connection.
512 """
513 return MoneroRpcConnection(
514 cls.WALLET_RPC_URI, cls.WALLET_RPC_USERNAME, cls.WALLET_RPC_PASSWORD,
515 cls.WALLET_RPC_ZMQ_URI if cls.WALLET_RPC_ZMQ_ENABLED else ''
516 )
518 @classmethod
519 def is_wallet_rpc_open(cls, wallet: MoneroWalletRpc) -> bool:
520 """Indicates if the wallet rpc server has a wallet open, by asking it for the primary address.
522 MoneroWalletRpc.is_closed() is not used: it takes the error "No wallet file" for a closed wallet only with the code -8, and the
523 server answers it with -13 (WALLET_RPC_ERROR_CODE_NOT_OPEN), so it never says that a server has no wallet open.
525 TODO workaround for a bug of monero-cpp, fixed in its branch fix/wallet-rpc-is-closed and waiting for the pull request to be merged
526 and for the submodule to point at it. Then this is `not wallet.is_closed()`, and the strict xfail of
527 TestMoneroWalletRpcCreation.test_is_closed fails (it passes) to remind of it.
529 :param MoneroWalletRpc wallet: wallet rpc to ask.
530 :returns bool: `True` if the server has a wallet open, `False` if it has none.
531 """
532 try:
533 wallet.get_primary_address()
534 return True
535 except MoneroRpcError as e:
536 if "No wallet file" in str(e):
537 return False
538 raise
540 @classmethod
541 def get_wallet_rpc(cls) -> MoneroWalletRpc:
542 """Get rpc test wallet.
544 :returns MoneroWalletRpc: rpc test wallet.
545 """
547 if cls._WALLET_RPC is None:
549 # construct wallet rpc instance with daemon connection
550 rpc: MoneroRpcConnection = cls.get_wallet_rpc_connection()
551 cls._WALLET_RPC = MoneroWalletRpc(rpc)
553 # attempt to open test wallet. It is not opened again when the server has it open: the test classes share it, and opening an open
554 # wallet fails with -1, which would create it from the seed. That wallet has no outgoing destinations, accounts or subaddresses
555 if not cls.is_wallet_rpc_open(cls._WALLET_RPC):
556 try:
557 cls._WALLET_RPC.open_wallet(cls.WALLET_NAME, cls.WALLET_PASSWORD)
558 except MoneroRpcError as e:
559 # -1 returned when wallet does not exist or fails to open e.g. it's already open by another application
560 if e.code == -1:
561 # create wallet
562 config = MoneroWalletConfig()
563 config.path = cls.WALLET_NAME
564 config.password = cls.WALLET_PASSWORD
565 config.seed = cls.SEED
566 config.restore_height = cls.FIRST_RECEIVE_HEIGHT
567 cls._WALLET_RPC.create_wallet(config)
568 else:
569 raise
571 # ensure we're testing the right wallet
572 assert cls.SEED == cls._WALLET_RPC.get_seed()
573 assert cls.ADDRESS == cls._WALLET_RPC.get_primary_address()
575 # sync wallet and ask the daemon which of its outputs are spent. The full wallet has the same keys and sends txs that are not
576 # mined: the server keeps the ones that it saw in the pool as pending, and 500 seconds after, when they are not there, it marks
577 # them as failed and sets their inputs as unspent, even when a different tx spent them. Its balance and outputs are wrong then
578 cls._WALLET_RPC.sync()
579 cls._WALLET_RPC.rescan_spent()
580 cls._WALLET_RPC.save()
581 cls._WALLET_RPC.start_syncing(cls.SYNC_PERIOD_IN_MS)
583 # return cached wallet rpc
584 return cls._WALLET_RPC
586 @classmethod
587 def open_wallet_rpc(cls, c: Optional[MoneroWalletConfig]) -> MoneroWalletRpc:
588 """Open a rpc wallet.
590 :param MoneroWalletConfig | None c: rpc wallet configuration.
591 :returns MoneroWalletRpc: opened rpc wallet.
592 """
593 return cls.RPC_WALLET_MANAGER.open_wallet(c, cls.IN_CONTAINER)
595 @classmethod
596 def create_wallet_rpc(cls, c: Optional[MoneroWalletConfig]) -> MoneroWalletRpc:
597 """Create rpc wallet.
599 :param MoneroWalletConfig | None c: rpc wallet configuration.
600 :returns MoneroWalletRpc: created rpc wallet.
601 """
602 return cls.RPC_WALLET_MANAGER.create_wallet(c, cls.IN_CONTAINER)
604 @classmethod
605 def get_all_rpc_connections(cls) -> list[MoneroRpcConnection]:
606 """Get all daemon and wallets rpc connections used in tests (ordered by connection uri).
608 :returns list[MoneroDaemonRpc | MoneroWalletRpc]: rpc connections to a daemon or wallet rpc.
609 """
610 result: list[MoneroRpcConnection] = []
611 # ordered by connection uri
612 result.append(cls.get_daemon_rpc_connection())
613 result.append(cls.get_wallet_rpc_connection())
614 result.extend(cls.RPC_WALLET_MANAGER.get_rpc_connections())
615 result.append(cls.get_mining_daemon_rpc_connection())
616 return result
618 @classmethod
619 def free_wallet_rpc_resources(cls, save: bool = False) -> None:
620 """Free all docker wallet rpc resources.
622 :param bool save: save wallets (default `False`).
623 """
624 cls.RPC_WALLET_MANAGER.clear(save)
626 @classmethod
627 def free_wallet_rpc_resource(cls, wallet: MoneroWallet, save: bool = False) -> None:
628 """Free docker resource used by wallet.
630 :param MoneroWallet wallet: wallet to free docker resource.
631 :param bool save: save wallet before closing (default `False`).
632 """
633 if cls.RPC_WALLET_MANAGER.is_docker_instance(wallet):
634 cls.RPC_WALLET_MANAGER.free_slot(wallet, save)
636 @classmethod
637 def create_wallet_ground_truth(
638 cls,
639 network_type: MoneroNetworkType,
640 seed: str,
641 start_height: int | None,
642 restore_height: int | None
643 ) -> MoneroWalletFull:
644 """Create a full wallet to use in equality tests.
646 :param MoneroNetworkType network_type: wallet network type.
647 :param str seed: wallet seed.
648 :param int | None start_height: wallet sync start height.
649 :param int | None restore_height: wallet restore height.
650 :returns MoneroWalletFull: ground-truth full wallet.
651 """
653 # create ground truth wallet
654 daemon_connection: MoneroRpcConnection = MoneroRpcConnection(cls.DAEMON_RPC_URI, cls.DAEMON_RPC_USERNAME, cls.DAEMON_RPC_PASSWORD)
655 path: str = cls.TEST_WALLETS_DIR + "/gt_wallet_" + GenUtils.current_timestamp_str()
656 config: MoneroWalletConfig = MoneroWalletConfig()
657 config.path = path
658 config.password = cls.WALLET_PASSWORD
659 config.network_type = network_type
660 config.seed = seed
661 config.server = daemon_connection
662 config.restore_height = restore_height
663 config.regtest = cls.REGTEST
665 if start_height is None:
666 start_height = 0 if restore_height is None else restore_height
668 gt_wallet: MoneroWalletFull = MoneroWalletFull.create_wallet(config)
669 assert restore_height == gt_wallet.get_restore_height()
670 gt_wallet.sync(start_height, WalletSyncPrinter(0.25))
671 gt_wallet.start_syncing(cls.SYNC_PERIOD_IN_MS)
673 # close the full wallet when the runtime is shutting down to release resources
675 return gt_wallet
677 @classmethod
678 def clear_wallet_full_txs_pool(cls) -> None:
679 """Clear full wallet txs pool and save."""
680 wallet_full: MoneroWalletFull = cls.get_wallet_full()
681 cls.WALLET_TX_TRACKER.wait_for_txs_to_clear_pool(wallet_full)
682 wallet_full.close(True)
685# load configuration
686TestUtils.load()