Coverage for tests/utils/daemon_utils.py: 85%

310 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 19:49 +0000

1import logging 

2 

3from abc import ABC 

4from monero import ( 

5 MoneroDaemon, MoneroPeer, MoneroDaemonInfo, MoneroDaemonSyncInfo, 

6 MoneroConnectionSpan, MoneroHardForkInfo, MoneroBlock, 

7 MoneroBan, MoneroMinerTxSum, MoneroTx, MoneroTxPoolStats, 

8 MoneroDaemonUpdateCheckResult, MoneroDaemonUpdateDownloadResult, 

9 MoneroNetworkType, MoneroSubmitTxResult, MoneroKeyImageSpentStatus, 

10 MoneroDaemonRpc, MoneroMinerData, MoneroDaemonNetworkStats 

11) 

12 

13from .gen_utils import GenUtils 

14 

15logger: logging.Logger = logging.getLogger("DaemonUtils") 

16 

17 

18class DaemonUtils(ABC): 

19 """Daemon test utilities.""" 

20 

21 @classmethod 

22 def is_regtest(cls, network_type_str: str | None) -> bool: 

23 """Check if network type string indicates `regtest` network. 

24 

25 :param str | None network_type_str: network type in string format. 

26 :returns bool: `True` if network type string indicates `regtest` network, `False` otherwise. 

27 """ 

28 if network_type_str is None: 

29 return False 

30 nettype: str = network_type_str.lower() 

31 return nettype == "regtest" or nettype == "reg" 

32 

33 @classmethod 

34 def parse_network_type(cls, nettype: str) -> MoneroNetworkType: 

35 """Parse network type string into enum. 

36 

37 :param str nettype: network type in string format. 

38 :returns MoneroNetworkType: parsed network type. 

39 """ 

40 net: str = nettype.lower() 

41 if net == "mainnet" or net == "main" or cls.is_regtest(net): 

42 return MoneroNetworkType.MAINNET 

43 elif net == "testnet" or net == "test": 

44 return MoneroNetworkType.TESTNET 

45 elif net == "stagenet" or net == "stage": 

46 return MoneroNetworkType.STAGENET 

47 

48 raise TypeError(f"Invalid network type provided: {str(nettype)}") 

49 

50 # region Test Utils 

51 

52 @classmethod 

53 def test_known_peer(cls, peer: MoneroPeer, from_connection: bool, debug: bool = True) -> None: 

54 """Test known daemon peer. 

55 

56 :param MoneroPeer peer: daemon peer to test. 

57 :param bool from_connection: indicates if `peer` is obtained from daemon connections. 

58 :param bool debug: log peer details before testing (default `True`). 

59 """ 

60 if debug: 

61 logger.debug(f"Testing known peer: {peer.serialize()}") 

62 # common peer validation 

63 assert peer.id is not None 

64 assert peer.host is not None 

65 assert peer.port is not None 

66 assert len(peer.id) > 0 

67 assert len(peer.host) > 0 

68 assert peer.port > 0 

69 assert peer.rpc_port is None or peer.rpc_port >= 0 

70 assert peer.is_online is not None 

71 assert peer.pruning_seed is None or peer.pruning_seed >= 0 

72 if peer.rpc_credits_per_hash is not None: 

73 GenUtils.test_unsigned_big_integer(peer.rpc_credits_per_hash) 

74 

75 if from_connection: 

76 # validate peer connection 

77 assert peer.last_seen_timestamp is None 

78 else: 

79 # validate known peer 

80 assert peer.last_seen_timestamp is not None 

81 assert peer.last_seen_timestamp >= 0, f"Last seen timestamp is invalid: {peer.last_seen_timestamp}" 

82 

83 @classmethod 

84 def test_peer(cls, peer: MoneroPeer) -> None: 

85 """Test daemon connection peer. 

86 

87 :param MoneroPeer peer: peer connection to test. 

88 """ 

89 logger.debug(f"Testing peer: {peer.serialize()}") 

90 cls.test_known_peer(peer, True, False) 

91 assert peer.hash is not None 

92 assert peer.avg_download is not None 

93 assert peer.avg_upload is not None 

94 assert peer.current_download is not None 

95 assert peer.current_upload is not None 

96 assert peer.height is not None 

97 assert peer.live_time is not None 

98 assert peer.num_receives is not None 

99 assert peer.receive_idle_time is not None 

100 assert peer.num_sends is not None 

101 assert peer.send_idle_time is not None 

102 assert peer.num_support_flags is not None 

103 

104 assert len(peer.hash) > 0 

105 assert peer.avg_download >= 0 

106 assert peer.avg_upload >= 0 

107 assert peer.current_download >= 0 

108 assert peer.current_upload >= 0 

109 assert peer.height >= 0 

110 assert peer.live_time >= 0 

111 assert peer.is_local_ip is not None 

112 assert peer.is_local_host is not None 

113 assert peer.num_receives >= 0 

114 assert peer.receive_idle_time >= 0 

115 assert peer.num_sends >= 0 

116 assert peer.send_idle_time >= 0 

117 assert peer.state is not None 

118 assert peer.num_support_flags >= 0 

119 assert peer.connection_type is not None 

120 

121 @classmethod 

122 def test_info(cls, info: MoneroDaemonInfo) -> None: 

123 """Test daemon information. 

124 

125 :param MoneroDaemonInfo info: daemon info to test. 

126 """ 

127 logger.debug(f"Testing daemon info: {info.serialize()}") 

128 assert info.version is not None 

129 assert info.num_alt_blocks is not None and info.num_alt_blocks >= 0 

130 assert info.block_size_limit is not None and info.block_size_limit > 0 

131 assert info.block_size_median is not None and info.block_size_median > 0 

132 assert info.bootstrap_daemon_address is None or len(info.bootstrap_daemon_address) > 0 

133 GenUtils.test_unsigned_big_integer(info.difficulty_low) 

134 GenUtils.test_unsigned_big_integer(info.difficulty_high) 

135 GenUtils.test_unsigned_big_integer(info.cumulative_difficulty_low) 

136 GenUtils.test_unsigned_big_integer(info.cumulative_difficulty_high) 

137 GenUtils.test_unsigned_big_integer(info.free_space) 

138 assert info.num_offline_peers is not None and info.num_offline_peers >= 0 

139 assert info.num_online_peers is not None and info.num_online_peers >= 0 

140 assert info.height is not None and info.height >= 0 

141 assert info.height_without_bootstrap is not None and info.height_without_bootstrap > 0 

142 assert info.num_incoming_connections is not None and info.num_incoming_connections >= 0 

143 assert info.num_outgoing_connections is not None and info.num_outgoing_connections >= 0 

144 assert info.network_type is not None 

145 assert info.is_offline is not None 

146 assert info.num_rpc_connections is not None and info.num_rpc_connections >= 0 

147 assert info.start_timestamp is not None and info.start_timestamp > 0 

148 assert info.adjusted_timestamp is not None and info.adjusted_timestamp > 0 

149 assert info.target is not None and info.target > 0 

150 assert info.target_height is not None and info.target_height >= 0 

151 assert info.num_txs is not None and info.num_txs >= 0 

152 assert info.num_txs_pool is not None and info.num_txs_pool >= 0 

153 assert info.was_bootstrap_ever_used is not None 

154 assert info.block_weight_limit is not None and info.block_weight_limit > 0 

155 assert info.block_weight_median is not None and info.block_weight_median > 0 

156 assert info.database_size is not None and info.database_size > 0 

157 assert info.update_available is not None 

158 # 0 credits 

159 GenUtils.test_unsigned_big_integer(info.credits, False) 

160 assert info.top_block_hash is not None 

161 assert len(info.top_block_hash) > 0 

162 assert info.is_busy_syncing is not None 

163 assert info.is_synchronized is not None 

164 assert info.is_regtest is not None 

165 

166 @classmethod 

167 def test_connection_span(cls, span: MoneroConnectionSpan) -> None: 

168 """Test daemon connection span. 

169 

170 :param MoneroConnectionSpan span: daemon connection span to test. 

171 """ 

172 logger.debug(f"Testing connection span: {span.serialize()}") 

173 raise NotImplementedError("DaemonUtils.test_connection_span(): not implemented") 

174 

175 @classmethod 

176 def test_sync_info(cls, sync_info: MoneroDaemonSyncInfo) -> None: 

177 """Test daemon synchronization info. 

178 

179 :param MoneroDaemonSyncInfo sync_info: daemon sync info to test. 

180 """ 

181 logger.debug(f"Testing daemon sync info: {sync_info.serialize()}") 

182 assert sync_info.height is not None and sync_info.height >= 0 

183 

184 # test peers 

185 assert len(sync_info.peers) > 0, "No peers found in daemon sync info to test." 

186 

187 for connection in sync_info.peers: 

188 cls.test_peer(connection) 

189 

190 # test connection spans 

191 for span in sync_info.spans: 

192 cls.test_connection_span(span) 

193 

194 assert sync_info.next_needed_pruning_seed is not None 

195 assert sync_info.next_needed_pruning_seed >= 0 

196 assert sync_info.overview is None 

197 # 0 credits 

198 GenUtils.test_unsigned_big_integer(sync_info.credits, False) 

199 assert sync_info.top_block_hash is None 

200 

201 @classmethod 

202 def test_hard_fork_info(cls, hard_fork_info: MoneroHardForkInfo) -> None: 

203 """Test daemon hard fork information. 

204 

205 :param MoneroHardForkInfo hard_fork_info: daemon hard fork information to test. 

206 """ 

207 logger.debug(f"Testing hard fork info: {hard_fork_info.serialize()}") 

208 assert hard_fork_info.earliest_height is not None 

209 assert hard_fork_info.is_enabled is not None 

210 assert hard_fork_info.state is not None 

211 assert hard_fork_info.threshold is not None 

212 assert hard_fork_info.version is not None 

213 assert hard_fork_info.num_votes is not None 

214 assert hard_fork_info.voting is not None 

215 assert hard_fork_info.window is not None 

216 # 0 credits 

217 GenUtils.test_unsigned_big_integer(hard_fork_info.credits, False) 

218 assert hard_fork_info.top_block_hash is None 

219 

220 @classmethod 

221 def test_ban(cls, ban: MoneroBan) -> None: 

222 """Test daemon ban. 

223 

224 :param MoneroBan ban: daemon ban to test. 

225 """ 

226 logger.debug(f"Testing ban: {ban.serialize()}") 

227 assert ban.host is not None 

228 assert ban.ip is not None 

229 assert ban.seconds is not None 

230 

231 @classmethod 

232 def test_miner_data(cls, data: MoneroMinerData) -> None: 

233 """Test daemon miner data. 

234 

235 :param MoneroMinerData data: miner data to test. 

236 """ 

237 logger.debug(f"Testing miner data: {data.serialize()}") 

238 assert data.major_version is not None and data.major_version > 0 

239 assert data.height is not None and data.height > 0 

240 assert data.prev_hash is not None and len(data.prev_hash) == 64 

241 assert data.seed_hash is not None and len(data.seed_hash) == 64 

242 # difficulty comes back as a hex string, e.g. "0x1f4" 

243 assert data.difficulty is not None and int(data.difficulty, 0) > 0 

244 assert data.median_weight is not None and data.median_weight >= 0 

245 assert data.already_generated_coins is not None and data.already_generated_coins > 0 

246 for tx in data.tx_pool_backlog: 

247 assert tx.hash is not None and len(tx.hash) == 64 

248 

249 @classmethod 

250 def test_network_stats(cls, stats: MoneroDaemonNetworkStats) -> None: 

251 """Test daemon network statistics. 

252 

253 :param MoneroDaemonNetworkStats stats: network statistics to test. 

254 """ 

255 logger.debug(f"Testing network stats: {stats.serialize()}") 

256 assert stats.start_time is not None and stats.start_time > 0 

257 assert stats.total_packets_in is not None and stats.total_packets_in >= 0 

258 assert stats.total_bytes_in is not None and stats.total_bytes_in >= 0 

259 assert stats.total_packets_out is not None and stats.total_packets_out >= 0 

260 assert stats.total_bytes_out is not None and stats.total_bytes_out >= 0 

261 

262 @classmethod 

263 def test_miner_tx_sum(cls, tx_sum: MoneroMinerTxSum) -> None: 

264 """Test miner tx sum result. 

265 

266 :param MoneroMinerTxSum tx_sum: miner tx sum to test. 

267 """ 

268 logger.debug(f"Testing tx sum: {tx_sum.serialize()}") 

269 GenUtils.test_unsigned_big_integer(tx_sum.emission_sum_low) 

270 GenUtils.test_unsigned_big_integer(tx_sum.emission_sum_high) 

271 GenUtils.test_unsigned_big_integer(tx_sum.fee_sum_low) 

272 GenUtils.test_unsigned_big_integer(tx_sum.fee_sum_high) 

273 

274 @classmethod 

275 def test_tx_pool_stats(cls, stats: MoneroTxPoolStats) -> None: 

276 """Test daemon tx pool statistics. 

277 

278 :param MoneroTxPoolStats stats: daemon tx pool statistics to test. 

279 """ 

280 logger.debug(f"Testing tx pool stats: {stats.serialize()}") 

281 assert stats is not None 

282 assert stats.num_txs is not None 

283 assert stats.num_txs >= 0 

284 if stats.num_txs > 0: 

285 # TODO test stats.histo 

286 

287 assert stats.bytes_max is not None and stats.bytes_max > 0 

288 assert stats.bytes_med is not None and stats.bytes_med > 0 

289 assert stats.bytes_min is not None and stats.bytes_min > 0 

290 assert stats.bytes_total is not None and stats.bytes_total > 0 

291 assert stats.oldest_timestamp is not None and stats.oldest_timestamp > 0 

292 assert stats.histo98pc is None or stats.histo98pc > 0 

293 assert stats.num10m is not None and stats.num10m >= 0 

294 assert stats.num_double_spends is not None and stats.num_double_spends >= 0 

295 assert stats.num_failing is not None and stats.num_failing >= 0 

296 assert stats.num_not_relayed is not None and stats.num_not_relayed >= 0 

297 

298 else: 

299 assert stats.bytes_max is None 

300 assert stats.bytes_med is None 

301 assert stats.bytes_min is None 

302 assert stats.bytes_total == 0 

303 assert stats.histo98pc is None 

304 assert stats.oldest_timestamp is None 

305 assert stats.num10m == 0 

306 assert stats.num_double_spends == 0 

307 assert stats.num_failing == 0 

308 assert stats.num_not_relayed == 0 

309 assert len(stats.histo.values()) == 0 

310 

311 @classmethod 

312 def test_update_check_result(cls, result: MoneroDaemonUpdateCheckResult, debug: bool = True) -> None: 

313 """Test daemon update check result. 

314 

315 :param MoneroDaemonUpdateCheckResult result: daemon update check result to test. 

316 :param bool debug: log the result before testing (default `True`). 

317 """ 

318 if debug: 

319 logger.debug(f"Testing update check result: {result.serialize()}") 

320 assert isinstance(result, MoneroDaemonUpdateCheckResult) 

321 assert result.is_update_available is not None 

322 if result.is_update_available: 

323 err_msg: str = "No auto uri is daemon online?" 

324 assert result.auto_uri is not None, err_msg 

325 assert len(result.auto_uri) > 0, err_msg 

326 

327 assert result.user_uri is not None 

328 assert len(result.user_uri) > 0 

329 

330 assert result.version is not None 

331 assert len(result.version) > 0 

332 

333 assert result.hash is not None 

334 assert len(result.hash) == 64 

335 

336 else: 

337 assert result.auto_uri is None 

338 assert result.user_uri is None 

339 assert result.version is None 

340 assert result.hash is None 

341 

342 @classmethod 

343 def test_update_download_result(cls, result: MoneroDaemonUpdateDownloadResult, path: str | None) -> None: 

344 """Test daemon update download result. 

345 

346 :param MoneroDaemonUpdateDownloadResult result: daemon update download result to test. 

347 :param str | None path: expected download path in result. 

348 """ 

349 logger.debug(f"Testing update download result: {result.serialize()}") 

350 cls.test_update_check_result(result, False) 

351 if result.is_update_available: 

352 if result.download_path is None: 

353 # TODO monero-project daemon returning empty status string on download update error 

354 logger.warning("TODO Result path is None") 

355 return 

356 #if path is not None: 

357 # assert path == result.download_path 

358 #else: 

359 # assert result.download_path is not None 

360 else: 

361 assert result.download_path is None 

362 

363 @classmethod 

364 def test_submit_tx_result_common(cls, result: MoneroSubmitTxResult) -> None: 

365 """Test common daemon submit tx result. 

366 

367 :param MoneroSubmitTxResult result: daemon submit tx result to test common structure. 

368 """ 

369 assert result.is_good is not None 

370 assert result.is_relayed is not None 

371 assert result.is_double_spend is not None 

372 assert result.is_fee_too_low is not None 

373 assert result.is_mixin_too_low is not None 

374 assert result.has_invalid_input is not None 

375 assert result.has_invalid_output is not None 

376 assert result.is_overspend is not None 

377 assert result.is_too_big is not None 

378 assert result.sanity_check_failed is not None 

379 assert result.reason is None or len(result.reason) > 0 

380 

381 @classmethod 

382 def test_submit_tx_result_good(cls, result: MoneroSubmitTxResult) -> None: 

383 """Test successful daemon submit tx result. 

384 

385 :param MoneroSubmitTxResult result: daemon submit tx result to test. 

386 """ 

387 logger.debug(f"Testing valid submit tx result: {result.serialize()}") 

388 cls.test_submit_tx_result_common(result) 

389 # test good tx submission 

390 assert result.is_double_spend is False, "tx submission is double spend." 

391 assert result.is_fee_too_low is False, "fee is too low." 

392 assert result.is_mixin_too_low is False, "mixin is too low." 

393 assert result.has_invalid_input is False, "tx has invalid input." 

394 assert result.has_invalid_output is False, "tx has invalid output." 

395 assert result.has_too_few_outputs is False, "tx has too few outputs." 

396 assert result.is_overspend is False, "tx is overspend." 

397 assert result.is_too_big is False, "tx is too big." 

398 assert result.sanity_check_failed is False, "tx sanity check failed." 

399 # 0 credits 

400 GenUtils.test_unsigned_big_integer(result.credits, False) 

401 assert result.top_block_hash is None 

402 assert result.is_tx_extra_too_big is False, "tx extra is too big." 

403 assert result.is_good is True 

404 assert result.is_nonzero_unlock_time is False, "tx has non-zero unlock time." 

405 

406 @classmethod 

407 def test_submit_tx_result_double_spend(cls, result: MoneroSubmitTxResult) -> None: 

408 """Test double spend daemon submit tx result. 

409 

410 :param MoneroSubmitTxResult result: daemon submit tx result to test. 

411 """ 

412 logger.debug(f"Testing double spend submit tx result: {result.serialize()}") 

413 cls.test_submit_tx_result_common(result) 

414 assert result.is_good is False 

415 assert result.is_double_spend is True 

416 assert result.is_fee_too_low is False 

417 assert result.is_mixin_too_low is False 

418 assert result.has_invalid_input is False 

419 assert result.has_invalid_output is False 

420 assert result.is_overspend is False 

421 assert result.is_too_big is False 

422 

423 @classmethod 

424 def test_spent_statuses(cls, daemon: MoneroDaemonRpc, key_images: list[str], expected_status: MoneroKeyImageSpentStatus) -> None: 

425 """Test key images spent statuses. 

426 

427 :param MoneroDaemonRpc daemon: daemon to get key image spent statuses from. 

428 :param list[str] key_images: list of key image hex to get spent status from daemon. 

429 :param MoneroKeyImageSpentStatus expected_status: expected key images spent status. 

430 """ 

431 # test image 

432 for key_image in key_images: 

433 assert daemon.get_key_image_spent_status(key_image) == expected_status 

434 

435 # test array of images 

436 statuses: list[MoneroKeyImageSpentStatus] = [] 

437 if len(key_images) > 0: 

438 statuses = daemon.get_key_image_spent_statuses(key_images) 

439 

440 assert len(key_images) == len(statuses) 

441 for status in statuses: 

442 assert status == expected_status 

443 

444 @classmethod 

445 def get_confirmed_txs(cls, daemon: MoneroDaemonRpc, num_txs: int) -> list[MoneroTx]: 

446 """ 

447 Get confirmed txs on blockchain. 

448 

449 :param MoneroDaemonRpc daemon: daemon to use to query blockchain. 

450 :param int num_txs: number of confirmed transactions to get from blockchain. 

451 :returns list[MoneroTx]: list of transactions confirmed on blockchain. 

452 """ 

453 txs: list[MoneroTx] = [] 

454 num_blocks_per_req: int = 50 

455 start_idx: int = daemon.get_height() - num_blocks_per_req - 1 

456 

457 while start_idx >= 0: 

458 blocks: list[MoneroBlock] = daemon.get_blocks_by_range(start_idx, start_idx + num_blocks_per_req) 

459 for block in blocks: 

460 for tx in block.txs: 

461 txs.append(tx) 

462 if len(txs) == num_txs: 

463 return txs 

464 

465 start_idx -= num_blocks_per_req 

466 

467 raise Exception(f"Could not get {num_txs} confirmed txs (found: {len(txs)})") 

468 

469 @classmethod 

470 def get_confirmed_tx_hashes(cls, daemon: MoneroDaemon) -> list[str]: 

471 """Get confirmed tx hashes from daemon from last 5 blocks. 

472 

473 :param MoneroDaemon daemon: daemon instance to get confirmed txs from. 

474 :returns list[str]: confirmed txs hashes. 

475 """ 

476 hashes: list[str] = [] 

477 height: int = daemon.get_height() 

478 while len(hashes) < 5 and height > 0: 

479 height -= 1 

480 block: MoneroBlock = daemon.get_block_by_height(height) 

481 for tx_hash in block.tx_hashes: 

482 hashes.append(tx_hash) 

483 return hashes 

484 

485 #endregion