ct_xmrwallet.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2024 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_py_d.ct_xmrwallet: xmrwallet tests for the cmdtest.py test suite
  20. """
  21. import sys,os,time,re,atexit,asyncio,shutil
  22. from subprocess import run,PIPE
  23. from collections import namedtuple
  24. from mmgen.util import msg,fmt,async_run,capfirst,is_int,die,list_gen
  25. from mmgen.obj import MMGenRange
  26. from mmgen.amt import XMRAmt
  27. from mmgen.addrlist import ViewKeyAddrList,KeyAddrList,AddrIdxList
  28. from ..include.common import (
  29. cfg,
  30. omsg,
  31. oqmsg_r,
  32. ok,
  33. imsg,
  34. imsg_r,
  35. write_data_to_file,
  36. read_from_file,
  37. silence,
  38. end_silence,
  39. strip_ansi_escapes
  40. )
  41. from .common import get_file_with_ext
  42. from .ct_base import CmdTestBase
  43. # atexit functions:
  44. def stop_daemons(self):
  45. for v in self.users.values():
  46. if '--restricted-rpc' in v.md.start_cmd:
  47. v.md.stop()
  48. else:
  49. async_run(v.md_rpc.stop_daemon())
  50. def stop_miner_wallet_daemon(self):
  51. async_run(self.users['miner'].wd_rpc.stop_daemon())
  52. def kill_proxy(cls,args):
  53. if sys.platform == 'linux':
  54. omsg(f'Killing SSH SOCKS server at localhost:{cls.socks_port}')
  55. cmd = [ 'pkill', '-f', ' '.join(args) ]
  56. run(cmd)
  57. class CmdTestXMRWallet(CmdTestBase):
  58. """
  59. Monero wallet operations
  60. """
  61. networks = ('xmr',)
  62. passthru_opts = ()
  63. tmpdir_nums = [29]
  64. dfl_random_txs = 3
  65. color = True
  66. socks_port = 49237
  67. # Bob’s daemon is stopped via process kill, not RPC, so put Bob last in list:
  68. user_data = (
  69. ('miner', '98831F3A', False, 130, '1-2', []),
  70. ('alice', 'FE3C6545', False, 150, '1-4', []),
  71. ('bob', '1378FC64', False, 140, None, ['--restricted-rpc']),
  72. )
  73. tx_relay_user = 'bob'
  74. datadir_base = os.path.join('test','daemons','xmrtest')
  75. cmd_group = (
  76. ('daemon_version', 'checking daemon version'),
  77. ('gen_kafiles', 'generating key-address files'),
  78. ('create_wallets_miner', 'creating Monero wallets (Miner)'),
  79. ('set_label_miner', 'setting an address label (Miner, primary account)'),
  80. ('mine_initial_coins', 'mining initial coins'),
  81. ('create_wallets_alice', 'creating Monero wallets (Alice)'),
  82. ('fund_alice', 'sending funds'),
  83. ('sync_wallets_all', 'syncing all wallets'),
  84. ('new_account_alice', 'creating a new account (Alice)'),
  85. ('new_account_alice_label', 'creating a new account (Alice, with label)'),
  86. ('new_address_alice', 'creating a new address (Alice)'),
  87. ('new_address_alice_label', 'creating a new address (Alice, with label)'),
  88. ('remove_label_alice', 'removing an address label (Alice, subaddress)'),
  89. ('set_label_alice', 'setting an address label (Alice, subaddress)'),
  90. ('sync_wallets_selected', 'syncing selected wallets'),
  91. ('sweep_to_address_proxy', 'sweeping to new address (via TX relay + proxy)'),
  92. ('sweep_to_account', 'sweeping to new account'),
  93. ('sweep_to_address_noproxy', 'sweeping to new address (via TX relay, no proxy)'),
  94. ('transfer_to_miner_proxy', 'transferring funds to Miner (via TX relay + proxy)'),
  95. ('transfer_to_miner_noproxy', 'transferring funds to Miner (via TX relay, no proxy)'),
  96. ('transfer_to_miner_create1', 'transferring funds to Miner (create TX)'),
  97. ('transfer_to_miner_send1', 'transferring funds to Miner (send TX via proxy)'),
  98. ('transfer_to_miner_create2', 'transferring funds to Miner (create TX)'),
  99. ('transfer_to_miner_send2', 'transferring funds to Miner (send TX, no proxy)'),
  100. ('sweep_create_and_send', 'sweeping to new account (create TX + send TX, in stages)'),
  101. ('list_wallets_all', 'listing wallets'),
  102. ('stop_daemons', 'stopping all wallet and coin daemons'),
  103. )
  104. def __init__(self,trunner,cfgs,spawn):
  105. CmdTestBase.__init__(self,trunner,cfgs,spawn)
  106. if trunner is None:
  107. return
  108. from mmgen.protocol import init_proto
  109. self.proto = init_proto( cfg, 'XMR', network='mainnet' )
  110. self.extra_opts = ['--wallet-rpc-password=passw0rd']
  111. self.autosign_mountpoint = os.path.join(self.tmpdir,'mmgen_autosign')
  112. self.autosign_xmr_dir = os.path.join(self.tmpdir,'mmgen_autosign','xmr')
  113. self.init_users()
  114. self.init_daemon_args()
  115. self.autosign_opts = []
  116. for v in self.users.values():
  117. run(['mkdir','-p',v.udir])
  118. self.tx_relay_daemon_parm = 'localhost:{}'.format( self.users[self.tx_relay_user].md.rpc_port )
  119. self.tx_relay_daemon_proxy_parm = (
  120. self.tx_relay_daemon_parm + f':127.0.0.1:{self.socks_port}' ) # must be IP, not 'localhost'
  121. if not cfg.no_daemon_stop:
  122. atexit.register(stop_daemons,self)
  123. atexit.register(stop_miner_wallet_daemon,self)
  124. if not cfg.no_daemon_autostart:
  125. stop_daemons(self)
  126. time.sleep(0.2)
  127. if os.path.exists(self.datadir_base):
  128. shutil.rmtree(self.datadir_base)
  129. os.makedirs(self.datadir_base)
  130. self.start_daemons()
  131. self.init_proxy()
  132. self.balance = None
  133. # init methods
  134. @classmethod
  135. def init_proxy(cls,external_call=False):
  136. def port_in_use(port):
  137. import socket
  138. try:
  139. socket.create_connection(('localhost',port)).close()
  140. except:
  141. return False
  142. else:
  143. return True
  144. def start_proxy():
  145. if external_call or not cfg.no_daemon_autostart:
  146. run(a+b2)
  147. omsg(f'SSH SOCKS server started, listening at localhost:{cls.socks_port}')
  148. debug_file = os.path.join('' if external_call else cls.datadir_base,'txrelay-proxy.debug')
  149. a = ['ssh','-x','-o','ExitOnForwardFailure=True','-D',f'localhost:{cls.socks_port}']
  150. b0 = ['-o','PasswordAuthentication=False']
  151. b1 = ['localhost','true']
  152. b2 = ['-fN','-E', debug_file, 'localhost']
  153. if port_in_use(cls.socks_port):
  154. omsg(f'Port {cls.socks_port} already in use. Assuming SSH SOCKS server is running')
  155. else:
  156. cp = run(a+b0+b1,stdout=PIPE,stderr=PIPE)
  157. err = cp.stderr.decode()
  158. if err:
  159. omsg(err)
  160. if cp.returncode == 0:
  161. start_proxy()
  162. elif 'onnection refused' in err:
  163. die(2,fmt("""
  164. The SSH daemon must be running and listening on localhost in order to test
  165. XMR TX relaying via SOCKS proxy. If sshd is not running, please start it.
  166. Otherwise, add the line 'ListenAddress 127.0.0.1' to your sshd_config, and
  167. then restart the daemon.
  168. """,indent=' '))
  169. elif 'ermission denied' in err:
  170. msg(fmt(f"""
  171. In order to test XMR TX relaying via SOCKS proxy, it’s desirable to enable
  172. SSH to localhost without a password, which is not currently supported by
  173. your configuration. Your possible courses of action:
  174. 1. Continue by answering 'y' at this prompt, and enter your system password
  175. at the following prompt;
  176. 2. Exit the test here, add your user SSH public key to your user
  177. 'authorized_keys' file, and restart the test; or
  178. 3. Exit the test here, start the SSH SOCKS proxy manually by entering the
  179. following command, and restart the test:
  180. {' '.join(a+b2)}
  181. """,indent=' ',strip_char='\t'))
  182. from mmgen.ui import keypress_confirm
  183. if keypress_confirm(cfg,'Continue?'):
  184. start_proxy()
  185. else:
  186. die(1,'Exiting at user request')
  187. else:
  188. die(2,fmt(f"""
  189. Please start the SSH SOCKS proxy by entering the following command:
  190. {' '.join(a+b2)}
  191. Then restart the test.
  192. """,indent=' '))
  193. if not (external_call or cfg.no_daemon_stop):
  194. atexit.unregister(kill_proxy)
  195. atexit.register(kill_proxy, cls, a + b2)
  196. return True
  197. def init_users(self):
  198. from mmgen.daemon import CoinDaemon
  199. from mmgen.proto.xmr.daemon import MoneroWalletDaemon
  200. from mmgen.proto.xmr.rpc import MoneroRPCClient,MoneroWalletRPCClient
  201. self.users = {}
  202. tmpdir_num = self.tmpdir_nums[0]
  203. ud = namedtuple('user_data',[
  204. 'sid',
  205. 'mmwords',
  206. 'autosign',
  207. 'udir',
  208. 'datadir',
  209. 'kal_range',
  210. 'kafile',
  211. 'walletfile_fs',
  212. 'addrfile_fs',
  213. 'md',
  214. 'md_rpc',
  215. 'wd',
  216. 'wd_rpc',
  217. 'add_coind_args',
  218. ])
  219. # kal_range must be None, a single digit, or a single hyphenated range
  220. for ( user,
  221. sid,
  222. autosign,
  223. shift,
  224. kal_range,
  225. add_coind_args ) in self.user_data:
  226. tmpdir = os.path.join('test','tmp',str(tmpdir_num))
  227. udir = os.path.join(tmpdir,user)
  228. datadir = os.path.join(self.datadir_base,user)
  229. md = CoinDaemon(
  230. cfg = cfg,
  231. proto = self.proto,
  232. test_suite = True,
  233. port_shift = shift,
  234. opts = ['online'],
  235. datadir = datadir
  236. )
  237. md_rpc = MoneroRPCClient(
  238. cfg = cfg,
  239. proto = self.proto,
  240. host = 'localhost',
  241. port = md.rpc_port,
  242. user = None,
  243. passwd = None,
  244. test_connection = False,
  245. daemon = md,
  246. )
  247. wd = MoneroWalletDaemon(
  248. cfg = cfg,
  249. proto = self.proto,
  250. test_suite = True,
  251. wallet_dir = udir,
  252. user = 'foo',
  253. passwd = 'bar',
  254. port_shift = shift,
  255. monerod_addr = f'127.0.0.1:{md.rpc_port}',
  256. )
  257. wd_rpc = MoneroWalletRPCClient(
  258. cfg = cfg,
  259. daemon = wd,
  260. test_connection = False,
  261. )
  262. if autosign:
  263. kafile_suf = 'vkeys'
  264. fn_stem = 'MoneroWatchOnlyWallet'
  265. kafile_dir = self.autosign_xmr_dir
  266. else:
  267. kafile_suf = 'akeys'
  268. fn_stem = 'MoneroWallet'
  269. kafile_dir = udir
  270. self.users[user] = ud(
  271. sid = sid,
  272. mmwords = f'test/ref/{sid}.mmwords',
  273. autosign = autosign,
  274. udir = udir,
  275. datadir = datadir,
  276. kal_range = kal_range,
  277. kafile = f'{kafile_dir}/{sid}-XMR-M[{kal_range}].{kafile_suf}',
  278. walletfile_fs = f'{udir}/{sid}-{{}}-{fn_stem}',
  279. addrfile_fs = f'{udir}/{sid}-{{}}-{fn_stem}.address.txt',
  280. md = md,
  281. md_rpc = md_rpc,
  282. wd = wd,
  283. wd_rpc = wd_rpc,
  284. add_coind_args = add_coind_args,
  285. )
  286. def init_daemon_args(self):
  287. common_args = ['--p2p-bind-ip=127.0.0.1','--fixed-difficulty=1','--regtest'] # ,'--rpc-ssl-allow-any-cert']
  288. for u in self.users:
  289. other_ports = [self.users[u2].md.p2p_port for u2 in self.users if u2 != u]
  290. node_args = [f'--add-exclusive-node=127.0.0.1:{p}' for p in other_ports]
  291. self.users[u].md.usr_coind_args = (
  292. common_args +
  293. node_args +
  294. self.users[u].add_coind_args )
  295. # cmd_group methods
  296. def daemon_version(self):
  297. rpc_port = self.users['miner'].md.rpc_port
  298. return self.spawn( 'mmgen-tool', ['--coin=xmr', f'--rpc-port={rpc_port}', 'daemon_version'] )
  299. def gen_kafiles(self):
  300. for user,data in self.users.items():
  301. if not data.kal_range:
  302. continue
  303. if data.autosign:
  304. continue
  305. run(['mkdir','-p',data.udir])
  306. run(f'rm -f {data.kafile}',shell=True)
  307. t = self.spawn(
  308. 'mmgen-keygen', [
  309. '-q', '--accept-defaults', '--coin=xmr',
  310. f'--outdir={data.udir}', data.mmwords, data.kal_range
  311. ],
  312. extra_desc = f'({capfirst(user)})' )
  313. t.read()
  314. t.ok()
  315. t.skip_ok = True
  316. return t
  317. def create_wallets_miner(self):
  318. return self.create_wallets('miner')
  319. def create_wallets_alice(self):
  320. return self.create_wallets('alice')
  321. def create_wallets(self,user,wallet=None,add_opts=[],op='create'):
  322. assert wallet is None or is_int(wallet), 'wallet arg'
  323. data = self.users[user]
  324. stem_glob = data.walletfile_fs.format(wallet or '*')
  325. for glob in (
  326. stem_glob,
  327. stem_glob + '.keys',
  328. stem_glob + '.address.txt' ):
  329. run( f'rm -f {glob}', shell=True )
  330. t = self.spawn(
  331. 'mmgen-xmrwallet',
  332. [f'--wallet-dir={data.udir}']
  333. + self.extra_opts
  334. + (self.autosign_opts if data.autosign else [])
  335. + add_opts
  336. + [op]
  337. + ([] if data.autosign else [data.kafile])
  338. + [wallet or data.kal_range]
  339. )
  340. for i in MMGenRange(wallet or data.kal_range).items:
  341. write_data_to_file(
  342. cfg,
  343. self.users[user].addrfile_fs.format(i),
  344. t.expect_getend('Address: '),
  345. quiet = True
  346. )
  347. return t
  348. def new_addr_alice(self,spec,cfg,expect,kafile=None):
  349. data = self.users['alice']
  350. t = self.spawn(
  351. 'mmgen-xmrwallet',
  352. self.extra_opts +
  353. [f'--wallet-dir={data.udir}'] +
  354. [f'--daemon=localhost:{data.md.rpc_port}'] +
  355. (['--no-start-wallet-daemon'] if cfg in ('continue','stop') else []) +
  356. (['--no-stop-wallet-daemon'] if cfg in ('start','continue') else []) +
  357. ['new', (kafile or data.kafile), spec] )
  358. t.expect(expect, 'y', regex=True)
  359. return t
  360. na_idx = 1
  361. def new_account_alice(self):
  362. return self.new_addr_alice(
  363. '4',
  364. 'start',
  365. r'Creating new account for wallet .*4.* with label .*‘xmrwallet new account .*y/N\): ')
  366. def new_account_alice_label(self):
  367. return self.new_addr_alice(
  368. '4,Alice’s new account',
  369. 'continue',
  370. r'Creating new account for wallet .*4.* with label .*‘Alice’s new account .*y/N\): ')
  371. def new_address_alice(self):
  372. return self.new_addr_alice(
  373. '4:2',
  374. 'continue',
  375. r'Creating new address for wallet .*4.*, account .*#2.* with label .*‘xmrwallet new address .*y/N\): ')
  376. def new_address_alice_label(self):
  377. return self.new_addr_alice(
  378. '4:2,Alice’s new address',
  379. 'stop',
  380. r'Creating new address for wallet .*4.*, account .*#2.* with label .*‘Alice’s new address .*y/N\): ')
  381. async def mine_initial_coins(self):
  382. self.spawn('', msg_only=True, extra_desc='(opening wallet)')
  383. await self.open_wallet_user('miner',1)
  384. ok()
  385. # NB: a large balance is required to avoid ‘insufficient outputs’ error
  386. return await self.mine_chk('miner',1,0,lambda x: x.ub > 2000,'unlocked balance > 2000')
  387. async def fund_alice(self,wallet=1,check_bal=True):
  388. self.spawn('', msg_only=True, extra_desc='(transferring funds from Miner wallet)')
  389. await self.transfer(
  390. 'miner',
  391. 1234567891234,
  392. read_from_file(self.users['alice'].addrfile_fs.format(wallet)),
  393. )
  394. if not check_bal:
  395. return 'ok'
  396. ok()
  397. bal = '1.234567891234'
  398. return await self.mine_chk(
  399. 'alice',wallet,0,
  400. lambda x: str(x.ub) == bal,f'unlocked balance == {bal}',
  401. random_txs = self.dfl_random_txs
  402. )
  403. def set_label_miner(self):
  404. return self.set_label_user('miner', '1:0:0,"Miner’s new primary account label [1:0:0]"', 'updated')
  405. def remove_label_alice(self):
  406. return self.set_label_user('alice', '4:2:2,""', 'removed')
  407. def set_label_alice(self):
  408. return self.set_label_user('alice', '4:2:2,"Alice’s new subaddress label [4:2:2]"', 'set')
  409. def set_label_user(self,user,label_spec,expect):
  410. data = self.users[user]
  411. cmd_opts = [f'--wallet-dir={data.udir}', f'--daemon=localhost:{data.md.rpc_port}']
  412. t = self.spawn(
  413. 'mmgen-xmrwallet',
  414. self.extra_opts + cmd_opts + ['label', data.kafile, label_spec]
  415. )
  416. t.expect('(y/N): ','y')
  417. t.expect(f'Label successfully {expect}')
  418. return t
  419. def sync_wallets_all(self):
  420. return self.sync_wallets('alice',add_opts=['--rescan-blockchain'])
  421. def sync_wallets_selected(self):
  422. return self.sync_wallets('alice',wallets='1-2,4')
  423. def list_wallets_all(self):
  424. return self.sync_wallets('alice',op='list')
  425. def sync_wallets(self,user,op='sync',wallets=None,add_opts=[],bal_chk_func=None):
  426. data = self.users[user]
  427. cmd_opts = list_gen(
  428. [f'--wallet-dir={data.udir}'],
  429. [f'--daemon=localhost:{data.md.rpc_port}'],
  430. )
  431. t = self.spawn(
  432. 'mmgen-xmrwallet',
  433. self.extra_opts
  434. + cmd_opts
  435. + self.autosign_opts
  436. + add_opts
  437. + [op]
  438. + ([] if data.autosign else [data.kafile])
  439. + ([wallets] if wallets else [])
  440. )
  441. wlist = AddrIdxList(wallets) if wallets else MMGenRange(data.kal_range).items
  442. for n,wnum in enumerate(wlist,1):
  443. t.expect('ing wallet {}/{} ({})'.format(
  444. n,
  445. len(wlist),
  446. os.path.basename(data.walletfile_fs.format(wnum)),
  447. ))
  448. if op in ('view','listview'):
  449. t.expect('Wallet height: ')
  450. else:
  451. t.expect('Chain height: ')
  452. t.expect('Wallet height: ')
  453. res = strip_ansi_escapes(t.expect_getend('Balance: '))
  454. if bal_chk_func:
  455. m = re.match( r'(\S+) Unlocked balance: (\S+)', res, re.DOTALL )
  456. amts = [XMRAmt(amt) for amt in m.groups()]
  457. assert bal_chk_func(n,*amts), f'balance check for wallet {n} failed!'
  458. return t
  459. def do_op(
  460. self,
  461. op,
  462. user,
  463. arg2,
  464. tx_relay_parm = None,
  465. no_relay = False,
  466. return_amt = False,
  467. reuse_acct = False,
  468. add_desc = None,
  469. do_ret = False):
  470. data = self.users[user]
  471. cmd_opts = list_gen(
  472. [f'--wallet-dir={data.udir}'],
  473. [f'--outdir={data.udir}', not data.autosign],
  474. [f'--daemon=localhost:{data.md.rpc_port}'],
  475. [f'--tx-relay-daemon={tx_relay_parm}', tx_relay_parm],
  476. ['--no-relay', no_relay and not data.autosign],
  477. [f'--autosign-mountpoint={self.autosign_mountpoint}', data.autosign],
  478. )
  479. add_desc = (', ' + add_desc) if add_desc else ''
  480. t = self.spawn(
  481. 'mmgen-xmrwallet',
  482. self.extra_opts
  483. + cmd_opts
  484. + [op]
  485. + ([] if data.autosign else [data.kafile])
  486. + [arg2],
  487. extra_desc = f'({capfirst(user)}{add_desc})' )
  488. if op == 'sign':
  489. return t
  490. if op == 'sweep':
  491. t.expect(
  492. r'Create new {} .* \(y/N\): '.format(('address','account')[',' in arg2]),
  493. ('y','n')[reuse_acct],
  494. regex=True )
  495. if reuse_acct:
  496. t.expect( r'to last existing account .* \(y/N\): ','y', regex=True )
  497. if return_amt:
  498. amt = XMRAmt(strip_ansi_escapes(t.expect_getend('Amount: ')).replace('XMR','').strip())
  499. dtype = 'unsigned' if data.autosign else 'signed'
  500. t.expect(f'Save {dtype} transaction? (y/N): ','y')
  501. t.written_to_file(f'{dtype.capitalize()} transaction')
  502. if not no_relay:
  503. t.expect(f'Relay {op} transaction? (y/N): ','y')
  504. get_file_with_ext(self.users[user].udir,'sigtx',delete_all=True)
  505. t.read()
  506. return t if do_ret else amt if return_amt else t.ok()
  507. def sweep_to_address_proxy(self):
  508. self.do_op('sweep','alice','1:0',self.tx_relay_daemon_proxy_parm)
  509. return self.mine_chk('alice',1,0,lambda x: x.ub > 1,'unlocked balance > 1')
  510. def sweep_to_account(self):
  511. self.do_op('sweep','alice','1:0,2')
  512. return self.mine_chk('alice',2,1,lambda x: x.ub > 1,'unlocked balance > 1')
  513. def sweep_to_address_noproxy(self):
  514. self.do_op('sweep','alice','2:1',self.tx_relay_daemon_parm)
  515. return self.mine_chk('alice',2,1,lambda x: x.ub > 0.9,'unlocked balance > 0.9')
  516. async def transfer_to_miner_proxy(self):
  517. addr = read_from_file(self.users['miner'].addrfile_fs.format(2))
  518. amt = '0.135'
  519. self.do_op('transfer','alice',f'2:1:{addr},{amt}',self.tx_relay_daemon_proxy_parm)
  520. await self.stop_wallet_user('miner')
  521. await self.open_wallet_user('miner',2)
  522. await self.mine_chk('miner',2,0,lambda x: str(x.ub) == amt,f'unlocked balance == {amt}')
  523. ok()
  524. return await self.mine_chk('alice',2,1,lambda x: x.ub > 0.9,'unlocked balance > 0.9')
  525. async def transfer_to_miner_noproxy(self):
  526. addr = read_from_file(self.users['miner'].addrfile_fs.format(2))
  527. self.do_op('transfer','alice',f'2:1:{addr},0.0995',self.tx_relay_daemon_parm)
  528. await self.mine_chk('miner',2,0,lambda x: str(x.ub) == '0.2345','unlocked balance == 0.2345')
  529. ok()
  530. return await self.mine_chk('alice',2,1,lambda x: x.ub > 0.9,'unlocked balance > 0.9')
  531. def transfer_to_miner_create(self,amt):
  532. get_file_with_ext(self.users['alice'].udir,'sigtx',delete_all=True)
  533. addr = read_from_file(self.users['miner'].addrfile_fs.format(2))
  534. return self.do_op('transfer','alice',f'2:1:{addr},{amt}',no_relay=True,do_ret=True)
  535. def transfer_to_miner_create1(self):
  536. return self.transfer_to_miner_create('0.0111')
  537. def transfer_to_miner_create2(self):
  538. return self.transfer_to_miner_create('0.0012')
  539. def relay_tx(self,relay_opt,add_desc=None):
  540. user = 'alice'
  541. data = self.users[user]
  542. add_desc = (', ' + add_desc) if add_desc else ''
  543. t = self.spawn(
  544. 'mmgen-xmrwallet',
  545. self.extra_opts
  546. + [ relay_opt, 'relay', get_file_with_ext(data.udir,'sigtx') ],
  547. extra_desc = f'(relaying TX, {capfirst(user)}{add_desc})' )
  548. t.expect('Relay transaction? ','y')
  549. t.read()
  550. t.ok()
  551. return t
  552. async def transfer_to_miner_send1(self):
  553. self.relay_tx(f'--tx-relay-daemon={self.tx_relay_daemon_proxy_parm}',add_desc='via proxy')
  554. await self.mine_chk('miner',2,0,lambda x: str(x.ub) == '0.2456','unlocked balance == 0.2456')
  555. ok()
  556. return await self.mine_chk('alice',2,1,lambda x: x.ub > 0.9,'unlocked balance > 0.9')
  557. async def transfer_to_miner_send2(self):
  558. self.relay_tx(f'--tx-relay-daemon={self.tx_relay_daemon_parm}',add_desc='no proxy')
  559. await self.mine_chk('miner',2,0,lambda x: str(x.ub) == '0.2468','unlocked balance == 0.2468')
  560. ok()
  561. return await self.mine_chk('alice',2,1,lambda x: x.ub > 0.9,'unlocked balance > 0.9')
  562. async def sweep_create_and_send(self):
  563. bal = XMRAmt('0')
  564. min_bal = XMRAmt('0.9')
  565. for i in range(4):
  566. if i:
  567. ok()
  568. get_file_with_ext(self.users['alice'].udir,'sigtx',delete_all=True)
  569. send_amt = self.do_op(
  570. 'sweep','alice','2:1,3', # '2:1,3'
  571. no_relay = True,
  572. reuse_acct = True,
  573. add_desc = f'TX #{i+1}',
  574. return_amt = True )
  575. ok()
  576. self.relay_tx(f'--tx-relay-daemon={self.tx_relay_daemon_parm}',add_desc=f'send amt: {send_amt} XMR')
  577. await self.mine_chk('alice',2,1,lambda x: 'chk_bal_chg','balance has changed')
  578. ok()
  579. bal_info = await self.mine_chk('alice',3,0,lambda x,y=bal: x.ub > y, f'bal > {bal}',return_bal=True)
  580. bal += bal_info.ub
  581. if bal >= min_bal:
  582. return 'ok'
  583. return False
  584. # wallet methods
  585. async def open_wallet_user(self,user,wnum):
  586. data = self.users[user]
  587. silence()
  588. kal = (ViewKeyAddrList if data.autosign else KeyAddrList)(
  589. cfg = cfg,
  590. proto = self.proto,
  591. addrfile = data.kafile,
  592. skip_chksum_msg = True,
  593. key_address_validity_check = False )
  594. end_silence()
  595. self.users[user].wd.start(silent=not (cfg.exact_output or cfg.verbose))
  596. return data.wd_rpc.call(
  597. 'open_wallet',
  598. filename = os.path.basename(data.walletfile_fs.format(wnum)),
  599. password = kal.entry(wnum).wallet_passwd )
  600. async def stop_wallet_user(self,user):
  601. await self.users[user].wd_rpc.stop_daemon(silent=not (cfg.exact_output or cfg.verbose))
  602. return 'ok'
  603. # mining methods
  604. async def mine5(self):
  605. return await self.mine(5)
  606. async def _get_height(self):
  607. u = self.users['miner']
  608. for _ in range(20):
  609. try:
  610. return u.md_rpc.call('get_last_block_header')['block_header']['height']
  611. except Exception as e:
  612. if 'onnection refused' in str(e):
  613. omsg(f'{e}\nMonerod appears to have crashed. Attempting to restart...')
  614. await asyncio.sleep(5)
  615. u.md.restart()
  616. await asyncio.sleep(5)
  617. await self.start_mining()
  618. else:
  619. raise
  620. else:
  621. die(2,'Restart attempt limit exceeded')
  622. async def mine10(self):
  623. return await self.mine(10)
  624. async def mine30(self):
  625. return await self.mine(30)
  626. async def mine100(self):
  627. return await self.mine(100)
  628. async def mine(self,nblks):
  629. start_height = height = await self._get_height()
  630. imsg(f'Height: {height}')
  631. imsg_r(f'Mining {nblks} blocks...')
  632. await self.start_mining()
  633. while height < start_height + nblks:
  634. await asyncio.sleep(2)
  635. height = await self._get_height()
  636. imsg_r('.')
  637. ret = await self.stop_mining()
  638. imsg('done')
  639. imsg(f'Height: {height}')
  640. return 'ok' if ret == 'OK' else False
  641. async def start_mining(self):
  642. data = self.users['miner']
  643. addr = read_from_file(data.addrfile_fs.format(1)) # mine to wallet #1, account 0
  644. for _ in range(20):
  645. # NB: threads_count > 1 provides no benefit and leads to connection errors with MSWin/MSYS2
  646. ret = data.md_rpc.call_raw(
  647. 'start_mining',
  648. do_background_mining = False, # run mining in background or foreground
  649. ignore_battery = True, # ignore battery state (on laptop)
  650. miner_address = addr, # account address to mine to
  651. threads_count = 1 ) # number of mining threads to run
  652. status = self.get_status(ret)
  653. if status == 'OK':
  654. return True
  655. elif status == 'BUSY':
  656. await asyncio.sleep(5)
  657. omsg('Daemon busy. Attempting to start mining...')
  658. else:
  659. die(2,f'Monerod returned status {status}')
  660. else:
  661. die(2,'Max retries exceeded')
  662. async def stop_mining(self):
  663. ret = self.users['miner'].md_rpc.call_raw('stop_mining')
  664. return self.get_status(ret)
  665. async def mine_chk(
  666. self,
  667. user,
  668. wnum,
  669. account,
  670. test,
  671. test_desc,
  672. test2 = None,
  673. test2_desc = None,
  674. random_txs = None,
  675. return_bal = False ):
  676. """
  677. - open destination wallet
  678. - optionally create and broadcast random TXs
  679. - start mining
  680. - mine until funds appear in wallet
  681. - stop mining
  682. - close wallet
  683. """
  684. async def send_random_txs():
  685. from mmgen.tool.api import tool_api
  686. t = tool_api(cfg)
  687. t.init_coin('XMR','mainnet')
  688. t.usr_randchars = 0
  689. imsg_r('Sending random transactions: ')
  690. for i in range(random_txs):
  691. await self.transfer(
  692. 'miner',
  693. 123456789,
  694. t.randpair()[1],
  695. )
  696. imsg_r(f'{i+1} ')
  697. oqmsg_r('+')
  698. await asyncio.sleep(0.5)
  699. imsg('')
  700. def print_balance(dest,bal_info):
  701. imsg('Total balances in {}’s wallet {}, account #{}: {} (total), {} (unlocked)'.format(
  702. capfirst(dest.user),
  703. dest.wnum,
  704. dest.account,
  705. bal_info.b.hl(),
  706. bal_info.ub.hl(),
  707. ))
  708. async def get_balance(dest,count):
  709. data = self.users[dest.user]
  710. data.wd_rpc.call('refresh')
  711. if count and not count % 20:
  712. data.wd_rpc.call('rescan_blockchain')
  713. ret = data.wd_rpc.call('get_accounts')['subaddress_accounts'][dest.account]
  714. d_tup = namedtuple('bal_info',['b','ub'])
  715. return d_tup(
  716. b = XMRAmt(ret['balance'],from_unit='atomic'),
  717. ub = XMRAmt(ret['unlocked_balance'],from_unit='atomic')
  718. )
  719. # start execution:
  720. self.do_msg(extra_desc =
  721. (f'sending {random_txs} random TXs, ' if random_txs else '') +
  722. f'mining, checking wallet {user}:{wnum}:{account}' )
  723. dest = namedtuple(
  724. 'dest_info',['user','wnum','account','test','test_desc','test2','test2_desc'])(
  725. user,wnum,account,test,test_desc,test2,test2_desc)
  726. if dest.user != 'miner':
  727. await self.open_wallet_user(dest.user,dest.wnum)
  728. bal_info_start = await get_balance(dest,0)
  729. chk_bal_chg = dest.test(bal_info_start) == 'chk_bal_chg'
  730. if random_txs:
  731. await send_random_txs()
  732. await self.start_mining()
  733. h = await self._get_height()
  734. imsg_r(f'Chain height: {h} ')
  735. max_iterations,min_height = (300,64) if sys.platform == 'win32' else (50,300)
  736. verbose = False
  737. for count in range(max_iterations):
  738. bal_info = await get_balance(dest,count)
  739. if h > min_height:
  740. if dest.test(bal_info) is True or (chk_bal_chg and bal_info.ub != bal_info_start.ub):
  741. imsg('')
  742. oqmsg_r('+')
  743. print_balance(dest,bal_info)
  744. if dest.test2:
  745. assert dest.test2(bal_info) is True, f'test failed: {dest.test2_desc} ({bal_info})'
  746. break
  747. await asyncio.sleep(2)
  748. h = await self._get_height()
  749. if count > 12: # something might have gone wrong, so be more verbose
  750. if not verbose:
  751. imsg('')
  752. imsg_r(f'Height: {h}, ')
  753. print_balance(dest,bal_info)
  754. verbose = True
  755. else:
  756. imsg_r(f'{h} ')
  757. oqmsg_r('+')
  758. else:
  759. die(2,f'Timeout exceeded, balance {bal_info.ub!r}')
  760. await self.stop_mining()
  761. if user != 'miner':
  762. await self.stop_wallet_user(dest.user)
  763. return bal_info if return_bal else 'ok'
  764. # util methods
  765. def get_status(self,ret):
  766. if ret['status'] != 'OK':
  767. imsg( 'RPC status: {}'.format( ret['status'] ))
  768. return ret['status']
  769. def do_msg(self,extra_desc=None):
  770. self.spawn(
  771. '',
  772. msg_only = True,
  773. extra_desc = f'({extra_desc})' if extra_desc else None
  774. )
  775. async def transfer(self,user,amt,addr):
  776. return self.users[user].wd_rpc.call('transfer',destinations=[{'amount':amt,'address':addr}])
  777. # daemon start/stop methods
  778. def start_daemons(self):
  779. for v in self.users.values():
  780. run(['mkdir','-p',v.datadir])
  781. v.md.start()
  782. def stop_daemons(self):
  783. self.spawn('', msg_only=True)
  784. if cfg.no_daemon_stop:
  785. omsg('[not stopping daemons at user request]')
  786. else:
  787. omsg('')
  788. stop_daemons(self)
  789. atexit.unregister(stop_daemons)
  790. stop_miner_wallet_daemon(self)
  791. atexit.unregister(stop_miner_wallet_daemon)
  792. return 'silent'