ts_autosign.py 15 KB

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