xmrwallet.py 59 KB

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