Coverage for tests/wallet/test_sync.py: 95%
281 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
1from __future__ import annotations
3import logging
4from datetime import datetime
5from time import sleep
6from typing import Optional
8import pytest
9from monero import (
10 MoneroDaemonRpc,
11 MoneroError,
12 MoneroRpcConnection,
13 MoneroSyncResult,
14 MoneroTxWallet,
15 MoneroWallet,
16 MoneroWalletConfig,
17 MoneroWalletFull,
18 MoneroWalletRpc,
19)
20from typing_extensions import override
22from utils import (
23 AssertUtils,
24 GenUtils,
25 MiningUtils,
26 SyncProgressTester,
27 SyncSeedTester,
28 TestUtils,
29 TestUtils as Utils,
30 TxWalletUtils,
31 WalletEqualityUtils,
32 WalletNotificationCollector,
33 WalletTxsUtils,
34)
35from .base_test_monero_wallet import BaseTestMoneroWallet
36from .wallet_support import FullWalletSupport, RpcWalletSupport, KeysWalletSupport
38logger: logging.Logger = logging.getLogger("TestMoneroWalletSync")
41class BaseTestMoneroWalletSync(BaseTestMoneroWallet):
42 """Common wallet sync tests."""
44 # Can sync (without progress)
45 # TODO test syncing from start height
46 @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled")
47 def test_sync_without_progress(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None:
48 num_blocks: int = 100
49 chain_height: int = daemon.get_height()
50 assert chain_height >= num_blocks
51 result: MoneroSyncResult = wallet.sync(chain_height - num_blocks) # sync end of chain
52 assert result.num_blocks_fetched >= 0
53 assert result.received_money is not None
55 # Can get the current height that the wallet is synchronized to
56 @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled")
57 def test_get_height(self, wallet: MoneroWallet) -> None:
58 height: int = wallet.get_height()
59 assert height >= 0
61 # Can get a blockchain height by date
62 @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled")
63 def test_get_height_by_date(self, wallet: MoneroWallet) -> None:
64 # collect dates to test starting 100 days ago
65 day_ms: int = 24 * 60 * 60 * 1000
66 # TODO monero-project: today's date can throw exception as "in future" so we test up to yesterday
67 yesterday: int = GenUtils.current_timestamp() - day_ms
68 dates: list[datetime] = []
69 date_range: list[int] = list(range(99))
70 date_range.reverse()
72 for i in date_range:
73 # subtract i days
74 dates.append(datetime.fromtimestamp((yesterday - day_ms * i) / 1000))
76 # test heights by date
77 last_height: Optional[int] = None
78 for date in dates:
79 height: int = wallet.get_height_by_date(date.year + 1900, date.month + 1, date.day)
80 assert (height >= 0)
81 if last_height is not None:
82 assert (height >= last_height)
83 last_height = height
85 assert last_height is not None
86 assert (last_height >= 0)
87 height = wallet.get_height()
88 assert (height >= 0)
90 # test future date
91 tomorrow: datetime = datetime.fromtimestamp((yesterday + day_ms * 2) / 1000)
92 with pytest.raises(MoneroError, match="specified date is in the future"):
93 wallet.get_height_by_date(tomorrow.year + 1900, tomorrow.month + 1, tomorrow.day)
95 # Can scan transactions by id
96 @pytest.mark.skipif(TestUtils.TEST_RESETS is False, reason="TEST_RESETS disabled")
97 def test_scan_txs(self, wallet: MoneroWallet) -> None:
98 config: MoneroWalletConfig = MoneroWalletConfig()
99 config.seed = wallet.get_seed()
100 config.restore_height = 0
101 scan_wallet: MoneroWallet = self._create_wallet(config)
102 logger.debug("Created scan wallet")
103 WalletTxsUtils.test_scan_txs(wallet, scan_wallet)
105 # Can rescan spent
106 @pytest.mark.skipif(TestUtils.TEST_RESETS is False, reason="TEST_RESETS disabled")
107 def test_rescan_spent(self, wallet: MoneroWallet) -> None:
108 wallet.rescan_spent()
110 # Can rescan the blockchain
111 @pytest.mark.skipif(TestUtils.TEST_RESETS is False, reason="TEST_RELAYS disabled")
112 @pytest.mark.skip(reason="Disabled so tests don't delete local cache")
113 def test_rescan_blockchain(self, wallet: MoneroWallet) -> None:
114 wallet.rescan_blockchain()
115 for tx in wallet.get_txs():
116 TxWalletUtils.test_tx_wallet(tx)
119@pytest.mark.integration
120class TestMoneroWalletFullSync(FullWalletSupport, BaseTestMoneroWalletSync):
121 """Full wallet sync integration tests."""
123 def _test_sync_seed(
124 self,
125 daemon: MoneroDaemonRpc,
126 wallet: MoneroWalletFull,
127 start_height: Optional[int],
128 restore_height: Optional[int],
129 skip_gt_comparison: bool = False,
130 test_post_sync_notifications: bool = False
131 ) -> None:
132 tester: SyncSeedTester = SyncSeedTester(
133 daemon, wallet, self._create_wallet,
134 start_height, restore_height,
135 skip_gt_comparison, test_post_sync_notifications
136 )
137 tester.test()
139 # Can sync a wallet with a randomly generated seed
140 @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled")
141 def test_sync_random(self, daemon: MoneroDaemonRpc) -> None:
142 assert daemon.is_connected(), "Not connected to daemon"
144 # create test wallet
145 wallet: MoneroWalletFull = self._create_wallet(MoneroWalletConfig(), False)
146 restore_height: int = daemon.get_height()
148 # test wallet's height before syncing
149 AssertUtils.assert_equals(Utils.get_daemon_rpc_connection(), wallet.get_daemon_connection())
150 assert restore_height == wallet.get_daemon_height()
151 assert wallet.is_connected_to_daemon()
152 assert wallet.is_synced() is False
153 assert wallet.get_height() == 1
154 assert wallet.get_restore_height() == restore_height
155 assert wallet.get_daemon_height() == daemon.get_height()
157 # sync the wallet
158 progress_tester: SyncProgressTester = SyncProgressTester(wallet, wallet.get_restore_height(), wallet.get_daemon_height())
159 result: MoneroSyncResult = wallet.sync(progress_tester)
160 progress_tester.on_done(wallet.get_daemon_height())
162 # test result after syncing
163 wallet_gt: MoneroWalletFull = Utils.create_wallet_ground_truth(Utils.NETWORK_TYPE, wallet.get_seed(), None, restore_height)
164 wallet_gt.sync()
166 try:
167 assert wallet.is_connected_to_daemon()
168 assert wallet.is_synced()
169 assert result.num_blocks_fetched == 0
170 assert result.received_money is False
171 assert wallet.get_height() == daemon.get_height()
173 # sync the wallet with default params
174 wallet.sync()
175 assert wallet.is_synced()
176 assert wallet.get_height() == daemon.get_height()
178 # compare wallet to ground truth
179 WalletEqualityUtils.test_wallet_full_equality_on_chain(wallet_gt, wallet)
180 finally:
181 wallet_gt.close(True)
182 wallet.close()
184 # attempt to sync unconnected wallet
185 config: MoneroWalletConfig = MoneroWalletConfig()
186 config.server = MoneroRpcConnection(Utils.OFFLINE_SERVER_URI)
187 wallet = self._create_wallet(config)
188 try:
189 with pytest.raises(Exception) as exc_info:
190 wallet.sync()
191 assert str(exc_info.value) == "Wallet is not connected to daemon"
192 finally:
193 wallet.close()
195 # Can sync a wallet created from seed from the genesis
196 @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled")
197 @pytest.mark.skipif(Utils.LITE_MODE, reason="LITE_MODE enabled")
198 def test_sync_seed_from_genesis(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletFull) -> None:
199 self._test_sync_seed(daemon, wallet, None, None, True, False)
201 # Can sync a wallet created from seed from a restore height
202 @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled")
203 @pytest.mark.skipif(Utils.LITE_MODE, reason="LITE_MODE enabled")
204 def test_sync_seed_from_restore_height(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletFull) -> None:
205 self._test_sync_seed(daemon, wallet, None, Utils.FIRST_RECEIVE_HEIGHT)
207 # Can sync a wallet created from seed from a start height
208 @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled")
209 @pytest.mark.skipif(Utils.LITE_MODE, reason="LITE_MODE enabled")
210 def test_sync_seed_from_start_height(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletFull) -> None:
211 self._test_sync_seed(daemon, wallet, Utils.FIRST_RECEIVE_HEIGHT, None, False, True)
213 # Can sync a wallet created from seed from a start height less than the restore height
214 @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled")
215 @pytest.mark.skipif(Utils.LITE_MODE, reason="LITE_MODE enabled")
216 def test_sync_seed_start_height_lt_restore_height(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletFull) -> None:
217 self._test_sync_seed(daemon, wallet, Utils.FIRST_RECEIVE_HEIGHT, Utils.FIRST_RECEIVE_HEIGHT + 3)
219 # Can sync a wallet created from seed from a start height greater than the restore height
220 @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled")
221 @pytest.mark.skipif(Utils.LITE_MODE, reason="LITE_MODE enabled")
222 def test_sync_seed_start_height_gt_restore_height(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletFull) -> None:
223 self._test_sync_seed(daemon, wallet, Utils.FIRST_RECEIVE_HEIGHT + 3, Utils.FIRST_RECEIVE_HEIGHT)
225 # Can sync a wallet created from keys
226 @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled")
227 @pytest.mark.skipif(Utils.LITE_MODE, reason="LITE_MODE enabled")
228 def test_sync_wallet_from_keys(self, daemon: MoneroDaemonRpc, wallet: MoneroWalletFull) -> None:
229 # recreate test wallet from keys
230 path: str = Utils.get_random_wallet_path()
231 config: MoneroWalletConfig = MoneroWalletConfig()
232 config.path = path
233 config.primary_address = wallet.get_primary_address()
234 config.private_view_key = wallet.get_private_view_key()
235 config.private_spend_key = wallet.get_private_spend_key()
236 config.restore_height = Utils.FIRST_RECEIVE_HEIGHT
237 wallet_keys: MoneroWalletFull = self._create_wallet(config, False)
239 # create ground truth wallet for comparison
240 wallet_gt: MoneroWalletFull = Utils.create_wallet_ground_truth(Utils.NETWORK_TYPE, Utils.SEED, None, Utils.FIRST_RECEIVE_HEIGHT)
242 # test wallet and close as final step
243 try:
244 assert wallet_keys.get_seed() == wallet_gt.get_seed()
245 assert wallet_keys.get_primary_address() == wallet_gt.get_primary_address()
246 assert wallet_keys.get_private_view_key() == wallet_gt.get_private_view_key()
247 assert wallet_keys.get_public_view_key() == wallet_gt.get_public_view_key()
248 assert wallet_keys.get_private_spend_key() == wallet_gt.get_private_spend_key()
249 assert wallet_keys.get_public_spend_key() == wallet_gt.get_public_spend_key()
250 assert Utils.FIRST_RECEIVE_HEIGHT == wallet_gt.get_restore_height()
251 assert wallet_keys.is_connected_to_daemon()
252 assert wallet_keys.is_synced() is False
254 # sync the wallet
255 progress_tester: SyncProgressTester = SyncProgressTester(wallet_keys, Utils.FIRST_RECEIVE_HEIGHT, wallet_keys.get_daemon_max_peer_height())
256 result: MoneroSyncResult = wallet_keys.sync(progress_tester)
257 progress_tester.on_done(wallet_keys.get_daemon_height())
259 # test result after syncing
260 assert wallet_keys.is_synced()
261 assert wallet_keys.get_daemon_height() - Utils.FIRST_RECEIVE_HEIGHT == result.num_blocks_fetched
262 assert result.received_money is True
263 assert wallet_keys.get_height() == daemon.get_height()
264 assert wallet_keys.get_daemon_height() == daemon.get_height()
266 # wallet should be fully synced so first tx happens on true restore height
267 txs: list[MoneroTxWallet] = wallet.get_txs()
268 assert len(txs) > 0
269 tx: MoneroTxWallet = txs[0]
270 tx_height: int | None = tx.get_height()
271 assert tx_height is not None
272 assert Utils.FIRST_RECEIVE_HEIGHT == tx_height
274 # compare with ground truth
275 WalletEqualityUtils.test_wallet_full_equality_on_chain(wallet_gt, wallet_keys)
276 finally:
277 wallet_gt.close(True)
278 wallet_keys.close()
280 # Can start and stop syncing
281 # TODO test start syncing, notification of syncs happening, stop syncing, no notifications, etc
282 @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled")
283 @pytest.mark.skipif(Utils.LITE_MODE, reason="LITE_MODE enabled")
284 def test_start_stop_syncing(self, daemon: MoneroDaemonRpc) -> None:
285 # test unconnected wallet
286 config: MoneroWalletConfig = MoneroWalletConfig()
287 config.server = MoneroRpcConnection(Utils.OFFLINE_SERVER_URI)
288 config.path = Utils.get_random_wallet_path()
289 wallet: MoneroWalletFull = self._create_wallet(config)
290 try:
291 assert len(wallet.get_seed()) > 0
292 assert wallet.get_height() == 1
293 assert wallet.get_balance() == 0
294 wallet.start_syncing() # succeeds while offline, syncing when a daemon becomes reachable
295 finally:
296 wallet.close()
298 # test connecting wallet
299 config = MoneroWalletConfig()
300 config.path = Utils.get_random_wallet_path()
301 config.server = MoneroRpcConnection(Utils.OFFLINE_SERVER_URI)
302 wallet = self._create_wallet(config)
303 try:
304 assert len(wallet.get_seed()) > 0
305 wallet.set_daemon_connection(daemon.get_rpc_connection())
306 assert wallet.get_height() == 1
307 assert wallet.is_synced() is False
308 assert wallet.get_balance() == 0
309 chain_height: int = wallet.get_daemon_height()
310 wallet.set_restore_height(chain_height - 3)
311 wallet.start_syncing()
312 assert chain_height - 3 == wallet.get_restore_height()
313 AssertUtils.assert_equals(daemon.get_rpc_connection(), wallet.get_daemon_connection())
314 wallet.stop_syncing()
315 wallet.sync()
316 wallet.stop_syncing()
317 wallet.stop_syncing()
318 finally:
319 wallet.close()
321 # test that sync starts automatically
322 restore_height: int = daemon.get_height() - 100
323 config = MoneroWalletConfig()
324 config.path = Utils.get_random_wallet_path()
325 config.seed = Utils.SEED
326 config.restore_height = restore_height
327 wallet = self._create_wallet(config, False)
328 try:
329 # start syncing
330 assert wallet.get_height() == 1
331 assert wallet.get_restore_height() == restore_height
332 assert wallet.is_synced() is False
333 assert wallet.get_balance() == 0
334 wallet.start_syncing(Utils.SYNC_PERIOD_IN_MS)
336 # pause for sync to start
337 sleep(1 + (Utils.SYNC_PERIOD_IN_MS / 1000))
339 # test that wallet has started syncing
340 assert wallet.get_height() > 1
342 # stop syncing
343 wallet.stop_syncing()
345 # TODO monero-project: wallet.cpp m_synchronized only ever set to true, never false
346 finally:
347 wallet.close()
349 @pytest.mark.skipif(Utils.REGTEST, reason="Cannot retrieve accurate height by date from regtest fakechain")
350 @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled")
351 @override
352 def test_get_height_by_date(self, wallet: MoneroWallet) -> None:
353 return super().test_get_height_by_date(wallet)
355 @pytest.mark.skipif(Utils.REGTEST is False, reason="REGTEST disabled")
356 @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled")
357 def test_get_height_by_date_regtest(self, wallet: MoneroWallet) -> None:
358 # the base test's fixed dates fall outside a short regtest chain
359 with pytest.raises(RuntimeError):
360 super().test_get_height_by_date(wallet)
362 # Can wait for the next block to be added and be notified of its height
363 @pytest.mark.skipif(Utils.TEST_NOTIFICATIONS is False, reason="TEST_NOTIFICATIONS disabled")
364 @pytest.mark.flaky(reruns=5, reruns_delay=10, only_rerun=[])
365 def test_wait_for_next_block(self, wallet: MoneroWalletFull) -> None:
366 height_before: int = wallet.get_height()
367 MiningUtils.try_start_mining()
368 try:
369 height: int = wallet.wait_for_next_block()
370 # the notification carries the height of the new block, which is the chain
371 # length the wallet knew before it was added, so it is only greater when the wallet lagged behind
372 assert height >= height_before
373 finally:
374 MiningUtils.try_stop_mining()
377@pytest.mark.integration
378class TestMoneroWalletRpcSync(RpcWalletSupport, BaseTestMoneroWalletSync):
379 """Rpc wallet sync integration tests."""
381 @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled")
382 def test_sync_progress(self, wallet: MoneroWalletRpc) -> None:
383 listener: WalletNotificationCollector = WalletNotificationCollector()
384 # expected error message
385 ERR_MSG: str = "Monero Wallet RPC does not support reporting sync progress"
387 # sync with listener
388 with pytest.raises(Exception) as exc_info:
389 wallet.sync(listener)
390 assert str(exc_info.value) == ERR_MSG
392 # sync with listener from start height
393 with pytest.raises(Exception) as exc_info:
394 wallet.sync(0, listener)
395 assert str(exc_info.value) == ERR_MSG
397 # Can set the poll period for wallet notifications
398 @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled")
399 def test_set_poll_period_in_ms(self, wallet: MoneroWalletRpc) -> None:
400 try:
401 wallet.set_poll_period_in_ms(1000)
402 finally:
403 # restore the configured period so later tests poll at the expected rate
404 wallet.set_poll_period_in_ms(Utils.SYNC_PERIOD_IN_MS)
406 @pytest.mark.not_supported
407 @override
408 def test_get_height_by_date(self, wallet: MoneroWallet) -> None:
409 return super().test_get_height_by_date(wallet)
412@pytest.mark.unit
413class TestMoneroWalletKeysSync(KeysWalletSupport, BaseTestMoneroWalletSync):
414 """Keys-only wallet sync unit tests."""
416 @pytest.mark.not_supported
417 @override
418 def test_sync_without_progress(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None:
419 return super().test_sync_without_progress(daemon, wallet)
421 @pytest.mark.not_supported
422 @override
423 def test_get_height(self, wallet: MoneroWallet) -> None:
424 return super().test_get_height(wallet)
426 @pytest.mark.not_supported
427 @override
428 def test_get_height_by_date(self, wallet: MoneroWallet) -> None:
429 return super().test_get_height_by_date(wallet)
431 @pytest.mark.not_supported
432 @override
433 def test_scan_txs(self, wallet: MoneroWallet) -> None:
434 return super().test_scan_txs(wallet)
436 @pytest.mark.not_supported
437 @override
438 def test_rescan_blockchain(self, wallet: MoneroWallet) -> None:
439 return super().test_rescan_blockchain(wallet)
441 @pytest.mark.not_supported
442 @override
443 def test_rescan_spent(self, wallet: MoneroWallet) -> None:
444 return super().test_rescan_spent(wallet)