ct_xmr_autosign.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, a command-line cryptocurrency wallet
  4. # Copyright (C)2013-2024 The MMGen Project <mmgen@tuta.io>
  5. # Licensed under the GNU General Public License, Version 3:
  6. # https://www.gnu.org/licenses
  7. # Public project repositories:
  8. # https://github.com/mmgen/mmgen-wallet
  9. # https://gitlab.com/mmgen/mmgen-wallet
  10. """
  11. test.cmdtest_py_d.ct_xmr_autosign: xmr autosigning tests for the cmdtest.py test suite
  12. """
  13. import os,time,re,shutil
  14. from pathlib import Path
  15. from mmgen.color import purple,gray,blue,cyan,brown
  16. from mmgen.util import fmt,async_run
  17. from ..include.common import cfg,imsg,silence,end_silence
  18. from .common import get_file_with_ext
  19. from .ct_xmrwallet import CmdTestXMRWallet
  20. from .ct_autosign import CmdTestAutosignThreaded
  21. def make_burn_addr():
  22. from mmgen.tool.coin import tool_cmd
  23. return tool_cmd(
  24. cfg = cfg,
  25. cmdname = 'privhex2addr',
  26. proto = cfg._proto,
  27. mmtype = 'monero' ).privhex2addr('beadcafe'*8)
  28. class CmdTestXMRAutosign(CmdTestXMRWallet,CmdTestAutosignThreaded):
  29. """
  30. Monero autosigning operations
  31. """
  32. tmpdir_nums = [39]
  33. # ct_xmrwallet attrs:
  34. tx_relay_user = 'miner'
  35. user_data = (
  36. ('miner', '98831F3A', False, 130, '1', []),
  37. ('alice', 'FE3C6545', True, 150, '1-2', []),
  38. )
  39. # ct_autosign attrs:
  40. coins = ['xmr']
  41. cmd_group = (
  42. ('daemon_version', 'checking daemon version'),
  43. ('create_tmp_wallets', 'creating temporary online wallets for Alice'),
  44. ('new_account_alice', 'adding an account to Alice’s tmp wallet'),
  45. ('new_address_alice', 'adding an address to Alice’s tmp wallet'),
  46. ('new_address_alice_label', 'adding an address to Alice’s tmp wallet (with label)'),
  47. ('dump_tmp_wallets', 'dumping Alice’s tmp wallets'),
  48. ('delete_tmp_wallets', 'deleting Alice’s tmp wallets'),
  49. ('autosign_setup', 'autosign setup with Alice’s seed'),
  50. ('autosign_xmr_setup', 'autosign setup (creation of Monero signing wallets)'),
  51. ('create_watchonly_wallets', 'creating online (watch-only) wallets for Alice'),
  52. ('delete_tmp_dump_files', 'deleting Alice’s dump files'),
  53. ('gen_kafiles', 'generating key-address files for Miner'),
  54. ('create_wallets_miner', 'creating Monero wallets for Miner'),
  55. ('mine_initial_coins', 'mining initial coins'),
  56. ('fund_alice1', 'sending funds to Alice (wallet #1)'),
  57. ('fund_alice2', 'sending funds to Alice (wallet #2)'),
  58. ('autosign_start_thread', 'starting autosign wait loop'),
  59. ('export_outputs1', 'exporting outputs from Alice’s watch-only wallet #1'),
  60. ('create_transfer_tx1', 'creating a transfer TX'),
  61. ('submit_transfer_tx1', 'submitting the transfer TX'),
  62. ('resubmit_transfer_tx1', 'resubmitting the transfer TX'),
  63. ('export_outputs2', 'exporting outputs from Alice’s watch-only wallet #1'),
  64. ('import_key_images1', 'importing signed key images into Alice’s online wallets'),
  65. ('sync_chkbal1', 'syncing Alice’s wallet #1'),
  66. ('abort_tx1', 'aborting the current transaction (error)'),
  67. ('create_transfer_tx2', 'creating a transfer TX (for relaying via proxy)'),
  68. ('abort_tx2', 'aborting the current transaction (OK, unsigned)'),
  69. ('create_transfer_tx2a', 'creating the transfer TX again'),
  70. ('submit_transfer_tx2', 'submitting the transfer TX (relaying via proxy)'),
  71. ('sync_chkbal2', 'syncing Alice’s wallets and checking balance'),
  72. ('dump_wallets', 'dumping Alice’s wallets'),
  73. ('delete_wallets', 'deleting Alice’s wallets'),
  74. ('restore_wallets', 'creating online (watch-only) wallets for Alice'),
  75. ('delete_dump_files', 'deleting Alice’s dump files'),
  76. ('export_outputs3', 'exporting outputs from Alice’s watch-only wallets'),
  77. ('import_key_images2', 'importing signed key images into Alice’s online wallets'),
  78. ('sync_chkbal3', 'syncing Alice’s wallets and checking balance'),
  79. ('autosign_kill_thread', 'stopping autosign wait loop'),
  80. ('stop_daemons', 'stopping all wallet and coin daemons'),
  81. ('view', 'viewing Alice’s wallet in offline mode (wallet #1)'),
  82. ('listview', 'list-viewing Alice’s wallet in offline mode (wallet #2)'),
  83. ('txlist', 'listing Alice’s submitted transactions'),
  84. ('txview', 'viewing Alice’s submitted transactions'),
  85. ('txview_all', 'viewing all raw, signed and submitted transactions'),
  86. ('check_tx_dirs', 'cleaning and checking signable file directories'),
  87. )
  88. def __init__(self,trunner,cfgs,spawn):
  89. CmdTestAutosignThreaded.__init__(self,trunner,cfgs,spawn)
  90. CmdTestXMRWallet.__init__(self,trunner,cfgs,spawn)
  91. if trunner is None:
  92. return
  93. from mmgen.cfg import Config
  94. self.cfg = Config({
  95. 'coin': 'XMR',
  96. 'outdir': self.users['alice'].udir,
  97. 'wallet_dir': self.users['alice'].udir,
  98. 'wallet_rpc_password': 'passwOrd',
  99. 'test_suite': True,
  100. })
  101. self.burn_addr = make_burn_addr()
  102. self.opts.append('--xmrwallets={}'.format(self.users['alice'].kal_range)) # mmgen-autosign opts
  103. self.autosign_opts = ['--autosign'] # mmgen-xmrwallet opts
  104. self.spawn_env['MMGEN_TEST_SUITE_XMR_AUTOSIGN'] = '1'
  105. def create_tmp_wallets(self):
  106. self.spawn('',msg_only=True)
  107. data = self.users['alice']
  108. from mmgen.wallet import Wallet
  109. from mmgen.xmrwallet import MoneroWalletOps,xmrwallet_uargs
  110. from mmgen.addrlist import KeyAddrList
  111. silence()
  112. kal = KeyAddrList(
  113. cfg = self.cfg,
  114. proto = self.proto,
  115. addr_idxs = '1-2',
  116. seed = Wallet(cfg,data.mmwords).seed,
  117. skip_chksum_msg = True,
  118. key_address_validity_check = False )
  119. kal.file.write(ask_overwrite=False)
  120. fn = get_file_with_ext(data.udir,'akeys')
  121. m = MoneroWalletOps.create(
  122. self.cfg,
  123. xmrwallet_uargs(fn, '1-2', None))
  124. async_run(m.main())
  125. async_run(m.stop_wallet_daemon())
  126. end_silence()
  127. return 'ok'
  128. def _new_addr_alice(self,*args):
  129. data = self.users['alice']
  130. return self.new_addr_alice(
  131. *args,
  132. kafile = get_file_with_ext(data.udir,'akeys') )
  133. def new_account_alice(self):
  134. return self._new_addr_alice(
  135. '2',
  136. 'start',
  137. r'Creating new account for wallet .*2.* with label .*‘xmrwallet new account .*y/N\): ')
  138. def new_address_alice(self):
  139. return self._new_addr_alice(
  140. '2:1',
  141. 'continue',
  142. r'Creating new address for wallet .*2.*, account .*#1.* with label .*‘xmrwallet new address .*y/N\): ')
  143. def new_address_alice_label(self):
  144. return self._new_addr_alice(
  145. '2:1,Alice’s new address',
  146. 'stop',
  147. r'Creating new address for wallet .*2.*, account .*#1.* with label .*‘Alice’s new address .*y/N\): ')
  148. def dump_tmp_wallets(self):
  149. return self._dump_wallets(autosign=False)
  150. def dump_wallets(self):
  151. return self._dump_wallets(autosign=True)
  152. def _dump_wallets(self,autosign):
  153. data = self.users['alice']
  154. self.insert_device_online()
  155. t = self.spawn(
  156. 'mmgen-xmrwallet',
  157. self.extra_opts
  158. + [f'--wallet-dir={data.udir}', f'--daemon=localhost:{data.md.rpc_port}']
  159. + (self.autosign_opts if autosign else [])
  160. + ['dump']
  161. + ([] if autosign else [get_file_with_ext(data.udir,'akeys')]) )
  162. t.expect('2 wallets dumped')
  163. self.remove_device_online()
  164. return t
  165. def _delete_files(self,*ext_list):
  166. data = self.users['alice']
  167. self.spawn('',msg_only=True)
  168. for ext in ext_list:
  169. get_file_with_ext(data.udir,ext,no_dot=True,delete_all=True)
  170. return 'ok'
  171. def delete_tmp_wallets(self):
  172. return self._delete_files( 'MoneroWallet', 'MoneroWallet.keys', '.akeys' )
  173. def delete_wallets(self):
  174. return self._delete_files( 'MoneroWatchOnlyWallet', '.keys', '.address.txt' )
  175. def delete_tmp_dump_files(self):
  176. return self._delete_files( '.dump' )
  177. def delete_dump_files(self):
  178. return self._delete_files( '.dump' )
  179. def fund_alice1(self):
  180. return self.fund_alice(wallet=1,check_bal=False)
  181. def fund_alice2(self):
  182. return self.fund_alice(wallet=2)
  183. def autosign_setup(self):
  184. self.insert_device()
  185. t = self.run_setup(
  186. mn_type = 'mmgen',
  187. mn_file = self.users['alice'].mmwords,
  188. use_dfl_wallet = None )
  189. t.expect('Continue with Monero setup? (Y/n): ','n')
  190. self.remove_device()
  191. return t
  192. def autosign_xmr_setup(self):
  193. self.do_mount_online()
  194. self.asi_online.xmr_dir.mkdir(exist_ok=True)
  195. (self.asi_online.xmr_dir / 'old.vkeys').touch()
  196. self.do_umount_online()
  197. t = self.spawn('mmgen-autosign', self.opts + ['xmr_setup'], no_passthru_opts=True)
  198. t.written_to_file('View keys')
  199. return t
  200. def create_watchonly_wallets(self):
  201. self.insert_device_online()
  202. t = self.create_wallets('alice', op='restore')
  203. t.read() # required!
  204. self.remove_device_online()
  205. return t
  206. def restore_wallets(self):
  207. return self.create_watchonly_wallets()
  208. def _create_transfer_tx(self, amt, add_opts=[]):
  209. self.insert_device_online()
  210. t = self.do_op(
  211. 'transfer',
  212. 'alice',
  213. f'1:0:{self.burn_addr},{amt}',
  214. no_relay = True,
  215. do_ret = True,
  216. add_opts = add_opts)
  217. t.read() # required!
  218. self.remove_device_online()
  219. return t
  220. def create_transfer_tx1(self):
  221. return self._create_transfer_tx('0.124', add_opts=['--priority=2'])
  222. def create_transfer_tx2(self):
  223. return self._create_transfer_tx('0.257')
  224. create_transfer_tx2a = create_transfer_tx2
  225. def _abort_tx(self,expect,send=None,exit_val=None):
  226. self.insert_device_online()
  227. t = self.spawn('mmgen-xmrwallet', ['--autosign', 'abort'], exit_val=exit_val)
  228. t.expect(expect)
  229. if send:
  230. t.send(send)
  231. t.read() # required!
  232. self.remove_device_online()
  233. return t
  234. def abort_tx1(self):
  235. return self._abort_tx('No unsent transactions present', exit_val=2)
  236. def abort_tx2(self):
  237. return self._abort_tx('(y/N): ', 'y')
  238. def _xmr_autosign_op(
  239. self,
  240. op,
  241. desc = None,
  242. signable_desc = None,
  243. ext = None,
  244. wallet_arg = None,
  245. add_opts = [],
  246. wait_signed = False):
  247. if wait_signed:
  248. self._wait_signed(signable_desc)
  249. data = self.users['alice']
  250. args = (
  251. self.extra_opts
  252. + self.autosign_opts
  253. + [f'--wallet-dir={data.udir}', f'--daemon=localhost:{data.md.rpc_port}']
  254. + add_opts
  255. + [ op ]
  256. + ([get_file_with_ext(self.asi.xmr_tx_dir,ext)] if ext else [])
  257. + ([wallet_arg] if wallet_arg else [])
  258. )
  259. desc_pfx = f'{desc}, ' if desc else ''
  260. return self.spawn( 'mmgen-xmrwallet', args, extra_desc=f'({desc_pfx}Alice)' )
  261. def _sync_chkbal(self,wallet_arg,bal_chk_func):
  262. return self.sync_wallets(
  263. 'alice',
  264. op = 'sync',
  265. wallets = wallet_arg,
  266. bal_chk_func = bal_chk_func )
  267. def sync_chkbal1(self):
  268. return self._sync_chkbal( '1', lambda n,b,ub: b == ub and 1 < b < 1.12 )
  269. # 1.234567891234 - 0.124 = 1.110567891234 (minus fees)
  270. def sync_chkbal2(self):
  271. return self._sync_chkbal( '1', lambda n,b,ub: b == ub and 0.8 < b < 0.86 )
  272. # 1.234567891234 - 0.124 - 0.257 = 0.853567891234 (minus fees)
  273. def sync_chkbal3(self):
  274. return self._sync_chkbal(
  275. '1-2',
  276. lambda n,b,ub: b == ub and ((n == 1 and 0.8 < b < 0.86) or (n == 2 and b > 1.23)) )
  277. def _mine_chk(self,desc):
  278. bal_type = {'locked':'b','unlocked':'ub'}[desc]
  279. return self.mine_chk(
  280. 'alice', 1, 0,
  281. lambda x: 0 < getattr(x,bal_type) < 1.234567891234,
  282. f'{desc} balance 0 < 1.234567891234' )
  283. def submit_transfer_tx1(self):
  284. return self._submit_transfer_tx()
  285. def resubmit_transfer_tx1(self):
  286. return self._submit_transfer_tx(
  287. relay_parm = self.tx_relay_daemon_proxy_parm,
  288. op = 'resubmit',
  289. check_bal = False)
  290. def submit_transfer_tx2(self):
  291. return self._submit_transfer_tx( relay_parm=self.tx_relay_daemon_parm )
  292. def _submit_transfer_tx(self,relay_parm=None,ext=None,op='submit',check_bal=True):
  293. self.insert_device_online()
  294. t = self._xmr_autosign_op(
  295. op = op,
  296. add_opts = [f'--tx-relay-daemon={relay_parm}'] if relay_parm else [],
  297. ext = ext,
  298. signable_desc = 'transaction',
  299. wait_signed = op == 'submit')
  300. t.expect( f'{op.capitalize()} transaction? (y/N): ', 'y' )
  301. t.written_to_file('Submitted transaction')
  302. self.remove_device_online()
  303. if check_bal:
  304. t.ok()
  305. return self._mine_chk('unlocked')
  306. else:
  307. return t
  308. def _export_outputs(self, wallet_arg, op, add_opts=[]):
  309. self.insert_device_online()
  310. t = self._xmr_autosign_op(
  311. op = op,
  312. wallet_arg = wallet_arg,
  313. add_opts = add_opts)
  314. t.written_to_file('Wallet outputs')
  315. self.remove_device_online()
  316. return t
  317. def export_outputs1(self):
  318. return self._export_outputs('1', op='export-outputs')
  319. def export_outputs2(self):
  320. return self._export_outputs('1', op='export-outputs-sign', add_opts=['--rescan-blockchain'])
  321. def export_outputs3(self):
  322. return self._export_outputs('1-2', op='export-outputs-sign')
  323. def _import_key_images(self,wallet_arg):
  324. self.insert_device_online()
  325. t = self._xmr_autosign_op(
  326. op = 'import-key-images',
  327. wallet_arg = wallet_arg,
  328. signable_desc = 'wallet outputs',
  329. wait_signed = True)
  330. t.read()
  331. self.remove_device_online()
  332. return t
  333. def import_key_images1(self):
  334. return self._import_key_images(None)
  335. def import_key_images2(self):
  336. return self._import_key_images(None)
  337. def txlist(self):
  338. self.insert_device_online()
  339. t = self.spawn( 'mmgen-xmrwallet', self.autosign_opts + ['txlist'] )
  340. t.match_expect_list([
  341. 'SUBMITTED',
  342. 'Network','Submitted',
  343. 'Transfer 1:0','-> ext',
  344. 'Transfer 1:0','-> ext'
  345. ])
  346. self.remove_device_online()
  347. return t
  348. def txview(self):
  349. self.insert_device_online()
  350. t = self.spawn('mmgen-xmrwallet', self.autosign_opts + ['txview'])
  351. t.read()
  352. self.remove_device_online()
  353. return t
  354. def txview_all(self):
  355. t = self.spawn('', msg_only=True)
  356. self.do_mount()
  357. imsg(blue('Opening transaction directory: ') + cyan(f'{self.asi.xmr_tx_dir}'))
  358. for fn in self.asi.xmr_tx_dir.iterdir():
  359. imsg('\n' + brown(f'Viewing ‘{fn.name}’'))
  360. self.spawn('mmgen-xmrwallet', ['txview', str(fn)], no_msg=True).read()
  361. imsg('')
  362. self.do_umount()
  363. return 'ok'
  364. def check_tx_dirs(self):
  365. self.insert_device()
  366. self.do_mount()
  367. before = '\n'.join(self._gen_listing())
  368. self.do_umount()
  369. t = self.spawn('mmgen-autosign', self.opts + ['clean'])
  370. t.read()
  371. self.do_mount()
  372. after = '\n'.join(self._gen_listing())
  373. self.do_umount()
  374. self.remove_device()
  375. imsg(f'\nBefore cleaning:\n{before}')
  376. imsg(f'\nAfter cleaning:\n{after}')
  377. pat = r'xmr/tx: \s*\S+\.subtx \S+\.subtx\s+xmr/outputs:\s*$'
  378. assert re.search( pat, after, re.DOTALL ), f'regex search for {pat} failed'
  379. return t
  380. def view(self):
  381. return self.sync_wallets('alice', op='view', wallets='1')
  382. def listview(self):
  383. return self.sync_wallets('alice', op='listview', wallets='2')