ts_autosign.py 14 KB

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