ts_autosign.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2019 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 mmgen.globalvars import g
  23. from mmgen.opts import opt
  24. from test.common import read_from_file
  25. from test.test_py_d.common import *
  26. from test.test_py_d.ts_base import *
  27. from test.test_py_d.ts_shared import *
  28. class TestSuiteAutosign(TestSuiteBase):
  29. 'autosigning with BTC, BCH, LTC, ETH and ETC'
  30. networks = ('btc',)
  31. tmpdir_nums = [18]
  32. cmd_group = (
  33. ('autosign', 'transaction autosigning (BTC,BCH,LTC,ETH,ETC)'),
  34. )
  35. def autosign_live(self):
  36. return self.autosign_minimal(live=True)
  37. def autosign_minimal(self,live=False):
  38. return self.autosign(
  39. coins=['btc','eth'],
  40. txfiles=['btc','eth','mm1','etc'],
  41. txcount=7,
  42. live=live)
  43. # tests everything except device detection, mount/unmount
  44. def autosign( self,
  45. coins=['btc','bch','ltc','eth'],
  46. txfiles=['btc','bch','ltc','eth','mm1','etc'],
  47. txcount=11,
  48. live=False):
  49. if self.skip_for_win(): return
  50. def make_wallet(opts):
  51. t = self.spawn('mmgen-autosign',opts+['gen_key'],extra_desc='(gen_key)')
  52. t.expect_getend('Wrote key file ')
  53. t.ok()
  54. t = self.spawn('mmgen-autosign',opts+['setup'],extra_desc='(setup)')
  55. t.expect('words: ','3')
  56. t.expect('OK? (Y/n): ','\n')
  57. mn_file = dfl_words_file
  58. mn = read_from_file(mn_file).strip().split()
  59. mn = ['foo'] + mn[:5] + ['realiz','realized'] + mn[5:]
  60. wnum = 1
  61. max_wordlen = 12
  62. def get_pad_chars(n):
  63. ret = ''
  64. for i in range(n):
  65. m = int(os.urandom(1).hex(),16) % 32
  66. ret += r'123579!@#$%^&*()_+-=[]{}"?/,.<>|'[m]
  67. return ret
  68. for i in range(len(mn)):
  69. w = mn[i]
  70. if len(w) > 5:
  71. w = w + '\n'
  72. else:
  73. w = get_pad_chars(3 if randbool() else 0) + w[0] + get_pad_chars(3) + w[1:] + get_pad_chars(7)
  74. w = w[:max_wordlen+1]
  75. em,rm = 'Enter word #{}: ','Repeat word #{}: '
  76. ret = t.expect((em.format(wnum),rm.format(wnum-1)))
  77. if ret == 0: wnum += 1
  78. for j in range(len(w)):
  79. t.send(w[j])
  80. time.sleep(0.005)
  81. wf = t.written_to_file('Autosign wallet')
  82. t.ok()
  83. def copy_files(mountpoint,remove_signed_only=False,include_bad_tx=True):
  84. fdata_in = (('btc',''),
  85. ('bch',''),
  86. ('ltc','litecoin'),
  87. ('eth','ethereum'),
  88. ('mm1','ethereum'),
  89. ('etc','ethereum_classic'))
  90. fdata = [e for e in fdata_in if e[0] in txfiles]
  91. from test.test_py_d.ts_ref import TestSuiteRef
  92. tfns = [TestSuiteRef.sources['ref_tx_file'][c][1] for c,d in fdata] + \
  93. [TestSuiteRef.sources['ref_tx_file'][c][0] for c,d in fdata]
  94. tfs = [joinpath(ref_dir,d[1],fn) for d,fn in zip(fdata+fdata,tfns)]
  95. for f,fn in zip(tfs,tfns):
  96. if fn: # use empty fn to skip file
  97. target = joinpath(mountpoint,'tx',fn)
  98. remove_signed_only or shutil.copyfile(f,target)
  99. try: os.unlink(target.replace('.rawtx','.sigtx'))
  100. except: pass
  101. # make a bad tx file
  102. bad_tx = joinpath(mountpoint,'tx','bad.rawtx')
  103. if include_bad_tx and not remove_signed_only:
  104. open(bad_tx,'w').write('bad tx data')
  105. if not include_bad_tx:
  106. try: os.unlink(bad_tx)
  107. except: pass
  108. def do_autosign_live(opts,mountpoint,led_opts=[],gen_wallet=True):
  109. def do_mount():
  110. try: subprocess.check_call(['mount',mountpoint])
  111. except: pass
  112. def do_unmount():
  113. try: subprocess.check_call(['umount',mountpoint])
  114. except: pass
  115. omsg_r(blue('\nRemove removable device and then hit ENTER '))
  116. input()
  117. if gen_wallet: make_wallet(opts)
  118. else: do_mount()
  119. copy_files(mountpoint,include_bad_tx=not led_opts)
  120. desc = '(sign)'
  121. m1 = "Running 'mmgen-autosign wait'"
  122. m2 = 'Insert removable device '
  123. if led_opts:
  124. if led_opts == ['--led']:
  125. m1 = "Running 'mmgen-autosign wait' with --led. The LED should start blinking slowly now"
  126. elif led_opts == ['--stealth-led']:
  127. m1 = "Running 'mmgen-autosign wait' with --stealth-led. You should see no LED activity now"
  128. m2 = 'Insert removable device and watch for fast LED activity during signing'
  129. desc = '(sign - {})'.format(led_opts[0])
  130. def do_loop():
  131. omsg(blue(m2))
  132. t.expect('{} transactions signed'.format(txcount))
  133. if not led_opts:
  134. t.expect('1 transaction failed to sign')
  135. t.expect('Waiting')
  136. do_unmount()
  137. omsg(green(m1))
  138. t = self.spawn('mmgen-autosign',opts+led_opts+['wait'],extra_desc=desc)
  139. if not opt.exact_output: omsg('')
  140. do_loop()
  141. do_mount() # race condition due to device insertion detection
  142. copy_files(mountpoint,remove_signed_only=True,include_bad_tx=not led_opts)
  143. do_unmount()
  144. do_loop()
  145. t.kill(2) # 2 = SIGINT
  146. t.req_exit_val = 1
  147. return t
  148. def do_autosign(opts,mountpoint):
  149. make_wallet(opts)
  150. copy_files(mountpoint,include_bad_tx=True)
  151. t = self.spawn('mmgen-autosign',opts+['wait'],extra_desc='(sign)')
  152. t.expect('{} transactions signed'.format(txcount))
  153. t.expect('1 transaction failed to sign')
  154. t.expect('Waiting')
  155. t.kill(2)
  156. t.req_exit_val = 1
  157. return t
  158. if live:
  159. mountpoint = '/mnt/tx'
  160. if not os.path.ismount(mountpoint):
  161. try:
  162. subprocess.check_call(['mount',mountpoint])
  163. imsg("Mounted '{}'".format(mountpoint))
  164. except:
  165. ydie(1,"Could not mount '{}'! Exiting".format(mountpoint))
  166. txdir = joinpath(mountpoint,'tx')
  167. if not os.path.isdir(txdir):
  168. ydie(1,"Directory '{}' does not exist! Exiting".format(mountpoint))
  169. opts = ['--coins='+','.join(coins)]
  170. led_files = { 'opi': ('/sys/class/leds/orangepi:red:status/brightness',),
  171. 'rpi': ('/sys/class/leds/led0/brightness','/sys/class/leds/led0/trigger') }
  172. for k in ('opi','rpi'):
  173. if os.path.exists(led_files[k][0]):
  174. led_support = k
  175. break
  176. else:
  177. led_support = None
  178. if led_support:
  179. for fn in (led_files[led_support]):
  180. subprocess.check_call(['sudo','chmod','0666',fn])
  181. omsg(purple('Running autosign test with no LED'))
  182. do_autosign_live(opts,mountpoint)
  183. omsg(purple("Running autosign test with '--led'"))
  184. do_autosign_live(opts,mountpoint,led_opts=['--led'],gen_wallet=False)
  185. omsg(purple("Running autosign test with '--stealth-led'"))
  186. return do_autosign_live(opts,mountpoint,led_opts=['--stealth-led'],gen_wallet=False)
  187. else:
  188. return do_autosign_live(opts,mountpoint)
  189. else:
  190. mountpoint = self.tmpdir
  191. opts = ['--no-insert-check','--mountpoint='+mountpoint,'--coins='+','.join(coins)]
  192. try: os.mkdir(joinpath(mountpoint,'tx'))
  193. except: pass
  194. return do_autosign(opts,mountpoint)
  195. class TestSuiteAutosignMinimal(TestSuiteAutosign):
  196. 'autosigning with BTC, ETH and ETC'
  197. cmd_group = (
  198. ('autosign_minimal', 'transaction autosigning (BTC,ETH,ETC)'),
  199. )
  200. class TestSuiteAutosignLive(TestSuiteAutosignMinimal):
  201. 'live autosigning operations'
  202. cmd_group = (
  203. ('autosign_live', 'transaction autosigning (BTC,ETH,ETC - test device insertion/removal + LED)'),
  204. )