ts_xmrwallet.py 27 KB

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