ts_xmr_autosign.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, a command-line cryptocurrency wallet
  4. # Copyright (C)2013-2023 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
  9. # https://gitlab.com/mmgen/mmgen
  10. """
  11. test.test_py_d.ts_xmr_autosign: xmr autosigning tests for the test.py test suite
  12. """
  13. from .ts_xmrwallet import *
  14. from pathlib import Path
  15. from .ts_autosign import TestSuiteAutosignBase
  16. def make_burn_addr():
  17. from mmgen.tool.coin import tool_cmd
  18. return tool_cmd(
  19. cfg = cfg,
  20. cmdname = 'privhex2addr',
  21. proto = cfg._proto,
  22. mmtype = 'monero' ).privhex2addr('beadcafe'*8)
  23. class TestSuiteXMRAutosign(TestSuiteXMRWallet,TestSuiteAutosignBase):
  24. """
  25. Monero autosigning operations
  26. """
  27. tmpdir_nums = [39]
  28. # ts_xmrwallet attrs:
  29. user_data = (
  30. ('miner', '98831F3A', False, 130, '1', []),
  31. ('alice', 'FE3C6545', True, 150, '1-2', []),
  32. )
  33. # ts_autosign attrs:
  34. coins = ['xmr']
  35. daemon_coins = []
  36. txfile_coins = []
  37. live = False
  38. simulate = False
  39. bad_tx_count = 0
  40. tx_relay_user = 'miner'
  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. ('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_alice', 'sending funds to Alice'),
  57. ('create_transfer_tx1', 'creating a transfer TX'),
  58. ('sign_transfer_tx1', 'signing the transfer TX'),
  59. ('submit_transfer_tx1', 'submitting the transfer TX'),
  60. ('create_transfer_tx2', 'creating a transfer TX (for relaying via proxy)'),
  61. ('sign_transfer_tx2', 'signing the transfer TX (for relaying via proxy)'),
  62. ('submit_transfer_tx2', 'submitting the transfer TX (relaying via proxy)'),
  63. ('list_wallets', 'listing Alice’s wallets and checking balance'),
  64. ('dump_wallets', 'dumping Alice’s wallets'),
  65. ('delete_wallets', 'deleting Alice’s wallets'),
  66. ('restore_wallets', 'creating online (watch-only) wallets for Alice'),
  67. ('delete_dump_files', 'deleting Alice’s dump files'),
  68. ('export_outputs', 'exporting outputs from Alice’s watch-only wallets'),
  69. ('export_key_images', 'exporting signed key images from Alice’s offline wallets'),
  70. ('import_key_images', 'importing signed key images into Alice’s online wallets'),
  71. ('list_wallets', 'listing Alice’s wallets and checking balance'),
  72. ('txlist', 'listing Alice’s submitted transactions'),
  73. ('check_tx_dirs', 'cleaning and checking signable file directories'),
  74. )
  75. def __init__(self,trunner,cfgs,spawn):
  76. TestSuiteXMRWallet.__init__(self,trunner,cfgs,spawn)
  77. TestSuiteAutosignBase.__init__(self,trunner,cfgs,spawn)
  78. if trunner == None:
  79. return
  80. from mmgen.cfg import Config
  81. self.cfg = Config({
  82. 'coin': 'XMR',
  83. 'outdir': self.users['alice'].udir,
  84. 'wallet_dir': self.users['alice'].udir,
  85. 'wallet_rpc_password': 'passwOrd',
  86. })
  87. self.burn_addr = make_burn_addr()
  88. self.opts.append('--xmrwallets={}'.format( self.users['alice'].kal_range )) # mmgen-autosign opts
  89. self.autosign_opts = [f'--autosign-mountpoint={self.mountpoint}'] # mmgen-xmrwallet opts
  90. self.tx_count = 1
  91. def create_tmp_wallets(self):
  92. self.spawn('',msg_only=True)
  93. data = self.users['alice']
  94. from mmgen.wallet import Wallet
  95. from mmgen.xmrwallet import MoneroWalletOps,xmrwallet_uargs
  96. silence()
  97. kal = KeyAddrList(
  98. cfg = self.cfg,
  99. proto = self.proto,
  100. addr_idxs = '1-2',
  101. seed = Wallet(cfg,data.mmwords).seed )
  102. kal.file.write(ask_overwrite=False)
  103. fn = get_file_with_ext(data.udir,'akeys')
  104. m = MoneroWalletOps.create(
  105. self.cfg,
  106. xmrwallet_uargs(fn, '1-2', None))
  107. async_run(m.main())
  108. async_run(m.stop_wallet_daemon())
  109. end_silence()
  110. return 'ok'
  111. def _new_addr_alice(self,*args):
  112. data = self.users['alice']
  113. return self.new_addr_alice(
  114. *args,
  115. kafile = get_file_with_ext(data.udir,'akeys') )
  116. def new_account_alice(self):
  117. return self._new_addr_alice(
  118. '2',
  119. 'start',
  120. fr'Creating new account.*Index:\s+{self.na_idx}\s')
  121. def new_address_alice(self):
  122. return self._new_addr_alice(
  123. '2:1',
  124. 'continue',
  125. fr'Account index:\s+1\s+Creating new address' )
  126. def new_address_alice_label(self):
  127. return self._new_addr_alice(
  128. '2:1,Alice’s new address',
  129. 'stop',
  130. fr'Account index:\s+1\s+Creating new address.*Alice’s new address' )
  131. def dump_tmp_wallets(self):
  132. return self._dump_wallets(autosign=False)
  133. def dump_wallets(self):
  134. return self._dump_wallets(autosign=True)
  135. def _dump_wallets(self,autosign):
  136. data = self.users['alice']
  137. t = self.spawn(
  138. 'mmgen-xmrwallet',
  139. self.extra_opts
  140. + [f'--wallet-dir={data.udir}', f'--daemon=localhost:{data.md.rpc_port}']
  141. + (self.autosign_opts if autosign else [])
  142. + ['dump']
  143. + ([] if autosign else [get_file_with_ext(data.udir,'akeys')]) )
  144. t.expect('2 wallets dumped')
  145. return t
  146. def _delete_files(self,*ext_list):
  147. data = self.users['alice']
  148. self.spawn('',msg_only=True)
  149. for ext in ext_list:
  150. get_file_with_ext(data.udir,ext,no_dot=True,delete_all=True)
  151. return 'ok'
  152. def delete_tmp_wallets(self):
  153. return self._delete_files( 'MoneroWallet', 'MoneroWallet.keys', '.akeys' )
  154. def delete_wallets(self):
  155. return self._delete_files( 'MoneroWatchOnlyWallet', '.keys', '.address.txt' )
  156. def delete_tmp_dump_files(self):
  157. return self._delete_files( '.dump' )
  158. def delete_dump_files(self):
  159. return self._delete_files( '.dump' )
  160. def autosign_setup(self):
  161. Path(self.autosign_xmr_dir).mkdir(parents=True,exist_ok=True)
  162. Path(self.autosign_xmr_dir,'old.vkeys').touch()
  163. t = self.run_setup(
  164. mn_type = 'mmgen',
  165. mn_file = self.users['alice'].mmwords,
  166. use_dfl_wallet = None )
  167. t.expect('Continue with Monero setup? (Y/n): ','y')
  168. t.written_to_file('View keys')
  169. return t
  170. def create_watchonly_wallets(self):
  171. return self.create_wallets( 'alice', op='restore' )
  172. def restore_wallets(self):
  173. return self.create_wallets( 'alice', op='restore' )
  174. def list_wallets(self):
  175. return self.sync_wallets(
  176. 'alice',
  177. op = 'list',
  178. bal_chk_func = lambda n,bal: (0.83 < bal < 0.8536) if n == 0 else True )
  179. # 1.234567891234 - 0.124 - 0.257 = 0.853567891234 (minus fees)
  180. def _create_transfer_tx(self,amt):
  181. return self.do_op('transfer','alice',f'1:0:{self.burn_addr},{amt}',no_relay=True,do_ret=True)
  182. def create_transfer_tx1(self):
  183. return self._create_transfer_tx('0.124')
  184. def create_transfer_tx2(self):
  185. get_file_with_ext(self.asi.xmr_tx_dir,'rawtx',delete_all=True)
  186. get_file_with_ext(self.asi.xmr_tx_dir,'sigtx',delete_all=True)
  187. return self._create_transfer_tx('0.257')
  188. def _sign_transfer_tx(self):
  189. return self.do_sign(['--full-summary'],tx_name='Monero transaction')
  190. def sign_transfer_tx1(self):
  191. return self._sign_transfer_tx()
  192. def sign_transfer_tx2(self):
  193. return self._sign_transfer_tx()
  194. def _xmr_autosign_op(self,op,desc,dtype=None,ext=None,wallet_arg=None,add_opts=[]):
  195. data = self.users['alice']
  196. args = (
  197. self.extra_opts
  198. + self.autosign_opts
  199. + [f'--wallet-dir={data.udir}']
  200. + ([f'--daemon=localhost:{data.md.rpc_port}'] if not op == 'submit' else [])
  201. + add_opts
  202. + [ op ]
  203. + ([get_file_with_ext(self.asi.xmr_tx_dir,ext)] if ext else [])
  204. + ([wallet_arg] if wallet_arg else [])
  205. )
  206. t = self.spawn( 'mmgen-xmrwallet', args, extra_desc=f'({desc}, Alice)' )
  207. if dtype:
  208. t.written_to_file(dtype.capitalize())
  209. return t
  210. def submit_transfer_tx1(self):
  211. return self._submit_transfer_tx( self.tx_relay_daemon_parm, ext='sigtx' )
  212. def submit_transfer_tx2(self):
  213. return self._submit_transfer_tx( self.tx_relay_daemon_proxy_parm, ext=None )
  214. def _submit_transfer_tx(self,relay_parm,ext):
  215. t = self._xmr_autosign_op(
  216. op = 'submit',
  217. desc = 'submitting TX',
  218. add_opts = [f'--tx-relay-daemon={relay_parm}'],
  219. ext = ext )
  220. t.expect( 'Submit transaction? (y/N): ', 'y' )
  221. t.written_to_file('Submitted transaction')
  222. t.ok()
  223. return self.mine_chk(
  224. 'alice', 1, 0,
  225. lambda x: 0 < x < 1.234567891234,
  226. 'unlocked balance 0 < 1.234567891234' )
  227. def export_outputs(self):
  228. return self._xmr_autosign_op(
  229. op = 'export-outputs',
  230. desc = 'exporting outputs',
  231. dtype = 'wallet outputs',
  232. wallet_arg = '1-2' )
  233. def export_key_images(self):
  234. self.tx_count = 2
  235. return self.do_sign(['--full-summary'],tx_name='Monero wallet outputs file')
  236. def import_key_images(self):
  237. return self._xmr_autosign_op(
  238. op = 'import-key-images',
  239. desc = 'importing key images' )
  240. def create_fake_tx_files(self):
  241. imsg('Creating fake transaction files')
  242. self.asi.msg_dir.mkdir(exist_ok=True)
  243. self.asi.xmr_dir.mkdir(exist_ok=True)
  244. self.asi.xmr_tx_dir.mkdir(exist_ok=True)
  245. self.asi.xmr_outputs_dir.mkdir(exist_ok=True)
  246. for fn in (
  247. 'a.rawtx', 'a.sigtx',
  248. 'b.rawtx', 'b.sigtx',
  249. 'c.rawtx',
  250. 'd.sigtx',
  251. ):
  252. (self.asi.tx_dir / fn).touch()
  253. for fn in (
  254. 'a.rawmsg.json', 'a.sigmsg.json',
  255. 'b.rawmsg.json',
  256. 'c.sigmsg.json',
  257. 'd.rawmsg.json', 'd.sigmsg.json',
  258. ):
  259. (self.asi.msg_dir / fn).touch()
  260. for fn in (
  261. 'a.rawtx', 'a.sigtx', 'a.subtx',
  262. 'b.rawtx', 'b.sigtx',
  263. 'c.subtx',
  264. 'd.rawtx', 'd.subtx',
  265. 'e.rawtx',
  266. 'f.sigtx','f.subtx',
  267. ):
  268. (self.asi.xmr_tx_dir / fn).touch()
  269. for fn in (
  270. 'a.raw', 'a.sig',
  271. 'b.raw',
  272. 'c.sig',
  273. ):
  274. (self.asi.xmr_outputs_dir / fn).touch()
  275. return 'ok'
  276. def _gen_listing(self):
  277. for k in ('tx_dir','msg_dir','xmr_tx_dir','xmr_outputs_dir'):
  278. d = getattr(self.asi,k)
  279. if d.is_dir():
  280. yield '{:12} {}'.format(
  281. str(Path(*d.parts[4:])) + ':',
  282. ' '.join(sorted(i.name for i in d.iterdir()))).strip()
  283. def clean(self):
  284. self.create_fake_tx_files()
  285. before = '\n'.join(self._gen_listing())
  286. t = self.spawn( 'mmgen-autosign', [f'--mountpoint={self.mountpoint}','clean'] )
  287. out = t.read()
  288. after = '\n'.join(self._gen_listing())
  289. chk = """
  290. tx: a.sigtx b.sigtx c.rawtx d.sigtx
  291. msg: a.sigmsg.json b.rawmsg.json c.sigmsg.json d.sigmsg.json
  292. xmr/tx: a.subtx b.sigtx c.subtx d.subtx e.rawtx f.subtx
  293. xmr/outputs:
  294. """
  295. shutil.rmtree(self.asi.mountpoint)
  296. self.asi.tx_dir.mkdir(parents=True)
  297. imsg(f'\nBefore cleaning:\n{before}')
  298. imsg(f'\nAfter cleaning:\n{after}')
  299. assert '13 files shredded' in out
  300. assert after + '\n' == fmt(chk), f'\n{after}\n!=\n{fmt(chk)}'
  301. return t
  302. def txlist(self):
  303. t = self.spawn( 'mmgen-xmrwallet', self.autosign_opts + ['txlist'] )
  304. t.match_expect_list([
  305. 'SUBMITTED',
  306. 'Network','Submitted',
  307. 'Transfer 1:0','-> ext',
  308. 'Transfer 1:0','-> ext'
  309. ])
  310. return t
  311. def check_tx_dirs(self):
  312. before = '\n'.join(self._gen_listing())
  313. t = self.spawn( 'mmgen-autosign', [f'--mountpoint={self.mountpoint}','clean'] )
  314. t.read()
  315. after = '\n'.join(self._gen_listing())
  316. imsg(f'\nBefore cleaning:\n{before}')
  317. imsg(f'\nAfter cleaning:\n{after}')
  318. pat = r'xmr/tx: \s*\S+\.subtx \S+\.subtx\s+xmr/outputs:\s*$'
  319. assert re.search( pat, after, re.DOTALL ), f'regex search for {pat} failed'
  320. return t