xmrwallet.py 26 KB

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