xmrwallet.py 29 KB

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