xmrwallet.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2022 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. xmrwallet.py - MoneroWalletOps class
  20. """
  21. import os,re,time,json
  22. from collections import namedtuple
  23. from .common import *
  24. from .objmethods import Hilite,InitErrors
  25. from .obj import CoinTxID
  26. from .seed import SeedID
  27. from .protocol import init_proto
  28. from .proto.common import b58a
  29. from .addr import CoinAddr,AddrIdx
  30. from .addrlist import KeyAddrList,AddrIdxList
  31. from .rpc import json_encoder
  32. from .base_proto.monero.rpc import MoneroRPCClientRaw,MoneroWalletRPCClient
  33. from .base_proto.monero.daemon import MoneroWalletDaemon
  34. xmrwallet_uarg_info = (
  35. lambda e,hp: {
  36. 'daemon': e('HOST:PORT', hp),
  37. 'tx_relay_daemon': e('HOST:PORT[:PROXY_HOST:PROXY_PORT]', rf'({hp})(?::({hp}))?'),
  38. 'transfer_spec': e('SOURCE_WALLET_NUM:ACCOUNT:ADDRESS,AMOUNT', rf'(\d+):(\d+):([{b58a}]+),([0-9.]+)'),
  39. 'sweep_spec': e('SOURCE_WALLET_NUM:ACCOUNT[,DEST_WALLET_NUM]', r'(\d+):(\d+)(?:,(\d+))?'),
  40. })(
  41. namedtuple('uarg_info_entry',['annot','pat']),
  42. r'(?:[^:]+):(?:\d+)'
  43. )
  44. class XMRWalletAddrSpec(str,Hilite,InitErrors,MMGenObject):
  45. color = 'cyan'
  46. width = 0
  47. trunc_ok = False
  48. min_len = 5 # 1:0:0
  49. max_len = 14 # 9999:9999:9999
  50. def __new__(cls,arg1,arg2=None,arg3=None):
  51. if type(arg1) == cls:
  52. return arg1
  53. try:
  54. if isinstance(arg1,str):
  55. me = str.__new__(cls,arg1)
  56. m = re.fullmatch( '({n}):({n}):({n}|None)'.format(n=r'[0-9]{1,4}'), arg1 )
  57. assert m is not None, f'{arg1!r}: invalid XMRWalletAddrSpec'
  58. for e in m.groups():
  59. if len(e) != 1 and e[0] == '0':
  60. die(2,f'{e}: leading zeroes not permitted in XMRWalletAddrSpec element')
  61. me.wallet = AddrIdx(m[1])
  62. me.account = int(m[2])
  63. me.account_address = None if m[3] == 'None' else int(m[3])
  64. else:
  65. me = str.__new__(cls,f'{arg1}:{arg2}:{arg3}')
  66. for arg in [arg1,arg2] + ([] if arg3 is None else [arg3]):
  67. assert isinstance(arg,int), f'{arg}: XMRWalletAddrSpec component not of type int'
  68. assert arg is None or arg <= 9999, f'{arg}: XMRWalletAddrSpec component greater than 9999'
  69. me.wallet = AddrIdx(arg1)
  70. me.account = arg2
  71. me.account_address = arg3
  72. return me
  73. except Exception as e:
  74. return cls.init_fail(e,me)
  75. class MoneroMMGenTX:
  76. class Base:
  77. def make_chksum(self,keys=None):
  78. res = json.dumps(
  79. dict( (k,v) for k,v in self.data._asdict().items() if (not keys or k in keys) ),
  80. cls = json_encoder
  81. )
  82. return make_chksum_6(res)
  83. @property
  84. def base_chksum(self):
  85. return self.make_chksum(
  86. ('op','create_time','network','seed_id','source','dest','amount')
  87. )
  88. @property
  89. def full_chksum(self):
  90. return self.make_chksum(set(self.data._fields) - {'metadata'})
  91. xmrwallet_tx_data = namedtuple('xmrwallet_tx_data',[
  92. 'op',
  93. 'create_time',
  94. 'sign_time',
  95. 'network',
  96. 'seed_id',
  97. 'source',
  98. 'dest',
  99. 'dest_address',
  100. 'txid',
  101. 'amount',
  102. 'fee',
  103. 'blob',
  104. 'metadata',
  105. ])
  106. def get_info(self,indent=''):
  107. d = self.data
  108. if d.dest:
  109. to_entry = f'\n{indent} To: ' + (
  110. 'Wallet {}, account {}, address {}'.format(
  111. d.dest.wallet.hl(),
  112. red(f'#{d.dest.account}'),
  113. red(f'#{d.dest.account_address}')
  114. )
  115. )
  116. return fmt("""
  117. Transaction info [Seed ID: {}. Network: {}]:
  118. TxID: {}
  119. Type: {}
  120. From: Wallet {}, account {}{}
  121. Amt: {} XMR
  122. Fee: {} XMR
  123. Dest: {}
  124. """,strip_char='\t',indent=indent).format(
  125. d.seed_id.hl(), d.network.upper(),
  126. d.txid.hl(),
  127. blue(capfirst(d.op)),
  128. d.source.wallet.hl(),
  129. red(f'#{d.source.account}'),
  130. to_entry if d.dest else '',
  131. d.amount.hl(),
  132. d.fee.hl(),
  133. d.dest_address.hl()
  134. )
  135. def write(self,delete_metadata=False):
  136. dict_data = self.data._asdict()
  137. if delete_metadata:
  138. dict_data['metadata'] = None
  139. out = json.dumps(
  140. { 'MoneroMMGenTX': {
  141. 'base_chksum': self.base_chksum,
  142. 'full_chksum': self.full_chksum,
  143. 'data': dict_data,
  144. }
  145. },
  146. cls = json_encoder,
  147. )
  148. fn = '{}{}-XMR[{!s}]{}.sigtx'.format(
  149. self.base_chksum.upper(),
  150. (lambda s: f'-{s.upper()}' if s else '')(self.full_chksum),
  151. self.data.amount,
  152. (lambda s: '' if s == 'mainnet' else f'.{s}')(self.data.network),
  153. )
  154. from .fileutil import write_data_to_file
  155. write_data_to_file(fn,out,desc='MoneroMMGenTX data',ask_write=True,ask_write_default_yes=False)
  156. class NewSigned(Base):
  157. def __init__(self,*args,**kwargs):
  158. assert not args, 'Non-keyword args not permitted'
  159. d = namedtuple('kwargs_tuple',kwargs)(**kwargs)
  160. proto = init_proto( 'xmr', network=d.network, need_amt=True )
  161. now = int(time.time())
  162. self.data = self.xmrwallet_tx_data(
  163. op = d.op,
  164. create_time = now,
  165. sign_time = now,
  166. network = d.network,
  167. seed_id = SeedID(sid=d.seed_id),
  168. source = XMRWalletAddrSpec(d.source),
  169. dest = None if d.dest is None else XMRWalletAddrSpec(d.dest),
  170. dest_address = CoinAddr(proto,d.dest_address),
  171. txid = CoinTxID(d.txid),
  172. amount = proto.coin_amt(d.amount,from_unit='atomic'),
  173. fee = proto.coin_amt(d.fee,from_unit='atomic'),
  174. blob = d.blob,
  175. metadata = d.metadata,
  176. )
  177. class Signed(Base):
  178. def __init__(self,fn):
  179. from .fileutil import get_data_from_file
  180. self.fn = fn
  181. d_wrap = json.loads(get_data_from_file(fn))['MoneroMMGenTX']
  182. d = self.xmrwallet_tx_data(**d_wrap['data'])
  183. proto = init_proto( 'xmr', network=d.network, need_amt=True )
  184. self.data = self.xmrwallet_tx_data(
  185. op = d.op,
  186. create_time = d.create_time,
  187. sign_time = d.sign_time,
  188. network = d.network,
  189. seed_id = SeedID(sid=d.seed_id),
  190. source = XMRWalletAddrSpec(d.source),
  191. dest = None if d.dest is None else XMRWalletAddrSpec(d.dest),
  192. dest_address = CoinAddr(proto,d.dest_address),
  193. txid = CoinTxID(d.txid),
  194. amount = proto.coin_amt(d.amount),
  195. fee = proto.coin_amt(d.fee),
  196. blob = d.blob,
  197. metadata = d.metadata,
  198. )
  199. for k in ('base_chksum','full_chksum'):
  200. a = getattr(self,k)
  201. b = d_wrap[k]
  202. assert a == b, f'{k} mismatch: {a} != {b}'
  203. class MoneroWalletOps:
  204. ops = ('create','sync','transfer','sweep','relay')
  205. opts = (
  206. 'wallet_dir',
  207. 'daemon',
  208. 'tx_relay_daemon',
  209. 'use_internal_keccak_module',
  210. 'hash_preset',
  211. 'restore_height',
  212. 'no_start_wallet_daemon',
  213. 'no_stop_wallet_daemon',
  214. 'do_not_relay',
  215. )
  216. pat_opts = ('daemon','tx_relay_daemon')
  217. class base(MMGenObject):
  218. opts = ('wallet_dir',)
  219. def __init__(self,uarg_tuple,uopt_tuple):
  220. def gen_classes():
  221. for cls in type(self).__mro__:
  222. yield cls
  223. if cls.__name__ == 'base':
  224. break
  225. classes = tuple(gen_classes())
  226. self.opts = tuple(set(opt for cls in classes for opt in cls.opts))
  227. global uarg, uopt, uarg_info, fmt_amt, hl_amt
  228. uarg = uarg_tuple
  229. uopt = uopt_tuple
  230. uarg_info = xmrwallet_uarg_info
  231. def fmt_amt(amt):
  232. return self.proto.coin_amt(amt,from_unit='atomic').fmt(fs='5.12',color=True)
  233. def hl_amt(amt):
  234. return self.proto.coin_amt(amt,from_unit='atomic').hl()
  235. id_cur = None
  236. for cls in classes:
  237. if id(cls.check_uopts) != id_cur:
  238. cls.check_uopts(self)
  239. id_cur = id(cls.check_uopts)
  240. self.proto = init_proto( 'xmr', testnet=g.testnet, need_amt=True )
  241. def check_uopts(self):
  242. def check_pat_opt(name):
  243. val = getattr(uopt,name)
  244. if not re.fullmatch(uarg_info[name].pat,val,re.ASCII):
  245. die(1,'{!r}: invalid value for --{}: it must have format {!r}'.format(
  246. val,
  247. name.replace('_','-'),
  248. uarg_info[name].annot
  249. ))
  250. for opt in uopt._asdict():
  251. if getattr(uopt,opt) and not opt in self.opts:
  252. die(1,'Option --{} not supported for {!r} operation'.format(
  253. opt.replace('_','-'),
  254. uarg.op
  255. ))
  256. for opt in MoneroWalletOps.pat_opts:
  257. if getattr(uopt,opt):
  258. check_pat_opt(opt)
  259. def display_tx_relay_info(self,indent=''):
  260. m = re.fullmatch(uarg_info['tx_relay_daemon'].pat,uopt.tx_relay_daemon,re.ASCII)
  261. msg(fmt(f"""
  262. TX relay info:
  263. Host: {blue(m[1])}
  264. Proxy: {blue(m[2] or 'None')}
  265. """,strip_char='\t',indent=indent))
  266. def post_main(self):
  267. pass
  268. async def stop_wallet_daemon(self):
  269. pass
  270. class wallet(base):
  271. opts = (
  272. 'use_internal_keccak_module',
  273. 'hash_preset',
  274. 'daemon',
  275. 'no_start_wallet_daemon',
  276. 'no_stop_wallet_daemon',
  277. )
  278. wallet_exists = True
  279. def __init__(self,uarg_tuple,uopt_tuple):
  280. def wallet_exists(fn):
  281. try: os.stat(fn)
  282. except: return False
  283. else: return True
  284. def check_wallets():
  285. for d in self.addr_data:
  286. fn = self.get_wallet_fn(d)
  287. exists = wallet_exists(fn)
  288. if exists and not self.wallet_exists:
  289. die(1,f'Wallet {fn!r} already exists!')
  290. elif not exists and self.wallet_exists:
  291. die(1,f'Wallet {fn!r} not found!')
  292. super().__init__(uarg_tuple,uopt_tuple)
  293. self.kal = KeyAddrList(self.proto,uarg.infile)
  294. self.create_addr_data()
  295. check_wallets()
  296. self.wd = MoneroWalletDaemon(
  297. proto = self.proto,
  298. wallet_dir = uopt.wallet_dir or '.',
  299. test_suite = g.test_suite,
  300. daemon_addr = uopt.daemon or None,
  301. )
  302. self.c = MoneroWalletRPCClient(daemon=self.wd,test_connection=False)
  303. if not uopt.no_start_wallet_daemon:
  304. run_session(self.c.restart_daemon())
  305. def create_addr_data(self):
  306. if uarg.wallets:
  307. idxs = AddrIdxList(uarg.wallets)
  308. self.addr_data = [d for d in self.kal.data if d.idx in idxs]
  309. if len(self.addr_data) != len(idxs):
  310. die(1,f'List {uarg.wallets!r} contains addresses not present in supplied key-address file')
  311. else:
  312. self.addr_data = self.kal.data
  313. async def stop_wallet_daemon(self):
  314. if not uopt.no_stop_wallet_daemon:
  315. await self.c.stop_daemon()
  316. def get_wallet_fn(self,d):
  317. return os.path.join(
  318. uopt.wallet_dir or '.','{}-{}-MoneroWallet{}{}'.format(
  319. self.kal.al_id.sid,
  320. d.idx,
  321. '.testnet' if g.testnet else '',
  322. '-α' if g.debug_utf8 else '' ))
  323. async def main(self):
  324. gmsg('\n{}ing {} wallet{}'.format(
  325. self.desc,
  326. len(self.addr_data),
  327. suf(self.addr_data) ))
  328. processed = 0
  329. for n,d in enumerate(self.addr_data): # [d.sec,d.addr,d.wallet_passwd,d.viewkey]
  330. fn = self.get_wallet_fn(d)
  331. gmsg('\n{}ing wallet {}/{} ({})'.format(
  332. self.desc,
  333. n+1,
  334. len(self.addr_data),
  335. os.path.basename(fn),
  336. ))
  337. processed += await self.process_wallet(
  338. d,
  339. fn,
  340. last = n == len(self.addr_data)-1 )
  341. gmsg(f'\n{processed} wallet{suf(processed)} {self.past}')
  342. return processed
  343. class rpc:
  344. def __init__(self,parent,d):
  345. self.parent = parent
  346. self.c = parent.c
  347. self.d = d
  348. self.fn = parent.get_wallet_fn(d)
  349. async def open_wallet(self,desc,refresh=True):
  350. gmsg_r(f'\n Opening {desc} wallet...')
  351. await self.c.call( # returns {}
  352. 'open_wallet',
  353. filename=os.path.basename(self.fn),
  354. password=self.d.wallet_passwd )
  355. gmsg('done')
  356. if refresh:
  357. gmsg_r(f' Refreshing {desc} wallet...')
  358. ret = await self.c.call('refresh')
  359. gmsg('done')
  360. if ret['received_money']:
  361. msg(' Wallet has received funds')
  362. async def close_wallet(self,desc):
  363. gmsg_r(f'\n Closing {desc} wallet...')
  364. await self.c.call('close_wallet')
  365. gmsg_r('done')
  366. async def stop_wallet(self,desc):
  367. msg(f'Stopping {self.c.daemon.desc} on port {self.c.daemon.bind_port}')
  368. gmsg_r(f'\n Stopping {desc} wallet...')
  369. await self.c.stop_daemon(quiet=True) # closes wallet
  370. gmsg_r('done')
  371. def print_accts(self,data,addrs_data,indent=' '):
  372. d = data['subaddress_accounts']
  373. msg('\n' + indent + f'Accounts of wallet {os.path.basename(self.fn)}:')
  374. fs = indent + ' {:6} {:18} {:<6} {:%s} {}' % max(len(e['label']) for e in d)
  375. msg(fs.format('Index ','Base Address','nAddrs','Label','Unlocked Balance'))
  376. for i,e in enumerate(d):
  377. msg(fs.format(
  378. str(e['account_index']),
  379. e['base_address'][:15] + '...',
  380. len(addrs_data[i]['addresses']),
  381. e['label'],
  382. fmt_amt(e['unlocked_balance']),
  383. ))
  384. async def get_accts(self,print=True):
  385. data = await self.c.call('get_accounts')
  386. addrs_data = [
  387. await self.c.call('get_address',account_index=i)
  388. for i in range(len(data['subaddress_accounts']))
  389. ]
  390. if print:
  391. self.print_accts(data,addrs_data)
  392. return ( data, addrs_data )
  393. async def create_acct(self):
  394. msg('\n Creating new account...')
  395. ret = await self.c.call(
  396. 'create_account',
  397. label = f'Sweep from {self.parent.source.idx}:{self.parent.account}'
  398. )
  399. msg(' Index: {}'.format( pink(str(ret['account_index'])) ))
  400. msg(' Address: {}'.format( cyan(ret['address']) ))
  401. return (ret['account_index'], ret['address'])
  402. def get_last_acct(self,accts_data):
  403. msg('\n Getting last account...')
  404. ret = accts_data['subaddress_accounts'][-1]
  405. msg(' Index: {}'.format( pink(str(ret['account_index'])) ))
  406. msg(' Address: {}'.format( cyan(ret['base_address']) ))
  407. return (ret['account_index'], ret['base_address'])
  408. async def print_addrs(self,accts_data,account):
  409. ret = await self.c.call('get_address',account_index=account)
  410. d = ret['addresses']
  411. msg('\n Addresses of account #{} ({}):'.format(
  412. account,
  413. accts_data['subaddress_accounts'][account]['label']))
  414. fs = ' {:6} {:18} {:%s} {}' % max(len(e['label']) for e in d)
  415. msg(fs.format('Index ','Address','Label','Used'))
  416. for e in d:
  417. msg(fs.format(
  418. str(e['address_index']),
  419. e['address'][:15] + '...',
  420. e['label'],
  421. e['used']
  422. ))
  423. async def create_new_addr(self,account):
  424. msg_r('\n Creating new address: ')
  425. ret = await self.c.call(
  426. 'create_address',
  427. account_index = account,
  428. label = 'Sweep from this account',
  429. )
  430. msg(cyan(ret['address']))
  431. return ret['address']
  432. async def get_last_addr(self,account,display=True):
  433. if display:
  434. msg('\n Getting last address:')
  435. ret = (await self.c.call(
  436. 'get_address',
  437. account_index = account,
  438. ))['addresses']
  439. addr = ret[-1]['address']
  440. if display:
  441. msg(' ' + cyan(addr))
  442. return ( addr, len(ret) - 1 )
  443. async def make_transfer_tx(self,account,addr,amt):
  444. res = await self.c.call(
  445. 'transfer',
  446. account_index = account,
  447. destinations = [{
  448. 'amount': amt.to_unit('atomic'),
  449. 'address': addr
  450. }],
  451. do_not_relay = True,
  452. get_tx_hex = True,
  453. get_tx_metadata = True
  454. )
  455. return MoneroMMGenTX.NewSigned(
  456. op = uarg.op,
  457. network = self.parent.proto.network,
  458. seed_id = self.parent.kal.al_id.sid,
  459. source = XMRWalletAddrSpec(self.parent.source.idx,self.parent.account,None),
  460. dest = None,
  461. dest_address = addr,
  462. txid = res['tx_hash'],
  463. amount = res['amount'],
  464. fee = res['fee'],
  465. blob = res['tx_blob'],
  466. metadata = res['tx_metadata'],
  467. )
  468. async def make_sweep_tx(self,account,dest_acct,dest_addr_idx,addr):
  469. res = await self.c.call(
  470. 'sweep_all',
  471. address = addr,
  472. account_index = account,
  473. do_not_relay = True,
  474. get_tx_hex = True,
  475. get_tx_metadata = True
  476. )
  477. if len(res['tx_hash_list']) > 1:
  478. die(3,'More than one TX required. Cannot perform this sweep')
  479. return MoneroMMGenTX.NewSigned(
  480. op = uarg.op,
  481. network = self.parent.proto.network,
  482. seed_id = self.parent.kal.al_id.sid,
  483. source = XMRWalletAddrSpec(self.parent.source.idx,self.parent.account,None),
  484. dest = XMRWalletAddrSpec(
  485. (self.parent.dest or self.parent.source).idx,
  486. dest_acct,
  487. dest_addr_idx),
  488. dest_address = addr,
  489. txid = res['tx_hash_list'][0],
  490. amount = res['amount_list'][0],
  491. fee = res['fee_list'][0],
  492. blob = res['tx_blob_list'][0],
  493. metadata = res['tx_metadata_list'][0],
  494. )
  495. async def relay_tx(self,tx_hex):
  496. ret = await self.c.call('relay_tx',hex=tx_hex)
  497. try:
  498. msg('\n Relayed {}'.format( CoinTxID(ret['tx_hash']).hl() ))
  499. except:
  500. msg(f'\n Server returned: {ret!s}')
  501. class create(wallet):
  502. name = 'create'
  503. desc = 'Creat'
  504. past = 'created'
  505. wallet_exists = False
  506. opts = ('restore_height',)
  507. def check_uopts(self):
  508. if int(uopt.restore_height) < 0:
  509. die(1,f"{uopt.restore_height}: invalid value for --restore-height (less than zero)")
  510. async def process_wallet(self,d,fn,last):
  511. msg_r('') # for pexpect
  512. from .xmrseed import xmrseed
  513. ret = await self.c.call(
  514. 'restore_deterministic_wallet',
  515. filename = os.path.basename(fn),
  516. password = d.wallet_passwd,
  517. seed = xmrseed().fromhex(d.sec.wif,tostr=True),
  518. restore_height = uopt.restore_height,
  519. language = 'English' )
  520. pp_msg(ret) if opt.debug else msg(' Address: {}'.format( ret['address'] ))
  521. return True
  522. class sync(wallet):
  523. name = 'sync'
  524. desc = 'Sync'
  525. past = 'synced'
  526. opts = ('rescan_blockchain',)
  527. def __init__(self,uarg_tuple,uopt_tuple):
  528. super().__init__(uarg_tuple,uopt_tuple)
  529. host,port = uopt.daemon.split(':') if uopt.daemon else ('localhost',self.wd.daemon_port)
  530. self.dc = MoneroRPCClientRaw(host=host, port=int(port), user=None, passwd=None)
  531. self.accts_data = {}
  532. async def process_wallet(self,d,fn,last):
  533. chain_height = (await self.dc.call('get_height'))['height']
  534. msg(f' Chain height: {chain_height}')
  535. t_start = time.time()
  536. msg_r(' Opening wallet...')
  537. await self.c.call(
  538. 'open_wallet',
  539. filename=os.path.basename(fn),
  540. password=d.wallet_passwd )
  541. msg('done')
  542. msg_r(' Getting wallet height (be patient, this could take a long time)...')
  543. wallet_height = (await self.c.call('get_height'))['height']
  544. msg_r('\r' + ' '*68 + '\r')
  545. msg(f' Wallet height: {wallet_height} ')
  546. behind = chain_height - wallet_height
  547. if behind > 1000:
  548. msg_r(f' Wallet is {behind} blocks behind chain tip. Please be patient. Syncing...')
  549. ret = await self.c.call('refresh')
  550. if behind > 1000:
  551. msg('done')
  552. if ret['received_money']:
  553. msg(' Wallet has received funds')
  554. for i in range(2):
  555. wallet_height = (await self.c.call('get_height'))['height']
  556. if wallet_height >= chain_height:
  557. break
  558. ymsg(f' Wallet failed to sync (wallet height [{wallet_height}] < chain height [{chain_height}])')
  559. if i or not uopt.rescan_blockchain:
  560. break
  561. msg_r(' Rescanning blockchain, please be patient...')
  562. await self.c.call('rescan_blockchain')
  563. await self.c.call('refresh')
  564. msg('done')
  565. t_elapsed = int(time.time() - t_start)
  566. bn = os.path.basename(fn)
  567. a,b = await self.rpc(self,d).get_accts(print=False)
  568. msg(' Balance: {} Unlocked balance: {}'.format(
  569. hl_amt(a['total_balance']),
  570. hl_amt(a['total_unlocked_balance']),
  571. ))
  572. self.accts_data[bn] = { 'accts': a, 'addrs': b }
  573. msg(f' Wallet height: {wallet_height}')
  574. msg(' Sync time: {:02}:{:02}'.format(
  575. t_elapsed // 60,
  576. t_elapsed % 60 ))
  577. if not last:
  578. await self.c.call('close_wallet')
  579. return wallet_height >= chain_height
  580. def post_main(self):
  581. d = self.accts_data
  582. for n,k in enumerate(d):
  583. ad = self.addr_data[n]
  584. self.rpc(self,ad).print_accts( d[k]['accts'], d[k]['addrs'], indent='')
  585. col1_w = max(map(len,d)) + 1
  586. fs = '{:%s} {} {}' % col1_w
  587. tbals = [0,0]
  588. msg('\n'+fs.format('Wallet','Balance ','Unlocked Balance'))
  589. for k in d:
  590. b = d[k]['accts']['total_balance']
  591. ub = d[k]['accts']['total_unlocked_balance']
  592. msg(fs.format( k + ':', fmt_amt(b), fmt_amt(ub) ))
  593. tbals[0] += b
  594. tbals[1] += ub
  595. msg(fs.format( '-'*col1_w, '-'*18, '-'*18 ))
  596. msg(fs.format( 'TOTAL:', fmt_amt(tbals[0]), fmt_amt(tbals[1]) ))
  597. class sweep(wallet):
  598. name = 'sweep'
  599. desc = 'Sweep'
  600. past = 'swept'
  601. spec_id = 'sweep_spec'
  602. spec_key = ( (1,'source'), (3,'dest') )
  603. opts = ('do_not_relay','tx_relay_daemon')
  604. def create_addr_data(self):
  605. m = re.fullmatch(uarg_info[self.spec_id].pat,uarg.spec,re.ASCII)
  606. if not m:
  607. fs = "{!r}: invalid {!r} arg: for {} operation, it must have format {!r}"
  608. die(1,fs.format( uarg.spec, self.spec_id, self.name, uarg_info[self.spec_id].annot ))
  609. def gen():
  610. for i,k in self.spec_key:
  611. if m[i] == None:
  612. setattr(self,k,None)
  613. else:
  614. idx = int(m[i])
  615. try:
  616. res = [d for d in self.kal.data if d.idx == idx][0]
  617. except:
  618. die(1,'Supplied key-address file does not contain address {}:{}'.format(
  619. self.kal.al_id.sid,
  620. idx ))
  621. else:
  622. setattr(self,k,res)
  623. yield res
  624. self.addr_data = list(gen())
  625. self.account = int(m[2])
  626. if self.name == 'transfer':
  627. self.dest_addr = CoinAddr(self.proto,m[3])
  628. self.amount = self.proto.coin_amt(m[4])
  629. def init_tx_relay_daemon(self):
  630. m = re.fullmatch(uarg_info['tx_relay_daemon'].pat,uopt.tx_relay_daemon,re.ASCII)
  631. wd2 = MoneroWalletDaemon(
  632. proto = self.proto,
  633. wallet_dir = uopt.wallet_dir or '.',
  634. test_suite = g.test_suite,
  635. daemon_addr = m[1],
  636. proxy = m[2] )
  637. if g.test_suite:
  638. wd2.usr_daemon_args = ['--daemon-ssl-allow-any-cert']
  639. wd2.start()
  640. self.c = MoneroWalletRPCClient(daemon=wd2)
  641. async def main(self):
  642. gmsg(f'\n{self.desc}ing account #{self.account} of wallet {self.source.idx}' + (
  643. f': {self.amount} XMR to {self.dest_addr}' if self.name == 'transfer'
  644. else ' to new address' if self.dest == None
  645. else f' to new account in wallet {self.dest.idx}' ))
  646. h = self.rpc(self,self.source)
  647. await h.open_wallet('source')
  648. accts_data = (await h.get_accts())[0]
  649. max_acct = len(accts_data['subaddress_accounts']) - 1
  650. if self.account > max_acct:
  651. die(1,f'{self.account}: requested account index out of bounds (>{max_acct})')
  652. await h.print_addrs(accts_data,self.account)
  653. if self.name == 'transfer':
  654. dest_addr = self.dest_addr
  655. elif self.dest == None:
  656. dest_acct = self.account
  657. if keypress_confirm(f'\nCreate new address for account #{self.account}?'):
  658. dest_addr_chk = await h.create_new_addr(self.account)
  659. elif keypress_confirm(f'Sweep to last existing address of account #{self.account}?'):
  660. dest_addr_chk = None
  661. else:
  662. die(1,'Exiting at user request')
  663. dest_addr,dest_addr_idx = await h.get_last_addr(self.account,display=not dest_addr_chk)
  664. assert dest_addr_chk in (None,dest_addr), 'dest_addr_chk1'
  665. await h.print_addrs(accts_data,self.account)
  666. else:
  667. await h.close_wallet('source')
  668. bn = os.path.basename(self.get_wallet_fn(self.dest))
  669. h2 = self.rpc(self,self.dest)
  670. await h2.open_wallet('destination')
  671. accts_data = (await h2.get_accts())[0]
  672. if keypress_confirm(f'\nCreate new account for wallet {bn!r}?'):
  673. dest_acct,dest_addr = await h2.create_acct()
  674. dest_addr_idx = 0
  675. await h2.get_accts()
  676. elif keypress_confirm(f'Sweep to last existing account of wallet {bn!r}?'):
  677. dest_acct,dest_addr_chk = h2.get_last_acct(accts_data)
  678. dest_addr,dest_addr_idx = await h2.get_last_addr(dest_acct,display=False)
  679. assert dest_addr_chk == dest_addr, 'dest_addr_chk2'
  680. else:
  681. die(1,'Exiting at user request')
  682. await h2.close_wallet('destination')
  683. await h.open_wallet('source',refresh=False)
  684. msg(f'\n Creating {self.name} transaction...')
  685. if self.name == 'transfer':
  686. new_tx = await h.make_transfer_tx(self.account,dest_addr,self.amount)
  687. elif self.name == 'sweep':
  688. new_tx = await h.make_sweep_tx(self.account,dest_acct,dest_addr_idx,dest_addr)
  689. msg('\n' + new_tx.get_info(indent=' '))
  690. if uopt.tx_relay_daemon:
  691. self.display_tx_relay_info(indent=' ')
  692. if uopt.do_not_relay:
  693. msg('Saving TX data to file')
  694. new_tx.write(delete_metadata=True)
  695. elif keypress_confirm(f'Relay {self.name} transaction?'):
  696. w_desc = 'source'
  697. if uopt.tx_relay_daemon:
  698. await h.stop_wallet('source')
  699. msg('')
  700. self.init_tx_relay_daemon()
  701. h = self.rpc(self,self.source)
  702. w_desc = 'TX relay source'
  703. await h.open_wallet(w_desc,refresh=False)
  704. msg_r(f'\n Relaying {self.name} transaction...')
  705. await h.relay_tx(new_tx.data.metadata)
  706. gmsg('\n\nAll done')
  707. else:
  708. die(1,'\nExiting at user request')
  709. return True
  710. class transfer(sweep):
  711. name = 'transfer'
  712. desc = 'Transfer'
  713. past = 'transferred'
  714. spec_id = 'transfer_spec'
  715. spec_key = ( (1,'source'), )
  716. class relay(base):
  717. name = 'relay'
  718. desc = 'Relay'
  719. past = 'relayed'
  720. opts = ('tx_relay_daemon',)
  721. def __init__(self,uarg_tuple,uopt_tuple):
  722. super().__init__(uarg_tuple,uopt_tuple)
  723. if uopt.tx_relay_daemon:
  724. m = re.fullmatch(uarg_info['tx_relay_daemon'].pat,uopt.tx_relay_daemon,re.ASCII)
  725. host,port = m[1].split(':')
  726. proxy = m[2]
  727. else:
  728. from .daemon import CoinDaemon
  729. md = CoinDaemon('xmr',test_suite=g.test_suite)
  730. host,port = md.host,md.rpc_port
  731. proxy = None
  732. self.dc = MoneroRPCClientRaw(
  733. host = host,
  734. port = int(port),
  735. user = None,
  736. passwd = None,
  737. proxy = proxy )
  738. self.tx = MoneroMMGenTX.Signed(uarg.infile)
  739. async def main(self):
  740. msg('\n' + self.tx.get_info())
  741. if uopt.tx_relay_daemon:
  742. self.display_tx_relay_info()
  743. if keypress_confirm('Relay transaction?'):
  744. res = await self.dc.call(
  745. 'send_raw_transaction',
  746. tx_as_hex = self.tx.data.blob
  747. )
  748. if res['status'] == 'OK':
  749. msg('Status: ' + green('OK'))
  750. if res['not_relayed']:
  751. ymsg('Transaction not relayed')
  752. return True
  753. else:
  754. die( 'RPCFailure', repr(res) )
  755. else:
  756. die(1,'Exiting at user request')