ct_shared.py 9.0 KB

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