ct_xmr_autosign.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  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
  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_clean', 'cleaning signable file directories'),
  50. ('autosign_setup', 'autosign setup with Alice’s seed'),
  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. ('create_transfer_tx1', 'creating a transfer TX'),
  60. ('submit_transfer_tx1', 'submitting the transfer TX'),
  61. ('resubmit_transfer_tx1', 'resubmitting the transfer TX'),
  62. ('export_outputs1', 'exporting outputs from Alice’s watch-only wallet #1'),
  63. ('import_key_images1', 'importing signed key images into Alice’s online wallets'),
  64. ('sync_chkbal1', 'syncing Alice’s wallet #1'),
  65. ('create_transfer_tx2', 'creating a transfer TX (for relaying via proxy)'),
  66. ('submit_transfer_tx2', 'submitting the transfer TX (relaying via proxy)'),
  67. ('sync_chkbal2', 'syncing Alice’s wallets and checking balance'),
  68. ('dump_wallets', 'dumping Alice’s wallets'),
  69. ('delete_wallets', 'deleting Alice’s wallets'),
  70. ('restore_wallets', 'creating online (watch-only) wallets for Alice'),
  71. ('delete_dump_files', 'deleting Alice’s dump files'),
  72. ('export_outputs2', 'exporting outputs from Alice’s watch-only wallets'),
  73. ('import_key_images2', 'importing signed key images into Alice’s online wallets'),
  74. ('sync_chkbal3', 'syncing Alice’s wallets and checking balance'),
  75. ('txlist', 'listing Alice’s submitted transactions'),
  76. ('check_tx_dirs', 'cleaning and checking signable file directories'),
  77. ('autosign_kill_thread', 'stopping autosign wait loop'),
  78. ('stop_daemons', 'stopping all wallet and coin daemons'),
  79. ('view', 'viewing Alice’s wallet in offline mode (wallet #1)'),
  80. ('listview', 'list-viewing Alice’s wallet in offline mode (wallet #2)'),
  81. )
  82. def __init__(self,trunner,cfgs,spawn):
  83. CmdTestAutosignThreaded.__init__(self,trunner,cfgs,spawn)
  84. CmdTestXMRWallet.__init__(self,trunner,cfgs,spawn)
  85. if trunner is None:
  86. return
  87. from mmgen.cfg import Config
  88. self.cfg = Config({
  89. 'coin': 'XMR',
  90. 'outdir': self.users['alice'].udir,
  91. 'wallet_dir': self.users['alice'].udir,
  92. 'wallet_rpc_password': 'passwOrd',
  93. 'test_suite': True,
  94. })
  95. self.burn_addr = make_burn_addr()
  96. self.opts.append('--xmrwallets={}'.format(self.users['alice'].kal_range)) # mmgen-autosign opts
  97. self.autosign_opts = ['--autosign'] # mmgen-xmrwallet opts
  98. self.spawn_env['MMGEN_TEST_SUITE_XMR_AUTOSIGN'] = '1'
  99. def create_tmp_wallets(self):
  100. self.spawn('',msg_only=True)
  101. data = self.users['alice']
  102. from mmgen.wallet import Wallet
  103. from mmgen.xmrwallet import MoneroWalletOps,xmrwallet_uargs
  104. from mmgen.addrlist import KeyAddrList
  105. silence()
  106. kal = KeyAddrList(
  107. cfg = self.cfg,
  108. proto = self.proto,
  109. addr_idxs = '1-2',
  110. seed = Wallet(cfg,data.mmwords).seed,
  111. skip_chksum_msg = True,
  112. key_address_validity_check = False )
  113. kal.file.write(ask_overwrite=False)
  114. fn = get_file_with_ext(data.udir,'akeys')
  115. m = MoneroWalletOps.create(
  116. self.cfg,
  117. xmrwallet_uargs(fn, '1-2', None))
  118. async_run(m.main())
  119. async_run(m.stop_wallet_daemon())
  120. end_silence()
  121. return 'ok'
  122. def _new_addr_alice(self,*args):
  123. data = self.users['alice']
  124. return self.new_addr_alice(
  125. *args,
  126. kafile = get_file_with_ext(data.udir,'akeys') )
  127. def new_account_alice(self):
  128. return self._new_addr_alice(
  129. '2',
  130. 'start',
  131. r'Creating new account for wallet .*2.* with label .*‘xmrwallet new account .*y/N\): ')
  132. def new_address_alice(self):
  133. return self._new_addr_alice(
  134. '2:1',
  135. 'continue',
  136. r'Creating new address for wallet .*2.*, account .*#1.* with label .*‘xmrwallet new address .*y/N\): ')
  137. def new_address_alice_label(self):
  138. return self._new_addr_alice(
  139. '2:1,Alice’s new address',
  140. 'stop',
  141. r'Creating new address for wallet .*2.*, account .*#1.* with label .*‘Alice’s new address .*y/N\): ')
  142. def dump_tmp_wallets(self):
  143. return self._dump_wallets(autosign=False)
  144. def dump_wallets(self):
  145. return self._dump_wallets(autosign=True)
  146. def _dump_wallets(self,autosign):
  147. data = self.users['alice']
  148. self.insert_device_online()
  149. t = self.spawn(
  150. 'mmgen-xmrwallet',
  151. self.extra_opts
  152. + [f'--wallet-dir={data.udir}', f'--daemon=localhost:{data.md.rpc_port}']
  153. + (self.autosign_opts if autosign else [])
  154. + ['dump']
  155. + ([] if autosign else [get_file_with_ext(data.udir,'akeys')]) )
  156. t.expect('2 wallets dumped')
  157. self.remove_device_online()
  158. return t
  159. def _delete_files(self,*ext_list):
  160. data = self.users['alice']
  161. self.spawn('',msg_only=True)
  162. for ext in ext_list:
  163. get_file_with_ext(data.udir,ext,no_dot=True,delete_all=True)
  164. return 'ok'
  165. def delete_tmp_wallets(self):
  166. return self._delete_files( 'MoneroWallet', 'MoneroWallet.keys', '.akeys' )
  167. def delete_wallets(self):
  168. return self._delete_files( 'MoneroWatchOnlyWallet', '.keys', '.address.txt' )
  169. def delete_tmp_dump_files(self):
  170. return self._delete_files( '.dump' )
  171. def delete_dump_files(self):
  172. return self._delete_files( '.dump' )
  173. def fund_alice1(self):
  174. return self.fund_alice(wallet=1,check_bal=False)
  175. def fund_alice2(self):
  176. return self.fund_alice(wallet=2)
  177. def autosign_setup(self):
  178. self.do_mount_online(no_xmr_chk=True)
  179. self.asi_online.xmr_dir.mkdir(exist_ok=True)
  180. (self.asi_online.xmr_dir / 'old.vkeys').touch()
  181. self.do_umount_online()
  182. self.insert_device()
  183. t = self.run_setup(
  184. mn_type = 'mmgen',
  185. mn_file = self.users['alice'].mmwords,
  186. use_dfl_wallet = None )
  187. t.expect('Continue with Monero setup? (Y/n): ','y')
  188. t.written_to_file('View keys')
  189. self.remove_device()
  190. return t
  191. def create_watchonly_wallets(self):
  192. self.insert_device_online()
  193. t = self.create_wallets('alice', op='restore')
  194. t.read() # required!
  195. self.remove_device_online()
  196. return t
  197. def restore_wallets(self):
  198. return self.create_watchonly_wallets()
  199. def _create_transfer_tx(self,amt):
  200. self.insert_device_online()
  201. t = self.do_op('transfer','alice',f'1:0:{self.burn_addr},{amt}',no_relay=True,do_ret=True)
  202. t.read() # required!
  203. self.remove_device_online()
  204. return t
  205. def create_transfer_tx1(self):
  206. return self._create_transfer_tx('0.124')
  207. def create_transfer_tx2(self):
  208. self.do_mount_online()
  209. get_file_with_ext(self.asi_online.xmr_tx_dir,'rawtx',delete_all=True)
  210. get_file_with_ext(self.asi_online.xmr_tx_dir,'sigtx',delete_all=True)
  211. self.do_umount_online()
  212. return self._create_transfer_tx('0.257')
  213. def _xmr_autosign_op(
  214. self,
  215. op,
  216. desc = None,
  217. signable_desc = None,
  218. ext = None,
  219. wallet_arg = None,
  220. add_opts = [],
  221. wait_signed = False):
  222. if wait_signed:
  223. self._wait_signed(signable_desc)
  224. data = self.users['alice']
  225. args = (
  226. self.extra_opts
  227. + self.autosign_opts
  228. + [f'--wallet-dir={data.udir}', f'--daemon=localhost:{data.md.rpc_port}']
  229. + add_opts
  230. + [ op ]
  231. + ([get_file_with_ext(self.asi.xmr_tx_dir,ext)] if ext else [])
  232. + ([wallet_arg] if wallet_arg else [])
  233. )
  234. desc_pfx = f'{desc}, ' if desc else ''
  235. return self.spawn( 'mmgen-xmrwallet', args, extra_desc=f'({desc_pfx}Alice)' )
  236. def _sync_chkbal(self,wallet_arg,bal_chk_func):
  237. return self.sync_wallets(
  238. 'alice',
  239. op = 'sync',
  240. wallets = wallet_arg,
  241. bal_chk_func = bal_chk_func )
  242. def sync_chkbal1(self):
  243. return self._sync_chkbal( '1', lambda n,b,ub: b == ub and 1 < b < 1.12 )
  244. # 1.234567891234 - 0.124 = 1.110567891234 (minus fees)
  245. def sync_chkbal2(self):
  246. return self._sync_chkbal( '1', lambda n,b,ub: b == ub and 0.8 < b < 0.86 )
  247. # 1.234567891234 - 0.124 - 0.257 = 0.853567891234 (minus fees)
  248. def sync_chkbal3(self):
  249. return self._sync_chkbal(
  250. '1-2',
  251. lambda n,b,ub: b == ub and ((n == 1 and 0.8 < b < 0.86) or (n == 2 and b > 1.23)) )
  252. def _mine_chk(self,desc):
  253. bal_type = {'locked':'b','unlocked':'ub'}[desc]
  254. return self.mine_chk(
  255. 'alice', 1, 0,
  256. lambda x: 0 < getattr(x,bal_type) < 1.234567891234,
  257. f'{desc} balance 0 < 1.234567891234' )
  258. def submit_transfer_tx1(self):
  259. return self._submit_transfer_tx()
  260. def resubmit_transfer_tx1(self):
  261. return self._submit_transfer_tx(
  262. relay_parm = self.tx_relay_daemon_proxy_parm,
  263. op = 'resubmit',
  264. check_bal = False)
  265. def submit_transfer_tx2(self):
  266. return self._submit_transfer_tx( relay_parm=self.tx_relay_daemon_parm )
  267. def _submit_transfer_tx(self,relay_parm=None,ext=None,op='submit',check_bal=True):
  268. self.insert_device_online()
  269. t = self._xmr_autosign_op(
  270. op = op,
  271. add_opts = [f'--tx-relay-daemon={relay_parm}'] if relay_parm else [],
  272. ext = ext,
  273. signable_desc = 'transaction',
  274. wait_signed = op == 'submit')
  275. t.expect( f'{op.capitalize()} transaction? (y/N): ', 'y' )
  276. t.written_to_file('Submitted transaction')
  277. self.remove_device_online()
  278. if check_bal:
  279. t.ok()
  280. return self._mine_chk('unlocked')
  281. else:
  282. return t
  283. def _export_outputs(self,wallet_arg,add_opts=[]):
  284. self.insert_device_online()
  285. t = self._xmr_autosign_op(
  286. op = 'export-outputs',
  287. wallet_arg = wallet_arg,
  288. add_opts = add_opts )
  289. t.written_to_file('Wallet outputs')
  290. self.remove_device_online()
  291. return t
  292. def export_outputs1(self):
  293. return self._export_outputs('1',['--rescan-blockchain'])
  294. def export_outputs2(self):
  295. return self._export_outputs('1-2')
  296. def _import_key_images(self,wallet_arg):
  297. self.insert_device_online()
  298. t = self._xmr_autosign_op(
  299. op = 'import-key-images',
  300. wallet_arg = wallet_arg,
  301. signable_desc = 'wallet outputs',
  302. wait_signed = True)
  303. t.read()
  304. self.remove_device_online()
  305. return t
  306. def import_key_images1(self):
  307. return self._import_key_images(None)
  308. def import_key_images2(self):
  309. return self._import_key_images(None)
  310. def create_fake_tx_files(self):
  311. imsg('Creating fake transaction files')
  312. self.asi_online.msg_dir.mkdir(exist_ok=True)
  313. self.asi_online.xmr_dir.mkdir(exist_ok=True)
  314. self.asi_online.xmr_tx_dir.mkdir(exist_ok=True)
  315. self.asi_online.xmr_outputs_dir.mkdir(exist_ok=True)
  316. for fn in (
  317. 'a.rawtx', 'a.sigtx',
  318. 'b.rawtx', 'b.sigtx',
  319. 'c.rawtx',
  320. 'd.sigtx',
  321. ):
  322. (self.asi_online.tx_dir / fn).touch()
  323. for fn in (
  324. 'a.rawmsg.json', 'a.sigmsg.json',
  325. 'b.rawmsg.json',
  326. 'c.sigmsg.json',
  327. 'd.rawmsg.json', 'd.sigmsg.json',
  328. ):
  329. (self.asi_online.msg_dir / fn).touch()
  330. for fn in (
  331. 'a.rawtx', 'a.sigtx', 'a.subtx',
  332. 'b.rawtx', 'b.sigtx',
  333. 'c.subtx',
  334. 'd.rawtx', 'd.subtx',
  335. 'e.rawtx',
  336. 'f.sigtx','f.subtx',
  337. ):
  338. (self.asi_online.xmr_tx_dir / fn).touch()
  339. for fn in (
  340. 'a.raw', 'a.sig',
  341. 'b.raw',
  342. 'c.sig',
  343. ):
  344. (self.asi_online.xmr_outputs_dir / fn).touch()
  345. return 'ok'
  346. def _gen_listing(self):
  347. for k in ('tx_dir','msg_dir','xmr_tx_dir','xmr_outputs_dir'):
  348. d = getattr(self.asi_online,k)
  349. if d.is_dir():
  350. yield '{:12} {}'.format(
  351. str(Path(*d.parts[6:])) + ':',
  352. ' '.join(sorted(i.name for i in d.iterdir()))).strip()
  353. def autosign_clean(self):
  354. self.do_mount_online(no_xmr_chk=True)
  355. self.create_fake_tx_files()
  356. before = '\n'.join(self._gen_listing())
  357. t = self.spawn('mmgen-autosign', self.opts + ['clean'])
  358. out = t.read()
  359. self.do_mount_online(no_xmr_chk=True)
  360. after = '\n'.join(self._gen_listing())
  361. for k in ('tx','msg','xmr'):
  362. shutil.rmtree(self.asi_online.mountpoint / k)
  363. self.asi_online.tx_dir.mkdir()
  364. self.do_umount_online()
  365. chk = """
  366. tx: a.sigtx b.sigtx c.rawtx d.sigtx
  367. msg: a.sigmsg.json b.rawmsg.json c.sigmsg.json d.sigmsg.json
  368. xmr/tx: a.subtx b.sigtx c.subtx d.subtx e.rawtx f.subtx
  369. xmr/outputs:
  370. """
  371. imsg(f'\nBefore cleaning:\n{before}')
  372. imsg(f'\nAfter cleaning:\n{after}')
  373. assert '13 files shredded' in out
  374. assert after + '\n' == fmt(chk), f'\n{after}\n!=\n{fmt(chk)}'
  375. return t
  376. def txlist(self):
  377. self.insert_device_online()
  378. t = self.spawn( 'mmgen-xmrwallet', self.autosign_opts + ['txlist'] )
  379. t.match_expect_list([
  380. 'SUBMITTED',
  381. 'Network','Submitted',
  382. 'Transfer 1:0','-> ext',
  383. 'Transfer 1:0','-> ext'
  384. ])
  385. self.remove_device_online()
  386. return t
  387. def check_tx_dirs(self):
  388. self.do_mount_online()
  389. before = '\n'.join(self._gen_listing())
  390. self.do_umount_online()
  391. t = self.spawn('mmgen-autosign', self.opts + ['clean'])
  392. t.read()
  393. self.do_mount_online()
  394. after = '\n'.join(self._gen_listing())
  395. self.do_umount_online()
  396. imsg(f'\nBefore cleaning:\n{before}')
  397. imsg(f'\nAfter cleaning:\n{after}')
  398. pat = r'xmr/tx: \s*\S+\.subtx \S+\.subtx\s+xmr/outputs:\s*$'
  399. assert re.search( pat, after, re.DOTALL ), f'regex search for {pat} failed'
  400. return t
  401. def view(self):
  402. return self.sync_wallets('alice', op='view', wallets='1')
  403. def listview(self):
  404. return self.sync_wallets('alice', op='listview', wallets='2')