xmrwallet.py 60 KB

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