ts_autosign.py 9.4 KB

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