Coverage for tests/utils/docker_wallet_rpc_manager.py: 93%
137 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 monero import (
4 MoneroWallet,
5 MoneroDaemonRpc, MoneroRpcConnection,
6 MoneroWalletRpc, MoneroWalletConfig
7)
9from .string_utils import StringUtils
11logger: logging.Logger = logging.getLogger("DockerWalletRpcManager")
14# TODO use some docker python package for managing instances dynamically
15class DockerWalletRpcManager:
16 """Manager for wallet rpc clients connected to monero-wallet-rpc docker instances."""
18 MAX_SLOTS: int = 2
19 """Maximum docker wallet rpc slots."""
21 #region Private Attributes
23 _domain: str
24 """Rpc wallet domain."""
25 _rpc_port_start: int
26 """Rpc wallet port start."""
27 _daemon: MoneroDaemonRpc
28 """Daemon rpc."""
29 _wallet_password: str
30 """Rpc wallet password."""
31 _wallets: dict[int, MoneroWalletRpc]
32 """Rpc wallets connected to docker instances."""
33 _rpc_user: str
34 """Rpc user used to authenticate with monero-wallet-rpc."""
35 _rpc_password: str
36 """Rpc password used to authenticate with monero-wallet-rpc."""
37 _sync_period_ms: int
38 """Sync period in milliseconds."""
39 _timeout_ms: int | None
40 """Connection timeout in milliseconds."""
42 #endregion
44 #region Public Properties
46 @property
47 def used_slots(self) -> int:
48 """Number of docker slots used.
50 :returns int: number of docker slots used.
51 """
52 return len(self._wallets)
54 @property
55 def free_slots(self) -> int:
56 """Number of docker slots not used.
58 :returns int: number of docker slots not used.
59 """
60 return self.MAX_SLOTS - self.used_slots
62 @property
63 def no_slot_left(self) -> bool:
64 """Indicates if no docker slot is left.
66 :returns bool: `True` if no docker slot is left, `False` otherwise.
67 """
68 return self.free_slots == 0
70 @property
71 def first_free_slot(self) -> int:
72 """The first free docker slot index (-1 for none).
74 :returns int: the first free docker slot index, or -1 if none is free.
75 """
76 slot_idxs: list[int] = list(self._wallets.keys())
77 slot_range: list[int] = list(range(self.MAX_SLOTS))
78 for slot_idx in slot_range:
79 if slot_idx not in slot_idxs:
80 return slot_idx
81 return -1
83 #endregion
85 def __init__(
86 self,
87 domain: str,
88 rpc_port_start: int,
89 daemon: MoneroDaemonRpc,
90 wallet_password: str,
91 sync_period_ms: int,
92 timeout_ms: int | None = None
93 ) -> None:
94 """Initialize a new docker wallet rpc manager.
96 :param str domain: RPC domain.
97 :param int rpc_port_start: RPC port start.
98 :param MoneroDaemonRpc daemon: daemon to use as wallet connection.
99 :param str wallet_password: password used by wallets.
100 :param int sync_period_ms: wallet sync period in milliseconds.
101 :param int timeout_ms: wallet connection timeout in milliseconds.
102 """
103 self._domain = domain
104 self._rpc_port_start = rpc_port_start
105 self._daemon = daemon
106 self._wallet_password = wallet_password
107 self._wallets = {}
108 self._sync_period_ms = sync_period_ms
109 self._timeout_ms = timeout_ms
110 self._rpc_user = ''
111 self._rpc_password = ''
113 def set_connection_credentials(self, username: str, password: str) -> None:
114 """Set wallet rpc global connection credentials.
116 :param str username: connection auth username.
117 :param str password: connection auth password.
118 """
119 self._rpc_user = username
120 self._rpc_password = password
122 def get_rpc_uri(self, slot: int) -> str:
123 """Get wallet rpc uri associated to slot.
125 :param int slot: docker slot index.
126 :returns str: docker rpc uri.
127 """
128 assert slot >= 0
129 assert slot < self.MAX_SLOTS
130 # first docker instance is reserved to test wallet
131 return f"{self._domain}:{self._rpc_port_start + slot + 1}"
133 def setup_create_wallet_config(self, config: MoneroWalletConfig) -> MoneroWalletConfig:
134 """Setup a `create` wallet configuration.
136 :param MoneroWalletConfig config: configuration to setup for wallet creation.
137 :returns MoneroWalletConfig: setup config.
138 """
139 random: bool = config.seed is None and config.primary_address is None
141 if config.path is None:
142 # set random wallet path
143 config.path = StringUtils.get_random_string()
145 if config.restore_height is None and not random:
146 # set restore height
147 config.restore_height = 0
149 return config
151 def setup_wallet_config(self, c: MoneroWalletConfig | None, create: bool, in_container: bool) -> MoneroWalletConfig:
152 """Setup a wallet configuration.
154 :param MoneroWalletConfig | None c: wallet configuration to setup (optional).
155 :param bool create: setup wallet creation configuration.
156 :param bool in_container: `True` if the daemon connection should target the containerized
157 daemon (`node_2`) instead of the default one.
158 :returns MoneroWalletConfig: setup configuration.
159 """
160 config: MoneroWalletConfig = c if c is not None else MoneroWalletConfig()
162 # assign defaults
163 if config.password is None:
164 config.password = self._wallet_password
166 if config.server is None:
167 config.server = MoneroRpcConnection(self._daemon.get_rpc_connection())
168 if in_container:
169 config.server.uri = "http://node_2:18081"
171 if create:
172 return self.setup_create_wallet_config(config)
174 logger.debug(f"Setup docker wallet config: {config.serialize()}")
176 return config
178 def get_rpc_connection(self, slot: int) -> MoneroRpcConnection:
179 """Get specific docker wallet rpc connection.
181 :param int slot: docker slot to use.
182 :returns MoneroRpcConnection: wallet rpc docker connection.
183 """
184 rpc_uri: str = self.get_rpc_uri(slot)
185 return MoneroRpcConnection(rpc_uri, self._rpc_user, self._rpc_password, timeout_ms=self._timeout_ms)
187 def get_rpc_connections(self) -> list[MoneroRpcConnection]:
188 """Get all docker wallet rpc connections.
190 :returns list[MoneroRpcConnection]: all wallet rpc docker connections.
191 """
192 connections: list[MoneroRpcConnection] = []
193 for i in range(self.MAX_SLOTS):
194 connections.append(self.get_rpc_connection(i))
195 return connections
197 def setup_wallet(self, c: MoneroWalletConfig | None, create: bool, in_container: bool) -> MoneroWalletRpc:
198 """Setup a rpc wallet.
200 :param MoneroWalletConfig | None c: wallet configuration.
201 :param bool create: create the wallet.
202 :param bool in_container: `True` if the daemon connection should target the containerized
203 daemon (`node_2`) instead of the default one.
204 :returns MoneroWalletRpc: wallet rpc client.
205 """
206 if self.no_slot_left:
207 raise Exception("Cannot open wallet: no rpc resources left")
209 # setup open wallet configuration
210 config: MoneroWalletConfig = self.setup_wallet_config(c, create, in_container)
212 # get first free slot and build wallet rpc uri
213 slot: int = self.first_free_slot
214 # create client connected to monero-wallet-rpc process
216 wallet: MoneroWalletRpc = MoneroWalletRpc(self.get_rpc_connection(slot))
218 # open wallet
219 wallet.stop_syncing()
220 if create:
221 wallet.create_wallet(config)
222 else:
223 wallet.open_wallet(config)
224 wallet.set_daemon_connection(wallet.get_daemon_connection(), True, None)
225 if wallet.is_connected_to_daemon():
226 wallet.start_syncing(self._sync_period_ms)
228 # cache wallet
229 self._wallets[slot] = wallet
231 return wallet
233 def create_wallet(self, c: MoneroWalletConfig | None, in_container: bool) -> MoneroWalletRpc:
234 """Create a rpc wallet.
236 :param MoneroWalletConfig | None c: wallet configuration.
237 :param bool in_container: `True` if the daemon connection should target the containerized
238 daemon (`node_2`) instead of the default one.
239 :returns MoneroWalletRpc: wallet rpc client.
240 """
241 return self.setup_wallet(c, True, in_container)
243 def open_wallet(self, c: MoneroWalletConfig | None, in_container: bool) -> MoneroWalletRpc:
244 """Open a rpc wallet.
246 :param MoneroWalletConfig | None c: wallet configuration.
247 :param bool in_container: `True` if the daemon connection should target the containerized
248 daemon (`node_2`) instead of the default one.
249 :returns MoneroWalletRpc: wallet rpc client.
250 """
251 return self.setup_wallet(c, False, in_container)
253 def is_docker_instance(self, wallet: MoneroWallet) -> bool:
254 """Check if wallet is a managed docker instance.
256 :param MoneroWallet wallet: wallet to check if it is a docker instance.
257 :returns bool: `True` if `wallet` is a managed docker instance, `False` otherwise.
258 """
259 for w in self._wallets.values():
260 if w == wallet:
261 return True
263 return False
265 def free_slot(self, wallet: MoneroWallet, save: bool = False) -> None:
266 """Free wallet rpc docker slot.
268 :param MoneroWallet wallet: wallet to free docker resource.
269 :param bool save: save the wallet before closing.
270 """
271 found: bool = False
272 for w_idx in self._wallets.keys():
273 w: MoneroWallet = self._wallets[w_idx]
274 if w == wallet:
275 found = True
276 try:
277 wallet.close(save)
278 except Exception as e:
279 e_msg: str = str(e)
280 if e_msg != "No wallet file":
281 logger.warning(e_msg)
283 del self._wallets[w_idx]
284 break
286 assert found, "wallet is not rpc docker instance"
288 def clear(self, save: bool = False) -> None:
289 """Free all docker wallet rpc resources.
291 :param bool save: save wallets (default `False`).
292 """
293 for wallet in self._wallets.values():
294 if not wallet.is_closed():
295 rpc_connection: MoneroRpcConnection | None = wallet.get_rpc_connection()
296 try:
297 wallet.close(save)
298 except Exception as e:
299 e_str: str = str(e)
300 if "No wallet file" != e_str:
301 raise
303 logger.debug(f"Closed docker wallet rpc: {rpc_connection.uri if rpc_connection is not None else 'None'}")
305 self._wallets.clear()