ts_xmrwallet.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2021 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. ts_xmrwallet.py: xmrwallet tests for the test.py test suite
  20. """
  21. import sys,os,atexit,asyncio
  22. from subprocess import run,PIPE
  23. from mmgen.globalvars import g
  24. from mmgen.opts import opt
  25. from mmgen.obj import MMGenRange,XMRAmt
  26. from mmgen.addr import KeyAddrList,AddrIdxList
  27. from ..include.common import *
  28. from .common import *
  29. from .ts_base import *
  30. class TestSuiteXMRWallet(TestSuiteBase):
  31. """
  32. Monero wallet operations
  33. """
  34. networks = ('xmr',)
  35. passthru_opts = ('coin',)
  36. tmpdir_nums = [29]
  37. dfl_random_txs = 3
  38. cmd_group = (
  39. ('gen_kafiles', 'generating key-address files'),
  40. ('create_wallets', 'creating Monero wallets'),
  41. ('set_dest_miner', 'opening miner wallet'),
  42. ('mine_blocks', 'mining blocks'),
  43. ('fund_alice', 'sending funds'),
  44. ('mine_blocks_tx', 'mining blocks'),
  45. ('sync_wallets', 'syncing all wallets'),
  46. ('sync_wallets_selected', 'syncing selected wallets'),
  47. ('sweep_to_address_proxy', 'sweeping to new address (via TX relay + proxy)'),
  48. ('mine_blocks', 'mining blocks'),
  49. ('sweep_to_account', 'sweeping to new account'),
  50. ('mine_blocks', 'mining blocks'),
  51. ('sweep_to_address_noproxy', 'sweeping to new address (via TX relay)'),
  52. ('mine_blocks', 'mining blocks'),
  53. )
  54. def __init__(self,trunner,cfgs,spawn):
  55. TestSuiteBase.__init__(self,trunner,cfgs,spawn)
  56. if trunner == None:
  57. return
  58. from mmgen.protocol import init_proto
  59. self.proto = init_proto('XMR',network='testnet')
  60. self.datadir_base = os.path.join('test','daemons','xmrtest')
  61. self.long_opts = ['--testnet=1', '--monero-wallet-rpc-password=passw0rd']
  62. self.init_users()
  63. self.init_daemon_args()
  64. for v in self.users.values():
  65. run(['mkdir','-p',v.udir])
  66. self.init_proxy()
  67. self.tx_relay_daemon_parm = 'localhost:{}'.format(self.users['bob'].md.rpc_port)
  68. self.tx_relay_daemon_proxy_parm = (
  69. self.tx_relay_daemon_parm + f':127.0.0.1:{self.socks_port}' # proxy must be IP, not 'localhost'
  70. if self.use_proxy else None )
  71. if not opt.no_daemon_autostart:
  72. self.start_daemons()
  73. self.start_wallet_daemons()
  74. if not opt.no_daemon_stop:
  75. atexit.register(self.stop_daemons)
  76. atexit.register(self.stop_wallet_daemons)
  77. self.balance = None
  78. # init methods
  79. def init_proxy(self):
  80. def port_in_use(port):
  81. import socket
  82. try: socket.create_connection(('localhost',port)).close()
  83. except: return False
  84. else: return True
  85. def start_proxy():
  86. if not opt.no_daemon_autostart:
  87. run(a+b2)
  88. omsg(f'SSH SOCKS server started, listening at localhost:{self.socks_port}')
  89. def kill_proxy():
  90. omsg(f'Killing SSH SOCKS server at localhost:{self.socks_port}')
  91. cmd = [ 'pkill', '-f', ' '.join(a + b2) ]
  92. run(cmd)
  93. self.use_proxy = False
  94. self.socks_port = 9060
  95. a = ['ssh','-x','-o','ExitOnForwardFailure=True','-D',f'localhost:{self.socks_port}']
  96. b0 = ['-o','PasswordAuthentication=False']
  97. b1 = ['localhost','true']
  98. b2 = ['-fN','-E','txrelay-proxy.debug','localhost']
  99. if port_in_use(self.socks_port):
  100. omsg(f'Port {self.socks_port} already in use. Assuming SSH SOCKS server is running')
  101. self.use_proxy = True
  102. else:
  103. cp = run(a+b0+b1,stdout=PIPE,stderr=PIPE)
  104. err = cp.stderr.decode()
  105. if err:
  106. omsg(err)
  107. if cp.returncode == 0:
  108. start_proxy()
  109. self.use_proxy = True
  110. elif 'onnection refused' in err:
  111. die(2,fmt("""
  112. The SSH daemon must be running and listening on localhost in order to test
  113. XMR TX relaying via SOCKS proxy. If sshd is not running, please start it.
  114. Otherwise, add the line 'ListenAddress 127.0.0.1' to your sshd_config, and
  115. then restart the daemon.
  116. """,indent=' '))
  117. elif 'ermission denied' in err:
  118. msg(fmt(f"""
  119. In order to test XMR TX relaying via SOCKS proxy, it’s desirable to enable
  120. SSH to localhost without a password, which is not currently supported by
  121. your configuration. Your possible courses of action:
  122. 1. Continue by answering 'y' at this prompt, and enter your system password
  123. at the following prompt;
  124. 2. Exit the test here, add your user SSH public key to your user
  125. 'authorized_keys' file, and restart the test; or
  126. 3. Exit the test here, start the SSH SOCKS proxy manually by entering the
  127. following command, and restart the test:
  128. {' '.join(a+b2)}
  129. """,indent=' ',strip_char='\t'))
  130. if keypress_confirm('Continue?'):
  131. start_proxy()
  132. self.use_proxy = True
  133. else:
  134. die(1,'Exiting at user request')
  135. else:
  136. die(2,fmt(f"""
  137. Please start the SSH SOCKS proxy by entering the following command:
  138. {' '.join(a+b2)}
  139. Then restart the test.
  140. """,indent=' '))
  141. if not opt.no_daemon_stop:
  142. atexit.register(kill_proxy)
  143. def init_users(self):
  144. from mmgen.daemon import CoinDaemon,MoneroWalletDaemon
  145. from mmgen.rpc import MoneroRPCClient,MoneroRPCClientRaw,MoneroWalletRPCClient
  146. self.users = {}
  147. n = self.tmpdir_nums[0]
  148. ud = namedtuple('user_data',[
  149. 'sid',
  150. 'mmwords',
  151. 'udir',
  152. 'datadir',
  153. 'kal_range',
  154. 'kafile',
  155. 'walletfile_fs',
  156. 'addrfile_fs',
  157. 'md',
  158. 'md_rpc',
  159. 'md_json_rpc',
  160. 'wd',
  161. 'wd_rpc',
  162. ])
  163. for user,sid,shift,kal_range in ( # kal_range must be None, a single digit, or a single hyphenated range
  164. ('miner', '98831F3A', 130, '1'),
  165. ('bob', '1378FC64', 140, None),
  166. ('alice', 'FE3C6545', 150, '1-4'),
  167. ):
  168. udir = os.path.join('test',f'tmp{n}',user)
  169. datadir = os.path.join(self.datadir_base,user)
  170. md = CoinDaemon(
  171. proto = self.proto,
  172. test_suite = True,
  173. port_shift = shift,
  174. opts = ['online'],
  175. datadir = datadir
  176. )
  177. md_rpc = MoneroRPCClientRaw(
  178. host = md.host,
  179. port = md.rpc_port,
  180. user = None,
  181. passwd = None,
  182. test_connection = False,
  183. )
  184. md_json_rpc = MoneroRPCClient(
  185. host = md.host,
  186. port = md.rpc_port,
  187. user = None,
  188. passwd = None,
  189. test_connection = False,
  190. )
  191. wd = MoneroWalletDaemon(
  192. user = 'foo',
  193. passwd = 'bar',
  194. wallet_dir = udir,
  195. test_suite = True,
  196. port_shift = shift,
  197. datadir = os.path.join('test','daemons'),
  198. daemon_addr = f'127.0.0.1:{md.rpc_port}',
  199. testnet = True
  200. )
  201. wd_rpc = MoneroWalletRPCClient(
  202. host = wd.host,
  203. port = wd.rpc_port,
  204. user = wd.user,
  205. passwd = wd.passwd,
  206. test_connection = False,
  207. )
  208. self.users[user] = ud(
  209. sid = sid,
  210. mmwords = f'test/ref/{sid}.mmwords',
  211. udir = udir,
  212. datadir = datadir,
  213. kal_range = kal_range,
  214. kafile = f'{udir}/{sid}-XMR-M[{kal_range}].testnet.akeys',
  215. walletfile_fs = f'{udir}/{sid}-{{}}-MoneroWallet.testnet',
  216. addrfile_fs = f'{udir}/{sid}-{{}}-MoneroWallet.testnet.address.txt',
  217. md = md,
  218. md_rpc = md_rpc,
  219. md_json_rpc = md_json_rpc,
  220. wd = wd,
  221. wd_rpc = wd_rpc,
  222. )
  223. def init_daemon_args(self):
  224. common_args = ['--p2p-bind-ip=127.0.0.1','--fixed-difficulty=1'] # ,'--rpc-ssl-allow-any-cert']
  225. for u in self.users:
  226. other_ports = [self.users[u2].md.p2p_port for u2 in self.users if u2 != u]
  227. node_args = [f'--add-exclusive-node=127.0.0.1:{p}' for p in other_ports]
  228. self.users[u].md.usr_coind_args = common_args + node_args
  229. # cmd_group methods
  230. def gen_kafiles(self):
  231. for user,data in self.users.items():
  232. if not data.kal_range:
  233. continue
  234. run(['mkdir','-p',data.udir])
  235. run(f'rm -f {data.kafile}',shell=True)
  236. t = self.spawn(
  237. 'mmgen-keygen', [
  238. '--testnet=1','-q', '--accept-defaults', '--coin=xmr',
  239. f'--outdir={data.udir}', data.mmwords, data.kal_range
  240. ],
  241. extra_desc = f'({capfirst(user)})' )
  242. t.read()
  243. t.ok()
  244. t.skip_ok = True
  245. return t
  246. def create_wallets(self):
  247. for user,data in self.users.items():
  248. if not data.kal_range:
  249. continue
  250. run('rm -f {}*'.format( data.walletfile_fs.format('*') ),shell=True)
  251. dir_opt = [f'--outdir={data.udir}']
  252. t = self.spawn(
  253. 'mmgen-xmrwallet',
  254. self.long_opts + dir_opt + [ 'create', data.kafile, data.kal_range ],
  255. extra_desc = f'({capfirst(user)})' )
  256. t.expect('Check key-to-address validity? (y/N): ','n')
  257. for i in MMGenRange(data.kal_range).items:
  258. t.expect('Address: ')
  259. t.read()
  260. t.ok()
  261. t.skip_ok = True
  262. return t
  263. async def set_dest_miner(self):
  264. self.do_msg()
  265. self.set_dest('miner',1,0,lambda x: x > 20,'unlocked balance > 20')
  266. await self.open_wallet_user('miner',1)
  267. return 'ok'
  268. async def fund_alice(self):
  269. self.do_msg()
  270. await self.transfer(
  271. 'miner',
  272. 1234567891234,
  273. read_from_file(self.users['alice'].addrfile_fs.format(1)),
  274. )
  275. self.set_dest('alice',1,0,lambda x: str(x) == '1.234567891234','unlocked balance == 1.234567891234')
  276. return 'ok'
  277. def sync_wallets_selected(self):
  278. return self.sync_wallets(wallets='1,3-4')
  279. def sync_wallets(self,wallets=None):
  280. data = self.users['alice']
  281. dir_opt = [f'--outdir={data.udir}']
  282. cmd_opts = [f'--daemon=localhost:{data.md.rpc_port}']
  283. t = self.spawn(
  284. 'mmgen-xmrwallet',
  285. self.long_opts + dir_opt + cmd_opts + [ 'sync', data.kafile ] + ([wallets] if wallets else []) )
  286. t.expect('Check key-to-address validity? (y/N): ','n')
  287. wlist = AddrIdxList(wallets) if wallets else MMGenRange(data.kal_range).items
  288. for n,wnum in enumerate(wlist):
  289. t.expect('Syncing wallet {}/{} ({})'.format(
  290. n+1,
  291. len(wlist),
  292. os.path.basename(data.walletfile_fs.format(wnum)),
  293. ))
  294. t.expect('Chain height: ')
  295. t.expect('Wallet height: ')
  296. t.expect('Balance: ')
  297. t.read()
  298. return t
  299. def do_op(self,op,user,spec,tx_relay_parm):
  300. data = self.users[user]
  301. dir_opt = [f'--outdir={data.udir}']
  302. cmd_opts = list_gen(
  303. [f'--daemon=localhost:{data.md.rpc_port}'],
  304. [f'--tx-relay-daemon={tx_relay_parm}', tx_relay_parm]
  305. )
  306. t = self.spawn(
  307. 'mmgen-xmrwallet',
  308. self.long_opts + dir_opt + cmd_opts + [ op, data.kafile, spec ],
  309. extra_desc = f'({capfirst(user)})' )
  310. t.expect('Check key-to-address validity? (y/N): ','n')
  311. if op == 'sweep':
  312. t.expect(
  313. 'Create new {} .* \(y/N\): '.format('account' if ',' in spec else 'address'),
  314. 'y', regex=True )
  315. t.expect(f'Relay {op} transaction? (y/N): ','y')
  316. t.read()
  317. return t
  318. def sweep_to_address_proxy(self):
  319. ret = self.do_op('sweep','alice','1:0',self.tx_relay_daemon_proxy_parm)
  320. self.set_dest('alice',1,0,lambda x: x > 1,'unlocked balance > 1')
  321. return ret
  322. def sweep_to_account(self):
  323. ret = self.do_op('sweep','alice','1:0,2',None)
  324. self.set_dest('alice',2,1,lambda x: x > 1,'unlocked balance > 1')
  325. return ret
  326. def sweep_to_address_noproxy(self):
  327. ret = self.do_op('sweep','alice','2:1',self.tx_relay_daemon_parm)
  328. self.set_dest('alice',2,1,lambda x: x > 1,'unlocked balance > 1')
  329. return ret
  330. # wallet methods
  331. async def open_wallet_user(self,user,wnum):
  332. data = self.users[user]
  333. silence()
  334. kal = KeyAddrList(self.proto,data.kafile,skip_key_address_validity_check=True)
  335. end_silence()
  336. return await data.wd_rpc.call(
  337. 'open_wallet',
  338. filename = os.path.basename(data.walletfile_fs.format(wnum)),
  339. password = kal.entry(wnum).wallet_passwd )
  340. async def close_wallet_user(self,user):
  341. ret = await self.users[user].wd_rpc.call('close_wallet')
  342. return 'ok'
  343. # mining methods
  344. async def start_mining(self):
  345. data = self.users['miner']
  346. addr = read_from_file(data.addrfile_fs.format(1)) # mine to wallet #1, account 0
  347. for i in range(20):
  348. ret = await data.md_rpc.call(
  349. 'start_mining',
  350. do_background_mining = False, # run mining in background or foreground
  351. ignore_battery = True, # ignore battery state (on laptop)
  352. miner_address = addr, # account address to mine to
  353. threads_count = 3 ) # number of mining threads to run
  354. status = self.get_status(ret)
  355. if status == 'OK':
  356. return True
  357. elif status == 'BUSY':
  358. await asyncio.sleep(5)
  359. omsg('Daemon busy. Attempting to start mining...')
  360. else:
  361. die(2,f'Monerod returned status {status}')
  362. else:
  363. die(2,'Max retries exceeded')
  364. async def stop_mining(self):
  365. ret = await self.users['miner'].md_rpc.call('stop_mining')
  366. return self.get_status(ret)
  367. async def mine_blocks(self,random_txs=None):
  368. """
  369. - open destination wallet
  370. - optionally create and broadcast random TXs
  371. - start mining
  372. - mine until funds appear in wallet
  373. - stop mining
  374. - close wallet
  375. """
  376. async def get_height():
  377. u = self.users['miner']
  378. for i in range(20):
  379. try:
  380. return (await u.md_json_rpc.call('get_last_block_header'))['block_header']['height']
  381. except Exception as e:
  382. if 'onnection refused' in str(e):
  383. omsg(f'{e}\nMonerod appears to have crashed. Attempting to restart...')
  384. await asyncio.sleep(5)
  385. u.md.restart()
  386. await asyncio.sleep(5)
  387. await self.start_mining()
  388. else:
  389. raise
  390. else:
  391. die(2,'Restart attempt limit exceeded')
  392. async def send_random_txs():
  393. from mmgen.tool import tool_api
  394. t = tool_api()
  395. t.init_coin('XMR','testnet')
  396. t.usr_randchars = 0
  397. imsg_r(f'Sending random transactions: ')
  398. for i in range(random_txs):
  399. await self.transfer(
  400. 'miner',
  401. 123456789,
  402. t.randpair()[1],
  403. )
  404. imsg_r(f'{i+1} ')
  405. oqmsg_r('+')
  406. await asyncio.sleep(0.5)
  407. imsg('')
  408. def print_balance(dest,ub):
  409. imsg('Total balance in {}’s wallet #{}, account {}: {}'.format(
  410. capfirst(dest.user),
  411. dest.wnum,
  412. dest.account,
  413. ub.hl()
  414. ))
  415. async def get_balance(dest):
  416. data = self.users[dest.user]
  417. await data.wd_rpc.call('refresh')
  418. ret = await data.wd_rpc.call('get_accounts')
  419. return XMRAmt(ret['subaddress_accounts'][dest.account]['unlocked_balance'],from_unit='atomic')
  420. self.do_msg(extra_desc=f'+{random_txs} random TXs' if random_txs else None)
  421. if self.dest.user != 'miner':
  422. await self.open_wallet_user(self.dest.user,self.dest.wnum)
  423. if random_txs:
  424. await send_random_txs()
  425. await self.start_mining()
  426. h = await get_height()
  427. imsg_r(f'Chain height: {h} ')
  428. while True:
  429. ub = await get_balance(self.dest)
  430. if self.dest.test(ub):
  431. imsg('')
  432. oqmsg_r('+')
  433. print_balance(self.dest,ub)
  434. break
  435. # else:
  436. # imsg(f'Test {self.dest.test_desc!r} failed')
  437. await asyncio.sleep(2)
  438. h = await get_height()
  439. imsg_r(f'{h} ')
  440. oqmsg_r('+')
  441. await self.stop_mining()
  442. if self.dest.user != 'miner':
  443. await self.close_wallet_user(self.dest.user)
  444. return 'ok'
  445. async def mine_blocks_tx(self):
  446. return await self.mine_blocks(random_txs=self.dfl_random_txs)
  447. # util methods
  448. def get_status(self,ret):
  449. if ret['status'] != 'OK':
  450. imsg( 'RPC status: {}'.format(ret['status']) )
  451. return ret['status']
  452. def do_msg(self,extra_desc=None):
  453. self.spawn(
  454. '',
  455. msg_only = True,
  456. extra_desc = f'({extra_desc})' if extra_desc else None
  457. )
  458. def set_dest(self,user,wnum,account,test,test_desc):
  459. self.dest = namedtuple(
  460. 'dest_info',['user','wnum','account','test','test_desc'])(user,wnum,account,test,test_desc)
  461. async def transfer(self,user,amt,addr):
  462. return await self.users[user].wd_rpc.call('transfer',destinations=[{'amount':amt,'address':addr}])
  463. # daemon start/stop methods
  464. def start_daemons(self):
  465. self.stop_daemons()
  466. for v in self.users.values():
  467. run(['mkdir','-p',v.datadir])
  468. v.md.start()
  469. def stop_daemons(self):
  470. for v in self.users.values():
  471. if v.md.state != 'stopped':
  472. v.md.stop()
  473. run(['rm','-rf',self.datadir_base])
  474. def start_wallet_daemons(self):
  475. for v in self.users.values():
  476. if v.kal_range:
  477. v.wd.start()
  478. def stop_wallet_daemons(self):
  479. for v in self.users.values():
  480. if v.kal_range and v.wd.state != 'stopped':
  481. v.wd.stop()