ts_shared.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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. test.test_py_d.ts_shared: Shared methods for the test.py test suite
  20. """
  21. import os
  22. from mmgen.globalvars import g
  23. from mmgen.opts import opt
  24. from mmgen.util import ymsg
  25. from mmgen.wallet import get_wallet_cls
  26. from ..include.common import *
  27. from .common import *
  28. class TestSuiteShared(object):
  29. 'shared methods for the test.py test suite'
  30. def txcreate_ui_common(self,t,
  31. caller = None,
  32. menu = [],
  33. inputs = '1',
  34. file_desc = 'Unsigned transaction',
  35. input_sels_prompt = 'to spend',
  36. bad_input_sels = False,
  37. interactive_fee = '',
  38. fee_desc = 'transaction fee',
  39. fee_res = None,
  40. eth_fee_res = None,
  41. add_comment = '',
  42. view = 't',
  43. save = True,
  44. tweaks = [],
  45. used_chg_addr_resp = None,
  46. auto_chg_arg = None,
  47. auto_chg_choices = 1 ):
  48. txdo = (caller or self.test_name)[:4] == 'txdo'
  49. expect_pat = r'\[q\]uit view, .*?:.'
  50. delete_pat = r'Enter account number .*:.'
  51. confirm_pat = r'Is this what you want.*:.'
  52. if used_chg_addr_resp is not None:
  53. t.expect('reuse harms your privacy.*:.*',used_chg_addr_resp,regex=True)
  54. if auto_chg_arg is not None:
  55. if auto_chg_choices > 1:
  56. t.expect('Enter a number> ',f'{auto_chg_choices}\n')
  57. t.expect(fr'Using .*{auto_chg_arg}:\d+.* as.*address','y',regex=True)
  58. pat = expect_pat
  59. for choice in menu + ['q']:
  60. t.expect(pat,choice,regex=True)
  61. if self.proto.base_proto == 'Ethereum':
  62. pat = confirm_pat if pat == delete_pat else delete_pat if choice == 'D' else expect_pat
  63. if bad_input_sels:
  64. for r in ('x','3-1','9999'):
  65. t.expect(input_sels_prompt+': ',r+'\n')
  66. t.expect(input_sels_prompt+': ',inputs+'\n')
  67. have_est_fee = t.expect([fee_desc+': ','OK? (Y/n): ']) == 1
  68. if have_est_fee and not interactive_fee:
  69. t.send('y')
  70. else:
  71. if have_est_fee:
  72. t.send('n')
  73. if self.proto.coin == 'BCH' or self.proto.base_coin == 'ETH': # TODO: pexpect race condition?
  74. time.sleep(0.1)
  75. if eth_fee_res:
  76. t.expect('or gas price: ',interactive_fee+'\n')
  77. else:
  78. t.send(interactive_fee+'\n')
  79. if fee_res:
  80. t.expect(fee_res,regex=True)
  81. t.expect('OK? (Y/n): ','y')
  82. t.expect('(Y/n): ','\n') # chg amt OK?
  83. if 'confirm_non_mmgen' in tweaks:
  84. t.expect('Continue? (Y/n)','\n')
  85. t.do_comment(add_comment)
  86. t.view_tx(view)
  87. if not txdo:
  88. t.expect('(y/N): ',('n','y')[save])
  89. t.written_to_file(file_desc)
  90. return t
  91. def txsign_ui_common(self,t,
  92. caller = None,
  93. view = 't',
  94. add_comment = '',
  95. file_desc = 'Signed transaction',
  96. ni = False,
  97. save = True,
  98. do_passwd = False,
  99. has_label = False ):
  100. txdo = (caller or self.test_name)[:4] == 'txdo'
  101. if do_passwd:
  102. t.passphrase('MMGen wallet',self.wpasswd)
  103. if not ni and not txdo:
  104. t.view_tx(view)
  105. t.do_comment(add_comment,has_label=has_label)
  106. t.expect('(Y/n): ',('n','y')[save])
  107. t.written_to_file(file_desc)
  108. return t
  109. def txsend_ui_common(self,t,
  110. caller = None,
  111. view = 'n',
  112. add_comment = '',
  113. file_desc = 'Sent transaction',
  114. confirm_send = True,
  115. bogus_send = True,
  116. quiet = False,
  117. has_label = False ):
  118. txdo = (caller or self.test_name)[:4] == 'txdo'
  119. if not txdo:
  120. t.license() # MMGEN_NO_LICENSE is set, so does nothing
  121. t.view_tx(view)
  122. t.do_comment(add_comment,has_label=has_label)
  123. self._do_confirm_send(t,quiet=quiet,confirm_send=confirm_send)
  124. if bogus_send:
  125. txid = ''
  126. t.expect('BOGUS transaction NOT sent')
  127. else:
  128. txid = strip_ansi_escapes(t.expect_getend('Transaction sent: '))
  129. assert len(txid) == 64, f'{txid!r}: Incorrect txid length!'
  130. t.written_to_file(file_desc)
  131. return txid
  132. def txsign_end(self,t,tnum=None,has_label=False):
  133. t.expect('Signing transaction')
  134. t.do_comment(False,has_label=has_label)
  135. t.expect(r'Save signed transaction.*?\? \(Y/n\): ','y',regex=True)
  136. t.written_to_file('Signed transaction' + (' #' + tnum if tnum else ''), oo=True)
  137. return t
  138. def txsign(self,wf,txfile,
  139. pf = '',
  140. bumpf = '',
  141. save = True,
  142. has_label = False,
  143. extra_opts = [],
  144. extra_desc = '',
  145. view = 'n',
  146. dfl_wallet = False ):
  147. opts = extra_opts + ['-d',self.tmpdir,txfile] + ([wf] if wf else [])
  148. t = self.spawn('mmgen-txsign', opts, extra_desc)
  149. t.license()
  150. t.view_tx(view)
  151. wcls = get_wallet_cls( ext = 'mmdat' if dfl_wallet else get_extension(wf) )
  152. if wcls.enc and wcls.type != 'brain':
  153. t.passphrase(wcls.desc,self.wpasswd)
  154. if save:
  155. self.txsign_end(t,has_label=has_label)
  156. else:
  157. t.do_comment(False,has_label=has_label)
  158. t.expect('Save signed transaction? (Y/n): ','n')
  159. t.expect('not saved')
  160. t.req_exit_val = 1
  161. return t
  162. def ref_brain_chk(self,bw_file=ref_bw_file):
  163. wf = joinpath(ref_dir,bw_file)
  164. add_args = [f'-l{self.seed_len}', f'-p{ref_bw_hash_preset}']
  165. return self.walletchk(wf,pf=None,add_args=add_args,sid=self.ref_bw_seed_id)
  166. def walletchk(self,wf,pf,wcls=None,add_args=[],sid=None,extra_desc='',dfl_wallet=False):
  167. hp = self.hash_preset if hasattr(self,'hash_preset') else '1'
  168. wcls = wcls or get_wallet_cls(ext=get_extension(wf))
  169. t = self.spawn('mmgen-walletchk',
  170. ([] if dfl_wallet else ['-i',wcls.fmt_codes[0]])
  171. + add_args + ['-p',hp]
  172. + ([wf] if wf else []),
  173. extra_desc=extra_desc)
  174. if wcls.type != 'incog_hidden':
  175. t.expect(f"Getting {wcls.desc} from file '")
  176. if wcls.enc and wcls.type != 'brain':
  177. t.passphrase(wcls.desc,self.wpasswd)
  178. t.expect(['Passphrase is OK', 'Passphrase.* are correct'],regex=True)
  179. chk = t.expect_getend(f'Valid {wcls.desc} for Seed ID ')[:8]
  180. if sid:
  181. cmp_or_die(chk,sid)
  182. return t
  183. def addrgen(self,wf,
  184. pf = None,
  185. check_ref = False,
  186. ftype = 'addr',
  187. id_str = None,
  188. extra_args = [],
  189. mmtype = None,
  190. stdout = False,
  191. dfl_wallet = False ):
  192. passgen = ftype[:4] == 'pass'
  193. if not mmtype and not passgen:
  194. mmtype = self.segwit_mmtype
  195. cmd_pfx = (ftype,'pass')[passgen]
  196. t = self.spawn(f'mmgen-{cmd_pfx}gen',
  197. ['-d',self.tmpdir] + extra_args +
  198. ([],['--type='+str(mmtype)])[bool(mmtype)] +
  199. ([],['--stdout'])[stdout] +
  200. ([],[wf])[bool(wf)] +
  201. ([],[id_str])[bool(id_str)] +
  202. [getattr(self,f'{cmd_pfx}_idx_list')],
  203. extra_desc=f'({mmtype})' if mmtype in ('segwit','bech32') else '')
  204. t.license()
  205. wcls = get_wallet_cls( ext = 'mmdat' if dfl_wallet else get_extension(wf) )
  206. t.passphrase(wcls.desc,self.wpasswd)
  207. t.expect('Passphrase is OK')
  208. desc = ('address','password')[passgen]
  209. chk = t.expect_getend(rf'Checksum for {desc} data .*?: ',regex=True)
  210. if passgen:
  211. t.expect('Encrypt password list? (y/N): ','N')
  212. t.read() if stdout else t.written_to_file(('Addresses','Password list')[passgen])
  213. if check_ref:
  214. chk_ref = (self.chk_data[self.test_name] if passgen else
  215. self.chk_data[self.test_name][self.fork][self.proto.testnet])
  216. cmp_or_die(chk,chk_ref,desc=f'{ftype}list data checksum')
  217. return t
  218. def keyaddrgen(self,wf,pf=None,check_ref=False,mmtype=None):
  219. if not mmtype:
  220. mmtype = self.segwit_mmtype
  221. args = ['-d',self.tmpdir,self.usr_rand_arg,wf,self.addr_idx_list]
  222. t = self.spawn('mmgen-keygen',
  223. ([],['--type='+str(mmtype)])[bool(mmtype)] + args,
  224. extra_desc=f'({mmtype})' if mmtype in ('segwit','bech32') else '')
  225. t.license()
  226. wcls = get_wallet_cls(ext=get_extension(wf))
  227. t.passphrase(wcls.desc,self.wpasswd)
  228. chk = t.expect_getend(r'Checksum for key-address data .*?: ',regex=True)
  229. if check_ref:
  230. chk_ref = self.chk_data[self.test_name][self.fork][self.proto.testnet]
  231. cmp_or_die(chk,chk_ref,desc='key-address list data checksum')
  232. t.expect('Encrypt key list? (y/N): ','y')
  233. t.usr_rand(self.usr_rand_chars)
  234. t.hash_preset('new key-address list','1')
  235. t.passphrase_new('new key-address list',self.kapasswd)
  236. t.written_to_file('Encrypted secret keys',oo=True)
  237. return t
  238. def _do_confirm_send(self,t,quiet=False,confirm_send=True,sure=True):
  239. if sure:
  240. t.expect('Are you sure you want to broadcast this')
  241. m = ('YES, I REALLY WANT TO DO THIS','YES')[quiet]
  242. t.expect(f'{m!r} to confirm: ',('',m)[confirm_send]+'\n')