ts_autosign.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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. class TestSuiteAutosign(TestSuiteBase):
  32. 'autosigning with BTC, BCH, LTC, ETH and ETC'
  33. networks = ('btc',)
  34. tmpdir_nums = [18]
  35. color = True
  36. cmd_group = (
  37. ('autosign', 'transaction autosigning (BTC,BCH,LTC,ETH,ETC)'),
  38. )
  39. def autosign_live(self):
  40. return self.autosign_btc(live=True)
  41. def autosign_live_simulate(self):
  42. return self.autosign_btc(live=True,simulate=True)
  43. def autosign_btc(self,live=False,simulate=False):
  44. return self.autosign(
  45. coins=['btc'],
  46. daemon_coins=['btc'],
  47. txfiles=['btc'],
  48. txcount=3,
  49. live=live,
  50. simulate=simulate )
  51. # tests everything except mount/unmount
  52. def autosign( self,
  53. coins=['btc','bch','ltc','eth'],
  54. daemon_coins=['btc','bch','ltc'],
  55. txfiles=['btc','bch','ltc','eth','mm1','etc'],
  56. txcount=12,
  57. live=False,
  58. simulate=False):
  59. if self.skip_for_win():
  60. return 'skip'
  61. def gen_key(opts):
  62. if not getattr(self,'key_generated',False):
  63. t = self.spawn('mmgen-autosign',opts+['gen_key'],extra_desc='(gen_key)')
  64. t.expect_getend('Wrote key file ')
  65. t.ok()
  66. self.key_generated = True
  67. def make_wallet(opts,mn_type=None):
  68. mn_desc = mn_type or 'default'
  69. mn_type = mn_type or 'mmgen'
  70. t = self.spawn(
  71. 'mmgen-autosign',
  72. opts +
  73. ([] if mn_desc == 'default' else [f'--mnemonic-fmt={mn_type}']) +
  74. ['setup'],
  75. extra_desc = f'(setup - {mn_desc} mnemonic)' )
  76. t.expect('words: ','3')
  77. t.expect('OK? (Y/n): ','\n')
  78. mn_file = { 'mmgen': dfl_words_file, 'bip39': dfl_bip39_file }[mn_type]
  79. mn = read_from_file(mn_file).strip().split()
  80. from mmgen.mn_entry import mn_entry
  81. entry_mode = 'full'
  82. mne = mn_entry(mn_type,entry_mode)
  83. t.expect('Type a number.*: ',str(mne.entry_modes.index(entry_mode)+1),regex=True)
  84. stealth_mnemonic_entry(t,mne,mn,entry_mode)
  85. wf = t.written_to_file('Autosign wallet')
  86. t.ok()
  87. def copy_files(
  88. mountpoint,
  89. remove_signed_only=False,
  90. include_bad_tx=True,
  91. fdata_in = (('btc',''),
  92. ('bch',''),
  93. ('ltc','litecoin'),
  94. ('eth','ethereum'),
  95. ('mm1','ethereum'),
  96. ('etc','ethereum_classic')) ):
  97. fdata = [e for e in fdata_in if e[0] in txfiles]
  98. from .ts_ref import TestSuiteRef
  99. tfns = [TestSuiteRef.sources['ref_tx_file'][c][1] for c,d in fdata] + \
  100. [TestSuiteRef.sources['ref_tx_file'][c][0] for c,d in fdata] + \
  101. ['25EFA3[2.34].testnet.rawtx'] # TX with 2 non-MMGen outputs
  102. tfs = [joinpath(ref_dir,d[1],fn) for d,fn in zip(fdata+fdata+[('btc','')],tfns)]
  103. for f,fn in zip(tfs,tfns):
  104. if fn: # use empty fn to skip file
  105. if g.debug_utf8:
  106. ext = '.testnet.rawtx' if fn.endswith('.testnet.rawtx') else '.rawtx'
  107. fn = fn[:-len(ext)] + '-α' + ext
  108. target = joinpath(mountpoint,'tx',fn)
  109. remove_signed_only or shutil.copyfile(f,target)
  110. try: os.unlink(target.replace('.rawtx','.sigtx'))
  111. except: pass
  112. # make 2 bad tx files
  113. for n in (1,2):
  114. bad_tx = joinpath(mountpoint,'tx',f'bad{n}.rawtx')
  115. if include_bad_tx and not remove_signed_only:
  116. with open(bad_tx,'w') as fp:
  117. fp.write('bad tx data')
  118. if not include_bad_tx:
  119. try: os.unlink(bad_tx)
  120. except: pass
  121. def do_autosign_live(opts,mountpoint,led_opts=[],gen_wallet=True):
  122. omsg(purple(
  123. 'Running autosign test with ' +
  124. (f"'{' '.join(led_opts)}'" if led_opts else 'no LED')
  125. ))
  126. def do_mount():
  127. try: run(['mount',mountpoint],check=True)
  128. except: pass
  129. def do_unmount():
  130. try: run(['umount',mountpoint],check=True)
  131. except: pass
  132. omsg_r(blue('\nRemove removable device and then hit ENTER '))
  133. input()
  134. if gen_wallet:
  135. if not opt.skip_deps:
  136. gen_key(opts)
  137. make_wallet(opts)
  138. else:
  139. do_mount()
  140. copy_files(mountpoint,include_bad_tx=not led_opts)
  141. desc = '(sign)'
  142. m1 = "Running 'mmgen-autosign wait'"
  143. m2 = 'Insert removable device '
  144. if led_opts:
  145. if led_opts == ['--led']:
  146. m1 = "Running 'mmgen-autosign wait' with --led. The LED should start blinking slowly now"
  147. elif led_opts == ['--stealth-led']:
  148. m1 = "Running 'mmgen-autosign wait' with --stealth-led. You should see no LED activity now"
  149. m2 = 'Insert removable device and watch for fast LED activity during signing'
  150. desc = '(sign - {})'.format(led_opts[0])
  151. def do_loop():
  152. omsg(blue(m2))
  153. t.expect(f'{txcount} transactions signed')
  154. if not led_opts:
  155. t.expect('2 transactions failed to sign')
  156. t.expect('Waiting')
  157. do_unmount()
  158. omsg(green(m1))
  159. t = self.spawn('mmgen-autosign',opts+led_opts+['--quiet','--no-summary','wait'],extra_desc=desc)
  160. if not opt.exact_output: omsg('')
  161. do_loop()
  162. do_mount() # race condition due to device insertion detection
  163. copy_files(mountpoint,remove_signed_only=True,include_bad_tx=not led_opts)
  164. do_unmount()
  165. do_loop()
  166. imsg(purple('\nKilling wait loop!'))
  167. t.kill(2) # 2 = SIGINT
  168. t.req_exit_val = 1
  169. if simulate and led_opts:
  170. t.expect("Stopping LED")
  171. return t
  172. def do_autosign(opts,mountpoint,mn_type=None,short=False):
  173. def autosign_expect(t,txcount):
  174. t.expect(f'{txcount} transactions signed')
  175. t.expect('2 transactions failed to sign')
  176. t.expect('Waiting')
  177. t.kill(2)
  178. t.req_exit_val = 1
  179. imsg('')
  180. t.ok()
  181. if not opt.skip_deps:
  182. gen_key(opts)
  183. make_wallet(opts,mn_type)
  184. copy_files(mountpoint,include_bad_tx=True)
  185. t = self.spawn('mmgen-autosign',opts+['--quiet','wait'],extra_desc='(sign)')
  186. autosign_expect(t,txcount)
  187. if short:
  188. return t
  189. copy_files(mountpoint,remove_signed_only=True)
  190. t = self.spawn('mmgen-autosign',opts+['--full-summary','wait'],extra_desc='(sign - full summary)')
  191. autosign_expect(t,txcount)
  192. copy_files(mountpoint,include_bad_tx=True,fdata_in=(('btc',''),))
  193. t = self.spawn(
  194. 'mmgen-autosign',
  195. opts + ['--quiet','--stealth-led','wait'],
  196. extra_desc='(sign - --quiet --stealth-led)' )
  197. autosign_expect(t,3)
  198. copy_files(mountpoint,include_bad_tx=False,fdata_in=(('btc',''),))
  199. t = self.spawn('mmgen-autosign',opts+['--quiet','--led'],extra_desc='(sign - --quiet --led)')
  200. t.read()
  201. imsg('')
  202. return t
  203. def check_mountpoint(mountpoint):
  204. if not os.path.ismount(mountpoint):
  205. try:
  206. run(['mount',mountpoint],check=True)
  207. imsg(f'Mounted {mountpoint}')
  208. except:
  209. ydie(1,f'Could not mount {mountpoint}! Exiting')
  210. txdir = joinpath(mountpoint,'tx')
  211. if not os.path.isdir(txdir):
  212. ydie(1,f'Directory {txdir} does not exist! Exiting')
  213. def init_led():
  214. try:
  215. cf = LEDControl(enabled=True,simulate=simulate)
  216. except Exception as e:
  217. msg(str(e))
  218. ydie(2,'LEDControl initialization failed')
  219. for fn in (cf.board.status,cf.board.trigger):
  220. if fn:
  221. run(['sudo','chmod','0666',fn],check=True)
  222. # begin execution
  223. if simulate and not opt.exact_output:
  224. rmsg('This command must be run with --exact-output enabled!')
  225. return False
  226. if simulate or not live:
  227. os.environ['MMGEN_TEST_SUITE_AUTOSIGN_LED_SIMULATE'] = '1'
  228. LEDControl.create_dummy_control_files()
  229. network_ids = [c+'_tn' for c in daemon_coins] + daemon_coins
  230. start_test_daemons(*network_ids)
  231. try:
  232. if live:
  233. mountpoint = '/mnt/tx'
  234. opts = ['--coins='+','.join(coins)]
  235. check_mountpoint(mountpoint)
  236. init_led()
  237. foo = do_autosign_live(opts,mountpoint)
  238. foo = do_autosign_live(opts,mountpoint,led_opts=['--led'],gen_wallet=False)
  239. ret = do_autosign_live(opts,mountpoint,led_opts=['--stealth-led'],gen_wallet=False)
  240. else:
  241. mountpoint = self.tmpdir
  242. opts = ['--no-insert-check','--mountpoint='+mountpoint,'--coins='+','.join(coins)]
  243. try: os.mkdir(joinpath(mountpoint,'tx'))
  244. except: pass
  245. foo = do_autosign(opts,mountpoint,mn_type='mmgen',short=True)
  246. foo = do_autosign(opts,mountpoint,mn_type='bip39',short=True)
  247. ret = do_autosign(opts,mountpoint)
  248. finally:
  249. if simulate or not live:
  250. LEDControl.delete_dummy_control_files()
  251. stop_test_daemons(*[i for i in network_ids if i != 'btc'])
  252. return ret
  253. class TestSuiteAutosignBTC(TestSuiteAutosign):
  254. 'autosigning with BTC'
  255. cmd_group = (
  256. ('autosign_btc', 'transaction autosigning (BTC only)'),
  257. )
  258. class TestSuiteAutosignLive(TestSuiteAutosignBTC):
  259. 'live autosigning operations with device insertion/removal and LED check'
  260. cmd_group = (
  261. ('autosign_live', 'transaction autosigning (BTC,ETH,ETC - test device insertion/removal + LED)'),
  262. )
  263. class TestSuiteAutosignLiveSimulate(TestSuiteAutosignBTC):
  264. 'live autosigning operations with device insertion/removal and LED check in simulated environment'
  265. cmd_group = (
  266. ('autosign_live_simulate', 'transaction autosigning (BTC,ETH,ETC - test device insertion/removal + simulated LED)'),
  267. )