xmrwallet.py 28 KB

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