ts_autosign.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2023 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.test_py_d.ts_autosign: Autosign tests for the test.py test suite
  20. """
  21. import os,shutil
  22. from subprocess import run
  23. from pathlib import Path
  24. from mmgen.cfg import gc
  25. from mmgen.color import red,green,blue,purple
  26. from mmgen.util import msg,suf,die
  27. from mmgen.led import LEDControl
  28. from mmgen.autosign import Autosign,AutosignConfig
  29. from ..include.common import (
  30. cfg,
  31. omsg,
  32. omsg_r,
  33. start_test_daemons,
  34. stop_test_daemons,
  35. joinpath,
  36. imsg,
  37. read_from_file
  38. )
  39. from .common import ref_dir,dfl_words_file,dfl_bip39_file
  40. from .ts_base import TestSuiteBase
  41. from .input import stealth_mnemonic_entry
  42. filedir_map = (
  43. ('btc',''),
  44. ('bch',''),
  45. ('ltc','litecoin'),
  46. ('eth','ethereum'),
  47. ('mm1','ethereum'),
  48. ('etc','ethereum_classic'),
  49. )
  50. def init_led(simulate):
  51. try:
  52. cf = LEDControl(enabled=True,simulate=simulate)
  53. except Exception as e:
  54. msg(str(e))
  55. die(2,'LEDControl initialization failed')
  56. for fn in (cf.board.status,cf.board.trigger):
  57. if fn:
  58. run(['sudo','chmod','0666',fn],check=True)
  59. def check_mountpoint(asi):
  60. if not asi.mountpoint.is_mount():
  61. try:
  62. run(['mount',asi.mountpoint],check=True)
  63. imsg(f'Mounted {asi.mountpoint}')
  64. except:
  65. die(2,f'Could not mount {asi.mountpoint}! Exiting')
  66. if not asi.tx_dir.is_dir():
  67. die(2,f'Directory {asi.tx_dir} does not exist! Exiting')
  68. def do_mount(mountpoint):
  69. if not os.path.ismount(mountpoint):
  70. try:
  71. run(['mount',mountpoint],check=True)
  72. except:
  73. pass
  74. def do_umount(mountpoint):
  75. if os.path.ismount(mountpoint):
  76. try:
  77. run(['umount',mountpoint],check=True)
  78. except:
  79. pass
  80. class TestSuiteAutosignBase(TestSuiteBase):
  81. networks = ('btc',)
  82. tmpdir_nums = [18]
  83. color = True
  84. mountpoint_basename = 'mmgen_autosign'
  85. no_insert_check = True
  86. win_skip = True
  87. def __init__(self,trunner,cfgs,spawn):
  88. super().__init__(trunner,cfgs,spawn)
  89. if trunner is None:
  90. return
  91. self.network_ids = [c+'_tn' for c in self.daemon_coins] + self.daemon_coins
  92. if not self.live:
  93. self.wallet_dir = Path( self.tmpdir, 'dev.shm.autosign' )
  94. self.asi = Autosign(
  95. AutosignConfig({
  96. 'coins': ','.join(self.coins),
  97. 'mountpoint': (
  98. None if self.live else
  99. os.path.join(self.tmpdir,self.mountpoint_basename)
  100. ),
  101. 'wallet_dir': None if self.live else self.wallet_dir,
  102. 'test_suite': True,
  103. 'test_suite_xmr_autosign': self.name == 'TestSuiteXMRAutosign',
  104. })
  105. )
  106. self.mountpoint = self.asi.mountpoint
  107. if self.simulate and not cfg.exact_output:
  108. die(1,red('This command must be run with --exact-output enabled!'))
  109. if self.simulate or not self.live:
  110. LEDControl.create_dummy_control_files()
  111. self.spawn_env['MMGEN_TEST_SUITE_AUTOSIGN_LED_SIMULATE'] = '1'
  112. self.opts = ['--coins='+','.join(self.coins)]
  113. if self.live:
  114. check_mountpoint(self.asi)
  115. init_led(self.simulate)
  116. else:
  117. self.asi.tx_dir.mkdir(parents=True,exist_ok=True) # creates mountpoint
  118. self.wallet_dir.mkdir(parents=True,exist_ok=True)
  119. self.opts.extend([
  120. f'--mountpoint={self.mountpoint}',
  121. f'--wallet-dir={self.wallet_dir}',
  122. ])
  123. if self.no_insert_check:
  124. self.opts.append('--no-insert-check')
  125. self.tx_file_ops('set_count') # initialize tx_count here so we can resume anywhere
  126. def gen_msg_fns():
  127. fmap = dict(filedir_map)
  128. for coin in self.coins:
  129. if coin == 'xmr':
  130. continue
  131. sdir = os.path.join('test','ref',fmap[coin])
  132. for fn in os.listdir(sdir):
  133. if fn.endswith(f'[{coin.upper()}].rawmsg.json'):
  134. yield os.path.join(sdir,fn)
  135. self.ref_msgfiles = tuple(gen_msg_fns())
  136. self.good_msg_count = 0
  137. self.bad_msg_count = 0
  138. def __del__(self):
  139. if gc.platform == 'win' or self.tr is None:
  140. return
  141. if self.simulate or not self.live:
  142. LEDControl.delete_dummy_control_files()
  143. def start_daemons(self):
  144. self.spawn('',msg_only=True)
  145. start_test_daemons(*self.network_ids)
  146. return 'ok'
  147. def stop_daemons(self):
  148. self.spawn('',msg_only=True)
  149. stop_test_daemons(*self.network_ids)
  150. return 'ok'
  151. def gen_key(self):
  152. t = self.spawn( 'mmgen-autosign', self.opts + ['gen_key'] )
  153. t.expect_getend('Wrote key file ')
  154. return t
  155. def create_dfl_wallet(self):
  156. t = self.spawn( 'mmgen-walletconv', [
  157. f'--outdir={cfg.data_dir}',
  158. '--usr-randchars=0', '--quiet', '--hash-preset=1', '--label=foo',
  159. 'test/ref/98831F3A.hex'
  160. ]
  161. )
  162. t.passphrase_new('new MMGen wallet','abc')
  163. t.written_to_file('MMGen wallet')
  164. return t
  165. def run_setup_dfl_wallet(self):
  166. return self.run_setup(mn_type='default',use_dfl_wallet=True)
  167. def run_setup_bip39(self):
  168. return self.run_setup(mn_type='bip39')
  169. def run_setup(self,mn_type=None,mn_file=None,use_dfl_wallet=False):
  170. mn_desc = mn_type or 'default'
  171. mn_type = mn_type or 'mmgen'
  172. t = self.spawn(
  173. 'mmgen-autosign',
  174. self.opts +
  175. ([] if mn_desc == 'default' else [f'--mnemonic-fmt={mn_type}']) +
  176. ['setup'] )
  177. if use_dfl_wallet:
  178. t.expect( 'Use default wallet for autosigning? (Y/n): ', 'y' )
  179. t.passphrase( 'MMGen wallet', 'abc' )
  180. else:
  181. if use_dfl_wallet is not None: # None => no dfl wallet present
  182. t.expect( 'Use default wallet for autosigning? (Y/n): ', 'n' )
  183. mn_file = mn_file or { 'mmgen': dfl_words_file, 'bip39': dfl_bip39_file }[mn_type]
  184. mn = read_from_file(mn_file).strip().split()
  185. from mmgen.mn_entry import mn_entry
  186. entry_mode = 'full'
  187. mne = mn_entry( cfg, mn_type, entry_mode )
  188. t.expect('words: ',{ 12:'1', 18:'2', 24:'3' }[len(mn)])
  189. t.expect('OK? (Y/n): ','\n')
  190. t.expect('Type a number.*: ',str(mne.entry_modes.index(entry_mode)+1),regex=True)
  191. stealth_mnemonic_entry(t,mne,mn,entry_mode)
  192. t.written_to_file('Autosign wallet')
  193. return t
  194. def copy_tx_files(self):
  195. self.spawn('',msg_only=True)
  196. return self.tx_file_ops('copy')
  197. def remove_signed_txfiles(self):
  198. self.tx_file_ops('remove_signed')
  199. return 'skip'
  200. def remove_signed_txfiles_btc(self):
  201. self.tx_file_ops('remove_signed',txfile_coins=['btc'])
  202. return 'skip'
  203. def tx_file_ops(self,op,txfile_coins=[]):
  204. assert op in ('copy','set_count','remove_signed')
  205. fdata = [e for e in filedir_map if e[0] in (txfile_coins or self.txfile_coins)]
  206. from .ts_ref import TestSuiteRef
  207. tfns = [TestSuiteRef.sources['ref_tx_file'][c][1] for c,d in fdata] + \
  208. [TestSuiteRef.sources['ref_tx_file'][c][0] for c,d in fdata] + \
  209. ['25EFA3[2.34].testnet.rawtx'] # TX with 2 non-MMGen outputs
  210. self.tx_count = len([fn for fn in tfns if fn])
  211. if op == 'set_count':
  212. return
  213. tfs = [joinpath(ref_dir,d[1],fn) for d,fn in zip(fdata+fdata+[('btc','')],tfns)]
  214. for f,fn in zip(tfs,tfns):
  215. if fn: # use empty fn to skip file
  216. if cfg.debug_utf8:
  217. ext = '.testnet.rawtx' if fn.endswith('.testnet.rawtx') else '.rawtx'
  218. fn = fn[:-len(ext)] + '-α' + ext
  219. target = joinpath(self.mountpoint,'tx',fn)
  220. if not op == 'remove_signed':
  221. shutil.copyfile(f,target)
  222. try:
  223. os.unlink(target.replace('.rawtx','.sigtx'))
  224. except:
  225. pass
  226. return 'ok'
  227. def create_bad_txfiles(self):
  228. return self.bad_txfiles('create')
  229. def remove_bad_txfiles(self):
  230. return self.bad_txfiles('remove')
  231. def bad_txfiles(self,op):
  232. if self.live:
  233. do_mount(self.mountpoint)
  234. # create or delete 2 bad tx files
  235. self.spawn('',msg_only=True)
  236. fns = [joinpath(self.mountpoint,'tx',f'bad{n}.rawtx') for n in (1,2)]
  237. if op == 'create':
  238. for fn in fns:
  239. with open(fn,'w') as fp:
  240. fp.write('bad tx data\n')
  241. self.bad_tx_count = 2
  242. elif op == 'remove':
  243. for fn in fns:
  244. try:
  245. os.unlink(fn)
  246. except:
  247. pass
  248. self.bad_tx_count = 0
  249. return 'ok'
  250. def copy_msgfiles(self):
  251. return self.msgfile_ops('copy')
  252. def remove_signed_msgfiles(self):
  253. return self.msgfile_ops('remove_signed')
  254. def create_invalid_msgfile(self):
  255. return self.msgfile_ops('create_invalid')
  256. def remove_invalid_msgfile(self):
  257. return self.msgfile_ops('remove_invalid')
  258. def msgfile_ops(self,op):
  259. self.spawn('',msg_only=True)
  260. destdir = joinpath(self.mountpoint,'msg')
  261. os.makedirs(destdir,exist_ok=True)
  262. if op.endswith('_invalid'):
  263. fn = os.path.join(destdir,'DEADBE[BTC].rawmsg.json')
  264. if op == 'create_invalid':
  265. with open(fn,'w') as fp:
  266. fp.write('bad data\n')
  267. self.bad_msg_count += 1
  268. elif op == 'remove_invalid':
  269. os.unlink(fn)
  270. self.bad_msg_count -= 1
  271. else:
  272. for fn in self.ref_msgfiles:
  273. if op == 'copy':
  274. if os.path.basename(fn) == 'ED405C[BTC].rawmsg.json': # contains bad Seed ID
  275. self.bad_msg_count += 1
  276. else:
  277. self.good_msg_count += 1
  278. imsg(f'Copying: {fn} -> {destdir}')
  279. shutil.copy2(fn,destdir)
  280. elif op == 'remove_signed':
  281. os.unlink(os.path.join( destdir, os.path.basename(fn).replace('rawmsg','sigmsg') ))
  282. return 'ok'
  283. def do_sign(self,args,have_msg=False,tx_name='transaction'):
  284. t = self.spawn('mmgen-autosign', self.opts + args )
  285. t.expect(
  286. f'{self.tx_count} {tx_name}{suf(self.tx_count)} signed' if self.tx_count else
  287. 'No unsigned transactions' )
  288. if self.bad_tx_count:
  289. t.expect(f'{self.bad_tx_count} {tx_name}{suf(self.bad_tx_count)} failed to sign')
  290. t.req_exit_val = 1
  291. if have_msg:
  292. t.expect(
  293. f'{self.good_msg_count} message file{suf(self.good_msg_count)}{{0,1}} signed'
  294. if self.good_msg_count else
  295. 'No unsigned message files', regex=True )
  296. if self.bad_msg_count:
  297. t.expect(
  298. f'{self.bad_msg_count} message file{suf(self.bad_msg_count)}{{0,1}} failed to sign',
  299. regex = True )
  300. t.req_exit_val = 1
  301. if 'wait' in args:
  302. t.expect('Waiting')
  303. imsg(purple('\nKilling wait loop!'))
  304. t.kill(2)
  305. t.req_exit_val = 1
  306. else:
  307. t.read()
  308. imsg('')
  309. return t
  310. class TestSuiteAutosign(TestSuiteAutosignBase):
  311. 'autosigning transactions for all supported coins'
  312. coins = ['btc','bch','ltc','eth']
  313. daemon_coins = ['btc','bch','ltc']
  314. txfile_coins = ['btc','bch','ltc','eth','mm1','etc']
  315. live = False
  316. simulate = False
  317. bad_tx_count = 0
  318. cmd_group = (
  319. ('start_daemons', 'starting daemons'),
  320. ('copy_tx_files', 'copying transaction files'),
  321. ('gen_key', 'generating key'),
  322. ('create_dfl_wallet', 'creating default MMGen wallet'),
  323. ('run_setup_dfl_wallet', 'running ‘autosign setup’ (with default wallet)'),
  324. ('sign_quiet', 'signing transactions (--quiet)'),
  325. ('remove_signed_txfiles', 'removing signed transaction files'),
  326. ('run_setup_bip39', 'running ‘autosign setup’ (BIP39 mnemonic)'),
  327. ('create_bad_txfiles', 'creating bad transaction files'),
  328. ('sign_full_summary', 'signing transactions (--full-summary)'),
  329. ('remove_signed_txfiles_btc','removing transaction files (BTC only)'),
  330. ('remove_bad_txfiles', 'removing bad transaction files'),
  331. ('sign_led', 'signing transactions (--led - BTC files only)'),
  332. ('remove_signed_txfiles', 'removing signed transaction files'),
  333. ('sign_stealth_led', 'signing transactions (--stealth-led)'),
  334. ('remove_signed_txfiles', 'removing signed transaction files'),
  335. ('copy_msgfiles', 'copying message files'),
  336. ('sign_quiet_msg', 'signing transactions and messages (--quiet)'),
  337. ('remove_signed_txfiles', 'removing signed transaction files'),
  338. ('create_bad_txfiles', 'creating bad transaction files'),
  339. ('remove_signed_msgfiles', 'removing signed message files'),
  340. ('create_invalid_msgfile', 'creating invalid message file'),
  341. ('sign_full_summary_msg', 'signing transactions and messages (--full-summary)'),
  342. ('remove_invalid_msgfile', 'removing invalid message file'),
  343. ('remove_bad_txfiles', 'removing bad transaction files'),
  344. ('sign_no_unsigned_msg', 'signing transactions and messages (nothing to sign)'),
  345. ('stop_daemons', 'stopping daemons'),
  346. )
  347. def sign_quiet(self):
  348. return self.do_sign(['--quiet','wait'])
  349. def sign_full_summary(self):
  350. return self.do_sign(['--full-summary','wait'])
  351. def sign_led(self):
  352. return self.do_sign(['--quiet','--led'])
  353. def sign_stealth_led(self):
  354. return self.do_sign(['--quiet','--stealth-led','wait'])
  355. def sign_quiet_msg(self):
  356. return self.do_sign(['--quiet','wait'],have_msg=True)
  357. def sign_full_summary_msg(self):
  358. return self.do_sign(['--full-summary','wait'],have_msg=True)
  359. def sign_no_unsigned_msg(self):
  360. self.tx_count = 0
  361. self.good_msg_count = 0
  362. self.bad_msg_count = 0
  363. return self.do_sign(['--quiet','wait'],have_msg=True)
  364. class TestSuiteAutosignBTC(TestSuiteAutosign):
  365. 'autosigning BTC transactions'
  366. coins = ['btc']
  367. daemon_coins = ['btc']
  368. txfile_coins = ['btc']
  369. class TestSuiteAutosignLive(TestSuiteAutosignBTC):
  370. 'live autosigning BTC transactions'
  371. live = True
  372. cmd_group = (
  373. ('start_daemons', 'starting daemons'),
  374. ('copy_tx_files', 'copying transaction files'),
  375. ('gen_key', 'generating key'),
  376. ('run_setup_mmgen', 'running ‘autosign setup’ (MMGen native mnemonic)'),
  377. ('sign_live', 'signing transactions'),
  378. ('create_bad_txfiles', 'creating bad transaction files'),
  379. ('sign_live_led', 'signing transactions (--led)'),
  380. ('remove_bad_txfiles', 'removing bad transaction files'),
  381. ('sign_live_stealth_led','signing transactions (--stealth-led)'),
  382. ('stop_daemons', 'stopping daemons'),
  383. )
  384. def run_setup_mmgen(self):
  385. return self.run_setup(mn_type='mmgen',use_dfl_wallet=None)
  386. def sign_live(self):
  387. return self.do_sign_live([])
  388. def sign_live_led(self):
  389. return self.do_sign_live(['--led'])
  390. def sign_live_stealth_led(self):
  391. return self.do_sign_live(['--stealth-led'])
  392. def do_sign_live(self,led_opts):
  393. def prompt_remove():
  394. omsg_r(blue('\nRemove removable device and then hit ENTER '))
  395. input()
  396. def prompt_insert_sign(t):
  397. omsg(blue(insert_msg))
  398. t.expect(f'{self.tx_count} transactions signed')
  399. if self.bad_tx_count:
  400. t.expect(f'{self.bad_tx_count} transactions failed to sign')
  401. t.expect('Waiting')
  402. if led_opts:
  403. opts_msg = "'" + ' '.join(led_opts) + "'"
  404. info_msg = f"Running 'mmgen-autosign wait' with {led_opts[0]}. " + {
  405. '--led': "The LED should start blinking slowly now",
  406. '--stealth-led': "You should see no LED activity now"
  407. }[led_opts[0]]
  408. insert_msg = 'Insert removable device and watch for fast LED activity during signing'
  409. else:
  410. opts_msg = 'no LED'
  411. info_msg = "Running 'mmgen-autosign wait'"
  412. insert_msg = 'Insert removable device '
  413. omsg(purple(f'Running autosign test with {opts_msg}'))
  414. do_umount(self.mountpoint)
  415. prompt_remove()
  416. omsg(green(info_msg))
  417. t = self.spawn(
  418. 'mmgen-autosign',
  419. self.opts + led_opts + ['--quiet','--no-summary','wait'])
  420. if not cfg.exact_output:
  421. omsg('')
  422. prompt_insert_sign(t)
  423. do_mount(self.mountpoint) # race condition due to device insertion detection
  424. self.remove_signed_txfiles()
  425. do_umount(self.mountpoint)
  426. imsg(purple('\nKilling wait loop!'))
  427. t.kill(2) # 2 = SIGINT
  428. t.req_exit_val = 1
  429. if self.simulate and led_opts:
  430. t.expect("Stopping LED")
  431. return t
  432. class TestSuiteAutosignLiveSimulate(TestSuiteAutosignLive):
  433. 'live autosigning BTC transactions with simulated LED support'
  434. simulate = True