xmrwallet.py 26 KB

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