xmrwallet.py 56 KB

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