ct_shared.py 9.8 KB

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