ct_autosign.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996
  1. #!/usr/bin/env python3
  2. #
  3. # MMGen Wallet, a terminal-based cryptocurrency wallet
  4. # Copyright (C)2013-2024 The MMGen Project <mmgen@tuta.io>
  5. #
  6. # This program is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. """
  19. test.cmdtest_d.ct_autosign: Autosign tests for the cmdtest.py test suite
  20. """
  21. import sys, os, time, shutil, atexit
  22. from subprocess import run, DEVNULL
  23. from pathlib import Path
  24. from mmgen.cfg import Config
  25. from mmgen.color import red, blue, yellow, cyan, orange, purple, gray
  26. from mmgen.util import msg, suf, die, indent, fmt
  27. from mmgen.led import LEDControl
  28. from mmgen.autosign import Autosign, Signable
  29. from ..include.common import (
  30. cfg,
  31. omsg,
  32. omsg_r,
  33. oqmsg,
  34. oqmsg_r,
  35. start_test_daemons,
  36. stop_test_daemons,
  37. joinpath,
  38. imsg,
  39. read_from_file,
  40. silence,
  41. end_silence,
  42. VirtBlockDevice,
  43. )
  44. from .common import ref_dir, dfl_words_file, dfl_bip39_file
  45. from .ct_base import CmdTestBase
  46. from .input import stealth_mnemonic_entry
  47. class CmdTestAutosignBase(CmdTestBase):
  48. networks = ('btc',)
  49. tmpdir_nums = [18]
  50. color = True
  51. platform_skip = ('win32',)
  52. threaded = False
  53. daemon_coins = []
  54. def __init__(self, trunner, cfgs, spawn):
  55. CmdTestBase.__init__(self, trunner, cfgs, spawn)
  56. if trunner is None:
  57. return
  58. self.silent_mount = self.live or not (cfg.exact_output or cfg.verbose)
  59. self.network_ids = [c+'_tn' for c in self.daemon_coins] + self.daemon_coins
  60. self._create_autosign_instances(create_dirs=not cfg.skipping_deps)
  61. self.fs_image_path = Path(self.tmpdir).absolute() / 'removable_device_image'
  62. if sys.platform == 'linux':
  63. self.txdev = VirtBlockDevice(self.fs_image_path, '10M')
  64. if not (cfg.skipping_deps or self.live):
  65. self._create_removable_device()
  66. if sys.platform == 'darwin' and not cfg.no_daemon_stop:
  67. atexit.register(self._macOS_eject_disk, self.asi.dev_label)
  68. self.opts = ['--coins='+','.join(self.coins)]
  69. if not self.live:
  70. self.spawn_env['MMGEN_TEST_SUITE_ROOT_PFX'] = self.tmpdir
  71. if self.threaded:
  72. self.spawn_env['MMGEN_TEST_SUITE_AUTOSIGN_THREADED'] = '1'
  73. def __del__(self):
  74. if hasattr(self, 'have_dummy_control_files'):
  75. db = LEDControl.boards['dummy']
  76. for fn in (db.status, db.trigger):
  77. run(f'sudo rm -f {fn}'.split(), check=True)
  78. if hasattr(self, 'txdev'):
  79. del self.txdev
  80. if not cfg.no_daemon_stop:
  81. if sys.platform == 'darwin':
  82. for label in (self.asi.dev_label, self.asi.ramdisk.label):
  83. self._macOS_eject_disk(label)
  84. def _create_autosign_instances(self, create_dirs):
  85. d = {'offline': {'name':'asi'}}
  86. if self.have_online:
  87. d['online'] = {'name':'asi_online'}
  88. for subdir, data in d.items():
  89. asi = Autosign(
  90. Config({
  91. 'coins': ','.join(self.coins),
  92. 'test_suite': True,
  93. 'test_suite_xmr_autosign': self.name == 'CmdTestXMRAutosign',
  94. 'test_suite_autosign_threaded': self.threaded,
  95. 'test_suite_root_pfx': None if self.live else self.tmpdir,
  96. 'online': subdir == 'online',
  97. }))
  98. if create_dirs and not self.live:
  99. for k in ('mountpoint', 'shm_dir', 'wallet_dir'):
  100. if subdir == 'online' and k in ('shm_dir', 'wallet_dir'):
  101. continue
  102. if sys.platform == 'darwin' and k != 'mountpoint':
  103. continue
  104. getattr(asi, k).mkdir(parents=True, exist_ok=True)
  105. if sys.platform == 'darwin' and k == 'mountpoint':
  106. asi.mountpoint.rmdir()
  107. continue
  108. setattr(self, data['name'], asi)
  109. def _set_e2label(self, label):
  110. imsg(f'Setting label to {label}')
  111. run(['/sbin/e2label', str(self.txdev.img_path), label], check=True)
  112. def _create_removable_device(self):
  113. if sys.platform == 'linux':
  114. self.txdev.create()
  115. self.txdev.attach(silent=True)
  116. cmd = [
  117. '/sbin/mkfs.ext2',
  118. '-E', 'root_owner={}:{}'.format(os.getuid(), os.getgid()),
  119. '-L', self.asi.dev_label,
  120. str(self.txdev.img_path)]
  121. redir = DEVNULL
  122. run(cmd, stdout=redir, stderr=redir, check=True)
  123. self.txdev.detach(silent=True)
  124. elif sys.platform == 'darwin':
  125. cmd = [
  126. 'hdiutil', 'create', '-size', '10M', '-fs', 'exFAT',
  127. '-volname', self.asi.dev_label,
  128. str(self.fs_image_path)]
  129. redir = None if cfg.exact_output or cfg.verbose else DEVNULL
  130. run(cmd, stdout=redir, check=True)
  131. def _macOS_mount_fs_image(self, loc):
  132. time.sleep(0.2)
  133. run(
  134. ['hdiutil', 'attach', '-mountpoint', str(loc.mountpoint), f'{self.fs_image_path}.dmg'],
  135. stdout=DEVNULL, check=True)
  136. def _macOS_eject_disk(self, label):
  137. try:
  138. run(['diskutil' , 'eject', label], stdout=DEVNULL, stderr=DEVNULL)
  139. except:
  140. pass
  141. def start_daemons(self):
  142. self.spawn('', msg_only=True)
  143. start_test_daemons(*self.network_ids)
  144. return 'ok'
  145. def stop_daemons(self):
  146. self.spawn('', msg_only=True)
  147. stop_test_daemons(*self.network_ids)
  148. return 'ok'
  149. def run_setup(
  150. self,
  151. mn_type = None,
  152. mn_file = None,
  153. use_dfl_wallet = False,
  154. seed_len = None,
  155. usr_entry_modes = False,
  156. passwd = 'abc',
  157. expect_args = []):
  158. mn_desc = mn_type or 'default'
  159. mn_type = mn_type or 'mmgen'
  160. if sys.platform == 'darwin' and not cfg.no_daemon_stop:
  161. self._macOS_eject_disk(self.asi.ramdisk.label)
  162. self.insert_device()
  163. t = self.spawn(
  164. 'mmgen-autosign',
  165. self.opts
  166. + ([] if mn_desc == 'default' else [f'--mnemonic-fmt={mn_type}'])
  167. + ([f'--seed-len={seed_len}'] if seed_len else [])
  168. + ['setup'],
  169. no_passthru_opts = True)
  170. if use_dfl_wallet:
  171. t.expect('Use default wallet for autosigning? (Y/n): ', 'y')
  172. t.passphrase('MMGen wallet', passwd)
  173. else:
  174. if use_dfl_wallet is not None: # None => no dfl wallet present
  175. t.expect('Use default wallet for autosigning? (Y/n): ', 'n')
  176. mn_file = mn_file or {'mmgen': dfl_words_file, 'bip39': dfl_bip39_file}[mn_type]
  177. mn = read_from_file(mn_file).strip().split()
  178. if not seed_len:
  179. t.expect('words: ', {12:'1', 18:'2', 24:'3'}[len(mn)])
  180. t.expect('OK? (Y/n): ', '\n')
  181. from mmgen.mn_entry import mn_entry
  182. entry_mode = 'full'
  183. mne = mn_entry(cfg, mn_type, entry_mode)
  184. if usr_entry_modes:
  185. t.expect('user-configured')
  186. else:
  187. t.expect(
  188. 'Type a number.*: ',
  189. str(mne.entry_modes.index(entry_mode) + 1),
  190. regex = True)
  191. stealth_mnemonic_entry(t, mne, mn, entry_mode)
  192. t.written_to_file('Autosign wallet')
  193. if expect_args:
  194. t.expect(*expect_args)
  195. t.read()
  196. self.remove_device()
  197. if sys.platform == 'darwin' and not cfg.no_daemon_stop:
  198. atexit.register(self._macOS_eject_disk, self.asi.ramdisk.label)
  199. return t
  200. def insert_device(self, asi='asi'):
  201. if self.live:
  202. return
  203. loc = getattr(self, asi)
  204. if sys.platform == 'linux':
  205. self._set_e2label(loc.dev_label)
  206. self.txdev.attach()
  207. for _ in range(20):
  208. if loc.device_inserted:
  209. break
  210. time.sleep(0.1)
  211. else:
  212. die(2, f'device insert timeout exceeded {loc.dev_label}')
  213. elif sys.platform == 'darwin':
  214. self._macOS_mount_fs_image(loc)
  215. def remove_device(self, asi='asi'):
  216. if self.live:
  217. return
  218. loc = getattr(self, asi)
  219. if sys.platform == 'linux':
  220. self.txdev.detach()
  221. for _ in range(20):
  222. if not loc.device_inserted:
  223. break
  224. time.sleep(0.1)
  225. else:
  226. die(2, f'device remove timeout exceeded {loc.dev_label}')
  227. elif sys.platform == 'darwin':
  228. self._macOS_eject_disk(loc.dev_label)
  229. def _mount_ops(self, loc, cmd, *args, **kwargs):
  230. return getattr(getattr(self, loc), cmd)(*args, silent=self.silent_mount, **kwargs)
  231. def do_mount(self, *args, **kwargs):
  232. return self._mount_ops('asi', 'do_mount', *args, **kwargs)
  233. def do_umount(self, *args, **kwargs):
  234. return self._mount_ops('asi', 'do_umount', *args, **kwargs)
  235. def _gen_listing(self):
  236. for k in self.asi.dirs:
  237. d = getattr(self.asi, k)
  238. if d.is_dir():
  239. yield '{:12} {}'.format(
  240. str(Path(*d.parts[6:])) + ':',
  241. ' '.join(sorted(i.name for i in d.iterdir()))).strip()
  242. class CmdTestAutosignClean(CmdTestAutosignBase):
  243. have_online = False
  244. live = False
  245. simulate_led = True
  246. no_insert_check = False
  247. coins = ['btc']
  248. tmpdir_nums = [38]
  249. cmd_group = (
  250. ('clean_no_xmr', 'cleaning signable file directories (no XMR)'),
  251. ('clean_xmr_only', 'cleaning signable file directories (XMR-only)'),
  252. ('clean_all', 'cleaning signable file directories (with XMR)'),
  253. )
  254. def create_fake_tx_files(self):
  255. imsg('Creating fake transaction files')
  256. if not self.asi.xmr_only:
  257. for fn in (
  258. 'a.rawtx', 'a.sigtx',
  259. 'b.rawtx', 'b.sigtx',
  260. 'c.rawtx',
  261. 'd.sigtx',
  262. ):
  263. (self.asi.tx_dir / fn).touch()
  264. for fn in (
  265. 'a.arawtx', 'a.asigtx', 'a.asubtx',
  266. 'b.arawtx', 'b.asigtx',
  267. 'c.asubtx',
  268. 'd.arawtx', 'd.asubtx',
  269. 'e.arawtx',
  270. 'f.asigtx', 'f.asubtx',
  271. ):
  272. (self.asi.txauto_dir / fn).touch()
  273. for fn in (
  274. 'a.rawmsg.json', 'a.sigmsg.json',
  275. 'b.rawmsg.json',
  276. 'c.sigmsg.json',
  277. 'd.rawmsg.json', 'd.sigmsg.json',
  278. ):
  279. (self.asi.msg_dir / fn).touch()
  280. if self.asi.have_xmr:
  281. for fn in (
  282. 'a.rawtx', 'a.sigtx', 'a.subtx',
  283. 'b.rawtx', 'b.sigtx',
  284. 'c.subtx',
  285. 'd.rawtx', 'd.subtx',
  286. 'e.rawtx',
  287. 'f.sigtx', 'f.subtx',
  288. ):
  289. (self.asi.xmr_tx_dir / fn).touch()
  290. for fn in (
  291. 'a.raw', 'a.sig',
  292. 'b.raw',
  293. 'c.sig',
  294. ):
  295. (self.asi.xmr_outputs_dir / fn).touch()
  296. return 'ok'
  297. def clean_no_xmr(self):
  298. return self._clean('btc,ltc,eth')
  299. def clean_xmr_only(self):
  300. self.asi = Autosign(Config({'_clone': self.asi.cfg, 'coins': 'xmr'}))
  301. return self._clean('xmr')
  302. def clean_all(self):
  303. self.asi = Autosign(Config({'_clone': self.asi.cfg, 'coins': 'xmr,btc,bch,eth'}))
  304. return self._clean('xmr,btc,bch,eth')
  305. def _clean(self, coins):
  306. self.spawn('', msg_only=True)
  307. self.insert_device()
  308. silence()
  309. self.do_mount()
  310. end_silence()
  311. self.create_fake_tx_files()
  312. before = '\n'.join(self._gen_listing())
  313. t = self.spawn('mmgen-autosign', [f'--coins={coins}', 'clean'], no_msg=True)
  314. out = t.read()
  315. if sys.platform == 'darwin':
  316. self.insert_device()
  317. silence()
  318. self.do_mount()
  319. end_silence()
  320. after = '\n'.join(self._gen_listing())
  321. chk_non_xmr = """
  322. tx: a.sigtx b.sigtx c.rawtx d.sigtx
  323. txauto: a.asubtx b.asigtx c.asubtx d.asubtx e.arawtx f.asubtx
  324. msg: a.sigmsg.json b.rawmsg.json c.sigmsg.json d.sigmsg.json
  325. """
  326. chk_xmr = """
  327. xmr: outputs tx
  328. xmr/tx: a.subtx b.sigtx c.subtx d.subtx e.rawtx f.subtx
  329. xmr/outputs:
  330. """
  331. chk = ''
  332. shred_count = 0
  333. if not self.asi.xmr_only:
  334. for k in ('tx_dir', 'txauto_dir', 'msg_dir'):
  335. shutil.rmtree(getattr(self.asi, k))
  336. chk += chk_non_xmr.rstrip()
  337. shred_count += 9
  338. if self.asi.have_xmr:
  339. shutil.rmtree(self.asi.xmr_dir)
  340. chk += chk_xmr.rstrip()
  341. shred_count += 9
  342. self.do_umount()
  343. self.remove_device()
  344. imsg(f'\nBefore cleaning:\n{before}')
  345. imsg(f'\nAfter cleaning:\n{after}')
  346. assert f'{shred_count} files shredded' in out
  347. assert after + '\n' == fmt(chk), f'\n{after}\n!=\n{fmt(chk)}'
  348. return t
  349. class CmdTestAutosignThreaded(CmdTestAutosignBase):
  350. have_online = True
  351. live = False
  352. no_insert_check = False
  353. threaded = True
  354. def _wait_loop_start(self):
  355. t = self.spawn(
  356. 'mmgen-autosign',
  357. self.opts + ['--full-summary', 'wait'],
  358. direct_exec = True,
  359. no_passthru_opts = True,
  360. spawn_env_override = self.spawn_env | {'EXEC_WRAPPER_DO_RUNTIME_MSG': ''})
  361. self.write_to_tmpfile('autosign_thread_pid', str(t.ep.pid))
  362. return t
  363. def wait_loop_start(self):
  364. import threading
  365. threading.Thread(target=self._wait_loop_start, name='Autosign wait loop').start()
  366. time.sleep(0.1) # try to ensure test output is displayed before next test starts
  367. return 'silent'
  368. def wait_loop_kill(self):
  369. self.spawn('', msg_only=True)
  370. pid = int(self.read_from_tmpfile('autosign_thread_pid'))
  371. self.delete_tmpfile('autosign_thread_pid')
  372. from signal import SIGTERM
  373. imsg(purple(f'Killing autosign wait loop [PID {pid}]'))
  374. try:
  375. os.kill(pid, SIGTERM)
  376. except:
  377. imsg(yellow(f'{pid}: no such process'))
  378. return 'ok'
  379. def _wait_signed(self, desc):
  380. oqmsg_r(gray(f'→ offline wallet{"s" if desc.endswith("s") else ""} waiting for {desc}'))
  381. assert not self.asi.device_inserted, f'‘{self.asi.dev_label}’ is inserted!'
  382. assert not self.asi.mountpoint.is_mount(), f'‘{self.asi.mountpoint}’ is mounted!'
  383. self.insert_device()
  384. while True:
  385. oqmsg_r(gray('.'))
  386. if self.asi.mountpoint.is_mount():
  387. oqmsg_r(gray(' signing '))
  388. break
  389. time.sleep(0.1)
  390. while True:
  391. oqmsg_r(gray('>'))
  392. if not self.asi.mountpoint.is_mount():
  393. oqmsg(gray(' done'))
  394. break
  395. time.sleep(0.1)
  396. imsg('')
  397. self.remove_device()
  398. return 'ok'
  399. def insert_device_online(self):
  400. return self.insert_device(asi='asi_online')
  401. def remove_device_online(self):
  402. return self.remove_device(asi='asi_online')
  403. def do_mount_online(self, *args, **kwargs):
  404. return self._mount_ops('asi_online', 'do_mount', *args, **kwargs)
  405. def do_umount_online(self, *args, **kwargs):
  406. return self._mount_ops('asi_online', 'do_umount', *args, **kwargs)
  407. async def txview(self):
  408. self.spawn('', msg_only=True)
  409. self.insert_device()
  410. self.do_mount()
  411. src = Path(self.asi.txauto_dir)
  412. from mmgen.tx import CompletedTX
  413. txs = sorted(
  414. [await CompletedTX(cfg=cfg, filename=path, quiet_open=True) for path in sorted(src.iterdir())],
  415. key = lambda x: x.timestamp)
  416. for tx in txs:
  417. imsg(blue(f'\nViewing ‘{tx.infile.name}’:'))
  418. out = tx.info.format(terse=True)
  419. imsg(indent(out, indent=' '))
  420. self.do_umount()
  421. self.remove_device()
  422. return 'ok'
  423. class CmdTestAutosign(CmdTestAutosignBase):
  424. 'autosigning transactions for all supported coins'
  425. coins = ['btc', 'bch', 'ltc', 'eth']
  426. daemon_coins = ['btc', 'bch', 'ltc']
  427. txfile_coins = ['btc', 'bch', 'ltc', 'eth', 'mm1', 'etc']
  428. have_online = False
  429. live = False
  430. simulate_led = True
  431. no_insert_check = True
  432. filedir_map = (
  433. ('btc', ''),
  434. ('bch', ''),
  435. ('ltc', 'litecoin'),
  436. ('eth', 'ethereum'),
  437. ('mm1', 'ethereum'),
  438. ('etc', 'ethereum_classic'),
  439. )
  440. cmd_group = (
  441. ('start_daemons', 'starting daemons'),
  442. ('copy_tx_files', 'copying transaction files'),
  443. ('gen_key', 'generating key'),
  444. ('create_dfl_wallet', 'creating default MMGen wallet'),
  445. ('bad_opt1', 'running ‘mmgen-autosign’ with --seed-len in invalid context'),
  446. ('bad_opt2', 'running ‘mmgen-autosign’ with --mnemonic-fmt in invalid context'),
  447. ('bad_opt3', 'running ‘mmgen-autosign’ with --led in invalid context'),
  448. ('run_setup_dfl_wallet', 'running ‘autosign setup’ (with default wallet)'),
  449. ('sign_quiet', 'signing transactions (--quiet)'),
  450. ('remove_signed_txfiles', 'removing signed transaction files'),
  451. ('run_setup_bip39', 'running ‘autosign setup’ (BIP39 mnemonic)'),
  452. ('create_bad_txfiles', 'creating bad transaction files'),
  453. ('sign_full_summary', 'signing transactions (--full-summary)'),
  454. ('remove_signed_txfiles_btc', 'removing transaction files (BTC only)'),
  455. ('remove_bad_txfiles', 'removing bad transaction files'),
  456. ('sign_led', 'signing transactions (--led - BTC files only)'),
  457. ('remove_signed_txfiles', 'removing signed transaction files'),
  458. ('sign_stealth_led', 'signing transactions (--stealth-led)'),
  459. ('remove_signed_txfiles', 'removing signed transaction files'),
  460. ('copy_msgfiles', 'copying message files'),
  461. ('sign_quiet_msg', 'signing transactions and messages (--quiet)'),
  462. ('remove_signed_txfiles', 'removing signed transaction files'),
  463. ('create_bad_txfiles2', 'creating bad transaction files'),
  464. ('remove_signed_msgfiles', 'removing signed message files'),
  465. ('create_invalid_msgfile', 'creating invalid message file'),
  466. ('sign_full_summary_msg', 'signing transactions and messages (--full-summary)'),
  467. ('remove_invalid_msgfile', 'removing invalid message file'),
  468. ('remove_bad_txfiles2', 'removing bad transaction files'),
  469. ('sign_no_unsigned', 'signing transactions and messages (nothing to sign)'),
  470. ('sign_no_unsigned_xmr', 'signing transactions and messages (nothing to sign, with XMR)'),
  471. ('sign_no_unsigned_xmronly', 'signing transactions and messages (nothing to sign, XMR-only)'),
  472. ('wipe_key', 'wiping the wallet encryption key'),
  473. ('stop_daemons', 'stopping daemons'),
  474. ('sign_bad_no_daemon', 'signing transactions (error, no daemons running)'),
  475. )
  476. def __init__(self, trunner, cfgs, spawn):
  477. super().__init__(trunner, cfgs, spawn)
  478. if trunner is None:
  479. return
  480. if self.live and not cfg.exact_output:
  481. die(1, red('autosign_live tests must be run with --exact-output enabled!'))
  482. if self.no_insert_check:
  483. self.opts.append('--no-insert-check')
  484. self.tx_file_ops('set_count') # initialize self.tx_count here so we can resume anywhere
  485. self.bad_tx_count = 0
  486. def gen_msg_fns():
  487. fmap = dict(self.filedir_map)
  488. for coin in self.coins:
  489. if coin == 'xmr':
  490. continue
  491. sdir = os.path.join('test', 'ref', fmap[coin])
  492. for fn in os.listdir(sdir):
  493. if fn.endswith(f'[{coin.upper()}].rawmsg.json'):
  494. yield os.path.join(sdir, fn)
  495. self.ref_msgfiles = tuple(gen_msg_fns())
  496. self.good_msg_count = 0
  497. self.bad_msg_count = 0
  498. if self.simulate_led:
  499. LEDControl.create_dummy_control_files()
  500. db = LEDControl.boards['dummy']
  501. usrgrp = {'linux': 'root:root', 'darwin': 'root:wheel'}[sys.platform]
  502. for fn in (db.status, db.trigger): # trigger the auto-chmod feature
  503. run(f'sudo chmod 644 {fn}'.split(), check=True)
  504. run(f'sudo chown {usrgrp} {fn}'.split(), check=True)
  505. self.have_dummy_control_files = True
  506. self.spawn_env['MMGEN_TEST_SUITE_AUTOSIGN_LED_SIMULATE'] = '1'
  507. def gen_key(self):
  508. self.insert_device()
  509. t = self.spawn('mmgen-autosign', self.opts + ['gen_key'])
  510. t.expect_getend('Wrote key file ')
  511. t.read()
  512. self.remove_device()
  513. return t
  514. def create_dfl_wallet(self):
  515. t = self.spawn('mmgen-walletconv', [
  516. f'--outdir={cfg.data_dir}',
  517. '--usr-randchars=0', '--quiet', '--hash-preset=1', '--label=foo',
  518. 'test/ref/98831F3A.hex'
  519. ]
  520. )
  521. t.passphrase_new('new MMGen wallet', 'abc')
  522. t.written_to_file('MMGen wallet')
  523. return t
  524. def _bad_opt(self, cmdline, expect):
  525. t = self.spawn('mmgen-autosign', ['--coins=btc'] + cmdline, exit_val=1)
  526. t.expect(expect)
  527. return t
  528. def bad_opt1(self):
  529. return self._bad_opt(['--seed-len=128'], 'makes sense')
  530. def bad_opt2(self):
  531. return self._bad_opt(['--mnemonic-fmt=bip39', 'wait'], 'makes sense')
  532. def bad_opt3(self):
  533. return self._bad_opt(['--led', 'gen_key'], 'makes no sense')
  534. def run_setup_dfl_wallet(self):
  535. return self.run_setup(mn_type='default', use_dfl_wallet=True)
  536. def run_setup_bip39(self):
  537. from mmgen.cfgfile import mmgen_cfg_file
  538. fn = mmgen_cfg_file(cfg, 'usr').fn
  539. old_data = mmgen_cfg_file(cfg, 'usr').get_data(fn)
  540. new_data = [d.replace('bip39:fixed', 'bip39:full')[2:]
  541. if d.startswith('# mnemonic_entry_modes') else d for d in old_data]
  542. with open(fn, 'w') as fh:
  543. fh.write('\n'.join(new_data) + '\n')
  544. t = self.run_setup(
  545. mn_type = 'bip39',
  546. seed_len = 256,
  547. usr_entry_modes = True)
  548. with open(fn, 'w') as fh:
  549. fh.write('\n'.join(old_data) + '\n')
  550. return t
  551. def copy_tx_files(self):
  552. self.spawn('', msg_only=True)
  553. return self.tx_file_ops('copy')
  554. def remove_signed_txfiles(self):
  555. self.tx_file_ops('remove_signed')
  556. return 'skip'
  557. def remove_signed_txfiles_btc(self):
  558. self.tx_file_ops('remove_signed', txfile_coins=['btc'])
  559. return 'skip'
  560. def tx_file_ops(self, op, txfile_coins=[]):
  561. assert op in ('copy', 'set_count', 'remove_signed')
  562. from .ct_ref import CmdTestRef
  563. def gen():
  564. d = CmdTestRef.sources['ref_tx_file']
  565. dirmap = [e for e in self.filedir_map if e[0] in (txfile_coins or self.txfile_coins)]
  566. for coin, coindir in dirmap:
  567. for network in (0, 1):
  568. fn = d[coin][network]
  569. if fn:
  570. yield (coindir, fn)
  571. data = list(gen()) + [('', '25EFA3[2.34].testnet.rawtx')] # TX with 2 non-MMGen outputs
  572. self.tx_count = len(data)
  573. if op == 'set_count':
  574. return
  575. self.insert_device()
  576. silence()
  577. self.do_mount(verbose=cfg.verbose or cfg.exact_output)
  578. end_silence()
  579. for coindir, fn in data:
  580. src = joinpath(ref_dir, coindir, fn)
  581. if cfg.debug_utf8:
  582. ext = '.testnet.rawtx' if fn.endswith('.testnet.rawtx') else '.rawtx'
  583. fn = fn[:-len(ext)] + '-α' + ext
  584. target = joinpath(self.asi.tx_dir, fn)
  585. if not op == 'remove_signed':
  586. shutil.copyfile(src, target)
  587. try:
  588. os.unlink(target.replace('.rawtx', '.sigtx'))
  589. except:
  590. pass
  591. self.do_umount()
  592. self.remove_device()
  593. return 'ok'
  594. def create_bad_txfiles(self):
  595. return self.bad_txfiles('create')
  596. def remove_bad_txfiles(self):
  597. return self.bad_txfiles('remove')
  598. create_bad_txfiles2 = create_bad_txfiles
  599. remove_bad_txfiles2 = remove_bad_txfiles
  600. def bad_txfiles(self, op):
  601. self.insert_device()
  602. self.do_mount()
  603. # create or delete 2 bad tx files
  604. self.spawn('', msg_only=True)
  605. fns = [joinpath(self.asi.tx_dir, f'bad{n}.rawtx') for n in (1, 2)]
  606. if op == 'create':
  607. for fn in fns:
  608. with open(fn, 'w') as fp:
  609. fp.write('bad tx data\n')
  610. self.bad_tx_count = 2
  611. elif op == 'remove':
  612. for fn in fns:
  613. try:
  614. os.unlink(fn)
  615. except:
  616. pass
  617. self.bad_tx_count = 0
  618. self.do_umount()
  619. self.remove_device()
  620. return 'ok'
  621. def copy_msgfiles(self):
  622. return self.msgfile_ops('copy')
  623. def remove_signed_msgfiles(self):
  624. return self.msgfile_ops('remove_signed')
  625. def create_invalid_msgfile(self):
  626. return self.msgfile_ops('create_invalid')
  627. def remove_invalid_msgfile(self):
  628. return self.msgfile_ops('remove_invalid')
  629. def msgfile_ops(self, op):
  630. self.spawn('', msg_only=True)
  631. destdir = joinpath(self.asi.mountpoint, 'msg')
  632. self.insert_device()
  633. self.do_mount()
  634. os.makedirs(destdir, exist_ok=True)
  635. if op.endswith('_invalid'):
  636. fn = os.path.join(destdir, 'DEADBE[BTC].rawmsg.json')
  637. if op == 'create_invalid':
  638. with open(fn, 'w') as fp:
  639. fp.write('bad data\n')
  640. self.bad_msg_count += 1
  641. elif op == 'remove_invalid':
  642. os.unlink(fn)
  643. self.bad_msg_count -= 1
  644. else:
  645. for fn in self.ref_msgfiles:
  646. if op == 'copy':
  647. if os.path.basename(fn) == 'ED405C[BTC].rawmsg.json': # contains bad Seed ID
  648. self.bad_msg_count += 1
  649. else:
  650. self.good_msg_count += 1
  651. imsg(f'Copying: {fn} -> {destdir}')
  652. shutil.copy2(fn, destdir)
  653. elif op == 'remove_signed':
  654. os.unlink(os.path.join(destdir, os.path.basename(fn).replace('rawmsg', 'sigmsg')))
  655. self.do_umount()
  656. self.remove_device()
  657. return 'ok'
  658. def do_sign(self, args=[], have_msg=False, exc_exit_val=None, expect_str=None):
  659. tx_desc = Signable.transaction.desc
  660. self.insert_device()
  661. def do_return():
  662. if expect_str:
  663. t.expect(expect_str)
  664. t.read()
  665. self.remove_device()
  666. imsg('')
  667. return t
  668. t = self.spawn(
  669. 'mmgen-autosign',
  670. self.opts + args,
  671. exit_val = exc_exit_val or (1 if self.bad_tx_count or (have_msg and self.bad_msg_count) else None))
  672. if exc_exit_val:
  673. return do_return()
  674. t.expect(
  675. f'{self.tx_count} {tx_desc}{suf(self.tx_count)} signed' if self.tx_count else
  676. f'No unsigned {tx_desc}s')
  677. if self.bad_tx_count:
  678. t.expect(f'{self.bad_tx_count} {tx_desc}{suf(self.bad_tx_count)} failed to sign')
  679. if have_msg:
  680. t.expect(
  681. f'{self.good_msg_count} message file{suf(self.good_msg_count)}{{0,1}} signed'
  682. if self.good_msg_count else
  683. 'No unsigned message files', regex=True)
  684. if self.bad_msg_count:
  685. t.expect(
  686. f'{self.bad_msg_count} message file{suf(self.bad_msg_count)}{{0,1}} failed to sign',
  687. regex = True)
  688. return do_return()
  689. def sign_quiet(self):
  690. return self.do_sign(['--quiet'])
  691. def sign_full_summary(self):
  692. return self.do_sign(['--full-summary'])
  693. def sign_led(self):
  694. return self.do_sign(['--quiet', '--led'])
  695. def sign_stealth_led(self):
  696. return self.do_sign(['--quiet', '--stealth-led'])
  697. def sign_quiet_msg(self):
  698. return self.do_sign(['--quiet'], have_msg=True)
  699. def sign_full_summary_msg(self):
  700. return self.do_sign(['--full-summary'], have_msg=True)
  701. def sign_bad_no_daemon(self):
  702. return self.do_sign(exc_exit_val=2, expect_str='listening on the correct port')
  703. def sign_no_unsigned(self):
  704. return self._sign_no_unsigned(
  705. coins = 'BTC',
  706. present = ['non_xmr_signables'],
  707. absent = ['xmr_signables'])
  708. def sign_no_unsigned_xmr(self):
  709. if self.coins == ['btc']:
  710. return 'skip'
  711. return self._sign_no_unsigned(
  712. coins = 'XMR,BTC',
  713. present = ['xmr_signables', 'non_xmr_signables'])
  714. def sign_no_unsigned_xmronly(self):
  715. if self.coins == ['btc']:
  716. return 'skip'
  717. return self._sign_no_unsigned(
  718. coins = 'XMR',
  719. present = ['xmr_signables'],
  720. absent = ['non_xmr_signables'])
  721. def _sign_no_unsigned(self, coins, present=[], absent=[]):
  722. self.insert_device()
  723. t = self.spawn('mmgen-autosign', ['--quiet', '--no-insert-check', f'--coins={coins}'])
  724. res = t.read()
  725. self.remove_device()
  726. for signable_list in present:
  727. for signable_clsname in getattr(Signable, signable_list):
  728. desc = getattr(Signable, signable_clsname).desc
  729. assert f'No unsigned {desc}s' in res, f'‘No unsigned {desc}s’ missing in output'
  730. for signable_list in absent:
  731. for signable_clsname in getattr(Signable, signable_list):
  732. desc = getattr(Signable, signable_clsname).desc
  733. assert not f'No unsigned {desc}s' in res, f'‘No unsigned {desc}s’ should be absent in output'
  734. return t
  735. def wipe_key(self):
  736. self.insert_device()
  737. t = self.spawn('mmgen-autosign', ['--quiet', '--no-insert-check', 'wipe_key'])
  738. t.expect('Shredding')
  739. t.read()
  740. self.remove_device()
  741. return t
  742. class CmdTestAutosignBTC(CmdTestAutosign):
  743. 'autosigning BTC transactions'
  744. coins = ['btc']
  745. daemon_coins = ['btc']
  746. txfile_coins = ['btc']
  747. class CmdTestAutosignLive(CmdTestAutosignBTC):
  748. 'live autosigning BTC transactions'
  749. live = True
  750. simulate_led = False
  751. no_insert_check = False
  752. cmd_group = (
  753. ('start_daemons', 'starting daemons'),
  754. ('copy_tx_files', 'copying transaction files'),
  755. ('gen_key', 'generating key'),
  756. ('run_setup_mmgen', 'running ‘autosign setup’ (MMGen native mnemonic)'),
  757. ('sign_live', 'signing transactions'),
  758. ('create_bad_txfiles', 'creating bad transaction files'),
  759. ('sign_live_led', 'signing transactions (--led)'),
  760. ('remove_bad_txfiles', 'removing bad transaction files'),
  761. ('sign_live_stealth_led', 'signing transactions (--stealth-led)'),
  762. ('stop_daemons', 'stopping daemons'),
  763. )
  764. def __init__(self, trunner, cfgs, spawn):
  765. super().__init__(trunner, cfgs, spawn)
  766. if trunner is None:
  767. return
  768. try:
  769. LEDControl(enabled=True, simulate=self.simulate_led)
  770. except Exception as e:
  771. msg(str(e))
  772. die(2, 'LEDControl initialization failed')
  773. def run_setup_mmgen(self):
  774. return self.run_setup(mn_type='mmgen', use_dfl_wallet=None)
  775. def sign_live(self):
  776. return self.do_sign_live()
  777. def sign_live_led(self):
  778. return self.do_sign_live(['--led'], 'The LED should start blinking slowly now')
  779. def sign_live_stealth_led(self):
  780. return self.do_sign_live(['--stealth-led'], 'You should see no LED activity now')
  781. def do_sign_live(self, led_opts=None, led_msg=None):
  782. def prompt_remove():
  783. omsg_r(orange('\nExtract removable device and then hit ENTER '))
  784. input()
  785. def prompt_insert_sign(t):
  786. omsg(orange(insert_msg))
  787. t.expect(f'{self.tx_count} non-automount transactions signed')
  788. if self.bad_tx_count:
  789. t.expect(f'{self.bad_tx_count} non-automount transactions failed to sign')
  790. t.expect('Waiting')
  791. if led_opts:
  792. opts_msg = '‘' + ' '.join(led_opts) + '’'
  793. info_msg = 'Running ‘mmgen-autosign wait’ with {}. {}'.format(opts_msg, led_msg)
  794. insert_msg = 'Insert removable device and watch for fast LED activity during signing'
  795. else:
  796. opts_msg = 'no LED'
  797. info_msg = 'Running ‘mmgen-autosign wait’'
  798. insert_msg = 'Insert removable device '
  799. self.spawn('', msg_only=True)
  800. self.do_umount()
  801. prompt_remove()
  802. omsg('\n' + cyan(indent(info_msg)))
  803. t = self.spawn(
  804. 'mmgen-autosign',
  805. self.opts + (led_opts or []) + ['--quiet', '--no-summary', 'wait'],
  806. no_msg = True,
  807. exit_val = 1)
  808. if not cfg.exact_output:
  809. omsg('')
  810. prompt_insert_sign(t)
  811. self.do_mount() # race condition due to device insertion detection
  812. self.remove_signed_txfiles()
  813. self.do_umount()
  814. imsg(purple('\nKilling wait loop!'))
  815. t.kill(2) # 2 = SIGINT
  816. if self.simulate_led and led_opts:
  817. t.expect('Stopping LED')
  818. return t
  819. class CmdTestAutosignLiveSimulate(CmdTestAutosignLive):
  820. 'live autosigning BTC transactions with simulated LED support'
  821. simulate_led = True