Coverage for tests/utils/single_tx_sender.py: 97%

184 statements  

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

1import logging 

2 

3import pytest 

4 

5from typing import Optional 

6from monero import ( 

7 MoneroWallet, MoneroTxConfig, MoneroAccount, 

8 MoneroSubaddress, MoneroDaemonRpc, MoneroDestination, 

9 MoneroTxWallet, MoneroTxQuery 

10) 

11 

12from .context import TxContext 

13from .assert_utils import AssertUtils 

14from .wallet_tx_tracker import WalletTxTracker as TxTracker 

15from .test_utils import TestUtils 

16from .tx_wallet_utils import TxWalletUtils 

17from .wallet_txs_utils import WalletTxsUtils 

18from .transfer_utils import TransferUtils 

19 

20logger: logging.Logger = logging.getLogger("SingleTxSender") 

21 

22 

23class SingleTxSender: 

24 """Sends funds from the first unlocked account to primary account address.""" 

25 

26 SEND_DIVISOR: int = 10 

27 """Transaction amount send divisor.""" 

28 

29 _config: MoneroTxConfig 

30 """Transaction configuration.""" 

31 _wallet: MoneroWallet 

32 """Wallet reference.""" 

33 _daemon: MoneroDaemonRpc 

34 """Daemon reference.""" 

35 

36 _from_account: Optional[MoneroAccount] = None 

37 """Account to use to send funds.""" 

38 _from_subaddress: Optional[MoneroSubaddress] = None 

39 """Subaddress to use to send funds.""" 

40 

41 @property 

42 def tracker(self) -> TxTracker: 

43 """Wallet transaction tracker. 

44 

45 :returns TxTracker: the wallet transaction tracker. 

46 """ 

47 return TestUtils.WALLET_TX_TRACKER 

48 

49 @property 

50 def balance_before(self) -> int: 

51 """Wallet balance before sending. 

52 

53 :returns int: the sending subaddress' balance before sending, or 0 if not yet selected. 

54 """ 

55 balance: int | None = self._from_subaddress.balance if self._from_subaddress is not None else 0 

56 return balance if balance is not None else 0 

57 

58 @property 

59 def unlocked_balance_before(self) -> int: 

60 """Wallet unlocked balance before sending. 

61 

62 :returns int: the sending subaddress' unlocked balance before sending, or 0 if not yet 

63 selected. 

64 """ 

65 balance: int | None = self._from_subaddress.unlocked_balance if self._from_subaddress is not None else 0 

66 return balance if balance is not None else 0 

67 

68 @property 

69 def send_amount(self) -> int: 

70 """Amount to send. 

71 

72 :returns int: the amount to send, derived from the unlocked balance before sending. 

73 """ 

74 b: int = self.unlocked_balance_before 

75 return int((b - TxWalletUtils.MAX_FEE) / self.SEND_DIVISOR) 

76 

77 @property 

78 def address(self) -> str: 

79 """Primary wallet address. 

80 

81 :returns str: the wallet's primary address. 

82 """ 

83 return self._wallet.get_primary_address() 

84 

85 def __init__(self, wallet: MoneroWallet, config: Optional[MoneroTxConfig]) -> None: 

86 """Initialize a new single transaction sender. 

87 

88 :param MoneroWallet wallet: wallet reference. 

89 :param MoneroTxConfig | None config: transaction configuration. 

90 """ 

91 self._wallet = wallet 

92 self._daemon = TestUtils.get_daemon_rpc() 

93 self._config = config if config is not None else MoneroTxConfig() 

94 

95 #region Private Methods 

96 

97 def _build_tx_config(self) -> MoneroTxConfig: 

98 """Build transaction configuration. 

99 

100 :returns MoneroTxConfig: transaction configuration. 

101 """ 

102 assert self._from_account is not None 

103 assert self._from_account.index is not None 

104 assert self._from_subaddress is not None 

105 assert self._from_subaddress.index is not None 

106 self._config.destinations.append(MoneroDestination(self.address, self.send_amount)) 

107 self._config.account_index = self._from_account.index 

108 self._config.subaddress_indices.append(self._from_subaddress.index) 

109 return self._config 

110 

111 def _get_locked_txs(self) -> list[MoneroTxWallet]: 

112 """Returns locked txs. 

113 

114 :returns list[MoneroTxWallet]: locked txs. 

115 """ 

116 # query locked txs 

117 query: MoneroTxQuery = MoneroTxQuery() 

118 query.is_locked = True 

119 locked_txs: list[MoneroTxWallet] = WalletTxsUtils.get_and_test_txs(self._wallet, query, None, True, TestUtils.REGTEST) 

120 

121 for locked_tx in locked_txs: 

122 assert locked_tx.is_locked, "Expected locked tx" 

123 

124 return locked_txs 

125 

126 def _check_balance(self) -> None: 

127 """Asserts that wallet has sufficient balance.""" 

128 # wait for wallet to clear unconfirmed txs 

129 self.tracker.wait_for_txs_to_clear_pool([self._wallet]) 

130 sufficient_balance: bool = False 

131 accounts: list[MoneroAccount] = self._wallet.get_accounts(True) 

132 # iterate over all wallet addresses 

133 for account in accounts: 

134 for i, subaddress in enumerate(account.subaddresses): 

135 if i == 0: 

136 continue 

137 assert subaddress.balance is not None 

138 assert subaddress.unlocked_balance is not None 

139 if subaddress.balance > TxWalletUtils.MAX_FEE: 

140 sufficient_balance = True 

141 if subaddress.unlocked_balance > TxWalletUtils.MAX_FEE: 

142 self._from_account = account 

143 self._from_subaddress = subaddress 

144 break 

145 if self._from_account is not None: 

146 break 

147 # check for sufficient balance 

148 assert sufficient_balance, "No non-primary subaddress found with sufficient balance" 

149 assert self._from_subaddress is not None, "Wallet is waiting on unlocked funds" 

150 logger.debug(f"Selected subaddress ({self._from_subaddress.account_index},{self._from_subaddress.index}), balance: {self._from_subaddress.balance}") 

151 

152 def _check_balance_decreased(self) -> None: 

153 """Checks that wallet balance decreased.""" 

154 # TODO test that other balances did not decrease 

155 assert self._from_account is not None 

156 assert self._from_subaddress is not None 

157 assert self._from_account.index is not None 

158 assert self._from_subaddress.index is not None 

159 subaddress: MoneroSubaddress = self._wallet.get_subaddress(self._from_account.index, self._from_subaddress.index) 

160 assert subaddress.balance is not None 

161 assert subaddress.balance < self.balance_before, f"Expected {subaddress.balance} < {self.balance_before}" 

162 assert subaddress.unlocked_balance is not None 

163 assert subaddress.unlocked_balance < self.unlocked_balance_before, f"Expected {subaddress.unlocked_balance} < {self.unlocked_balance_before}" 

164 logger.debug(f"Balance decreased from {self.balance_before} to {subaddress.balance}") 

165 

166 def _send_to_invalid(self, config: MoneroTxConfig) -> None: 

167 """Send to invalid address. 

168 

169 :param MoneroTxConfig config: tx configuration. 

170 """ 

171 max_retries: int = 3 

172 

173 for attempt in range(1, max_retries + 2): 

174 logger.debug(f"Trying sending to invalid address ({attempt}/{max_retries + 1})...") 

175 config.set_address("my invalid address") 

176 try: 

177 with pytest.raises(Exception) as exc_info: 

178 if config.can_split is not False: 

179 self._wallet.create_txs(config) 

180 else: 

181 self._wallet.create_tx(config) 

182 finally: 

183 config.set_address(self.address) 

184 

185 # retry on transient network error 

186 if str(exc_info.value) == "Network error" and attempt <= max_retries: 

187 continue 

188 

189 assert str(exc_info.value) == "Invalid destination address" 

190 return 

191 

192 def _send_to_self(self, config: MoneroTxConfig) -> list[MoneroTxWallet]: 

193 """Test sending to self. 

194 

195 :param MoneroTxConfig config: tx configuration. 

196 :returns list[MoneroTxWallet]: created txs. 

197 """ 

198 txs: list[MoneroTxWallet] = self._wallet.create_txs(config) 

199 

200 if config.can_split is False: 

201 # must have exactly one tx if no split 

202 assert len(txs) == 1 

203 

204 return txs 

205 

206 def _handle_non_relayed_tx(self, txs: list[MoneroTxWallet], config: MoneroTxConfig) -> list[MoneroTxWallet]: 

207 """Handle non relayed wallet txs. 

208 

209 :param list[MoneroTxWallet] txs: Transactions to handle. 

210 :param MoneroTxConfig config: Context transaction configuration. 

211 :returns list[MoneroTxWallet]: Handled transactions. 

212 """ 

213 if config.relay is True: 

214 return txs 

215 

216 # build test context 

217 ctx: TxContext = TxContext() 

218 ctx.wallet = self._wallet 

219 ctx.config = config 

220 ctx.is_send_response = True 

221 

222 # test transactions 

223 TxWalletUtils.test_txs_wallet(txs, ctx) 

224 

225 # txs are not in the pool 

226 for tx_created in txs: 

227 for tx_pool in self._daemon.get_tx_pool(): 

228 assert tx_pool.hash is not None 

229 assert tx_created is not None 

230 assert tx_pool.hash != tx_created.hash, "Created tx should not be in the pool" 

231 

232 # relay txs 

233 tx_hashes: list[str] = [] 

234 if config.can_split is not True: 

235 # test relay_tx() with single transaction 

236 tx_hashes = [self._wallet.relay_tx(txs[0])] 

237 else: 

238 tx_metadatas: list[str] = [] 

239 for tx in txs: 

240 assert tx.metadata is not None 

241 tx_metadatas.append(tx.metadata) 

242 # test relayTxs() with potentially multiple transactions 

243 tx_hashes = self._wallet.relay_txs(tx_metadatas) 

244 

245 for tx_hash in tx_hashes: 

246 assert len(tx_hash) == 64 

247 

248 # fetch txs for testing 

249 query: MoneroTxQuery = MoneroTxQuery() 

250 query.hashes = tx_hashes 

251 return self._wallet.get_txs(query) 

252 

253 #endregion 

254 

255 def send(self) -> None: 

256 """Send single transaction from wallet with configuration.""" 

257 # check wallet balance 

258 self._check_balance() 

259 

260 assert self._from_subaddress is not None 

261 assert self._from_account is not None 

262 

263 # init tx config 

264 config: MoneroTxConfig = self._build_tx_config() 

265 config_copy: MoneroTxConfig = config.copy() 

266 

267 # test sending to invalid address 

268 self._send_to_invalid(config) 

269 

270 # test send to self 

271 txs: list[MoneroTxWallet] = self._send_to_self(config) 

272 

273 logger.debug(f"Created {len(txs)} txs") 

274 

275 # test that config is unchanged 

276 assert config_copy != config 

277 AssertUtils.assert_equals(config_copy, config) 

278 

279 # test common tx set among txs 

280 TxWalletUtils.test_common_tx_sets(txs, False, False, False) 

281 

282 # handle non-relayed transaction 

283 txs = self._handle_non_relayed_tx(txs, config) 

284 

285 logger.debug(f"Handled {len(txs)} non relayed txs") 

286 

287 # test that balance and unlocked balance decreased 

288 self._check_balance_decreased() 

289 

290 locked_txs: list[MoneroTxWallet] = self._get_locked_txs() 

291 

292 # build test context 

293 ctx: TxContext = TxContext() 

294 ctx.wallet = self._wallet 

295 ctx.config = config 

296 ctx.is_send_response = config.relay is True 

297 

298 # test transactions 

299 assert len(txs) > 0 

300 for tx in txs: 

301 TxWalletUtils.test_tx_wallet(tx, ctx) 

302 assert tx.outgoing_transfer is not None 

303 assert self._from_account.index == tx.outgoing_transfer.account_index 

304 assert len(tx.outgoing_transfer.subaddress_indices) == 1 

305 assert self._from_subaddress.index == tx.outgoing_transfer.subaddress_indices[0] 

306 assert self.send_amount == tx.get_outgoing_amount() 

307 if config.payment_id is not None: 

308 assert config.payment_id == tx.payment_id 

309 

310 # test outgoing destinations 

311 dest_count: int = len(tx.outgoing_transfer.destinations) 

312 if dest_count > 0: 

313 assert dest_count == 1 

314 for dest in tx.outgoing_transfer.destinations: 

315 TransferUtils.test_destination(dest) 

316 assert dest.address == self.address 

317 assert self.send_amount == dest.amount 

318 

319 # tx is among locked txs 

320 found: bool = False 

321 for locked in locked_txs: 

322 if locked.hash == tx.hash: 

323 found = True 

324 break 

325 

326 assert found, "Created txs should be among locked txs"