ct_xmrwallet.py 29 KB

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