ct_autosign.py 28 KB

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