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

1import logging 

2 

3from monero import ( 

4 MoneroWallet, 

5 MoneroDaemonRpc, MoneroRpcConnection, 

6 MoneroWalletRpc, MoneroWalletConfig 

7) 

8 

9from .string_utils import StringUtils 

10 

11logger: logging.Logger = logging.getLogger("DockerWalletRpcManager") 

12 

13 

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.""" 

17 

18 MAX_SLOTS: int = 2 

19 """Maximum docker wallet rpc slots.""" 

20 

21 #region Private Attributes 

22 

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.""" 

41 

42 #endregion 

43 

44 #region Public Properties 

45 

46 @property 

47 def used_slots(self) -> int: 

48 """Number of docker slots used. 

49 

50 :returns int: number of docker slots used. 

51 """ 

52 return len(self._wallets) 

53 

54 @property 

55 def free_slots(self) -> int: 

56 """Number of docker slots not used. 

57 

58 :returns int: number of docker slots not used. 

59 """ 

60 return self.MAX_SLOTS - self.used_slots 

61 

62 @property 

63 def no_slot_left(self) -> bool: 

64 """Indicates if no docker slot is left. 

65 

66 :returns bool: `True` if no docker slot is left, `False` otherwise. 

67 """ 

68 return self.free_slots == 0 

69 

70 @property 

71 def first_free_slot(self) -> int: 

72 """The first free docker slot index (-1 for none). 

73 

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 

82 

83 #endregion 

84 

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. 

95 

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 = '' 

112 

113 def set_connection_credentials(self, username: str, password: str) -> None: 

114 """Set wallet rpc global connection credentials. 

115 

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 

121 

122 def get_rpc_uri(self, slot: int) -> str: 

123 """Get wallet rpc uri associated to slot. 

124 

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}" 

132 

133 def setup_create_wallet_config(self, config: MoneroWalletConfig) -> MoneroWalletConfig: 

134 """Setup a `create` wallet configuration. 

135 

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 

140 

141 if config.path is None: 

142 # set random wallet path 

143 config.path = StringUtils.get_random_string() 

144 

145 if config.restore_height is None and not random: 

146 # set restore height 

147 config.restore_height = 0 

148 

149 return config 

150 

151 def setup_wallet_config(self, c: MoneroWalletConfig | None, create: bool, in_container: bool) -> MoneroWalletConfig: 

152 """Setup a wallet configuration. 

153 

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() 

161 

162 # assign defaults 

163 if config.password is None: 

164 config.password = self._wallet_password 

165 

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" 

170 

171 if create: 

172 return self.setup_create_wallet_config(config) 

173 

174 logger.debug(f"Setup docker wallet config: {config.serialize()}") 

175 

176 return config 

177 

178 def get_rpc_connection(self, slot: int) -> MoneroRpcConnection: 

179 """Get specific docker wallet rpc connection. 

180 

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) 

186 

187 def get_rpc_connections(self) -> list[MoneroRpcConnection]: 

188 """Get all docker wallet rpc connections. 

189 

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 

196 

197 def setup_wallet(self, c: MoneroWalletConfig | None, create: bool, in_container: bool) -> MoneroWalletRpc: 

198 """Setup a rpc wallet. 

199 

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") 

208 

209 # setup open wallet configuration 

210 config: MoneroWalletConfig = self.setup_wallet_config(c, create, in_container) 

211 

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 

215 

216 wallet: MoneroWalletRpc = MoneroWalletRpc(self.get_rpc_connection(slot)) 

217 

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) 

227 

228 # cache wallet 

229 self._wallets[slot] = wallet 

230 

231 return wallet 

232 

233 def create_wallet(self, c: MoneroWalletConfig | None, in_container: bool) -> MoneroWalletRpc: 

234 """Create a rpc wallet. 

235 

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) 

242 

243 def open_wallet(self, c: MoneroWalletConfig | None, in_container: bool) -> MoneroWalletRpc: 

244 """Open a rpc wallet. 

245 

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) 

252 

253 def is_docker_instance(self, wallet: MoneroWallet) -> bool: 

254 """Check if wallet is a managed docker instance. 

255 

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 

262 

263 return False 

264 

265 def free_slot(self, wallet: MoneroWallet, save: bool = False) -> None: 

266 """Free wallet rpc docker slot. 

267 

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) 

282 

283 del self._wallets[w_idx] 

284 break 

285 

286 assert found, "wallet is not rpc docker instance" 

287 

288 def clear(self, save: bool = False) -> None: 

289 """Free all docker wallet rpc resources. 

290 

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 

302 

303 logger.debug(f"Closed docker wallet rpc: {rpc_connection.uri if rpc_connection is not None else 'None'}") 

304 

305 self._wallets.clear()