ct_autosign.py 25 KB

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