xmrwallet.py 55 KB

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