shared.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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.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 .include.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. passwd = None,
  114. has_label = False):
  115. txdo = (caller or self.test_name)[:4] == 'txdo'
  116. if do_passwd and txdo:
  117. t.passphrase('MMGen wallet', passwd or self.wpasswd)
  118. if not (ni or txdo):
  119. t.view_tx(view)
  120. if do_passwd:
  121. t.passphrase('MMGen wallet', passwd or self.wpasswd)
  122. t.do_comment(add_comment, has_label=has_label)
  123. t.expect('(Y/n): ', ('n', 'y')[save])
  124. t.written_to_file(file_desc)
  125. return t
  126. def txsend_ui_common(
  127. self,
  128. t,
  129. caller = None,
  130. view = 'n',
  131. add_comment = '',
  132. file_desc = 'Sent transaction',
  133. confirm_send = True,
  134. bogus_send = True,
  135. test = False,
  136. quiet = False,
  137. has_label = False):
  138. txdo = (caller or self.test_name)[:4] == 'txdo'
  139. if not txdo:
  140. t.license() # MMGEN_NO_LICENSE is set, so does nothing
  141. t.view_tx(view)
  142. t.do_comment(add_comment, has_label=has_label)
  143. if not test:
  144. self._do_confirm_send(t, quiet=quiet, confirm_send=confirm_send)
  145. if bogus_send:
  146. txid = ''
  147. t.expect('BOGUS transaction NOT sent')
  148. elif test == 'tx_proxy':
  149. t.expect('can be sent')
  150. return True
  151. else:
  152. m = 'TxID: ' if test else 'Transaction sent: '
  153. txid = strip_ansi_escapes(t.expect_getend(m))
  154. assert len(txid) == 64, f'{txid!r}: Incorrect txid length!'
  155. if not test:
  156. t.written_to_file(file_desc)
  157. return txid
  158. def txbump_ui_common(self, t, *, fee, fee_desc='transaction fee', bad_fee=None):
  159. t.expect('(Y/n): ', 'n') # network-estimated fee OK?
  160. if bad_fee:
  161. t.expect(f'{fee_desc}: ', f'{bad_fee}\n')
  162. t.expect(f'{fee_desc}: ', f'{fee}\n')
  163. t.expect('(Y/n): ', 'y') # fee OK?
  164. t.expect('(Y/n): ', 'y') # signoff
  165. t.expect('(y/N): ', 'n') # edit comment
  166. t.expect('(y/N): ', 'y') # save TX?
  167. t.written_to_file('Fee-bumped transaction')
  168. return t
  169. def txsign_end(self, t, tnum=None, has_label=False):
  170. t.expect('Signing transaction')
  171. t.do_comment(False, has_label=has_label)
  172. t.expect(r'Save signed transaction.*?\? \(Y/n\): ', 'y', regex=True)
  173. t.written_to_file('Signed transaction' + (' #' + tnum if tnum else ''))
  174. return t
  175. def txsign(
  176. self,
  177. wf,
  178. txfile,
  179. save = True,
  180. has_label = False,
  181. extra_opts = [],
  182. extra_desc = '',
  183. view = 'n',
  184. dfl_wallet = False):
  185. opts = extra_opts + ['-d', self.tmpdir, txfile] + ([wf] if wf else [])
  186. wcls = get_wallet_cls(ext = 'mmdat' if dfl_wallet else get_extension(wf))
  187. t = self.spawn(
  188. 'mmgen-txsign',
  189. opts,
  190. extra_desc,
  191. no_passthru_opts = ['coin'],
  192. exit_val = None if save or (wcls.enc and wcls.type != 'brain') else 1)
  193. t.license()
  194. t.view_tx(view)
  195. if wcls.enc and wcls.type != 'brain':
  196. t.passphrase(wcls.desc, self.wpasswd)
  197. if save:
  198. self.txsign_end(t, has_label=has_label)
  199. else:
  200. t.do_comment(False, has_label=has_label)
  201. t.expect('Save signed transaction? (Y/n): ', 'n')
  202. t.expect('not saved')
  203. return t
  204. def ref_brain_chk(self, bw_file=ref_bw_file):
  205. wf = joinpath(ref_dir, bw_file)
  206. add_args = [f'-l{self.seed_len}', f'-p{ref_bw_hash_preset}']
  207. return self.walletchk(wf, add_args=add_args, sid=self.ref_bw_seed_id)
  208. def walletchk(
  209. self,
  210. wf,
  211. wcls = None,
  212. add_args = [],
  213. sid = None,
  214. extra_desc = '',
  215. dfl_wallet = False):
  216. hp = self.hash_preset if hasattr(self, 'hash_preset') else '1'
  217. wcls = wcls or get_wallet_cls(ext=get_extension(wf))
  218. t = self.spawn(
  219. 'mmgen-walletchk',
  220. ([] if dfl_wallet else ['-i', wcls.fmt_codes[0]])
  221. + self.testnet_opt
  222. + add_args + ['-p', hp]
  223. + ([wf] if wf else []),
  224. extra_desc = extra_desc,
  225. no_passthru_opts = True)
  226. if wcls.type != 'incog_hidden':
  227. t.expect(f"Getting {wcls.desc} from file ‘")
  228. if wcls.enc and wcls.type != 'brain':
  229. t.passphrase(wcls.desc, self.wpasswd)
  230. t.expect(['Passphrase is OK', 'Passphrase.* are correct'], regex=True)
  231. chksum = t.expect_getend(f'Valid {wcls.desc} for Seed ID ')[:8]
  232. if sid:
  233. cmp_or_die(chksum, sid)
  234. return t
  235. def addrgen(
  236. self,
  237. wf,
  238. check_ref = False,
  239. ftype = 'addr',
  240. id_str = None,
  241. extra_opts = [],
  242. mmtype = None,
  243. stdout = False,
  244. dfl_wallet = False,
  245. no_passthru_opts = False):
  246. list_type = ftype[:4]
  247. passgen = list_type == 'pass'
  248. if not mmtype and not passgen:
  249. mmtype = self.segwit_mmtype
  250. t = self.spawn(
  251. f'mmgen-{list_type}gen',
  252. ['-d', self.tmpdir] + extra_opts +
  253. ([], ['--type='+str(mmtype)])[bool(mmtype)] +
  254. ([], ['--stdout'])[stdout] +
  255. ([], [wf])[bool(wf)] +
  256. ([], [id_str])[bool(id_str)] +
  257. [getattr(self, f'{list_type}_idx_list')],
  258. extra_desc = f'({mmtype})' if mmtype in ('segwit', 'bech32') else '',
  259. no_passthru_opts = no_passthru_opts)
  260. t.license()
  261. wcls = get_wallet_cls(ext = 'mmdat' if dfl_wallet else get_extension(wf))
  262. t.passphrase(wcls.desc, self.wpasswd)
  263. t.expect('Passphrase is OK')
  264. desc = ('address', 'password')[passgen]
  265. chksum = strip_ansi_escapes(t.expect_getend(rf'Checksum for {desc} data .*?: ', regex=True))
  266. if check_ref:
  267. chksum_chk = (
  268. self.chk_data[self.test_name] if passgen else
  269. self.chk_data[self.test_name][self.fork][self.proto.testnet])
  270. cmp_or_die(chksum, chksum_chk, desc=f'{ftype}list data checksum')
  271. if passgen:
  272. t.expect('Encrypt password list? (y/N): ', 'N')
  273. if stdout:
  274. t.read()
  275. else:
  276. fn = t.written_to_file('Password list' if passgen else 'Addresses')
  277. cls = PasswordList if passgen else AddrList
  278. silence()
  279. al = cls(cfg, self.proto, infile=fn, skip_chksum_msg=True) # read back the file we’ve written
  280. end_silence()
  281. cmp_or_die(al.chksum, chksum, desc=f'{ftype}list data checksum from file')
  282. return t
  283. def keyaddrgen(self, wf, check_ref=False, extra_opts=[], mmtype=None):
  284. if not mmtype:
  285. mmtype = self.segwit_mmtype
  286. args = ['-d', self.tmpdir, self.usr_rand_arg, wf, self.addr_idx_list]
  287. t = self.spawn('mmgen-keygen',
  288. ([f'--type={mmtype}'] if mmtype else []) + extra_opts + args,
  289. extra_desc = f'({mmtype})' if mmtype in ('segwit', 'bech32') else '')
  290. t.license()
  291. wcls = get_wallet_cls(ext=get_extension(wf))
  292. t.passphrase(wcls.desc, self.wpasswd)
  293. chksum = t.expect_getend(r'Checksum for key-address data .*?: ', regex=True)
  294. if check_ref:
  295. chksum_chk = self.chk_data[self.test_name][self.fork][self.proto.testnet]
  296. cmp_or_die(chksum, chksum_chk, desc='key-address list data checksum')
  297. t.expect('Encrypt key list? (y/N): ', 'y')
  298. t.usr_rand(self.usr_rand_chars)
  299. t.hash_preset('new key-address list', '1')
  300. t.passphrase_new('new key-address list', self.kapasswd)
  301. t.written_to_file('Encrypted secret keys')
  302. return t
  303. def _do_confirm_send(self, t, quiet=False, confirm_send=True, sure=True):
  304. if sure:
  305. t.expect('Are you sure you want to broadcast this')
  306. m = ('YES, I REALLY WANT TO DO THIS', 'YES')[quiet]
  307. t.expect(f'{m!r} to confirm: ', ('', m)[confirm_send]+'\n')