xmrwallet.py 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2023 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 re,time,json,atexit
  22. from collections import namedtuple
  23. from pathlib import Path
  24. from .objmethods import MMGenObject,HiliteStr,InitErrors
  25. from .obj import CoinTxID
  26. from .color import red,yellow,green,blue,cyan,pink,orange,purple
  27. from .util import (
  28. msg,
  29. msg_r,
  30. gmsg,
  31. bmsg,
  32. ymsg,
  33. rmsg,
  34. gmsg_r,
  35. pp_msg,
  36. die,
  37. fmt,
  38. suf,
  39. async_run,
  40. make_timestr,
  41. make_chksum_N,
  42. capfirst,
  43. list_gen,
  44. )
  45. from .fileutil import get_data_from_file
  46. from .seed import SeedID
  47. from .protocol import init_proto
  48. from .proto.btc.common import b58a
  49. from .addr import CoinAddr,AddrIdx
  50. from .addrlist import KeyAddrList,ViewKeyAddrList,AddrIdxList
  51. from .rpc import json_encoder
  52. from .proto.xmr.rpc import MoneroRPCClient,MoneroWalletRPCClient
  53. from .proto.xmr.daemon import MoneroWalletDaemon
  54. from .ui import keypress_confirm
  55. from .autosign import get_autosign_obj
  56. xmrwallet_uargs = namedtuple('xmrwallet_uargs',[
  57. 'infile',
  58. 'wallets',
  59. 'spec',
  60. ])
  61. xmrwallet_uarg_info = (
  62. lambda e,hp: {
  63. 'daemon': e('HOST:PORT', hp),
  64. 'tx_relay_daemon': e('HOST:PORT[:PROXY_HOST:PROXY_PORT]', rf'({hp})(?::({hp}))?'),
  65. 'newaddr_spec': e('WALLET_NUM[:ACCOUNT][,"label text"]', r'(\d+)(?::(\d+))?(?:,(.*))?'),
  66. 'transfer_spec': e('SOURCE_WALLET_NUM:ACCOUNT:ADDRESS,AMOUNT', rf'(\d+):(\d+):([{b58a}]+),([0-9.]+)'),
  67. 'sweep_spec': e('SOURCE_WALLET_NUM:ACCOUNT[,DEST_WALLET_NUM]', r'(\d+):(\d+)(?:,(\d+))?'),
  68. 'label_spec': e('WALLET_NUM:ACCOUNT:ADDRESS,"label text"', r'(\d+):(\d+):(\d+),(.*)'),
  69. })(
  70. namedtuple('uarg_info_entry',['annot','pat']),
  71. r'(?:[^:]+):(?:\d+)'
  72. )
  73. # required to squelch pylint:
  74. def fmt_amt(amt):
  75. return str(amt)
  76. def hl_amt(amt):
  77. return str(amt)
  78. class XMRWalletAddrSpec(HiliteStr,InitErrors,MMGenObject):
  79. color = 'cyan'
  80. width = 0
  81. trunc_ok = False
  82. min_len = 5 # 1:0:0
  83. max_len = 14 # 9999:9999:9999
  84. def __new__(cls,arg1,arg2=None,arg3=None):
  85. if isinstance(arg1,cls):
  86. return arg1
  87. try:
  88. if isinstance(arg1,str):
  89. me = str.__new__(cls,arg1)
  90. m = re.fullmatch( '({n}):({n}):({n}|None)'.format(n=r'[0-9]{1,4}'), arg1 )
  91. assert m is not None, f'{arg1!r}: invalid XMRWalletAddrSpec'
  92. for e in m.groups():
  93. if len(e) != 1 and e[0] == '0':
  94. die(2,f'{e}: leading zeroes not permitted in XMRWalletAddrSpec element')
  95. me.wallet = AddrIdx(m[1])
  96. me.account = int(m[2])
  97. me.account_address = None if m[3] == 'None' else int(m[3])
  98. else:
  99. me = str.__new__(cls,f'{arg1}:{arg2}:{arg3}')
  100. for arg in [arg1,arg2] + ([] if arg3 is None else [arg3]):
  101. assert isinstance(arg,int), f'{arg}: XMRWalletAddrSpec component not of type int'
  102. assert arg is None or arg <= 9999, f'{arg}: XMRWalletAddrSpec component greater than 9999'
  103. me.wallet = AddrIdx(arg1)
  104. me.account = arg2
  105. me.account_address = arg3
  106. return me
  107. except Exception as e:
  108. return cls.init_fail(e,me)
  109. def is_xmr_tx_file(cfg,fn):
  110. try:
  111. MoneroMMGenTX.Completed(cfg,fn)
  112. return True
  113. except Exception as e:
  114. if not 'MoneroMMGenTXFileParseError' in type(e).__name__:
  115. ymsg(f'\n{type(e).__name__}: {e}')
  116. return False
  117. class MoneroMMGenFile:
  118. silent_load = False
  119. def make_chksum(self,keys=None):
  120. res = json.dumps(
  121. dict( (k,v) for k,v in self.data._asdict().items() if (not keys or k in keys) ),
  122. cls = json_encoder
  123. )
  124. return make_chksum_N( res, rounds=1, nchars=self.chksum_nchars, upper=False )
  125. @property
  126. def base_chksum(self):
  127. return self.make_chksum(self.base_chksum_fields)
  128. @property
  129. def full_chksum(self):
  130. return self.make_chksum(self.full_chksum_fields) if self.full_chksum_fields else None
  131. def check_checksums(self,d_wrap):
  132. for k in ('base_chksum','full_chksum'):
  133. a = getattr(self,k)
  134. if a is not None:
  135. b = d_wrap[k]
  136. assert a == b, f'{k} mismatch: {a} != {b}'
  137. def make_wrapped_data(self,in_data):
  138. out = {
  139. 'base_chksum': self.base_chksum,
  140. 'full_chksum': self.full_chksum,
  141. 'data': in_data,
  142. } if self.full_chksum else {
  143. 'base_chksum': self.base_chksum,
  144. 'data': in_data,
  145. }
  146. return json.dumps(
  147. { self.data_label: out },
  148. cls = json_encoder,
  149. indent = 2,
  150. )
  151. def extract_data_from_file(self,cfg,fn):
  152. return json.loads(
  153. get_data_from_file( cfg, str(fn), self.desc, silent=self.silent_load )
  154. )[self.data_label]
  155. class MoneroMMGenTX:
  156. class Base(MoneroMMGenFile):
  157. data_label = 'MoneroMMGenTX'
  158. # both base_chksum and full_chksum are used to make the filename stem, so we must not include
  159. # fields that change when TX is signed and submitted (e.g. ‘sign_time’, ‘submit_time’)
  160. base_chksum_fields = {
  161. 'op',
  162. 'create_time',
  163. 'network',
  164. 'seed_id',
  165. 'source',
  166. 'dest',
  167. 'amount' }
  168. full_chksum_fields = {
  169. 'op',
  170. 'create_time',
  171. 'network',
  172. 'seed_id',
  173. 'source',
  174. 'dest',
  175. 'amount',
  176. 'fee',
  177. 'blob' }
  178. oneline_fs = '{a:7} {b:8} {c:19} {d:13} {e:8} {f:6} {x:2} {g:6} {h:17} {j}'
  179. chksum_nchars = 6
  180. xmrwallet_tx_data = namedtuple('xmrwallet_tx_data',[
  181. 'op',
  182. 'create_time',
  183. 'sign_time',
  184. 'submit_time',
  185. 'network',
  186. 'seed_id',
  187. 'source',
  188. 'dest',
  189. 'dest_address',
  190. 'txid',
  191. 'amount',
  192. 'fee',
  193. 'blob',
  194. 'metadata',
  195. 'unsigned_txset',
  196. 'signed_txset',
  197. 'complete',
  198. ])
  199. def __init__(self):
  200. self.name = type(self).__name__
  201. @property
  202. def src_wallet_idx(self):
  203. return int(self.data.source.split(':')[0])
  204. def get_info_oneline(self,indent='',cols=None):
  205. d = self.data
  206. return self.oneline_fs.format(
  207. a = yellow(d.network),
  208. b = d.seed_id.hl(),
  209. c = make_timestr(d.submit_time if d.submit_time is not None else d.create_time),
  210. d = orange(self.file_id),
  211. e = purple(capfirst(d.op.ljust(8))),
  212. f = red('{}:{}'.format(d.source.wallet,d.source.account).ljust(6)),
  213. g = red('{}:{}'.format(d.dest.wallet,d.dest.account).ljust(6)) if d.dest else cyan('ext '),
  214. h = d.amount.fmt( color=True, iwidth=4, prec=12 ),
  215. j = d.dest_address.fmt(width=cols-95,color=True) if cols else d.dest_address.hl(),
  216. x = '->'
  217. )
  218. def get_info(self,indent='',cols=None):
  219. d = self.data
  220. pmt_id = d.dest_address.parsed.payment_id
  221. fs = '\n'.join(list_gen(
  222. ['Info for transaction {a} [Seed ID: {b}. Network: {c}]:'],
  223. [' TxID: {d}'],
  224. [' Created: {e:19} [{f}]'],
  225. [' Signed: {g:19} [{h}]', d.sign_time],
  226. [' Submitted: {s:19} [{t}]', d.submit_time],
  227. [' Type: {i}{S}'],
  228. [' From: Wallet {j}, account {k}'],
  229. [' To: Wallet {x}, account {y}, address {z}', d.dest],
  230. [' Amount: {m} XMR'],
  231. [' Fee: {n} XMR'],
  232. [' Dest: {o}'],
  233. [' Payment ID: {P}', pmt_id],
  234. ))
  235. from .util2 import format_elapsed_hr
  236. return fmt(fs,strip_char='\t',indent=indent).format(
  237. a = orange(self.file_id),
  238. b = d.seed_id.hl(),
  239. c = yellow(d.network.upper()),
  240. d = d.txid.hl(),
  241. e = make_timestr(d.create_time),
  242. f = format_elapsed_hr(d.create_time),
  243. g = make_timestr(d.sign_time) if d.sign_time else None,
  244. h = format_elapsed_hr(d.sign_time) if d.sign_time else None,
  245. i = blue(capfirst(d.op)),
  246. j = d.source.wallet.hl(),
  247. k = red(f'#{d.source.account}'),
  248. m = d.amount.hl(),
  249. n = d.fee.hl(),
  250. o = d.dest_address.hl(),
  251. P = pink(pmt_id.hex()) if pmt_id else None,
  252. s = make_timestr(d.submit_time) if d.submit_time else None,
  253. S = pink(f" [cold signed{', submitted' if d.complete else ''}]") if d.signed_txset else '',
  254. t = format_elapsed_hr(d.submit_time) if d.submit_time else None,
  255. x = d.dest.wallet.hl() if d.dest else None,
  256. y = red(f'#{d.dest.account}') if d.dest else None,
  257. z = red(f'#{d.dest.account_address}') if d.dest else None,
  258. )
  259. @property
  260. def file_id(self):
  261. return (self.base_chksum + ('-' + self.full_chksum if self.full_chksum else '')).upper()
  262. def write(self,delete_metadata=False,ask_write=True,ask_overwrite=True):
  263. dict_data = self.data._asdict()
  264. if delete_metadata:
  265. dict_data['metadata'] = None
  266. fn = '{a}-XMR[{b!s}]{c}.{d}'.format(
  267. a = self.file_id,
  268. b = self.data.amount,
  269. c = '' if self.data.network == 'mainnet' else f'.{self.data.network}',
  270. d = self.ext
  271. )
  272. if self.cfg.autosign:
  273. fn = get_autosign_obj(self.cfg,'xmr').xmr_tx_dir / fn
  274. from .fileutil import write_data_to_file
  275. write_data_to_file(
  276. cfg = self.cfg,
  277. outfile = str(fn),
  278. data = self.make_wrapped_data(dict_data),
  279. desc = self.desc,
  280. ask_write = ask_write,
  281. ask_write_default_yes = not ask_write,
  282. ask_overwrite = ask_overwrite,
  283. ignore_opt_outdir = self.cfg.autosign )
  284. class New(Base):
  285. def __init__(self,*args,**kwargs):
  286. super().__init__()
  287. assert not args, 'Non-keyword args not permitted'
  288. if '_in_tx' in kwargs:
  289. in_data = kwargs.pop('_in_tx').data._asdict()
  290. in_data.update(kwargs)
  291. else:
  292. in_data = kwargs
  293. d = namedtuple('monero_tx_in_data_tuple',in_data)(**in_data)
  294. self.cfg = d.cfg
  295. proto = init_proto( self.cfg, 'xmr', network=d.network, need_amt=True )
  296. now = int(time.time())
  297. self.data = self.xmrwallet_tx_data(
  298. op = d.op,
  299. create_time = now if self.name in ('NewSigned','NewUnsigned') else getattr(d,'create_time',None),
  300. sign_time = now if self.name in ('NewSigned','NewColdSigned') else getattr(d,'sign_time',None),
  301. submit_time = now if self.name == 'NewSubmitted' else None,
  302. network = d.network,
  303. seed_id = SeedID(sid=d.seed_id),
  304. source = XMRWalletAddrSpec(d.source),
  305. dest = None if d.dest is None else XMRWalletAddrSpec(d.dest),
  306. dest_address = CoinAddr(proto,d.dest_address),
  307. txid = CoinTxID(d.txid),
  308. amount = proto.coin_amt(d.amount,from_unit='atomic'),
  309. fee = proto.coin_amt(d.fee,from_unit='atomic'),
  310. blob = d.blob,
  311. metadata = d.metadata,
  312. unsigned_txset = d.unsigned_txset,
  313. signed_txset = getattr(d,'signed_txset',None),
  314. complete = self.name in ('NewSigned','NewSubmitted'),
  315. )
  316. class NewUnsigned(New):
  317. desc = 'unsigned transaction'
  318. ext = 'rawtx'
  319. signed = False
  320. class NewSigned(New):
  321. desc = 'signed transaction'
  322. ext = 'sigtx'
  323. signed = True
  324. class NewColdSigned(NewSigned):
  325. pass
  326. class NewSubmitted(NewColdSigned):
  327. desc = 'submitted transaction'
  328. ext = 'subtx'
  329. class Completed(Base):
  330. desc = 'transaction'
  331. forbidden_fields = ()
  332. def __init__(self,cfg,fn):
  333. super().__init__()
  334. self.cfg = cfg
  335. self.fn = Path(fn)
  336. try:
  337. d_wrap = self.extract_data_from_file( cfg, fn )
  338. except Exception as e:
  339. die( 'MoneroMMGenTXFileParseError', f'{type(e).__name__}: {e}\nCould not load transaction file' )
  340. if 'unsigned_txset' in d_wrap['data']: # post-autosign
  341. self.full_chksum_fields &= set(d_wrap['data']) # allow for added chksum fields in future
  342. else:
  343. self.full_chksum_fields = set(d_wrap['data']) - {'metadata'}
  344. for key in self.xmrwallet_tx_data._fields: # backwards compat: fill in missing fields
  345. if not key in d_wrap['data']:
  346. d_wrap['data'][key] = None
  347. d = self.xmrwallet_tx_data(**d_wrap['data'])
  348. if self.name not in ('View','Completed'):
  349. assert fn.name.endswith('.'+self.ext), 'TX file {fn} has incorrect extension (not {self.ext!r})'
  350. assert getattr(d,self.req_field), f'{self.name} TX missing required field {self.req_field!r}'
  351. assert bool(d.sign_time) == self.signed, '{a} has {b}sign time!'.format(
  352. a = self.desc,
  353. b = 'no ' if self.signed else'' )
  354. for f in self.forbidden_fields:
  355. assert not getattr(d,f), f'{self.name} TX mismatch: contains forbidden field {f!r}'
  356. proto = init_proto( cfg, 'xmr', network=d.network, need_amt=True )
  357. self.data = self.xmrwallet_tx_data(
  358. op = d.op,
  359. create_time = d.create_time,
  360. sign_time = d.sign_time,
  361. submit_time = d.submit_time,
  362. network = d.network,
  363. seed_id = SeedID(sid=d.seed_id),
  364. source = XMRWalletAddrSpec(d.source),
  365. dest = None if d.dest is None else XMRWalletAddrSpec(d.dest),
  366. dest_address = CoinAddr(proto,d.dest_address),
  367. txid = CoinTxID(d.txid),
  368. amount = proto.coin_amt(d.amount),
  369. fee = proto.coin_amt(d.fee),
  370. blob = d.blob,
  371. metadata = d.metadata,
  372. unsigned_txset = d.unsigned_txset,
  373. signed_txset = d.signed_txset,
  374. complete = d.complete,
  375. )
  376. self.check_checksums(d_wrap)
  377. class Unsigned(Completed):
  378. desc = 'unsigned transaction'
  379. ext = 'rawtx'
  380. signed = False
  381. req_field = 'unsigned_txset'
  382. forbidden_fields = ('signed_txset',)
  383. class Signed(Completed):
  384. desc = 'signed transaction'
  385. ext = 'sigtx'
  386. signed = True
  387. req_field = 'blob'
  388. forbidden_fields = ('signed_txset','unsigned_txset')
  389. class ColdSigned(Signed):
  390. req_field = 'signed_txset'
  391. forbidden_fields = ()
  392. class Submitted(ColdSigned):
  393. desc = 'submitted transaction'
  394. ext = 'subtx'
  395. silent_load = True
  396. class View(Completed):
  397. silent_load = True
  398. class MoneroWalletOutputsFile:
  399. class Base(MoneroMMGenFile):
  400. desc = 'wallet outputs'
  401. data_label = 'MoneroMMGenWalletOutputsFile'
  402. base_chksum_fields = {'seed_id','wallet_index','outputs_data_hex',}
  403. full_chksum_fields = {'seed_id','wallet_index','outputs_data_hex','signed_key_images'}
  404. fn_fs = '{a}-outputs-{b}.{c}'
  405. ext_offset = 25 # len('-outputs-') + len(chksum) ({b})
  406. chksum_nchars = 16
  407. data_tuple = namedtuple('wallet_outputs_data',[
  408. 'seed_id',
  409. 'wallet_index',
  410. 'outputs_data_hex',
  411. 'signed_key_images',
  412. ])
  413. def __init__(self,cfg):
  414. self.name = type(self).__name__
  415. self.cfg = cfg
  416. def write(self,add_suf=''):
  417. from .fileutil import write_data_to_file
  418. write_data_to_file(
  419. cfg = self.cfg,
  420. outfile = str(self.get_outfile( self.cfg, self.wallet_fn )) + add_suf,
  421. data = self.make_wrapped_data(self.data._asdict()),
  422. desc = self.desc,
  423. ask_overwrite = False,
  424. ignore_opt_outdir = True )
  425. def get_outfile(self,cfg,wallet_fn):
  426. return (
  427. get_autosign_obj(cfg,'xmr').xmr_outputs_dir if cfg.autosign else
  428. wallet_fn.parent ) / self.fn_fs.format(
  429. a = wallet_fn.name,
  430. b = self.base_chksum,
  431. c = self.ext,
  432. )
  433. def get_wallet_fn(self,fn):
  434. assert fn.name.endswith(f'.{self.ext}'), (
  435. f'{self.name}: filename does not end with {"."+self.ext!r}'
  436. )
  437. return fn.parent / fn.name[:-(len(self.ext)+self.ext_offset+1)]
  438. def get_info(self,indent=''):
  439. if self.data.signed_key_images is not None:
  440. data = self.data.signed_key_images or []
  441. return f'{indent}{self.wallet_fn.name}: {len(data)} signed key image{suf(data)}'
  442. else:
  443. return f'{indent}{self.wallet_fn.name}: no key images'
  444. class New(Base):
  445. ext = 'raw'
  446. def __init__( self, parent, wallet_fn, data, wallet_idx=None ):
  447. super().__init__(parent.cfg)
  448. self.wallet_fn = wallet_fn
  449. init_data = dict.fromkeys(self.data_tuple._fields)
  450. init_data.update({
  451. 'seed_id': parent.kal.al_id.sid,
  452. 'wallet_index': wallet_idx or parent.get_idx_from_fn(wallet_fn),
  453. })
  454. init_data.update({k:v for k,v in data.items() if k in init_data})
  455. self.data = self.data_tuple(**init_data)
  456. class Completed(New):
  457. def __init__( self, parent, fn=None, wallet_fn=None ):
  458. def check_equal(desc,a,b):
  459. assert a == b, f'{desc} mismatch: {a} (from file) != {b} (from filename)'
  460. fn = fn or self.get_outfile( parent.cfg, wallet_fn )
  461. wallet_fn = wallet_fn or self.get_wallet_fn(fn)
  462. d_wrap = self.extract_data_from_file( parent.cfg, fn )
  463. data = d_wrap['data']
  464. check_equal( 'Seed ID', data['seed_id'], parent.kal.al_id.sid )
  465. wallet_idx = parent.get_idx_from_fn(wallet_fn)
  466. check_equal( 'Wallet index', data['wallet_index'], wallet_idx )
  467. super().__init__(
  468. parent = parent,
  469. wallet_fn = wallet_fn,
  470. data = data,
  471. wallet_idx = wallet_idx,
  472. )
  473. self.check_checksums(d_wrap)
  474. @classmethod
  475. def find_fn_from_wallet_fn(cls,cfg,wallet_fn,ret_on_no_match=False):
  476. path = get_autosign_obj(cfg,'xmr').xmr_outputs_dir or Path()
  477. pat = cls.fn_fs.format(
  478. a = wallet_fn.name,
  479. b = f'[0-9a-f]{{{cls.chksum_nchars}}}\\',
  480. c = cls.ext,
  481. )
  482. matches = [f for f in path.iterdir() if re.match(pat,f.name)]
  483. if not matches and ret_on_no_match:
  484. return None
  485. if not matches or len(matches) > 1:
  486. die(2,"{a} matching pattern {b!r} found in '{c}'!".format(
  487. a = 'No files' if not matches else 'More than one file',
  488. b = pat,
  489. c = path
  490. ))
  491. return matches[0]
  492. class Unsigned(Completed):
  493. pass
  494. class SignedNew(New):
  495. desc = 'signed key images'
  496. ext = 'sig'
  497. class Signed(Completed,SignedNew):
  498. pass
  499. class MoneroWalletDumpFile:
  500. class Base:
  501. desc = 'Monero wallet dump'
  502. data_label = 'MoneroMMGenWalletDumpFile'
  503. base_chksum_fields = {'seed_id','wallet_index','wallet_metadata'}
  504. full_chksum_fields = None
  505. ext = 'dump'
  506. ext_offset = 0
  507. data_tuple = namedtuple('wallet_dump_data',[
  508. 'seed_id',
  509. 'wallet_index',
  510. 'wallet_metadata',
  511. ])
  512. def get_outfile(self,cfg,wallet_fn):
  513. return wallet_fn.parent / f'{wallet_fn.name}.{self.ext}'
  514. class New(Base,MoneroWalletOutputsFile.New):
  515. pass
  516. class Completed(Base,MoneroWalletOutputsFile.Completed):
  517. pass
  518. class MoneroWalletOps:
  519. ops = (
  520. 'create',
  521. 'create_offline',
  522. 'sync',
  523. 'list',
  524. 'new',
  525. 'transfer',
  526. 'sweep',
  527. 'relay',
  528. 'txview',
  529. 'txlist',
  530. 'label',
  531. 'sign',
  532. 'submit',
  533. 'resubmit',
  534. 'dump',
  535. 'restore',
  536. 'export_outputs',
  537. 'import_key_images' )
  538. kafile_arg_ops = (
  539. 'create',
  540. 'sync',
  541. 'list',
  542. 'label',
  543. 'new',
  544. 'transfer',
  545. 'sweep',
  546. 'dump',
  547. 'restore' )
  548. opts = (
  549. 'wallet_dir',
  550. 'daemon',
  551. 'tx_relay_daemon',
  552. 'use_internal_keccak_module',
  553. 'hash_preset',
  554. 'restore_height',
  555. 'no_start_wallet_daemon',
  556. 'no_stop_wallet_daemon',
  557. 'no_relay',
  558. 'watch_only',
  559. 'autosign' )
  560. pat_opts = ('daemon','tx_relay_daemon')
  561. class base(MMGenObject):
  562. opts = ('wallet_dir',)
  563. trust_monerod = False
  564. do_umount = True
  565. def __init__(self,cfg,uarg_tuple):
  566. def gen_classes():
  567. for cls in type(self).__mro__:
  568. yield cls
  569. if cls.__name__ == 'base':
  570. break
  571. self.name = type(self).__name__
  572. self.cfg = cfg
  573. classes = tuple(gen_classes())
  574. self.opts = tuple(set(opt for cls in classes for opt in cls.opts))
  575. if not hasattr(self,'stem'):
  576. self.stem = self.name
  577. global uarg, uarg_info, fmt_amt, hl_amt
  578. uarg = uarg_tuple
  579. uarg_info = xmrwallet_uarg_info
  580. def fmt_amt(amt):
  581. return self.proto.coin_amt(amt,from_unit='atomic').fmt( iwidth=5, prec=12, color=True )
  582. def hl_amt(amt):
  583. return self.proto.coin_amt(amt,from_unit='atomic').hl()
  584. id_cur = None
  585. for cls in classes:
  586. if id(cls.check_uopts) != id_cur:
  587. cls.check_uopts(self)
  588. id_cur = id(cls.check_uopts)
  589. self.proto = init_proto( cfg, 'xmr', network=self.cfg.network, need_amt=True )
  590. def check_uopts(self):
  591. def check_pat_opt(name):
  592. val = getattr(self.cfg,name)
  593. if not re.fullmatch( uarg_info[name].pat, val, re.ASCII ):
  594. die(1,'{!r}: invalid value for --{}: it must have format {!r}'.format(
  595. val,
  596. name.replace('_','-'),
  597. uarg_info[name].annot
  598. ))
  599. for attr in self.cfg.__dict__:
  600. if attr in MoneroWalletOps.opts and not attr in self.opts:
  601. die(1,'Option --{} not supported for {!r} operation'.format(
  602. attr.replace('_','-'),
  603. self.name,
  604. ))
  605. for opt in MoneroWalletOps.pat_opts:
  606. if getattr(self.cfg,opt,None):
  607. check_pat_opt(opt)
  608. def parse_tx_relay_opt(self):
  609. return re.fullmatch(
  610. uarg_info['tx_relay_daemon'].pat,
  611. self.cfg.tx_relay_daemon,
  612. re.ASCII )
  613. def display_tx_relay_info(self,indent=''):
  614. m = self.parse_tx_relay_opt()
  615. msg(fmt(f"""
  616. TX relay info:
  617. Host: {blue(m[1])}
  618. Proxy: {blue(m[2] or 'None')}
  619. """,strip_char='\t',indent=indent))
  620. def post_main_success(self):
  621. pass
  622. def post_main_failure(self):
  623. pass
  624. async def stop_wallet_daemon(self):
  625. pass
  626. class wallet(base):
  627. opts = (
  628. 'use_internal_keccak_module',
  629. 'hash_preset',
  630. 'daemon',
  631. 'no_start_wallet_daemon',
  632. 'no_stop_wallet_daemon',
  633. 'autosign',
  634. 'watch_only',
  635. )
  636. wallet_exists = True
  637. start_daemon = True
  638. offline = False
  639. skip_wallet_check = False # for debugging
  640. test_monerod = False
  641. def __init__(self,cfg,uarg_tuple):
  642. def wallet_exists(fn):
  643. try:
  644. fn.stat()
  645. except:
  646. return False
  647. else:
  648. return True
  649. def check_wallets():
  650. for d in self.addr_data:
  651. fn = self.get_wallet_fn(d)
  652. exists = wallet_exists(fn)
  653. if exists and not self.wallet_exists:
  654. die(1,f"Wallet '{fn}' already exists!")
  655. elif not exists and self.wallet_exists:
  656. die(1,f"Wallet '{fn}' not found!")
  657. super().__init__(cfg,uarg_tuple)
  658. if self.offline:
  659. from .wallet import Wallet
  660. self.seed_src = Wallet(
  661. cfg = cfg,
  662. fn = uarg.infile,
  663. ignore_in_fmt = True )
  664. gmsg('\nCreating ephemeral key-address list for offline wallets')
  665. self.kal = KeyAddrList(
  666. cfg = cfg,
  667. proto = self.proto,
  668. seed = self.seed_src.seed,
  669. addr_idxs = uarg.wallets,
  670. skip_chksum_msg = True )
  671. else:
  672. # with watch_only, make a second attempt to open the file as KeyAddrList:
  673. for first_try in (True,False):
  674. try:
  675. self.kal = (ViewKeyAddrList if (self.cfg.watch_only and first_try) else KeyAddrList)(
  676. cfg = cfg,
  677. proto = self.proto,
  678. addrfile = str(self.autosign_viewkey_addr_file) if self.cfg.autosign else uarg.infile,
  679. key_address_validity_check = True,
  680. skip_chksum_msg = True )
  681. break
  682. except:
  683. if first_try:
  684. msg(f"Attempting to open '{uarg.infile}' as key-address list")
  685. continue
  686. raise
  687. self.create_addr_data()
  688. if not self.skip_wallet_check:
  689. check_wallets()
  690. self.wd = MoneroWalletDaemon(
  691. cfg = self.cfg,
  692. proto = self.proto,
  693. wallet_dir = self.cfg.wallet_dir or '.',
  694. test_suite = self.cfg.test_suite,
  695. monerod_addr = self.cfg.daemon or None,
  696. trust_monerod = self.trust_monerod,
  697. test_monerod = self.test_monerod,
  698. )
  699. if self.offline or (self.name in ('create','restore') and self.cfg.restore_height is None):
  700. self.wd.usr_daemon_args = ['--offline']
  701. self.c = MoneroWalletRPCClient(
  702. cfg = self.cfg,
  703. daemon = self.wd,
  704. test_connection = False,
  705. )
  706. if self.start_daemon and not self.cfg.no_start_wallet_daemon:
  707. async_run(self.restart_wallet_daemon())
  708. @classmethod
  709. def get_idx_from_fn(cls,fn):
  710. return int( re.match(r'[0-9a-fA-F]{8}-(\d+)-Monero(WatchOnly)?Wallet.*',fn.name)[1] )
  711. def get_coin_daemon_rpc(self):
  712. host,port = self.cfg.daemon.split(':') if self.cfg.daemon else ('localhost',self.wd.monerod_port)
  713. from .daemon import CoinDaemon
  714. return MoneroRPCClient(
  715. cfg = self.cfg,
  716. proto = self.proto,
  717. daemon = CoinDaemon( self.cfg, 'xmr' ),
  718. host = host,
  719. port = int(port),
  720. user = None,
  721. passwd = None )
  722. @property
  723. def autosign_viewkey_addr_file(self):
  724. from .addrfile import ViewKeyAddrFile
  725. mpdir = get_autosign_obj(self.cfg,'xmr').xmr_dir
  726. flist = [f for f in mpdir.iterdir() if f.name.endswith(ViewKeyAddrFile.ext)]
  727. if len(flist) != 1:
  728. die(2,
  729. "{a} viewkey-address files found in autosign mountpoint directory '{b}'!\n".format(
  730. a = 'Multiple' if flist else 'No',
  731. b = mpdir
  732. )
  733. + 'Have you run ‘mmgen-autosign setup’ on your offline machine with the --xmrwallets option?'
  734. )
  735. else:
  736. return flist[0]
  737. def create_addr_data(self):
  738. if uarg.wallets:
  739. idxs = AddrIdxList(uarg.wallets)
  740. self.addr_data = [d for d in self.kal.data if d.idx in idxs]
  741. if len(self.addr_data) != len(idxs):
  742. die(1,f'List {uarg.wallets!r} contains addresses not present in supplied key-address file')
  743. else:
  744. self.addr_data = self.kal.data
  745. async def restart_wallet_daemon(self):
  746. atexit.register(lambda: async_run(self.stop_wallet_daemon()))
  747. await self.c.restart_daemon()
  748. async def stop_wallet_daemon(self):
  749. if not self.cfg.no_stop_wallet_daemon:
  750. try:
  751. await self.c.stop_daemon()
  752. except KeyboardInterrupt:
  753. ymsg('\nForce killing wallet daemon')
  754. self.c.daemon.force_kill = True
  755. self.c.daemon.stop()
  756. def get_wallet_fn(self,data,watch_only=None):
  757. if watch_only is None:
  758. watch_only = self.cfg.watch_only
  759. return Path(
  760. (self.cfg.wallet_dir or '.'),
  761. '{a}-{b}-Monero{c}Wallet{d}'.format(
  762. a = self.kal.al_id.sid,
  763. b = data.idx,
  764. c = 'WatchOnly' if watch_only else '',
  765. d = f'.{self.cfg.network}' if self.cfg.network != 'mainnet' else '')
  766. )
  767. @property
  768. def add_wallet_desc(self):
  769. return 'offline signing ' if self.offline else 'watch-only ' if self.cfg.watch_only else ''
  770. async def main(self):
  771. gmsg('\n{a}ing {b} {c}wallet{d}'.format(
  772. a = self.stem.capitalize(),
  773. b = len(self.addr_data),
  774. c = self.add_wallet_desc,
  775. d = suf(self.addr_data) ))
  776. processed = 0
  777. for n,d in enumerate(self.addr_data): # [d.sec,d.addr,d.wallet_passwd,d.viewkey]
  778. fn = self.get_wallet_fn(d)
  779. gmsg('\n{a}ing wallet {b}/{c} ({d})'.format(
  780. a = self.stem.capitalize(),
  781. b = n + 1,
  782. c = len(self.addr_data),
  783. d = fn.name,
  784. ))
  785. processed += await self.process_wallet(
  786. d,
  787. fn,
  788. last = n==len(self.addr_data)-1 )
  789. gmsg(f'\n{processed} wallet{suf(processed)} {self.stem}ed')
  790. return processed
  791. def head_msg(self,wallet_idx,fn):
  792. gmsg('\n{a} {b}wallet #{c} ({d})'.format(
  793. a = self.action.capitalize(),
  794. b = self.add_wallet_desc,
  795. c = wallet_idx,
  796. d = fn.name
  797. ))
  798. class rpc:
  799. def __init__(self,parent,d):
  800. self.parent = parent
  801. self.cfg = parent.cfg
  802. self.c = parent.c
  803. self.d = d
  804. self.fn = parent.get_wallet_fn(d)
  805. self.new_tx_cls = (
  806. MoneroMMGenTX.NewUnsigned if self.cfg.watch_only else
  807. MoneroMMGenTX.NewSigned )
  808. def open_wallet(self,desc=None,refresh=True):
  809. add_desc = desc + ' ' if desc else self.parent.add_wallet_desc
  810. gmsg_r(f'\n Opening {add_desc}wallet...')
  811. self.c.call( # returns {}
  812. 'open_wallet',
  813. filename = self.fn.name,
  814. password = self.d.wallet_passwd )
  815. gmsg('done')
  816. if refresh:
  817. gmsg_r(f' Refreshing {add_desc}wallet...')
  818. ret = self.c.call('refresh')
  819. gmsg('done')
  820. if ret['received_money']:
  821. msg(' Wallet has received funds')
  822. def close_wallet(self,desc):
  823. gmsg_r(f'\n Closing {desc} wallet...')
  824. self.c.call('close_wallet')
  825. gmsg_r('done')
  826. async def stop_wallet(self,desc):
  827. msg(f'Stopping {self.c.daemon.desc} on port {self.c.daemon.bind_port}')
  828. gmsg_r(f'\n Stopping {desc} wallet...')
  829. await self.c.stop_daemon(quiet=True) # closes wallet
  830. gmsg_r('done')
  831. def print_accts(self,data,addrs_data,indent=' '):
  832. d = data['subaddress_accounts']
  833. msg('\n' + indent + f'Accounts of wallet {self.fn.name}:')
  834. fs = indent + ' {a:6} {b:18} {c:<6} {d:%s} {e}' % max(len(e['label']) for e in d)
  835. msg(fs.format(a='Index ',b='Base Address',c='nAddrs',d='Label',e='Unlocked Balance'))
  836. for i,e in enumerate(d):
  837. msg(fs.format(
  838. a = str(e['account_index']),
  839. b = e['base_address'][:15] + '...',
  840. c = len(addrs_data[i]['addresses']),
  841. d = e['label'],
  842. e = fmt_amt(e['unlocked_balance']),
  843. ))
  844. def get_accts(self,print=True):
  845. data = self.c.call('get_accounts')
  846. addrs_data = [
  847. self.c.call('get_address',account_index=i)
  848. for i in range(len(data['subaddress_accounts']))
  849. ]
  850. if print:
  851. self.print_accts(data,addrs_data)
  852. return ( data, addrs_data )
  853. def create_acct(self,label=None):
  854. msg('\n Creating new account...')
  855. ret = self.c.call(
  856. 'create_account',
  857. label = label or 'Sweep from {}:{} [{}]'.format(
  858. self.parent.source.idx,
  859. self.parent.account,
  860. make_timestr() ))
  861. msg(' Index: {}'.format( pink(str(ret['account_index'])) ))
  862. msg(' Address: {}'.format( cyan(ret['address']) ))
  863. return (ret['account_index'], ret['address'])
  864. def get_last_acct(self,accts_data):
  865. msg('\n Getting last account...')
  866. ret = accts_data['subaddress_accounts'][-1]
  867. msg(' Index: {}'.format( pink(str(ret['account_index'])) ))
  868. msg(' Address: {}'.format( cyan(ret['base_address']) ))
  869. return (ret['account_index'], ret['base_address'])
  870. def print_addrs(self,accts_data,account):
  871. ret = self.c.call('get_address',account_index=account)
  872. d = ret['addresses']
  873. msg('\n Addresses of account #{} ({}):'.format(
  874. account,
  875. accts_data['subaddress_accounts'][account]['label']))
  876. fs = ' {:6} {:18} {:%s} {}' % max((len(e['label']) for e in d), default=0)
  877. msg(fs.format('Index ','Address','Label','Used'))
  878. for e in d:
  879. msg(fs.format(
  880. str(e['address_index']),
  881. e['address'][:15] + '...',
  882. e['label'],
  883. e['used']
  884. ))
  885. return ret
  886. def create_new_addr(self,account,label=None):
  887. msg_r('\n Creating new address: ')
  888. ret = self.c.call(
  889. 'create_address',
  890. account_index = account,
  891. label = label or f'Sweep from this account [{make_timestr()}]',
  892. )
  893. msg(cyan(ret['address']))
  894. return ret['address']
  895. def get_last_addr(self,account,display=True):
  896. if display:
  897. msg('\n Getting last address:')
  898. ret = self.c.call(
  899. 'get_address',
  900. account_index = account,
  901. )['addresses']
  902. addr = ret[-1]['address']
  903. if display:
  904. msg(' ' + cyan(addr))
  905. return ( addr, len(ret) - 1 )
  906. def set_label(self,account,address_idx,label):
  907. return self.c.call(
  908. 'label_address',
  909. index = { 'major': account, 'minor': address_idx },
  910. label = label
  911. )
  912. def make_transfer_tx(self,account,addr,amt):
  913. res = self.c.call(
  914. 'transfer',
  915. account_index = account,
  916. destinations = [{
  917. 'amount': amt.to_unit('atomic'),
  918. 'address': addr
  919. }],
  920. do_not_relay = True,
  921. get_tx_hex = True,
  922. get_tx_metadata = True
  923. )
  924. return self.new_tx_cls(
  925. cfg = self.cfg,
  926. op = self.parent.name,
  927. network = self.parent.proto.network,
  928. seed_id = self.parent.kal.al_id.sid,
  929. source = XMRWalletAddrSpec(self.parent.source.idx,self.parent.account,None),
  930. dest = None,
  931. dest_address = addr,
  932. txid = res['tx_hash'],
  933. amount = res['amount'],
  934. fee = res['fee'],
  935. blob = res['tx_blob'],
  936. metadata = res['tx_metadata'],
  937. unsigned_txset = res['unsigned_txset'] if self.cfg.watch_only else None,
  938. )
  939. def make_sweep_tx(self,account,dest_acct,dest_addr_idx,addr):
  940. res = self.c.call(
  941. 'sweep_all',
  942. address = addr,
  943. account_index = account,
  944. do_not_relay = True,
  945. get_tx_hex = True,
  946. get_tx_metadata = True
  947. )
  948. if len(res['tx_hash_list']) > 1:
  949. die(3,'More than one TX required. Cannot perform this sweep')
  950. return self.new_tx_cls(
  951. cfg = self.cfg,
  952. op = self.parent.name,
  953. network = self.parent.proto.network,
  954. seed_id = self.parent.kal.al_id.sid,
  955. source = XMRWalletAddrSpec(self.parent.source.idx,self.parent.account,None),
  956. dest = XMRWalletAddrSpec(
  957. (self.parent.dest or self.parent.source).idx,
  958. dest_acct,
  959. dest_addr_idx),
  960. dest_address = addr,
  961. txid = res['tx_hash_list'][0],
  962. amount = res['amount_list'][0],
  963. fee = res['fee_list'][0],
  964. blob = res['tx_blob_list'][0],
  965. metadata = res['tx_metadata_list'][0],
  966. unsigned_txset = res['unsigned_txset'] if self.cfg.watch_only else None,
  967. )
  968. def relay_tx(self,tx_hex):
  969. ret = self.c.call('relay_tx',hex=tx_hex)
  970. try:
  971. msg('\n Relayed {}'.format( CoinTxID(ret['tx_hash']).hl() ))
  972. except:
  973. msg(f'\n Server returned: {ret!s}')
  974. class create(wallet):
  975. stem = 'creat'
  976. wallet_exists = False
  977. opts = ('restore_height',)
  978. def check_uopts(self):
  979. if self.cfg.restore_height != 'current':
  980. if int(self.cfg.restore_height or 0) < 0:
  981. die(1,f'{self.cfg.restore_height}: invalid value for --restore-height (less than zero)')
  982. async def process_wallet(self,d,fn,last):
  983. msg_r('') # for pexpect
  984. if self.cfg.restore_height == 'current':
  985. restore_height = self.get_coin_daemon_rpc().call_raw('get_height')['height']
  986. else:
  987. restore_height = self.cfg.restore_height
  988. if self.cfg.watch_only:
  989. ret = self.c.call(
  990. 'generate_from_keys',
  991. filename = fn.name,
  992. password = d.wallet_passwd,
  993. address = d.addr,
  994. viewkey = d.viewkey,
  995. restore_height = restore_height )
  996. else:
  997. from .xmrseed import xmrseed
  998. ret = self.c.call(
  999. 'restore_deterministic_wallet',
  1000. filename = fn.name,
  1001. password = d.wallet_passwd,
  1002. seed = xmrseed().fromhex(d.sec.wif,tostr=True),
  1003. restore_height = restore_height,
  1004. language = 'English' )
  1005. pp_msg(ret) if self.cfg.debug else msg(f' Address: {ret["address"]}')
  1006. return True
  1007. class create_offline(create):
  1008. offline = True
  1009. def __init__(self,cfg,uarg_tuple):
  1010. super().__init__(cfg,uarg_tuple)
  1011. gmsg('\nCreating viewkey-address file for watch-only wallets')
  1012. vkal = ViewKeyAddrList(
  1013. cfg = self.cfg,
  1014. proto = self.proto,
  1015. addrfile = None,
  1016. addr_idxs = uarg.wallets,
  1017. seed = self.seed_src.seed,
  1018. skip_chksum_msg = True )
  1019. vkf = vkal.file
  1020. # before writing viewkey-address file, shred any old ones in the directory:
  1021. for f in Path(self.cfg.outdir or '.').iterdir():
  1022. if f.name.endswith(vkf.ext):
  1023. from .fileutil import shred_file
  1024. msg(f"\nShredding old viewkey-address file '{f}'")
  1025. shred_file( f, verbose=self.cfg.verbose )
  1026. vkf.write() # write file to self.cfg.outdir
  1027. class restore(create):
  1028. def check_uopts(self):
  1029. if self.cfg.restore_height is not None:
  1030. die(1,'--restore-height must be unset when running the ‘restore’ command')
  1031. async def process_wallet(self,d,fn,last):
  1032. def get_dump_data():
  1033. def gen():
  1034. for fn in [self.get_wallet_fn(d,watch_only=wo) for wo in (True,False)]:
  1035. ret = fn.parent / (fn.name + '.dump')
  1036. if ret.exists():
  1037. yield ret
  1038. dump_fns = tuple(gen())
  1039. if not dump_fns:
  1040. die(1,f"No suitable dump file found for '{fn}'")
  1041. elif len(dump_fns) > 1:
  1042. ymsg(f"Warning: more than one dump file found for '{fn}' - using the first!")
  1043. return MoneroWalletDumpFile.Completed(
  1044. parent = self,
  1045. fn = dump_fns[0] ).data._asdict()['wallet_metadata']
  1046. def restore_accounts():
  1047. bmsg(' Restoring accounts:')
  1048. for acct_idx,acct_data in enumerate(data[1:],1):
  1049. msg(fs.format(acct_idx, 0, acct_data['address']))
  1050. self.c.call('create_account')
  1051. def restore_subaddresses():
  1052. bmsg(' Restoring subaddresses:')
  1053. for acct_idx,acct_data in enumerate(data):
  1054. for addr_idx,addr_data in enumerate(acct_data['addresses'][1:],1):
  1055. msg(fs.format(acct_idx, addr_idx, addr_data['address']))
  1056. self.c.call( 'create_address', account_index=acct_idx )
  1057. def restore_labels():
  1058. bmsg(' Restoring labels:')
  1059. for acct_idx,acct_data in enumerate(data):
  1060. for addr_idx,addr_data in enumerate(acct_data['addresses']):
  1061. addr_data['used'] = False # do this so that restored data matches
  1062. msg(fs.format(acct_idx, addr_idx, addr_data['label']))
  1063. self.c.call(
  1064. 'label_address',
  1065. index = { 'major': acct_idx, 'minor': addr_idx },
  1066. label = addr_data['label'],
  1067. )
  1068. def make_format_str():
  1069. return ' acct {:O>%s}, addr {:O>%s} [{}]' % (
  1070. len(str( len(data) - 1 )),
  1071. len(str( max(len(acct_data['addresses']) for acct_data in data) - 1))
  1072. )
  1073. def check_restored_data():
  1074. restored_data = h.get_accts(print=False)[1]
  1075. if restored_data != data:
  1076. rmsg('Restored data does not match original dump! Dumping bad data.')
  1077. MoneroWalletDumpFile.New(
  1078. parent = self,
  1079. wallet_fn = fn,
  1080. data = {'wallet_metadata': restored_data} ).write(add_suf='.bad')
  1081. die(3,'Fatal error')
  1082. await super().process_wallet(d,fn,last)
  1083. h = self.rpc(self,d)
  1084. h.open_wallet('newly created')
  1085. msg('')
  1086. data = get_dump_data()
  1087. fs = make_format_str()
  1088. gmsg('\nRestoring accounts, subaddresses and labels from dump file:\n')
  1089. restore_accounts()
  1090. restore_subaddresses()
  1091. restore_labels()
  1092. check_restored_data()
  1093. return True
  1094. class sync(wallet):
  1095. opts = ('rescan_blockchain',)
  1096. test_monerod = True
  1097. def check_uopts(self):
  1098. if self.cfg.rescan_blockchain and self.cfg.watch_only:
  1099. die(1,f'Operation {self.name!r} does not support --rescan-blockchain with watch-only wallets')
  1100. def __init__(self,cfg,uarg_tuple):
  1101. super().__init__(cfg,uarg_tuple)
  1102. self.dc = self.get_coin_daemon_rpc()
  1103. self.accts_data = {}
  1104. async def process_wallet(self,d,fn,last):
  1105. chain_height = self.dc.call_raw('get_height')['height']
  1106. msg(f' Chain height: {chain_height}')
  1107. t_start = time.time()
  1108. msg_r(' Opening wallet...')
  1109. self.c.call(
  1110. 'open_wallet',
  1111. filename = fn.name,
  1112. password = d.wallet_passwd )
  1113. msg('done')
  1114. msg_r(' Getting wallet height (be patient, this could take a long time)...')
  1115. wallet_height = self.c.call('get_height')['height']
  1116. msg_r('\r' + ' '*68 + '\r')
  1117. msg(f' Wallet height: {wallet_height} ')
  1118. behind = chain_height - wallet_height
  1119. if behind > 1000:
  1120. msg_r(f' Wallet is {behind} blocks behind chain tip. Please be patient. Syncing...')
  1121. ret = self.c.call('refresh')
  1122. if behind > 1000:
  1123. msg('done')
  1124. if ret['received_money']:
  1125. msg(' Wallet has received funds')
  1126. for i in range(2):
  1127. wallet_height = self.c.call('get_height')['height']
  1128. if wallet_height >= chain_height:
  1129. break
  1130. ymsg(f' Wallet failed to sync (wallet height [{wallet_height}] < chain height [{chain_height}])')
  1131. if i or not self.cfg.rescan_blockchain:
  1132. break
  1133. msg_r(' Rescanning blockchain, please be patient...')
  1134. self.c.call('rescan_blockchain')
  1135. self.c.call('refresh')
  1136. msg('done')
  1137. t_elapsed = int(time.time() - t_start)
  1138. a,b = self.rpc(self,d).get_accts(print=False)
  1139. msg(' Balance: {} Unlocked balance: {}'.format(
  1140. hl_amt(a['total_balance']),
  1141. hl_amt(a['total_unlocked_balance']),
  1142. ))
  1143. self.accts_data[fn.name] = { 'accts': a, 'addrs': b }
  1144. msg(f' Wallet height: {wallet_height}')
  1145. msg(f' Sync time: {t_elapsed//60:02}:{t_elapsed%60:02}')
  1146. if not last:
  1147. self.c.call('close_wallet')
  1148. return wallet_height >= chain_height
  1149. def post_main_success(self):
  1150. d = self.accts_data
  1151. for wnum,k in enumerate(d):
  1152. if self.name == 'sync':
  1153. self.rpc(self,self.addr_data[wnum]).print_accts( d[k]['accts'], d[k]['addrs'], indent='')
  1154. elif self.name == 'list':
  1155. fs = ' {:2} {} {} {}'
  1156. msg('\n' + green(f'Wallet {k}:'))
  1157. for acct_num,acct in enumerate(d[k]['addrs']):
  1158. msg('\n Account #{a} [{b} {c}]'.format(
  1159. a = acct_num,
  1160. b = self.proto.coin_amt(
  1161. d[k]['accts']['subaddress_accounts'][acct_num]['unlocked_balance'],
  1162. from_unit='atomic').hl(),
  1163. c = self.proto.coin_amt.hlc('XMR')
  1164. ))
  1165. msg(fs.format('','Address'.ljust(95),'Used ','Label'))
  1166. for addr in acct['addresses']:
  1167. msg(fs.format(
  1168. addr['address_index'],
  1169. CoinAddr(self.proto,addr['address']).hl(),
  1170. ( yellow('True ') if addr['used'] else green('False') ),
  1171. pink(addr['label']) ))
  1172. col1_w = max(map(len,d)) + 1
  1173. fs = '{:%s} {} {}' % col1_w
  1174. tbals = [0,0]
  1175. msg('\n'+fs.format('Wallet','Balance ','Unlocked Balance'))
  1176. for k in d:
  1177. b = d[k]['accts']['total_balance']
  1178. ub = d[k]['accts']['total_unlocked_balance']
  1179. msg(fs.format( k + ':', fmt_amt(b), fmt_amt(ub) ))
  1180. tbals[0] += b
  1181. tbals[1] += ub
  1182. msg(fs.format( '-'*col1_w, '-'*18, '-'*18 ))
  1183. msg(fs.format( 'TOTAL:', fmt_amt(tbals[0]), fmt_amt(tbals[1]) ))
  1184. class list(sync):
  1185. stem = 'sync'
  1186. class spec(wallet): # virtual class
  1187. def create_addr_data(self):
  1188. m = re.fullmatch(uarg_info[self.spec_id].pat,uarg.spec,re.ASCII)
  1189. if not m:
  1190. fs = "{!r}: invalid {!r} arg: for {} operation, it must have format {!r}"
  1191. die(1,fs.format( uarg.spec, self.spec_id, self.name, uarg_info[self.spec_id].annot ))
  1192. def gen():
  1193. for i,k in self.spec_key:
  1194. if m[i] is None:
  1195. setattr(self,k,None)
  1196. else:
  1197. idx = int(m[i])
  1198. try:
  1199. res = self.kal.entry(idx)
  1200. except:
  1201. die(1,f'Supplied key-address file does not contain address {self.kal.al_id.sid}:{idx}')
  1202. else:
  1203. setattr(self,k,res)
  1204. yield res
  1205. self.addr_data = list(gen())
  1206. self.account = None if m[2] is None else int(m[2])
  1207. def strip_quotes(s):
  1208. if s and s[0] in ("'",'"'):
  1209. if s[-1] != s[0] or len(s) < 2:
  1210. die(1,f'{s!r}: unbalanced quotes in label string!')
  1211. return s[1:-1]
  1212. else:
  1213. return s # None or empty string
  1214. if self.name == 'transfer':
  1215. self.dest_addr = CoinAddr(self.proto,m[3])
  1216. self.amount = self.proto.coin_amt(m[4])
  1217. elif self.name == 'new':
  1218. self.label = strip_quotes(m[3])
  1219. elif self.name == 'label':
  1220. self.address_idx = int(m[3])
  1221. self.label = strip_quotes(m[4])
  1222. class sweep(spec):
  1223. spec_id = 'sweep_spec'
  1224. spec_key = ( (1,'source'), (3,'dest') )
  1225. opts = ('no_relay','tx_relay_daemon','watch_only')
  1226. test_monerod = True
  1227. def check_uopts(self):
  1228. if self.cfg.tx_relay_daemon and (self.cfg.no_relay or self.cfg.autosign):
  1229. die(1,'--tx-relay-daemon makes no sense in this context!')
  1230. def init_tx_relay_daemon(self):
  1231. m = self.parse_tx_relay_opt()
  1232. wd2 = MoneroWalletDaemon(
  1233. cfg = self.cfg,
  1234. proto = self.proto,
  1235. wallet_dir = self.cfg.wallet_dir or '.',
  1236. test_suite = self.cfg.test_suite,
  1237. monerod_addr = m[1],
  1238. proxy = m[2] )
  1239. if self.cfg.test_suite:
  1240. wd2.usr_daemon_args = ['--daemon-ssl-allow-any-cert']
  1241. wd2.start()
  1242. self.c = MoneroWalletRPCClient(
  1243. cfg = self.cfg,
  1244. daemon = wd2 )
  1245. async def main(self):
  1246. gmsg(f'\n{self.stem.capitalize()}ing account #{self.account} of wallet {self.source.idx}' + (
  1247. f': {self.amount} XMR to {self.dest_addr}' if self.name == 'transfer'
  1248. else ' to new address' if self.dest is None
  1249. else f' to new account in wallet {self.dest.idx}' ))
  1250. h = self.rpc(self,self.source)
  1251. h.open_wallet('source')
  1252. accts_data = h.get_accts()[0]
  1253. max_acct = len(accts_data['subaddress_accounts']) - 1
  1254. if self.account > max_acct:
  1255. die(1,f'{self.account}: requested account index out of bounds (>{max_acct})')
  1256. h.print_addrs(accts_data,self.account)
  1257. if self.name == 'transfer':
  1258. dest_addr = self.dest_addr
  1259. elif self.dest is None:
  1260. dest_acct = self.account
  1261. if keypress_confirm( self.cfg, f'\nCreate new address for account #{self.account}?' ):
  1262. dest_addr_chk = h.create_new_addr(self.account)
  1263. elif keypress_confirm( self.cfg, f'Sweep to last existing address of account #{self.account}?' ):
  1264. dest_addr_chk = None
  1265. else:
  1266. die(1,'Exiting at user request')
  1267. dest_addr,dest_addr_idx = h.get_last_addr(self.account,display=not dest_addr_chk)
  1268. assert dest_addr_chk in (None,dest_addr), 'dest_addr_chk1'
  1269. h.print_addrs(accts_data,self.account)
  1270. else:
  1271. h.close_wallet('source')
  1272. wf = self.get_wallet_fn(self.dest)
  1273. h2 = self.rpc(self,self.dest)
  1274. h2.open_wallet('destination')
  1275. accts_data = h2.get_accts()[0]
  1276. if keypress_confirm( self.cfg, f'\nCreate new account for wallet {wf.name!r}?' ):
  1277. dest_acct,dest_addr = h2.create_acct()
  1278. dest_addr_idx = 0
  1279. h2.get_accts()
  1280. elif keypress_confirm( self.cfg, f'Sweep to last existing account of wallet {wf.name!r}?' ):
  1281. dest_acct,dest_addr_chk = h2.get_last_acct(accts_data)
  1282. dest_addr,dest_addr_idx = h2.get_last_addr(dest_acct,display=False)
  1283. assert dest_addr_chk == dest_addr, 'dest_addr_chk2'
  1284. else:
  1285. die(1,'Exiting at user request')
  1286. h2.close_wallet('destination')
  1287. h.open_wallet('source',refresh=False)
  1288. msg(f'\n Creating {self.name} transaction...')
  1289. if self.name == 'transfer':
  1290. new_tx = h.make_transfer_tx(self.account,dest_addr,self.amount)
  1291. elif self.name == 'sweep':
  1292. new_tx = h.make_sweep_tx(self.account,dest_acct,dest_addr_idx,dest_addr)
  1293. msg('\n' + new_tx.get_info(indent=' '))
  1294. if self.cfg.tx_relay_daemon:
  1295. self.display_tx_relay_info(indent=' ')
  1296. msg('Saving TX data to file')
  1297. new_tx.write(delete_metadata=True)
  1298. if self.cfg.no_relay or self.cfg.autosign:
  1299. return True
  1300. if keypress_confirm( self.cfg, f'Relay {self.name} transaction?' ):
  1301. if self.cfg.tx_relay_daemon:
  1302. await h.stop_wallet('source')
  1303. msg('')
  1304. self.init_tx_relay_daemon()
  1305. h = self.rpc(self,self.source)
  1306. h.open_wallet('TX-relay-configured source',refresh=False)
  1307. msg_r(f'\n Relaying {self.name} transaction...')
  1308. h.relay_tx(new_tx.data.metadata)
  1309. gmsg('\nAll done')
  1310. return True
  1311. else:
  1312. die(1,'\nExiting at user request')
  1313. class transfer(sweep):
  1314. stem = 'transferr'
  1315. spec_id = 'transfer_spec'
  1316. spec_key = ( (1,'source'), )
  1317. class new(spec):
  1318. spec_id = 'newaddr_spec'
  1319. spec_key = ( (1,'source'), )
  1320. async def main(self):
  1321. h = self.rpc(self,self.source)
  1322. h.open_wallet('Monero')
  1323. label = '{a} [{b}]'.format(
  1324. a = self.label or f"xmrwallet new {'account' if self.account is None else 'address'}",
  1325. b = make_timestr() )
  1326. if self.account is None:
  1327. h.create_acct(label=label)
  1328. else:
  1329. msg_r(f'\n Account index: {pink(str(self.account))}')
  1330. h.create_new_addr(self.account,label=label)
  1331. accts_data = h.get_accts()[0]
  1332. if self.account is not None:
  1333. h.print_addrs(accts_data,self.account)
  1334. # wallet must be left open: otherwise the 'stop_wallet' RPC call used to stop the daemon will fail
  1335. if self.cfg.no_stop_wallet_daemon:
  1336. h.close_wallet('Monero')
  1337. msg('')
  1338. class label(spec):
  1339. spec_id = 'label_spec'
  1340. spec_key = ( (1,'source'), )
  1341. opts = ()
  1342. async def main(self):
  1343. gmsg('\n{a} label for wallet {b}, account #{c}, address #{d}'.format(
  1344. a = 'Setting' if self.label else 'Removing',
  1345. b = self.source.idx,
  1346. c = self.account,
  1347. d = self.address_idx
  1348. ))
  1349. h = self.rpc(self,self.source)
  1350. h.open_wallet('source')
  1351. accts_data = h.get_accts()[0]
  1352. max_acct = len(accts_data['subaddress_accounts']) - 1
  1353. if self.account > max_acct:
  1354. die(1,f'{self.account}: requested account index out of bounds (>{max_acct})')
  1355. ret = h.print_addrs(accts_data,self.account)
  1356. if self.address_idx > len(ret['addresses']) - 1:
  1357. die(1,'{}: requested address index out of bounds (>{})'.format(
  1358. self.account,
  1359. len(ret['addresses']) - 1 ))
  1360. addr = ret['addresses'][self.address_idx]
  1361. msg('\n {a} {b}\n {c} {d}\n {e} {f}'.format(
  1362. a = 'Address: ',
  1363. b = cyan(addr['address'][:15] + '...'),
  1364. c = 'Existing label:',
  1365. d = pink(addr['label']) if addr['label'] else '[none]',
  1366. e = 'New label: ',
  1367. f = pink(self.label) if self.label else '[none]' ))
  1368. if addr['label'] == self.label:
  1369. ymsg('\nLabel is unchanged, operation cancelled')
  1370. elif keypress_confirm( self.cfg, ' {} label?'.format('Set' if self.label else 'Remove') ):
  1371. h.set_label( self.account, self.address_idx, self.label )
  1372. accts_data = h.get_accts(print=False)[0]
  1373. ret = h.print_addrs(accts_data,self.account)
  1374. new_label = ret['addresses'][self.address_idx]['label']
  1375. if new_label != self.label:
  1376. ymsg(f'Warning: new label {new_label!r} does not match requested value!')
  1377. return False
  1378. else:
  1379. msg(cyan('\nLabel successfully {}'.format('set' if self.label else 'removed')))
  1380. else:
  1381. ymsg('\nOperation cancelled by user request')
  1382. class sign(wallet):
  1383. action = 'signing transaction with'
  1384. start_daemon = False
  1385. offline = True
  1386. async def main(self,fn,restart_daemon=True):
  1387. if restart_daemon:
  1388. await self.restart_wallet_daemon()
  1389. tx = MoneroMMGenTX.Unsigned( self.cfg, fn )
  1390. h = self.rpc(self,self.addr_data[0])
  1391. self.head_msg(tx.src_wallet_idx,h.fn)
  1392. if restart_daemon:
  1393. h.open_wallet(refresh=False)
  1394. res = self.c.call(
  1395. 'sign_transfer',
  1396. unsigned_txset = tx.data.unsigned_txset,
  1397. export_raw = True,
  1398. get_tx_keys = True
  1399. )
  1400. new_tx = MoneroMMGenTX.NewColdSigned(
  1401. cfg = self.cfg,
  1402. txid = res['tx_hash_list'][0],
  1403. unsigned_txset = None,
  1404. signed_txset = res['signed_txset'],
  1405. _in_tx = tx,
  1406. )
  1407. return new_tx
  1408. class submit(wallet):
  1409. action = 'submitting transaction with'
  1410. opts = ('tx_relay_daemon',)
  1411. test_monerod = True
  1412. def check_uopts(self):
  1413. self.tx # trigger an exit if no suitable transaction present
  1414. def die_no_tx(self,desc,num_txs,tx_dir):
  1415. die('AutosignTXError', "{a} {b} transaction{c} in '{d}'!".format(
  1416. a = 'More than one' if num_txs else 'No',
  1417. b = desc,
  1418. c = suf(num_txs),
  1419. d = tx_dir,
  1420. ))
  1421. @property
  1422. def tx(self):
  1423. if not hasattr(self,'_tx'):
  1424. self._tx = self.get_tx()
  1425. return self._tx
  1426. def get_tx(self):
  1427. if uarg.infile:
  1428. fn = Path(uarg.infile)
  1429. else:
  1430. from .autosign import Signable
  1431. t = Signable.xmr_transaction( get_autosign_obj(self.cfg,'xmr') )
  1432. if len(t.unsubmitted) == 1:
  1433. fn = t.unsubmitted[0]
  1434. else:
  1435. self.die_no_tx( 'unsubmitted', len(t.unsubmitted), t.parent.xmr_tx_dir )
  1436. return MoneroMMGenTX.ColdSigned( cfg=self.cfg, fn=fn )
  1437. def get_relay_rpc(self):
  1438. relay_opt = self.parse_tx_relay_opt()
  1439. wd = MoneroWalletDaemon(
  1440. cfg = self.cfg,
  1441. proto = self.proto,
  1442. wallet_dir = self.cfg.wallet_dir or '.',
  1443. test_suite = self.cfg.test_suite,
  1444. monerod_addr = relay_opt[1],
  1445. trust_monerod = False,
  1446. test_monerod = False,
  1447. )
  1448. u = wd.usr_daemon_args = []
  1449. if self.cfg.test_suite:
  1450. u.append('--daemon-ssl-allow-any-cert')
  1451. if relay_opt[2]:
  1452. u.append(f'--proxy={relay_opt[2]}')
  1453. return MoneroWalletRPCClient(
  1454. cfg = self.cfg,
  1455. daemon = wd,
  1456. test_connection = False,
  1457. )
  1458. async def main(self):
  1459. tx = self.tx
  1460. h = self.rpc( self, self.kal.entry(tx.src_wallet_idx) )
  1461. self.head_msg(tx.src_wallet_idx,h.fn)
  1462. h.open_wallet()
  1463. if self.cfg.tx_relay_daemon:
  1464. await self.c.stop_daemon()
  1465. self.c = self.get_relay_rpc()
  1466. self.c.start_daemon()
  1467. h = self.rpc( self, self.kal.entry(tx.src_wallet_idx) )
  1468. h.open_wallet( 'TX-relay-configured watch-only', refresh=False )
  1469. msg('\n' + tx.get_info(indent=' '))
  1470. if self.cfg.tx_relay_daemon:
  1471. self.display_tx_relay_info(indent=' ')
  1472. if keypress_confirm( self.cfg, f'{self.name.capitalize()} transaction?' ):
  1473. if self.cfg.tx_relay_daemon:
  1474. msg_r('Relaying transaction to remote daemon, please be patient...')
  1475. res = self.c.call(
  1476. 'submit_transfer',
  1477. tx_data_hex = tx.data.signed_txset )
  1478. assert res['tx_hash_list'][0] == tx.data.txid, 'TxID mismatch in ‘submit_transfer’ result!'
  1479. if self.cfg.tx_relay_daemon:
  1480. msg('success')
  1481. else:
  1482. die(1,'Exiting at user request')
  1483. new_tx = MoneroMMGenTX.NewSubmitted(
  1484. cfg = self.cfg,
  1485. _in_tx = tx,
  1486. )
  1487. gmsg('\nOK')
  1488. new_tx.write(
  1489. ask_write = not self.cfg.autosign,
  1490. ask_overwrite = not self.cfg.autosign )
  1491. return new_tx
  1492. class resubmit(submit):
  1493. action = 'resubmitting transaction with'
  1494. def check_uopts(self):
  1495. if not self.cfg.autosign:
  1496. die(1,'--autosign is required for this operation')
  1497. def get_tx(self):
  1498. asi = get_autosign_obj(self.cfg,'xmr')
  1499. files = [f for f in asi.xmr_tx_dir.iterdir() if f.name.endswith('.'+MoneroMMGenTX.Submitted.ext)]
  1500. txs = sorted(
  1501. (MoneroMMGenTX.Submitted( self.cfg, Path(fn) ) for fn in files),
  1502. key = lambda x: getattr(x.data,'submit_time',None) or x.data.create_time
  1503. )
  1504. if txs:
  1505. return txs[-1]
  1506. else:
  1507. self.die_no_tx( 'submitted', 0, asi.xmr_tx_dir )
  1508. class dump(wallet):
  1509. async def process_wallet(self,d,fn,last):
  1510. h = self.rpc(self,d)
  1511. h.open_wallet('source')
  1512. _,addr_data = h.get_accts(print=False)
  1513. msg('')
  1514. MoneroWalletDumpFile.New(
  1515. parent = self,
  1516. wallet_fn = fn,
  1517. data = {'wallet_metadata': addr_data} ).write()
  1518. return True
  1519. class export_outputs(wallet):
  1520. action = 'exporting outputs from'
  1521. stem = 'process'
  1522. opts = ('rescan_blockchain',)
  1523. async def process_wallet(self,d,fn,last):
  1524. h = self.rpc(self,d)
  1525. h.open_wallet('source')
  1526. if self.cfg.rescan_blockchain:
  1527. gmsg_r('\n Rescanning blockchain...')
  1528. self.c.call('rescan_blockchain')
  1529. gmsg('done')
  1530. self.head_msg(d.idx,h.fn)
  1531. for ftype in ('Unsigned','Signed'):
  1532. old_fn = getattr(MoneroWalletOutputsFile,ftype).find_fn_from_wallet_fn(
  1533. cfg = self.cfg,
  1534. wallet_fn = fn,
  1535. ret_on_no_match = True )
  1536. if old_fn:
  1537. old_fn.unlink()
  1538. m = MoneroWalletOutputsFile.New(
  1539. parent = self,
  1540. wallet_fn = fn,
  1541. data = self.c.call('export_outputs', all=True),
  1542. )
  1543. m.write()
  1544. return True
  1545. class export_key_images(wallet):
  1546. action = 'signing wallet outputs file with'
  1547. start_daemon = False
  1548. offline = True
  1549. async def main(self,fn,wallet_idx,restart_daemon=True):
  1550. if restart_daemon:
  1551. await self.restart_wallet_daemon()
  1552. h = self.rpc(self,self.addr_data[0])
  1553. self.head_msg(wallet_idx,fn)
  1554. if restart_daemon:
  1555. h.open_wallet(refresh=False)
  1556. m = MoneroWalletOutputsFile.Unsigned(
  1557. parent = self,
  1558. fn = fn )
  1559. res = self.c.call(
  1560. 'import_outputs',
  1561. outputs_data_hex = m.data.outputs_data_hex )
  1562. idata = res['num_imported']
  1563. bmsg(f'\n {idata} output{suf(idata)} imported')
  1564. data = m.data._asdict()
  1565. data.update(self.c.call('export_key_images', all=True))
  1566. m = MoneroWalletOutputsFile.SignedNew(
  1567. parent = self,
  1568. wallet_fn = m.get_wallet_fn(fn),
  1569. data = data )
  1570. idata = m.data.signed_key_images or []
  1571. bmsg(f' {len(idata)} key image{suf(idata)} signed')
  1572. return m
  1573. class import_key_images(wallet):
  1574. action = 'importing key images into'
  1575. stem = 'process'
  1576. trust_monerod = True
  1577. def post_main_failure(self):
  1578. rw_msg = ' for requested wallets' if uarg.wallets else ''
  1579. die(1,yellow(f'No signed key image files found{rw_msg}!'))
  1580. async def process_wallet(self,d,fn,last):
  1581. keyimage_fn = MoneroWalletOutputsFile.Signed.find_fn_from_wallet_fn( self.cfg, fn, ret_on_no_match=True )
  1582. if not keyimage_fn:
  1583. msg(f'No signed key image file found for wallet #{d.idx}')
  1584. return False
  1585. h = self.rpc(self,d)
  1586. h.open_wallet()
  1587. self.head_msg(d.idx,h.fn)
  1588. m = MoneroWalletOutputsFile.Signed( parent=self, fn=keyimage_fn )
  1589. data = m.data.signed_key_images or []
  1590. bmsg(f'\n {len(data)} signed key image{suf(data)} to import')
  1591. if data:
  1592. res = self.c.call( 'import_key_images', signed_key_images=data )
  1593. bmsg(f' Success: {res}')
  1594. return True
  1595. class relay(base):
  1596. opts = ('tx_relay_daemon',)
  1597. def __init__(self,cfg,uarg_tuple):
  1598. super().__init__(cfg,uarg_tuple)
  1599. self.tx = MoneroMMGenTX.Signed( self.cfg, Path(uarg.infile) )
  1600. if self.cfg.tx_relay_daemon:
  1601. m = self.parse_tx_relay_opt()
  1602. host,port = m[1].split(':')
  1603. proxy = m[2]
  1604. md = None
  1605. else:
  1606. from .daemon import CoinDaemon
  1607. md = CoinDaemon( self.cfg, 'xmr', test_suite=self.cfg.test_suite )
  1608. host,port = ('localhost', md.rpc_port)
  1609. proxy = None
  1610. self.dc = MoneroRPCClient(
  1611. cfg = self.cfg,
  1612. proto = self.proto,
  1613. daemon = md,
  1614. host = host,
  1615. port = int(port),
  1616. user = None,
  1617. passwd = None,
  1618. test_connection = host == 'localhost', # avoid extra connections if relay is a public node
  1619. proxy = proxy )
  1620. async def main(self):
  1621. msg('\n' + self.tx.get_info(indent=' '))
  1622. if self.cfg.tx_relay_daemon:
  1623. self.display_tx_relay_info(indent=' ')
  1624. if keypress_confirm( self.cfg, 'Relay transaction?' ):
  1625. res = self.dc.call_raw(
  1626. 'send_raw_transaction',
  1627. tx_as_hex = self.tx.data.blob
  1628. )
  1629. if res['status'] == 'OK':
  1630. msg('Status: ' + green('OK'))
  1631. if res['not_relayed']:
  1632. ymsg('Transaction not relayed')
  1633. return True
  1634. else:
  1635. die( 'RPCFailure', repr(res) )
  1636. else:
  1637. die(1,'Exiting at user request')
  1638. class txview(base):
  1639. view_method = 'get_info'
  1640. opts = ('watch_only','autosign')
  1641. hdr = ''
  1642. col_hdr = ''
  1643. footer = ''
  1644. cols = None
  1645. do_umount = False
  1646. async def main(self,cols=None):
  1647. if self.cfg.autosign:
  1648. asi = get_autosign_obj(self.cfg,'xmr')
  1649. files = [f for f in asi.xmr_tx_dir.iterdir() if f.name.endswith('.'+MoneroMMGenTX.Submitted.ext)]
  1650. else:
  1651. files = uarg.infile
  1652. txs = sorted(
  1653. (MoneroMMGenTX.View( self.cfg, Path(fn) ) for fn in files),
  1654. # old TX files have no ‘submit_time’ field:
  1655. key = lambda x: getattr(x.data,'submit_time',None) or x.data.create_time
  1656. )
  1657. if self.cfg.autosign:
  1658. asi.do_umount()
  1659. self.cfg._util.stdout_or_pager(
  1660. (self.hdr if len(files) > 1 else '')
  1661. + self.col_hdr
  1662. + '\n'.join(getattr(tx,self.view_method)(cols=cols) for tx in txs)
  1663. + self.footer
  1664. )
  1665. class txlist(txview):
  1666. view_method = 'get_info_oneline'
  1667. add_nl = True
  1668. footer = '\n'
  1669. @property
  1670. def hdr(self):
  1671. return ('SUBMITTED ' if self.cfg.autosign else '') + 'MONERO TRANSACTIONS\n'
  1672. @property
  1673. def col_hdr(self):
  1674. return MoneroMMGenTX.View.oneline_fs.format(
  1675. a = 'Network',
  1676. b = 'Seed ID',
  1677. c = 'Submitted' if self.cfg.autosign else 'Date',
  1678. d = 'TxID',
  1679. e = 'Type',
  1680. f = 'Src',
  1681. g = 'Dest',
  1682. h = ' Amount',
  1683. j = 'Dest Address',
  1684. x = '',
  1685. ) + '\n'
  1686. async def main(self):
  1687. if self.cfg.pager:
  1688. cols = None
  1689. else:
  1690. from .term import get_terminal_size
  1691. cols = self.cfg.columns or get_terminal_size().width
  1692. if cols < 106:
  1693. die(1, 'A terminal at least 106 columns wide is required to display this output'
  1694. + ' (or use --columns or --pager)' )
  1695. await super().main(cols=cols)