ts_autosign.py 9.4 KB

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