ct_autosign.py 27 KB

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