Debian Codegraph @

tests/test_daemon.py

raw symbols SCIP
1 import asyncio
2 from collections import defaultdict
3 import os
4 from typing import Optional, Iterable
5 from unittest import mock
6
7 from electrum.commands import Commands
8 from electrum.daemon import Daemon
9 from electrum.simple_config import SimpleConfig
10 from electrum.wallet import Abstract_Wallet
11 from electrum.lnworker import LNWallet, LNPeerManager
12 from electrum.lnwatcher import LNWatcher
13 from electrum import util
14 from electrum.utils.memory_leak import count_objects_in_memory
15 from electrum import constants
16
17 from . import ElectrumTestCase, as_testnet, restore_wallet_from_text__for_unittest
18
19
20 class DaemonTestCase(ElectrumTestCase):
21 config: 'SimpleConfig'
22
23 def setUp(self):
24 super().setUp()
25 self.config = SimpleConfig({'electrum_path': self.electrum_path})
26 self.config.NETWORK_OFFLINE = True
27
28 self.wallet_dir = os.path.dirname(self.config.get_wallet_path())
29 assert "wallets" == os.path.basename(self.wallet_dir)
30
31 async def asyncSetUp(self):
32 await super().asyncSetUp()
33 self.daemon = Daemon(config=self.config, listen_jsonrpc=False)
34 assert self.daemon.network is None
35
36 async def asyncTearDown(self):
37 await self.daemon.stop()
38 await super().asyncTearDown()
39
40 def _restore_wallet_from_text(self, text, *, password: Optional[str], encrypt_file: bool = None, **kwargs) -> str:
41 """Returns path for created wallet."""
42 basename = util.get_new_wallet_name(self.wallet_dir)
43 path = os.path.join(self.wallet_dir, basename)
44 wallet_dict = restore_wallet_from_text__for_unittest(
45 text,
46 path=path,
47 password=password,
48 encrypt_file=encrypt_file,
49 config=self.config,
50 **kwargs,
51 )
52 # We return the path instead of the wallet object, as extreme
53 # care would be needed to use the wallet object directly:
54 # Unless the daemon knows about it, daemon._load_wallet might create a conflicting wallet object
55 # for the same fs path, and there would be two wallet objects contending for the same file.
56 return path
57
58
59 class TestUnifiedPassword(DaemonTestCase):
60
61 def setUp(self):
62 super().setUp()
63 self.config.WALLET_SHOULD_USE_SINGLE_PASSWORD = True
64
65 def _run_post_unif_sanity_checks(self, paths: Iterable[str], *, password: str):
66 for path in paths:
67 w = self.daemon.load_wallet(path, password)
68 self.assertIsNotNone(w)
69 w.check_password(password)
70 self.assertTrue(w.has_storage_encryption())
71 if w.can_have_keystore_encryption():
72 self.assertTrue(w.has_keystore_encryption())
73 if w.has_seed():
74 self.assertIsInstance(w.get_seed(password), str)
75 can_be_unified, is_unified, wallet_paths_can_unlock = self.daemon.check_password_for_directory(
76 old_password=password,
77 wallet_dir=self.wallet_dir,
78 )
79 self.assertEqual((True, True, len(paths)), (can_be_unified, is_unified, len(wallet_paths_can_unlock)))
80
81 # "cannot unify pw" tests --->
82
83 async def test_cannot_unify_two_std_wallets_both_have_ks_and_sto_enc(self):
84 path1 = self._restore_wallet_from_text("9dk", password="123456", encrypt_file=True)
85 path2 = self._restore_wallet_from_text("x8", password="asdasd", encrypt_file=True)
86 with open(path1, "rb") as f:
87 raw1_before = f.read()
88 with open(path2, "rb") as f:
89 raw2_before = f.read()
90
91 can_be_unified, is_unified, _ = self.daemon.check_password_for_directory(old_password="123456", wallet_dir=self.wallet_dir)
92 self.assertEqual((False, False), (can_be_unified, is_unified))
93 is_unified = self.daemon.update_password_for_directory(old_password="123456", new_password="123456")
94 self.assertFalse(is_unified)
95 # verify that files on disk haven't changed:
96 with open(path1, "rb") as f:
97 raw1_after = f.read()
98 with open(path2, "rb") as f:
99 raw2_after = f.read()
100 self.assertEqual(raw1_before, raw1_after)
101 self.assertEqual(raw2_before, raw2_after)
102
103 async def test_cannot_unify_mixed_wallets(self):
104 path1 = self._restore_wallet_from_text("9dk", password="123456", encrypt_file=True)
105 path2 = self._restore_wallet_from_text("9dk", password="asdasd", encrypt_file=False)
106 path3 = self._restore_wallet_from_text("9dk", password=None)
107 with open(path1, "rb") as f:
108 raw1_before = f.read()
109 with open(path2, "rb") as f:
110 raw2_before = f.read()
111 with open(path3, "rb") as f:
112 raw3_before = f.read()
113
114 can_be_unified, is_unified, _ = self.daemon.check_password_for_directory(old_password="123456", wallet_dir=self.wallet_dir)
115 self.assertEqual((False, False), (can_be_unified, is_unified))
116 is_unified = self.daemon.update_password_for_directory(old_password="123456", new_password="123456")
117 self.assertFalse(is_unified)
118 # verify that files on disk haven't changed:
119 with open(path1, "rb") as f:
120 raw1_after = f.read()
121 with open(path2, "rb") as f:
122 raw2_after = f.read()
123 with open(path3, "rb") as f:
124 raw3_after = f.read()
125 self.assertEqual(raw1_before, raw1_after)
126 self.assertEqual(raw2_before, raw2_after)
127 self.assertEqual(raw3_before, raw3_after)
128
129 # "can unify pw" tests --->
130
131 async def test_can_unify_two_std_wallets_both_have_ks_and_sto_enc(self):
132 path1 = self._restore_wallet_from_text("9dk", password="123456", encrypt_file=True)
133 path2 = self._restore_wallet_from_text("x8", password="123456", encrypt_file=True)
134 can_be_unified, is_unified, _ = self.daemon.check_password_for_directory(old_password="123456", wallet_dir=self.wallet_dir)
135 self.assertEqual((True, True), (can_be_unified, is_unified))
136 is_unified = self.daemon.update_password_for_directory(old_password="123456", new_password="123456")
137 self.assertTrue(is_unified)
138 self._run_post_unif_sanity_checks([path1, path2], password="123456")
139
140 async def test_can_unify_two_std_wallets_one_has_ks_enc_other_has_both_enc(self):
141 path1 = self._restore_wallet_from_text("9dk", password="123456", encrypt_file=True)
142 path2 = self._restore_wallet_from_text("x8", password="123456", encrypt_file=False)
143 with open(path2, "rb") as f:
144 raw2_before = f.read()
145
146 can_be_unified, is_unified, _ = self.daemon.check_password_for_directory(old_password="123456", wallet_dir=self.wallet_dir)
147 self.assertEqual((True, False), (can_be_unified, is_unified))
148 is_unified = self.daemon.update_password_for_directory(old_password="123456", new_password="123456")
149 self.assertTrue(is_unified)
150 self._run_post_unif_sanity_checks([path1, path2], password="123456")
151 # verify that file at path2 changed:
152 with open(path2, "rb") as f:
153 raw2_after = f.read()
154 self.assertNotEqual(raw2_before, raw2_after)
155
156 async def test_can_unify_two_std_wallets_one_without_password(self):
157 path1 = self._restore_wallet_from_text("9dk", password=None)
158 path2 = self._restore_wallet_from_text("x8", password="123456", encrypt_file=True)
159 can_be_unified, is_unified, _ = self.daemon.check_password_for_directory(old_password="123456", wallet_dir=self.wallet_dir)
160 self.assertEqual((True, False), (can_be_unified, is_unified))
161 is_unified = self.daemon.update_password_for_directory(old_password="123456", new_password="123456")
162 self.assertTrue(is_unified)
163 self._run_post_unif_sanity_checks([path1, path2], password="123456")
164
165 @as_testnet
166 async def test_can_unify_large_folder_yet_to_be_unified(self):
167 paths = []
168 # seed
169 paths.append(self._restore_wallet_from_text("9dk", password="123456", encrypt_file=True))
170 paths.append(self._restore_wallet_from_text("9dk", password="123456", encrypt_file=False))
171 paths.append(self._restore_wallet_from_text("9dk", password=None))
172 # xpub
173 xpub = "vpub5UqWay427dCjkpE3gPKLnkBUqDRoBed1328uNrLDoTyKo6HFSs9agfDMy1VXbVtcuBVRiAZQsPPsPdu1Ge8m8qvNZPyzJ4ecPsf6U1ieW4x"
174 paths.append(self._restore_wallet_from_text(xpub, password="123456", encrypt_file=True))
175 paths.append(self._restore_wallet_from_text(xpub, password="123456", encrypt_file=False))
176 paths.append(self._restore_wallet_from_text(xpub, password=None))
177 # xprv
178 xprv = "vprv9FrABTX8HFeSYL9aaMnLRcEkHBbJnBu9foDJaTvcF8SLvHx6uKqL8rtt7kTd66V4QPLfWPaCJMVZa3h9zuzLr7YFZd1uoEevqqyxp66oSbN"
179 paths.append(self._restore_wallet_from_text(xprv, password="123456", encrypt_file=True))
180 paths.append(self._restore_wallet_from_text(xprv, password="123456", encrypt_file=False))
181 paths.append(self._restore_wallet_from_text(xprv, password=None))
182 # WIFs
183 wifs= "p2wpkh:cRyfp9nJ8soK1bBUJAcWbMrsJZxKJpe7HBSxz5uXVbwydvUxz9zT p2wpkh:cV6J6T2AG4oXAXdYHAV6dbzR41QnGumDSVvWrmj2yYpos81RtyBK"
184 paths.append(self._restore_wallet_from_text(wifs, password="123456", encrypt_file=True))
185 paths.append(self._restore_wallet_from_text(wifs, password="123456", encrypt_file=False))
186 paths.append(self._restore_wallet_from_text(wifs, password=None))
187 # addrs
188 addrs = "tb1qq2tmmcngng78nllq2pvrkchcdukemtj5s6l0zu tb1qm7ckcjsed98zhvhv3dr56a22w3fehlkxyh4wgd"
189 paths.append(self._restore_wallet_from_text(addrs, password="123456", encrypt_file=True))
190 paths.append(self._restore_wallet_from_text(addrs, password="123456", encrypt_file=False))
191 paths.append(self._restore_wallet_from_text(addrs, password=None))
192 # do unification
193 can_be_unified, is_unified, _ = self.daemon.check_password_for_directory(old_password="123456", wallet_dir=self.wallet_dir)
194 self.assertEqual((True, False), (can_be_unified, is_unified))
195 is_unified = self.daemon.update_password_for_directory(old_password="123456", new_password="123456")
196 self.assertTrue(is_unified)
197 self._run_post_unif_sanity_checks(paths, password="123456")
198
199 # misc --->
200
201 async def test_wallet_objects_are_properly_garbage_collected_after_check_pw_for_dir(self):
202 orig_cb_count = util.callback_mgr.count_all_callbacks()
203 # GC sanity-check:
204 mclasses = [Abstract_Wallet, LNWallet, LNWatcher, LNPeerManager]
205 objmap = count_objects_in_memory(mclasses)
206 for mcls in mclasses:
207 self.assertEqual(len(objmap[mcls]), 0, msg=f"too many lingering objs of type={mcls}")
208 # restore some wallets
209 paths = []
210 paths.append(self._restore_wallet_from_text("9dk", password="123456", encrypt_file=True))
211 paths.append(self._restore_wallet_from_text("9dk", password="123456", encrypt_file=False))
212 paths.append(self._restore_wallet_from_text("9dk", password=None))
213 paths.append(self._restore_wallet_from_text("9dk", password="123456", encrypt_file=True, passphrase="hunter2"))
214 paths.append(self._restore_wallet_from_text("9dk", password="999999", encrypt_file=False, passphrase="hunter2"))
215 paths.append(self._restore_wallet_from_text("9dk", password=None, passphrase="hunter2"))
216 # test unification
217 can_be_unified, is_unified, paths_succeeded = self.daemon.check_password_for_directory(old_password="123456", wallet_dir=self.wallet_dir)
218 self.assertEqual((False, False, 5), (can_be_unified, is_unified, len(paths_succeeded)))
219 # gc
220 try:
221 async with util.async_timeout(5):
222 while True:
223 objmap = count_objects_in_memory(mclasses)
224 if sum(len(lst) for lst in objmap.values()) == 0:
225 break # all "mclasses"-type objects have been GC-ed
226 await asyncio.sleep(0.01)
227 except asyncio.TimeoutError:
228 for mcls in mclasses:
229 self.assertEqual(len(objmap[mcls]), 0, msg=f"too many lingering objs of type={mcls}")
230 # also check callbacks have been cleaned up:
231 self.assertEqual(orig_cb_count, util.callback_mgr.count_all_callbacks())
232
233
234 class TestCommandsWithDaemon(DaemonTestCase):
235 TESTNET = True
236 SEED = "bitter grass shiver impose acquire brush forget axis eager alone wine silver"
237
238 async def test_wp_command_with_inmemory_wallet_has_password(self):
239 cmds = Commands(config=self.config, daemon=self.daemon)
240 wallet = restore_wallet_from_text__for_unittest(
241 self.SEED,
242 path=None,
243 password="123456",
244 config=self.config)['wallet']
245 self.assertEqual(self.SEED, await cmds.getseed(wallet=wallet, password="123456"))
246
247 async def test_wp_command_with_inmemory_wallet_no_password(self):
248 cmds = Commands(config=self.config, daemon=self.daemon)
249 wallet = restore_wallet_from_text__for_unittest(
250 self.SEED,
251 path=None,
252 config=self.config)['wallet']
253 self.assertEqual(self.SEED, await cmds.getseed(wallet=wallet))
254
255 async def test_wp_command_with_diskfile_wallet_has_password(self):
256 cmds = Commands(config=self.config, daemon=self.daemon)
257 wpath = self._restore_wallet_from_text(self.SEED, password="123456", encrypt_file=True)
258 basename = os.path.basename(wpath)
259 await cmds.load_wallet(wallet_path=wpath, password="123456")
260 wallet = self.daemon.get_wallet(wpath)
261 self.assertIsInstance(wallet, Abstract_Wallet)
262 self.assertEqual(self.SEED, await cmds.getseed(wallet_path=wpath, password="123456"))
263 self.assertEqual(self.SEED, await cmds.getseed(wallet_path=basename, password='123456'))
264 self.assertEqual(self.SEED, await cmds.getseed(wallet=wallet, password="123456"))
265
266 async def test_wp_command_with_diskfile_wallet_no_password(self):
267 cmds = Commands(config=self.config, daemon=self.daemon)
268 wpath = self._restore_wallet_from_text(self.SEED, password=None)
269 basename = os.path.basename(wpath)
270 await cmds.load_wallet(wallet_path=wpath, password=None)
271 wallet = self.daemon.get_wallet(wpath)
272 self.assertIsInstance(wallet, Abstract_Wallet)
273 self.assertEqual(self.SEED, await cmds.getseed(wallet_path=wpath))
274 self.assertEqual(self.SEED, await cmds.getseed(wallet_path=basename))
275 self.assertEqual(self.SEED, await cmds.getseed(wallet=wallet))
276
277
278 class TestLoadWallet(DaemonTestCase):
279
280 async def test_simple_load(self):
281 path1 = self._restore_wallet_from_text("9dk", password=None)
282 wallet1 = self.daemon.load_wallet(path1, password=None)
283 await self.daemon._stop_wallet(path1)
284
285 async def test_password_checks_for_no_password(self):
286 real_password = None
287 path1 = self._restore_wallet_from_text("9dk", password=real_password)
288 # load_wallet will not validate the password arg unless needed for storage.decrypt():
289 wallet1 = self.daemon.load_wallet(path1, password="garbage")
290 await self.daemon._stop_wallet(path1)
291 # unless force_check_password is set:
292 with self.assertRaises(util.InvalidPassword):
293 wallet1 = self.daemon.load_wallet(path1, password="garbage", force_check_password=True)
294
295 wallet1 = self.daemon.load_wallet(path1, password=real_password)
296 await self.daemon._stop_wallet(path1)
297
298 wallet1 = self.daemon.load_wallet(path1, password=real_password, force_check_password=True)
299 await self.daemon._stop_wallet(path1)
300
301 # load_wallet will not validate the password arg if wallet is already loaded, unless force_check_password
302 wallet1 = self.daemon.load_wallet(path1, password=real_password)
303 wallet1 = self.daemon.load_wallet(path1, password="garbage")
304 with self.assertRaises(util.InvalidPassword):
305 wallet1 = self.daemon.load_wallet(path1, password="garbage", force_check_password=True)
306
307
308 async def test_password_checks_for_ks_enc(self):
309 real_password = "1234"
310 path1 = self._restore_wallet_from_text("9dk", password=real_password, encrypt_file=False)
311 # load_wallet will not validate the password arg unless needed for storage.decrypt():
312 wallet1 = self.daemon.load_wallet(path1, password="garbage")
313 await self.daemon._stop_wallet(path1)
314 # unless force_check_password is set:
315 with self.assertRaises(util.InvalidPassword):
316 wallet1 = self.daemon.load_wallet(path1, password="garbage", force_check_password=True)
317
318 wallet1 = self.daemon.load_wallet(path1, password=real_password)
319 await self.daemon._stop_wallet(path1)
320
321 wallet1 = self.daemon.load_wallet(path1, password=real_password, force_check_password=True)
322 await self.daemon._stop_wallet(path1)
323
324 # load_wallet will not validate the password arg if wallet is already loaded, unless force_check_password
325 wallet1 = self.daemon.load_wallet(path1, password=real_password)
326 wallet1 = self.daemon.load_wallet(path1, password="garbage")
327 with self.assertRaises(util.InvalidPassword):
328 wallet1 = self.daemon.load_wallet(path1, password="garbage", force_check_password=True)
329
330
331 async def test_password_checks_for_sto_enc(self):
332 real_password = "1234"
333 path1 = self._restore_wallet_from_text("9dk", password=real_password, encrypt_file=True)
334
335 with self.assertRaises(util.InvalidPassword):
336 wallet1 = self.daemon.load_wallet(path1, password="garbage")
337
338 with self.assertRaises(util.InvalidPassword):
339 wallet1 = self.daemon.load_wallet(path1, password="garbage", force_check_password=True)
340
341 wallet1 = self.daemon.load_wallet(path1, password=real_password)
342 await self.daemon._stop_wallet(path1)
343
344 wallet1 = self.daemon.load_wallet(path1, password=real_password, force_check_password=True)
345 await self.daemon._stop_wallet(path1)
346
347 # load_wallet will not validate the password arg if wallet is already loaded, unless force_check_password
348 wallet1 = self.daemon.load_wallet(path1, password=real_password)
349 wallet1 = self.daemon.load_wallet(path1, password="garbage")
350 with self.assertRaises(util.InvalidPassword):
351 wallet1 = self.daemon.load_wallet(path1, password="garbage", force_check_password=True)
352
353 async def test_mainnet_testnet_mixup(self):
354 """version bytes in addresses, xpubs, etc. differ between mainnet and testnet.
355 If the user tries to open a wallet for a different chain, try to show a reasonable error message.
356 """
357 # we are on mainnet, and will try to open testnet wallets:
358 assert constants.net.TESTNET is False
359
360 # case 1: fresh wallet created on wrong network
361 with mock.patch("electrum.constants.net", constants.BitcoinTestnet):
362 path = self._restore_wallet_from_text("9dk", password=None)
363 with self.assertRaises(util.WalletFileException):
364 wallet = self.daemon.load_wallet(path, password=None, upgrade=True)
365
366 # case 2: existing older wallet (db v57) that gets populated with 'genesis_blockhash' in convert_version_71
367 path = self.get_wallet_file_path("client_4_5_2_9dk_with_ln")
368 with self.assertRaises(util.WalletFileException):
369 wallet = self.daemon.load_wallet(path, password=None, upgrade=True)
370
371 # case 3: existing older wallet (db v18) that gets populated with 'genesis_blockhash' in convert_version_71
372 # // this test does not work: convert_version_20 raises InvalidMasterKeyVersionBytes
373 # path = self.get_wallet_file_path("client_3_3_8_xpub_with_realistic_history")
374 # with self.assertRaises(util.WalletFileException):
375 # wallet = self.daemon.load_wallet(path, password=None, upgrade=True)