Coverage for tests/utils/wallet_tx_tracker.py: 81%

155 statements  

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

1import logging 

2 

3from time import sleep 

4from monero import ( 

5 MoneroDaemon, MoneroWallet, MoneroWalletRpc, MoneroTxQuery, MoneroSyncResult, 

6 MoneroTxWallet, MoneroMiningStatus 

7) 

8 

9from .block_generation import is_generation_fast 

10 

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

12 

13 

14class WalletTxTracker: 

15 """Tracks wallets which are in sync with the tx pool and therefore whose txs in the pool 

16 do not need to be waited on for up-to-date pool information e.g. to create txs. 

17 

18 This is only necessary because txs relayed outside wallets are not fully incorporated 

19 into the wallet state until confirmed. 

20 

21 TODO monero-project: sync txs relayed outside wallet so this class is unnecessary. 

22 """ 

23 

24 _daemon: MoneroDaemon 

25 """Daemon test instance.""" 

26 _sync_period_ms: int 

27 """Sync period in milliseconds.""" 

28 _mining_address: str 

29 """Mining address.""" 

30 _can_generate_blocks: bool | None = None 

31 """Indicates if the daemon generates blocks on request (regtest only), `None` until it is tried.""" 

32 

33 @property 

34 def sync_period(self) -> float: 

35 """Sync period in seconds. 

36 

37 :returns float: sync period in seconds. 

38 """ 

39 return self._sync_period_ms / 1000 

40 

41 def __init__(self, daemon: MoneroDaemon, sync_period_ms: int, mining_address: str) -> None: 

42 """Initialize a new WalletTxTracker. 

43 

44 :param MoneroDaemon daemon: Daemon test instance. 

45 :param int sync_period_ms: Sync period in ms. 

46 :param str mining_address: Address used for mining. 

47 """ 

48 self._daemon = daemon 

49 self._sync_period_ms = sync_period_ms 

50 self._mining_address = mining_address 

51 

52 def _sleep(self) -> None: 

53 """Sleep for one sync period.""" 

54 sleep(self.sync_period) 

55 

56 def _generate_block(self) -> bool: 

57 """Generate one block, to clear the pool, when the difficulty is low. The CPU miner is not used for it then: it makes blocks without 

58 stopping and the chain grows past 10000 outputs, where monero-project fails the txs it creates with "Transaction sanity check failed". 

59 

60 :returns bool: `True` if a block was generated, `False` if the daemon can not generate blocks (not regtest) or mining is faster. 

61 """ 

62 if self._can_generate_blocks is False: 

63 return False 

64 if not is_generation_fast(self._daemon): 

65 return False 

66 try: 

67 self._daemon.generate_blocks(self._mining_address, 1) 

68 self._can_generate_blocks = True 

69 except Exception as e: 

70 logger.debug(f"The daemon can not generate blocks: {e}") 

71 self._can_generate_blocks = False 

72 return self._can_generate_blocks 

73 

74 def _wait_for_txs_to_clear(self, clear_from_wallet: bool, wallets: list[MoneroWallet]) -> None: 

75 """Wait for wallet txs to clear pool. 

76 

77 :param bool clear_from_wallet: Clear txs from wallet. 

78 :param list[MoneroWallet] wallets: Wallets to clear. 

79 """ 

80 # loop until pending txs cleared 

81 is_first: bool = True 

82 mining_started: bool = False 

83 num_it: int = 0 

84 while True: 

85 num_it += 1 

86 msg: str = f"Clearing pending wallet transactions from {len(wallets)} wallets (it={num_it})..." 

87 if not clear_from_wallet: 

88 msg = f"Clearing pool pending wallet transactions (it={num_it})..." 

89 logger.debug(msg) 

90 

91 # get pending wallet tx hashes 

92 tx_hashes_wallet: set[str] = set() 

93 for i, wallet in enumerate(wallets): 

94 result: MoneroSyncResult = wallet.sync() 

95 assert result.num_blocks_fetched is not None 

96 if result.num_blocks_fetched > 0: 

97 logger.debug(f"Synced wallet {i + 1}, blocks fetched {result.num_blocks_fetched}") 

98 query: MoneroTxQuery = MoneroTxQuery() 

99 query.in_tx_pool = True 

100 pool_txs: list[MoneroTxWallet] = wallet.get_txs(query) 

101 for tx in pool_txs: 

102 assert tx.hash is not None 

103 if tx.is_relayed is not True: 

104 continue 

105 elif tx.is_failed: 

106 # flush tx if failed 

107 logger.debug(f"Found wallet failed tx {tx.hash}") 

108 self._daemon.flush_tx_pool(tx.hash) 

109 logger.debug(f"Flushed failed tx wallet {tx.hash}") 

110 else: 

111 tx_hashes_wallet.add(tx.hash) 

112 

113 # get pending txs to wait for 

114 tx_hashes_pool: set[str] = set() 

115 if clear_from_wallet: 

116 tx_hashes_pool = tx_hashes_pool.union(tx_hashes_wallet) 

117 else: 

118 for tx in self._daemon.get_tx_pool(): 

119 assert tx.hash is not None 

120 if tx.is_relayed is not True: 

121 continue 

122 elif tx.is_failed: 

123 # flush tx if failed 

124 logger.debug(f"Found failed pool tx {tx.hash}") 

125 self._daemon.flush_tx_pool(tx.hash) 

126 logger.debug(f"Flushed failed pool tx {tx.hash}") 

127 elif tx.hash in tx_hashes_wallet: 

128 tx_hashes_pool.add(tx.hash) 

129 

130 num_txs_in_pool: int = len(tx_hashes_pool) 

131 # break if no txs to wait for 

132 if num_txs_in_pool == 0: 

133 logger.debug("No more pool txs to wait for") 

134 if mining_started: 

135 # stop mining if started 

136 self._daemon.stop_mining() 

137 break 

138 

139 # log message on the first iteration 

140 if is_first: 

141 logger.info(f"Waiting for wallet txs to clear from the pool in order to fully sync and avoid double spend attempts: {tx_hashes_pool}") 

142 

143 # on regtest a block is generated on each iteration, and the wallets are synced in the next one 

144 if self._generate_block(): 

145 is_first = False 

146 continue 

147 

148 # start mining if first iteration 

149 if is_first: 

150 is_first = False 

151 mining_status: MoneroMiningStatus = self._daemon.get_mining_status() 

152 if mining_status.is_active is not True: 

153 try: 

154 self._daemon.start_mining(self._mining_address, 1, False, False) 

155 mining_started = True 

156 except Exception as e: 

157 logger.warning(f"An error occurred while starting mining: {e}") 

158 # no problem 

159 else: 

160 logger.warning("Mining already active") 

161 

162 # sleep for sync period 

163 logger.debug(f"Waiting for {num_txs_in_pool} tx(s) to confirm (it={num_it})...") 

164 self._sleep() 

165 

166 # stop mining if started mining 

167 try: 

168 self._daemon.stop_mining() 

169 except Exception as e: 

170 logger.debug(str(e)) 

171 

172 # sync wallets with the pool 

173 for i, wallet in enumerate(wallets): 

174 while wallet.get_height() < self._daemon.get_height(): 

175 result = wallet.sync() 

176 assert result.num_blocks_fetched is not None 

177 if result.num_blocks_fetched > 0: 

178 logger.debug(f"Synced wallet {i + 1} with the pool, fetched {result.num_blocks_fetched} blocks") 

179 

180 # The server of a wallet rpc has the same keys as the full wallet, which sends txs and flushes them from the pool. The server keeps 

181 # as pending what it saw in the pool, and 500 seconds after, when it is not there, it marks it failed and sets its inputs as 

182 # unspent, even when another tx spent them. The next tx would use them and the daemon would reject it as a double spend. The 

183 # daemon says which outputs are spent (the ones in the pool too): asking it here, right before the txs that follow, leaves no time 

184 # for the server to change them again 

185 for wallet in wallets: 

186 if isinstance(wallet, MoneroWalletRpc): 

187 wallet.rescan_spent() 

188 

189 msg: str = f"Cleared pending wallet transactions from {len(wallets)} wallets" 

190 if not clear_from_wallet: 

191 msg = "Cleared pool pending wallet transactions" 

192 logger.debug(msg) 

193 

194 def wait_for_txs_to_clear_pool(self, wallets: list[MoneroWallet] | MoneroWallet) -> None: 

195 """Wait for pending wallet transactions to clear the pool. 

196 

197 :param list[MoneroWallet] wallets: Wallets to wait for pending transactions. 

198 """ 

199 if isinstance(wallets, MoneroWallet): 

200 self._wait_for_txs_to_clear(False, [wallets]) 

201 else: 

202 self._wait_for_txs_to_clear(False, wallets) 

203 

204 def wait_for_txs_to_clear_wallets(self, wallets: list[MoneroWallet]) -> None: 

205 """Wait for pending wallet transactions to clear from the wallets. 

206 

207 :param list[MoneroWallet] wallets: Wallets to wait for pending transactions. 

208 """ 

209 self._wait_for_txs_to_clear(True, wallets) 

210 

211 def wait_for_unlocked_balance( 

212 self, wallet: MoneroWallet, 

213 account_index: int, subaddress_index: int | None = None, min_amount: int | None = None 

214 ) -> int: 

215 """Wait for wallet unlocked balance. 

216 

217 :param MoneroWallet wallet: Wallet to wait for unlocked balance. 

218 :param int account_index: Wallet account index. 

219 :param int | None subaddress_index: Wallet subaddress index. 

220 :param int | None min_amount: Minimum amount to wait for. 

221 :returns int: Unlocked balance. 

222 """ 

223 if min_amount is None: 

224 min_amount = 0 

225 

226 # check if wallet has balance 

227 err: Exception = Exception("Wallet does not have enough balance to wait for") 

228 if subaddress_index is not None and wallet.get_balance(account_index, subaddress_index) < min_amount: 

229 raise err 

230 elif subaddress_index is None and wallet.get_balance(account_index) < min_amount: 

231 raise err 

232 

233 # check if wallet has unlocked balance 

234 unlocked_balance: int 

235 if subaddress_index is not None: 

236 unlocked_balance = wallet.get_unlocked_balance(account_index, subaddress_index) 

237 else: 

238 unlocked_balance = wallet.get_unlocked_balance(account_index) 

239 

240 if unlocked_balance > min_amount: 

241 logger.debug(f"Wallet has enough unlocked balance {unlocked_balance}") 

242 return unlocked_balance 

243 

244 # start mining 

245 mining_started: bool = False 

246 if not self._daemon.get_mining_status().is_active: 

247 try: 

248 self._daemon.start_mining(self._mining_address, 1, False, False) 

249 mining_started = True 

250 except Exception as e: 

251 logger.warning(f"An error occurred while starting mining: {str(e)}") 

252 # no problem 

253 

254 # wait for unlocked balance // TODO: promote to MoneroWallet interface? 

255 if unlocked_balance < min_amount: 

256 logger.info(f"Waiting for minimum unlocked balance: {min_amount}") 

257 else: 

258 logger.info("Wallet has sufficient balance") 

259 

260 while unlocked_balance < min_amount: 

261 logger.debug(f"Wallet unlocked balance: {unlocked_balance}, min amount: {min_amount}") 

262 

263 if subaddress_index is not None: 

264 unlocked_balance = wallet.get_unlocked_balance(account_index, subaddress_index) 

265 else: 

266 unlocked_balance = wallet.get_unlocked_balance(account_index) 

267 

268 self._sleep() 

269 

270 # stop mining if started 

271 if mining_started: 

272 self._daemon.stop_mining() 

273 

274 return unlocked_balance