ct_autosign.py 28 KB

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