tool.py 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2020 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. tool.py: Routines for the 'mmgen-tool' utility
  20. """
  21. from .protocol import hash160
  22. from .common import *
  23. from .crypto import *
  24. from .addr import *
  25. NL = ('\n','\r\n')[g.platform=='win']
  26. def _options_annot_str(l):
  27. return '(valid options: {})'.format(','.join(l))
  28. def _create_call_sig(cmd,parsed=False):
  29. m = MMGenToolCmds[cmd]
  30. if 'varargs_call_sig' in m.__code__.co_varnames: # hack
  31. flag = 'VAR_ARGS'
  32. va = m.__defaults__[0]
  33. args,dfls,ann = va['args'],va['dfls'],va['annots']
  34. else:
  35. flag = None
  36. args = m.__code__.co_varnames[1:m.__code__.co_argcount]
  37. dfls = m.__defaults__ or ()
  38. ann = m.__annotations__
  39. nargs = len(args) - len(dfls)
  40. def get_type_from_ann(arg):
  41. return ann[arg][1:] + (' or STDIN','')[parsed] if ann[arg] == 'sstr' else ann[arg].__name__
  42. if parsed:
  43. c_args = [(a,get_type_from_ann(a)) for a in args[:nargs]]
  44. c_kwargs = [(a,dfls[n]) for n,a in enumerate(args[nargs:])]
  45. return c_args,dict(c_kwargs),'STDIN_OK' if c_args and ann[args[0]] == 'sstr' else flag
  46. else:
  47. c_args = ['{} [{}]'.format(a,get_type_from_ann(a)) for a in args[:nargs]]
  48. c_kwargs = ['"{}" [{}={!r}{}]'.format(
  49. a, type(dfls[n]).__name__, dfls[n],
  50. (' ' + ann[a] if a in ann else ''))
  51. for n,a in enumerate(args[nargs:])]
  52. return ' '.join(c_args + c_kwargs)
  53. def _usage(cmd=None,exit_val=1):
  54. m1=('USAGE INFORMATION FOR MMGEN-TOOL COMMANDS:\n\n'
  55. ' Unquoted arguments are mandatory\n'
  56. ' Quoted arguments are optional, default values will be used\n'
  57. ' Argument types and default values are shown in square brackets\n')
  58. m2=(' To force a command to read from STDIN instead of file (for commands taking\n'
  59. ' a filename as their first argument), substitute "-" for the filename.\n\n'
  60. 'EXAMPLES:\n\n'
  61. ' Generate a random Bech32 public/private keypair for LTC:\n'
  62. ' $ mmgen-tool -r0 --coin=ltc --type=bech32 randpair\n\n'
  63. ' Generate a DASH compressed public key address from the supplied WIF key:\n'
  64. ' $ mmgen-tool --coin=dash --type=compressed wif2addr XJkVRC3eGKurc9Uzx1wfQoio3yqkmaXVqLMTa6y7s3M3jTBnmxfw\n\n'
  65. ' Generate a well-known burn address:\n'
  66. ' $ mmgen-tool hextob58chk 000000000000000000000000000000000000000000\n\n'
  67. ' Generate a random 12-word seed phrase:\n'
  68. ' $ mmgen-tool -r0 mn_rand128\n\n'
  69. ' Same as above, but get additional entropy from user:\n'
  70. ' $ mmgen-tool mn_rand128\n\n'
  71. ' Encode bytes from a file to base 58:\n'
  72. ' $ mmgen-tool bytestob58 /etc/timezone pad=20\n\n'
  73. ' Reverse a hex string:\n'
  74. ' $ mmgen-tool hexreverse "deadbeefcafe"\n\n'
  75. ' Same as above, but use a pipe:\n'
  76. ' $ echo "deadbeefcafe" | mmgen-tool hexreverse -')
  77. if not cmd:
  78. Msg(m1)
  79. for bc in MMGenToolCmds.classes.values():
  80. cls_info = bc.__doc__.strip().split('\n')[0]
  81. Msg(' {}{}\n'.format(cls_info[0].upper(),cls_info[1:]))
  82. max_w = max(map(len,bc.user_commands))
  83. for cmd in sorted(bc.user_commands):
  84. Msg(' {:{w}} {}'.format(cmd,_create_call_sig(cmd),w=max_w))
  85. Msg('')
  86. Msg(m2)
  87. elif cmd in MMGenToolCmds:
  88. msg('{}'.format(capfirst(MMGenToolCmds[cmd].__doc__.strip())))
  89. msg('USAGE: {} {} {}'.format(g.prog_name,cmd,_create_call_sig(cmd)))
  90. else:
  91. die(1,"'{}': no such tool command".format(cmd))
  92. sys.exit(exit_val)
  93. def _process_args(cmd,cmd_args):
  94. c_args,c_kwargs,flag = _create_call_sig(cmd,parsed=True)
  95. have_stdin_input = False
  96. if flag != 'VAR_ARGS':
  97. if len(cmd_args) < len(c_args):
  98. m1 = 'Command requires exactly {} non-keyword argument{}'
  99. msg(m1.format(len(c_args),suf(c_args)))
  100. _usage(cmd)
  101. u_args = cmd_args[:len(c_args)]
  102. # If we're reading from a pipe, replace '-' with output of previous command
  103. if flag == 'STDIN_OK' and u_args and u_args[0] == '-':
  104. if sys.stdin.isatty():
  105. raise BadFilename("Standard input is a TTY. Can't use '-' as a filename")
  106. else:
  107. max_dlen_spec = '10kB' # limit input to 10KB for now
  108. max_dlen = MMGenToolCmdUtil().bytespec(max_dlen_spec)
  109. u_args[0] = os.read(0,max_dlen)
  110. have_stdin_input = True
  111. if len(u_args[0]) >= max_dlen:
  112. die(2,'Maximum data input for this command is {}'.format(max_dlen_spec))
  113. if not u_args[0]:
  114. die(2,'{}: ERROR: no output from previous command in pipe'.format(cmd))
  115. u_nkwargs = len(cmd_args) - len(c_args)
  116. u_kwargs = {}
  117. if flag == 'VAR_ARGS':
  118. t = [a.split('=',1) for a in cmd_args if '=' in a]
  119. tk = [a[0] for a in t]
  120. tk_bad = [a for a in tk if a not in c_kwargs]
  121. if set(tk_bad) != set(tk[:len(tk_bad)]): # permit non-kw args to contain '='
  122. die(1,"'{}': illegal keyword argument".format(tk_bad[-1]))
  123. u_kwargs = dict(t[len(tk_bad):])
  124. u_args = cmd_args[:-len(u_kwargs) or None]
  125. elif u_nkwargs > 0:
  126. u_kwargs = dict([a.split('=',1) for a in cmd_args[len(c_args):] if '=' in a])
  127. if len(u_kwargs) != u_nkwargs:
  128. msg('Command requires exactly {} non-keyword argument{}'.format(len(c_args),suf(c_args)))
  129. _usage(cmd)
  130. if len(u_kwargs) > len(c_kwargs):
  131. msg('Command accepts no more than {} keyword argument{}'.format(len(c_kwargs),suf(c_kwargs)))
  132. _usage(cmd)
  133. for k in u_kwargs:
  134. if k not in c_kwargs:
  135. msg("'{}': invalid keyword argument".format(k))
  136. _usage(cmd)
  137. def conv_type(arg,arg_name,arg_type):
  138. if arg_type == 'bytes' and type(arg) != bytes:
  139. die(1,"'Binary input data must be supplied via STDIN")
  140. if have_stdin_input and arg_type == 'str' and isinstance(arg,bytes):
  141. arg = arg.decode()
  142. if arg[-len(NL):] == NL: # rstrip one newline
  143. arg = arg[:-len(NL)]
  144. if arg_type == 'bool':
  145. if arg.lower() in ('true','yes','1','on'): arg = True
  146. elif arg.lower() in ('false','no','0','off'): arg = False
  147. else:
  148. msg("'{}': invalid boolean value for keyword argument".format(arg))
  149. _usage(cmd)
  150. try:
  151. return __builtins__[arg_type](arg)
  152. except:
  153. die(1,"'{}': Invalid argument for argument {} ('{}' required)".format(arg,arg_name,arg_type))
  154. if flag == 'VAR_ARGS':
  155. args = [conv_type(u_args[i],c_args[0][0],c_args[0][1]) for i in range(len(u_args))]
  156. else:
  157. args = [conv_type(u_args[i],c_args[i][0],c_args[i][1]) for i in range(len(c_args))]
  158. kwargs = {k:conv_type(u_kwargs[k],k,type(c_kwargs[k]).__name__) for k in u_kwargs}
  159. return args,kwargs
  160. def _process_result(ret,pager=False,print_result=False):
  161. """
  162. Convert result to something suitable for output to screen and return it.
  163. If result is bytes and not convertible to utf8, output as binary using os.write().
  164. If 'print_result' is True, send the converted result directly to screen or
  165. pager instead of returning it.
  166. """
  167. def triage_result(o):
  168. return o if not print_result else do_pager(o) if pager else Msg(o)
  169. if ret == True:
  170. return True
  171. elif ret in (False,None):
  172. ydie(1,"tool command returned '{}'".format(ret))
  173. elif isinstance(ret,str):
  174. return triage_result(ret)
  175. elif isinstance(ret,int):
  176. return triage_result(str(ret))
  177. elif isinstance(ret,tuple):
  178. return triage_result('\n'.join([r.decode() if isinstance(r,bytes) else r for r in ret]))
  179. elif isinstance(ret,bytes):
  180. try:
  181. o = ret.decode()
  182. return o if not print_result else do_pager(o) if pager else Msg(o)
  183. except:
  184. # don't add NL to binary data if it can't be converted to utf8
  185. return ret if not print_result else os.write(1,ret)
  186. else:
  187. ydie(1,"tool.py: can't handle return value of type '{}'".format(type(ret).__name__))
  188. from .obj import MMGenAddrType
  189. def conv_cls_bip39():
  190. from .bip39 import bip39
  191. return bip39
  192. dfl_mnemonic_fmt = 'mmgen'
  193. mnemonic_fmts = {
  194. 'mmgen': { 'fmt': 'words', 'conv_cls': lambda: baseconv },
  195. 'bip39': { 'fmt': 'bip39', 'conv_cls': conv_cls_bip39 },
  196. 'xmrseed': { 'fmt': 'xmrseed','conv_cls': lambda: baseconv },
  197. }
  198. mn_opts_disp = "(valid options: '{}')".format("', '".join(mnemonic_fmts))
  199. class MMGenToolCmdMeta(type):
  200. classes = {}
  201. methods = {}
  202. def __new__(mcls,name,bases,namespace):
  203. methods = {k:v for k,v in namespace.items() if k[0] != '_' and callable(v) and v.__doc__}
  204. if g.test_suite:
  205. if name in mcls.classes:
  206. raise ValueError(f'Class {name!r} already defined!')
  207. for m in methods:
  208. if m in mcls.methods:
  209. raise ValueError(f'Method {m!r} already defined!')
  210. if not getattr(m,'__doc__',None):
  211. raise ValueError(f'Method {m!r} has no doc string!')
  212. cls = super().__new__(mcls,name,bases,namespace)
  213. if bases and name != 'tool_api':
  214. mcls.classes[name] = cls
  215. mcls.methods.update(methods)
  216. return cls
  217. def __iter__(cls):
  218. return cls.methods.__iter__()
  219. def __getitem__(cls,val):
  220. return cls.methods.__getitem__(val)
  221. def __contains__(cls,val):
  222. return cls.methods.__contains__(val)
  223. def classname(cls,cmd_name):
  224. return cls.methods[cmd_name].__qualname__.split('.')[0]
  225. def call(cls,cmd_name,*args,**kwargs):
  226. return getattr(cls.classes[cls.classname(cmd_name)](),cmd_name)(*args,**kwargs)
  227. @property
  228. def user_commands(cls):
  229. return {k:v for k,v in cls.__dict__.items() if k in cls.methods}
  230. class MMGenToolCmds(metaclass=MMGenToolCmdMeta):
  231. def __init__(self,proto=None):
  232. from .protocol import init_proto_from_opts
  233. self.proto = proto or init_proto_from_opts()
  234. if g.token:
  235. self.proto.tokensym = g.token.upper()
  236. def init_generators(self,arg=None):
  237. global at,kg,ag
  238. at = MMGenAddrType(
  239. proto = self.proto,
  240. id_str = getattr(opt,'type',None) or self.proto.dfl_mmtype )
  241. if arg != 'at':
  242. kg = KeyGenerator(self.proto,at)
  243. ag = AddrGenerator(self.proto,at)
  244. class MMGenToolCmdMisc(MMGenToolCmds):
  245. "miscellaneous commands"
  246. def help(self,command_name=''):
  247. "display usage information for a single command or all commands"
  248. _usage(command_name,exit_val=0)
  249. usage = help
  250. class MMGenToolCmdUtil(MMGenToolCmds):
  251. "general string conversion and hashing utilities"
  252. def bytespec(self,dd_style_byte_specifier:str):
  253. "convert a byte specifier such as '1GB' into an integer"
  254. return parse_bytespec(dd_style_byte_specifier)
  255. def randhex(self,nbytes='32'):
  256. "print 'n' bytes (default 32) of random data in hex format"
  257. return get_random(int(nbytes)).hex()
  258. def hexreverse(self,hexstr:'sstr'):
  259. "reverse bytes of a hexadecimal string"
  260. return bytes.fromhex(hexstr.strip())[::-1].hex()
  261. def hexlify(self,infile:str):
  262. "convert bytes in file to hexadecimal (use '-' for stdin)"
  263. data = get_data_from_file(infile,dash=True,quiet=True,binary=True)
  264. return data.hex()
  265. def unhexlify(self,hexstr:'sstr'):
  266. "convert hexadecimal value to bytes (warning: outputs binary data)"
  267. return bytes.fromhex(hexstr)
  268. def hexdump(self,infile:str,cols=8,line_nums='hex'):
  269. "create hexdump of data from file (use '-' for stdin)"
  270. data = get_data_from_file(infile,dash=True,quiet=True,binary=True)
  271. return pretty_hexdump(data,cols=cols,line_nums=line_nums).rstrip()
  272. def unhexdump(self,infile:str):
  273. "decode hexdump from file (use '-' for stdin) (warning: outputs binary data)"
  274. if g.platform == 'win':
  275. import msvcrt
  276. msvcrt.setmode(sys.stdout.fileno(),os.O_BINARY)
  277. hexdata = get_data_from_file(infile,dash=True,quiet=True)
  278. return decode_pretty_hexdump(hexdata)
  279. def hash160(self,hexstr:'sstr'):
  280. "compute ripemd160(sha256(data)) (convert hex pubkey to hex addr)"
  281. return hash160(hexstr)
  282. def hash256(self,string_or_bytes:str,file_input=False,hex_input=False): # TODO: handle stdin
  283. "compute sha256(sha256(data)) (double sha256)"
  284. from hashlib import sha256
  285. if file_input: b = get_data_from_file(string_or_bytes,binary=True)
  286. elif hex_input: b = decode_pretty_hexdump(string_or_bytes)
  287. else: b = string_or_bytes
  288. return sha256(sha256(b.encode()).digest()).hexdigest()
  289. def id6(self,infile:str):
  290. "generate 6-character MMGen ID for a file (use '-' for stdin)"
  291. return make_chksum_6(
  292. get_data_from_file(infile,dash=True,quiet=True,binary=True))
  293. def str2id6(self,string:'sstr'): # retain ignoring of space for backwards compat
  294. "generate 6-character MMGen ID for a string, ignoring spaces"
  295. return make_chksum_6(''.join(string.split()))
  296. def id8(self,infile:str):
  297. "generate 8-character MMGen ID for a file (use '-' for stdin)"
  298. return make_chksum_8(
  299. get_data_from_file(infile,dash=True,quiet=True,binary=True))
  300. def randb58(self,nbytes=32,pad=0):
  301. "generate random data (default: 32 bytes) and convert it to base 58"
  302. return baseconv.frombytes(get_random(nbytes),'b58',pad=pad,tostr=True)
  303. def bytestob58(self,infile:str,pad=0):
  304. "convert bytes to base 58 (supply data via STDIN)"
  305. data = get_data_from_file(infile,dash=True,quiet=True,binary=True)
  306. return baseconv.frombytes(data,'b58',pad=pad,tostr=True)
  307. def b58tobytes(self,b58num:'sstr',pad=0):
  308. "convert a base 58 number to bytes (warning: outputs binary data)"
  309. return baseconv.tobytes(b58num,'b58',pad=pad)
  310. def hextob58(self,hexstr:'sstr',pad=0):
  311. "convert a hexadecimal number to base 58"
  312. return baseconv.fromhex(hexstr,'b58',pad=pad,tostr=True)
  313. def b58tohex(self,b58num:'sstr',pad=0):
  314. "convert a base 58 number to hexadecimal"
  315. return baseconv.tohex(b58num,'b58',pad=pad)
  316. def hextob58chk(self,hexstr:'sstr'):
  317. "convert a hexadecimal number to base58-check encoding"
  318. from .protocol import _b58chk_encode
  319. return _b58chk_encode(bytes.fromhex(hexstr))
  320. def b58chktohex(self,b58chk_num:'sstr'):
  321. "convert a base58-check encoded number to hexadecimal"
  322. from .protocol import _b58chk_decode
  323. return _b58chk_decode(b58chk_num).hex()
  324. def hextob32(self,hexstr:'sstr',pad=0):
  325. "convert a hexadecimal number to MMGen's flavor of base 32"
  326. return baseconv.fromhex(hexstr,'b32',pad,tostr=True)
  327. def b32tohex(self,b32num:'sstr',pad=0):
  328. "convert an MMGen-flavor base 32 number to hexadecimal"
  329. return baseconv.tohex(b32num.upper(),'b32',pad)
  330. def hextob6d(self,hexstr:'sstr',pad=0,add_spaces=True):
  331. "convert a hexadecimal number to die roll base6 (base6d)"
  332. ret = baseconv.fromhex(hexstr,'b6d',pad,tostr=True)
  333. return block_format(ret,gw=5,cols=None).strip() if add_spaces else ret
  334. def b6dtohex(self,b6d_num:'sstr',pad=0):
  335. "convert a die roll base6 (base6d) number to hexadecimal"
  336. return baseconv.tohex(remove_whitespace(b6d_num),'b6d',pad)
  337. class MMGenToolCmdCoin(MMGenToolCmds):
  338. """
  339. cryptocoin key/address utilities
  340. May require use of the '--coin', '--type' and/or '--testnet' options
  341. Examples:
  342. mmgen-tool --coin=ltc --type=bech32 wif2addr <wif key>
  343. mmgen-tool --coin=zec --type=zcash_z randpair
  344. """
  345. def randwif(self):
  346. "generate a random private key in WIF format"
  347. self.init_generators('at')
  348. return PrivKey(
  349. self.proto,
  350. get_random(32),
  351. pubkey_type = at.pubkey_type,
  352. compressed = at.compressed ).wif
  353. def randpair(self):
  354. "generate a random private key/address pair"
  355. self.init_generators()
  356. privhex = PrivKey(
  357. self.proto,
  358. get_random(32),
  359. pubkey_type = at.pubkey_type,
  360. compressed = at.compressed )
  361. addr = ag.to_addr(kg.to_pubhex(privhex))
  362. return (privhex.wif,addr)
  363. def wif2hex(self,wifkey:'sstr'):
  364. "convert a private key from WIF to hex format"
  365. return PrivKey(
  366. self.proto,
  367. wif = wifkey )
  368. def hex2wif(self,privhex:'sstr'):
  369. "convert a private key from hex to WIF format"
  370. self.init_generators('at')
  371. return PrivKey(
  372. self.proto,
  373. bytes.fromhex(privhex),
  374. pubkey_type = at.pubkey_type,
  375. compressed = at.compressed ).wif
  376. def wif2addr(self,wifkey:'sstr'):
  377. "generate a coin address from a key in WIF format"
  378. self.init_generators()
  379. privhex = PrivKey(
  380. self.proto,
  381. wif = wifkey )
  382. addr = ag.to_addr(kg.to_pubhex(privhex))
  383. return addr
  384. def wif2redeem_script(self,wifkey:'sstr'): # new
  385. "convert a WIF private key to a Segwit P2SH-P2WPKH redeem script"
  386. assert opt.type == 'segwit','This command is meaningful only for --type=segwit'
  387. self.init_generators()
  388. privhex = PrivKey(
  389. self.proto,
  390. wif = wifkey )
  391. return ag.to_segwit_redeem_script(kg.to_pubhex(privhex))
  392. def wif2segwit_pair(self,wifkey:'sstr'):
  393. "generate both a Segwit P2SH-P2WPKH redeem script and address from WIF"
  394. assert opt.type == 'segwit','This command is meaningful only for --type=segwit'
  395. self.init_generators()
  396. pubhex = kg.to_pubhex(PrivKey(
  397. self.proto,
  398. wif = wifkey ))
  399. addr = ag.to_addr(pubhex)
  400. rs = ag.to_segwit_redeem_script(pubhex)
  401. return (rs,addr)
  402. def privhex2addr(self,privhex:'sstr',output_pubhex=False):
  403. "generate coin address from raw private key data in hexadecimal format"
  404. self.init_generators()
  405. pk = PrivKey(
  406. self.proto,
  407. bytes.fromhex(privhex),
  408. compressed = at.compressed,
  409. pubkey_type = at.pubkey_type )
  410. ph = kg.to_pubhex(pk)
  411. return ph if output_pubhex else ag.to_addr(ph)
  412. def privhex2pubhex(self,privhex:'sstr'): # new
  413. "generate a hex public key from a hex private key"
  414. return self.privhex2addr(privhex,output_pubhex=True)
  415. def pubhex2addr(self,pubkeyhex:'sstr'):
  416. "convert a hex pubkey to an address"
  417. if opt.type == 'segwit':
  418. return self.proto.pubhex2segwitaddr(pubkeyhex)
  419. else:
  420. return self.pubhash2addr(hash160(pubkeyhex))
  421. def pubhex2redeem_script(self,pubkeyhex:'sstr'): # new
  422. "convert a hex pubkey to a Segwit P2SH-P2WPKH redeem script"
  423. assert opt.type == 'segwit','This command is meaningful only for --type=segwit'
  424. return self.proto.pubhex2redeem_script(pubkeyhex)
  425. def redeem_script2addr(self,redeem_scripthex:'sstr'): # new
  426. "convert a Segwit P2SH-P2WPKH redeem script to an address"
  427. assert opt.type == 'segwit','This command is meaningful only for --type=segwit'
  428. assert redeem_scripthex[:4] == '0014','{!r}: invalid redeem script'.format(redeem_scripthex)
  429. assert len(redeem_scripthex) == 44,'{} bytes: invalid redeem script length'.format(len(redeem_scripthex)//2)
  430. return self.pubhash2addr(hash160(redeem_scripthex))
  431. def pubhash2addr(self,pubhashhex:'sstr'):
  432. "convert public key hash to address"
  433. if opt.type == 'bech32':
  434. return self.proto.pubhash2bech32addr(pubhashhex)
  435. else:
  436. self.init_generators('at')
  437. return self.proto.pubhash2addr(pubhashhex,at.addr_fmt=='p2sh')
  438. def addr2pubhash(self,addr:'sstr'):
  439. "convert coin address to public key hash"
  440. from .tx import addr2pubhash
  441. return addr2pubhash(self.proto,CoinAddr(self.proto,addr))
  442. def addr2scriptpubkey(self,addr:'sstr'):
  443. "convert coin address to scriptPubKey"
  444. from .tx import addr2scriptPubKey
  445. return addr2scriptPubKey(self.proto,CoinAddr(self.proto,addr))
  446. def scriptpubkey2addr(self,hexstr:'sstr'):
  447. "convert scriptPubKey to coin address"
  448. from .tx import scriptPubKey2addr
  449. return scriptPubKey2addr(self.proto,hexstr)[0]
  450. class MMGenToolCmdMnemonic(MMGenToolCmds):
  451. """
  452. seed phrase utilities (valid formats: 'mmgen' (default), 'bip39', 'xmrseed')
  453. IMPORTANT NOTE: MMGen's default seed phrase format uses the Electrum
  454. wordlist, however seed phrases are computed using a different algorithm
  455. and are NOT Electrum-compatible!
  456. BIP39 support is fully compatible with the standard, allowing users to
  457. import and export seed entropy from BIP39-compatible wallets. However,
  458. users should be aware that BIP39 support does not imply BIP32 support!
  459. MMGen uses its own key derivation scheme differing from the one described
  460. by the BIP32 protocol.
  461. For Monero ('xmrseed') seed phrases, input data is reduced to a spendkey
  462. before conversion so that a canonical seed phrase is produced. This is
  463. required because Monero seeds, unlike ordinary wallet seeds, are tied
  464. to a concrete key/address pair. To manually generate a Monero spendkey,
  465. use the 'hex2wif' command.
  466. """
  467. @staticmethod
  468. def _xmr_reduce(bytestr):
  469. from .protocol import init_proto
  470. proto = init_proto('xmr')
  471. if len(bytestr) != proto.privkey_len:
  472. m = '{!r}: invalid bit length for Monero private key (must be {})'
  473. die(1,m.format(len(bytestr*8),proto.privkey_len*8))
  474. return proto.preprocess_key(bytestr,None)
  475. def _do_random_mn(self,nbytes:int,fmt:str):
  476. assert nbytes in (16,24,32), 'nbytes must be 16, 24 or 32'
  477. randbytes = get_random(nbytes)
  478. if fmt == 'xmrseed':
  479. randbytes = self._xmr_reduce(randbytes)
  480. if opt.verbose:
  481. msg('Seed: {}'.format(randbytes.hex()))
  482. return self.hex2mn(randbytes.hex(),fmt=fmt)
  483. def mn_rand128(self, fmt:mn_opts_disp = dfl_mnemonic_fmt ):
  484. "generate random 128-bit mnemonic seed phrase"
  485. return self._do_random_mn(16,fmt)
  486. def mn_rand192(self, fmt:mn_opts_disp = dfl_mnemonic_fmt ):
  487. "generate random 192-bit mnemonic seed phrase"
  488. return self._do_random_mn(24,fmt)
  489. def mn_rand256(self, fmt:mn_opts_disp = dfl_mnemonic_fmt ):
  490. "generate random 256-bit mnemonic seed phrase"
  491. return self._do_random_mn(32,fmt)
  492. def _get_mnemonic_fmt(self,fmt):
  493. if fmt not in mnemonic_fmts:
  494. m = '{!r}: invalid format (valid options: {})'
  495. die(1,m.format(fmt,', '.join(mnemonic_fmts)))
  496. return mnemonic_fmts[fmt]['fmt']
  497. def hex2mn( self, hexstr:'sstr', fmt:mn_opts_disp = dfl_mnemonic_fmt ):
  498. "convert a 16, 24 or 32-byte hexadecimal number to a mnemonic seed phrase"
  499. if fmt == 'bip39':
  500. from .bip39 import bip39
  501. return ' '.join(bip39.fromhex(hexstr,fmt))
  502. else:
  503. bytestr = bytes.fromhex(hexstr)
  504. if fmt == 'xmrseed':
  505. bytestr = self._xmr_reduce(bytestr)
  506. return baseconv.frombytes(bytestr,fmt,'seed',tostr=True)
  507. def mn2hex( self, seed_mnemonic:'sstr', fmt:mn_opts_disp = dfl_mnemonic_fmt ):
  508. "convert a mnemonic seed phrase to a hexadecimal number"
  509. if fmt == 'bip39':
  510. from .bip39 import bip39
  511. return bip39.tohex(seed_mnemonic.split(),fmt)
  512. else:
  513. return baseconv.tohex(seed_mnemonic.split(),fmt,'seed')
  514. def mn2hex_interactive( self, fmt:mn_opts_disp=dfl_mnemonic_fmt, mn_len=24, print_mn=False ):
  515. "convert an interactively supplied mnemonic seed phrase to a hexadecimal number"
  516. from .mn_entry import mn_entry
  517. mn = mn_entry(fmt).get_mnemonic_from_user(25 if fmt == 'xmrseed' else mn_len,validate=False)
  518. if print_mn:
  519. msg(mn)
  520. return self.mn2hex(seed_mnemonic=mn,fmt=fmt)
  521. def mn_stats(self, fmt:mn_opts_disp = dfl_mnemonic_fmt ):
  522. "show stats for mnemonic wordlist"
  523. conv_cls = mnemonic_fmts[fmt]['conv_cls']()
  524. return conv_cls.check_wordlist(fmt)
  525. def mn_printlist( self, fmt:mn_opts_disp = dfl_mnemonic_fmt, enum=False, pager=False ):
  526. "print mnemonic wordlist"
  527. conv_cls = mnemonic_fmts[fmt]['conv_cls']()
  528. ret = conv_cls.get_wordlist(fmt)
  529. if enum:
  530. ret = ['{:>4} {}'.format(n,e) for n,e in enumerate(ret)]
  531. return '\n'.join(ret)
  532. class MMGenToolCmdFile(MMGenToolCmds):
  533. "utilities for viewing/checking MMGen address and transaction files"
  534. def _file_chksum(self,mmgen_addrfile,objname):
  535. opt.yes = True
  536. opt.quiet = True
  537. from .addr import AddrList,KeyAddrList,PasswordList
  538. ret = locals()[objname](self.proto,mmgen_addrfile)
  539. if opt.verbose:
  540. if ret.al_id.mmtype.name == 'password':
  541. fs = 'Passwd fmt: {}\nPasswd len: {}\nID string: {}'
  542. msg(fs.format(capfirst(ret.pw_info[ret.pw_fmt].desc),ret.pw_len,ret.pw_id_str))
  543. else:
  544. msg(f'Base coin: {ret.base_coin} {capfirst(ret.network)}')
  545. msg('MMType: {}'.format(capfirst(ret.al_id.mmtype.name)))
  546. msg('List length: {}'.format(len(ret.data)))
  547. return ret.chksum
  548. def addrfile_chksum(self,mmgen_addrfile:str):
  549. "compute checksum for MMGen address file"
  550. return self._file_chksum(mmgen_addrfile,'AddrList')
  551. def keyaddrfile_chksum(self,mmgen_keyaddrfile:str):
  552. "compute checksum for MMGen key-address file"
  553. return self._file_chksum(mmgen_keyaddrfile,'KeyAddrList')
  554. def passwdfile_chksum(self,mmgen_passwdfile:str):
  555. "compute checksum for MMGen password file"
  556. return self._file_chksum(mmgen_passwdfile,'PasswordList')
  557. async def txview( varargs_call_sig = { # hack to allow for multiple filenames
  558. 'args': (
  559. 'mmgen_tx_file(s)',
  560. 'pager',
  561. 'terse',
  562. 'sort',
  563. 'filesort' ),
  564. 'dfls': ( False, False, 'addr', 'mtime' ),
  565. 'annots': {
  566. 'mmgen_tx_file(s)': str,
  567. 'sort': '(valid options: addr,raw)',
  568. 'filesort': '(valid options: mtime,ctime,atime)'
  569. } },
  570. *infiles,**kwargs):
  571. "show raw/signed MMGen transaction in human-readable form"
  572. terse = bool(kwargs.get('terse'))
  573. tx_sort = kwargs.get('sort') or 'addr'
  574. file_sort = kwargs.get('filesort') or 'mtime'
  575. from .filename import MMGenFileList
  576. from .tx import MMGenTX
  577. flist = MMGenFileList(infiles,ftype=MMGenTX)
  578. flist.sort_by_age(key=file_sort) # in-place sort
  579. async def process_file(fn):
  580. if fn.endswith(MMGenTX.Signed.ext):
  581. tx = MMGenTX.Signed(
  582. filename = fn,
  583. quiet_open = True,
  584. tw = await MMGenTX.Signed.get_tracking_wallet(fn) )
  585. else:
  586. tx = MMGenTX.Unsigned(
  587. filename = fn,
  588. quiet_open = True )
  589. return tx.format_view(terse=terse,sort=tx_sort)
  590. return ('—'*77+'\n').join([await process_file(fn) for fn in flist.names()]).rstrip()
  591. class MMGenToolCmdFileCrypt(MMGenToolCmds):
  592. """
  593. file encryption and decryption
  594. MMGen encryption suite:
  595. * Key: Scrypt (user-configurable hash parameters, 32-byte salt)
  596. * Enc: AES256_CTR, 16-byte rand IV, sha256 hash + 32-byte nonce + data
  597. * The encrypted file is indistinguishable from random data
  598. """
  599. def encrypt(self,infile:str,outfile='',hash_preset=''):
  600. "encrypt a file"
  601. data = get_data_from_file(infile,'data for encryption',binary=True)
  602. enc_d = mmgen_encrypt(data,'user data',hash_preset)
  603. if not outfile:
  604. outfile = '{}.{}'.format(os.path.basename(infile),g.mmenc_ext)
  605. write_data_to_file(outfile,enc_d,'encrypted data',binary=True)
  606. return True
  607. def decrypt(self,infile:str,outfile='',hash_preset=''):
  608. "decrypt a file"
  609. enc_d = get_data_from_file(infile,'encrypted data',binary=True)
  610. while True:
  611. dec_d = mmgen_decrypt(enc_d,'user data',hash_preset)
  612. if dec_d: break
  613. msg('Trying again...')
  614. if not outfile:
  615. o = os.path.basename(infile)
  616. outfile = remove_extension(o,g.mmenc_ext)
  617. if outfile == o: outfile += '.dec'
  618. write_data_to_file(outfile,dec_d,'decrypted data',binary=True)
  619. return True
  620. class MMGenToolCmdFileUtil(MMGenToolCmds):
  621. "file utilities"
  622. def find_incog_data(self,filename:str,incog_id:str,keep_searching=False):
  623. "Use an Incog ID to find hidden incognito wallet data"
  624. ivsize,bsize,mod = g.aesctr_iv_len,4096,4096*8
  625. n,carry = 0,b' '*ivsize
  626. flgs = os.O_RDONLY|os.O_BINARY if g.platform == 'win' else os.O_RDONLY
  627. f = os.open(filename,flgs)
  628. for ch in incog_id:
  629. if ch not in '0123456789ABCDEF':
  630. die(2,"'{}': invalid Incog ID".format(incog_id))
  631. while True:
  632. d = os.read(f,bsize)
  633. if not d: break
  634. d = carry + d
  635. for i in range(bsize):
  636. if sha256(d[i:i+ivsize]).hexdigest()[:8].upper() == incog_id:
  637. if n+i < ivsize: continue
  638. msg('\rIncog data for ID {} found at offset {}'.format(incog_id,n+i-ivsize))
  639. if not keep_searching: sys.exit(0)
  640. carry = d[len(d)-ivsize:]
  641. n += bsize
  642. if not n % mod:
  643. msg_r('\rSearched: {} bytes'.format(n))
  644. msg('')
  645. os.close(f)
  646. return True
  647. def rand2file(self,outfile:str,nbytes:str,threads=4,silent=False):
  648. "write 'n' bytes of random data to specified file"
  649. from threading import Thread
  650. from queue import Queue
  651. from cryptography.hazmat.primitives.ciphers import Cipher,algorithms,modes
  652. from cryptography.hazmat.backends import default_backend
  653. def encrypt_worker(wid):
  654. ctr_init_val = os.urandom(g.aesctr_iv_len)
  655. c = Cipher(algorithms.AES(key),modes.CTR(ctr_init_val),backend=default_backend())
  656. encryptor = c.encryptor()
  657. while True:
  658. q2.put(encryptor.update(q1.get()))
  659. q1.task_done()
  660. def output_worker():
  661. while True:
  662. f.write(q2.get())
  663. q2.task_done()
  664. nbytes = parse_bytespec(nbytes)
  665. if opt.outdir:
  666. outfile = make_full_path(opt.outdir,outfile)
  667. f = open(outfile,'wb')
  668. key = get_random(32)
  669. q1,q2 = Queue(),Queue()
  670. for i in range(max(1,threads-2)):
  671. t = Thread(target=encrypt_worker,args=[i])
  672. t.daemon = True
  673. t.start()
  674. t = Thread(target=output_worker)
  675. t.daemon = True
  676. t.start()
  677. blk_size = 1024 * 1024
  678. for i in range(nbytes // blk_size):
  679. if not i % 4:
  680. msg_r('\rRead: {} bytes'.format(i * blk_size))
  681. q1.put(os.urandom(blk_size))
  682. if nbytes % blk_size:
  683. q1.put(os.urandom(nbytes % blk_size))
  684. q1.join()
  685. q2.join()
  686. f.close()
  687. fsize = os.stat(outfile).st_size
  688. if fsize != nbytes:
  689. die(3,'{}: incorrect random file size (should be {})'.format(fsize,nbytes))
  690. if not silent:
  691. msg('\rRead: {} bytes'.format(nbytes))
  692. qmsg("\r{} byte{} of random data written to file '{}'".format(nbytes,suf(nbytes),outfile))
  693. return True
  694. class MMGenToolCmdWallet(MMGenToolCmds):
  695. "key, address or subseed generation from an MMGen wallet"
  696. def get_subseed(self,subseed_idx:str,wallet=''):
  697. "get the Seed ID of a single subseed by Subseed Index for default or specified wallet"
  698. opt.quiet = True
  699. sf = get_seed_file([wallet] if wallet else [],1)
  700. from .wallet import Wallet
  701. return Wallet(sf).seed.subseed(subseed_idx).sid
  702. def get_subseed_by_seed_id(self,seed_id:str,wallet='',last_idx=g.subseeds):
  703. "get the Subseed Index of a single subseed by Seed ID for default or specified wallet"
  704. opt.quiet = True
  705. sf = get_seed_file([wallet] if wallet else [],1)
  706. from .wallet import Wallet
  707. ret = Wallet(sf).seed.subseed_by_seed_id(seed_id,last_idx)
  708. return ret.ss_idx if ret else None
  709. def list_subseeds(self,subseed_idx_range:str,wallet=''):
  710. "list a range of subseed Seed IDs for default or specified wallet"
  711. opt.quiet = True
  712. sf = get_seed_file([wallet] if wallet else [],1)
  713. from .wallet import Wallet
  714. return Wallet(sf).seed.subseeds.format(*SubSeedIdxRange(subseed_idx_range))
  715. def list_shares(self,
  716. share_count:int,
  717. id_str='default',
  718. master_share:"(min:1, max:{}, 0=no master share)".format(MasterShareIdx.max_val)=0,
  719. wallet=''):
  720. "list the Seed IDs of the shares resulting from a split of default or specified wallet"
  721. opt.quiet = True
  722. sf = get_seed_file([wallet] if wallet else [],1)
  723. from .wallet import Wallet
  724. return Wallet(sf).seed.split(share_count,id_str,master_share).format()
  725. def gen_key(self,mmgen_addr:str,wallet=''):
  726. "generate a single MMGen WIF key from default or specified wallet"
  727. return self.gen_addr(mmgen_addr,wallet,target='wif')
  728. def gen_addr(self,mmgen_addr:str,wallet='',target='addr'):
  729. "generate a single MMGen address from default or specified wallet"
  730. addr = MMGenID(self.proto,mmgen_addr)
  731. opt.quiet = True
  732. sf = get_seed_file([wallet] if wallet else [],1)
  733. from .wallet import Wallet
  734. ss = Wallet(sf)
  735. if ss.seed.sid != addr.sid:
  736. m = 'Seed ID of requested address ({}) does not match wallet ({})'
  737. die(1,m.format(addr.sid,ss.seed.sid))
  738. al = AddrList(
  739. proto = self.proto,
  740. seed = ss.seed,
  741. addr_idxs = AddrIdxList(str(addr.idx)),
  742. mmtype = addr.mmtype )
  743. d = al.data[0]
  744. ret = d.sec.wif if target=='wif' else d.addr
  745. return ret
  746. from .tw import TwAddrList,TwUnspentOutputs
  747. class MMGenToolCmdRPC(MMGenToolCmds):
  748. "tracking wallet commands using the JSON-RPC interface"
  749. async def getbalance(self,minconf=1,quiet=False,pager=False):
  750. "list confirmed/unconfirmed, spendable/unspendable balances in tracking wallet"
  751. from .tw import TwGetBalance
  752. return (await TwGetBalance(self.proto,minconf,quiet)).format()
  753. async def listaddress(self,
  754. mmgen_addr:str,
  755. minconf = 1,
  756. pager = False,
  757. showempty = True,
  758. showbtcaddr = True,
  759. age_fmt: _options_annot_str(TwAddrList.age_fmts) = 'confs',
  760. ):
  761. "list the specified MMGen address and its balance"
  762. return await self.listaddresses( mmgen_addrs = mmgen_addr,
  763. minconf = minconf,
  764. pager = pager,
  765. showempty = showempty,
  766. showbtcaddrs = showbtcaddr,
  767. age_fmt = age_fmt,
  768. )
  769. async def listaddresses( self,
  770. mmgen_addrs:'(range or list)' = '',
  771. minconf = 1,
  772. showempty = False,
  773. pager = False,
  774. showbtcaddrs = True,
  775. all_labels = False,
  776. sort:'(valid options: reverse,age)' = '',
  777. age_fmt: _options_annot_str(TwAddrList.age_fmts) = 'confs',
  778. ):
  779. "list MMGen addresses and their balances"
  780. show_age = bool(age_fmt)
  781. if sort:
  782. sort = set(sort.split(','))
  783. sort_params = {'reverse','age'}
  784. if not sort.issubset(sort_params):
  785. die(1,"The sort option takes the following parameters: '{}'".format("','".join(sort_params)))
  786. usr_addr_list = []
  787. if mmgen_addrs:
  788. a = mmgen_addrs.rsplit(':',1)
  789. if len(a) != 2:
  790. m = "'{}': invalid address list argument (must be in form <seed ID>:[<type>:]<idx list>)"
  791. die(1,m.format(mmgen_addrs))
  792. usr_addr_list = [MMGenID(self.proto,f'{a[0]}:{i}') for i in AddrIdxList(a[1])]
  793. al = await TwAddrList(self.proto,usr_addr_list,minconf,showempty,showbtcaddrs,all_labels)
  794. if not al:
  795. die(0,('No tracked addresses with balances!','No tracked addresses!')[showempty])
  796. return await al.format(showbtcaddrs,sort,show_age,age_fmt or 'confs')
  797. async def twview( self,
  798. pager = False,
  799. reverse = False,
  800. wide = False,
  801. minconf = 1,
  802. sort = 'age',
  803. age_fmt: _options_annot_str(TwUnspentOutputs.age_fmts) = 'confs',
  804. show_mmid = True,
  805. wide_show_confs = True):
  806. "view tracking wallet"
  807. twuo = await TwUnspentOutputs(self.proto,minconf=minconf)
  808. await twuo.get_unspent_data(reverse_sort=reverse)
  809. twuo.age_fmt = age_fmt
  810. twuo.show_mmid = show_mmid
  811. if wide:
  812. ret = twuo.format_for_printing(color=True,show_confs=wide_show_confs)
  813. else:
  814. ret = twuo.format_for_display()
  815. del twuo.wallet
  816. return await ret
  817. async def add_label(self,mmgen_or_coin_addr:str,label:str):
  818. "add descriptive label for address in tracking wallet"
  819. from .tw import TrackingWallet
  820. await (await TrackingWallet(self.proto,mode='w')).add_label(mmgen_or_coin_addr,label,on_fail='raise')
  821. return True
  822. async def remove_label(self,mmgen_or_coin_addr:str):
  823. "remove descriptive label for address in tracking wallet"
  824. await self.add_label(mmgen_or_coin_addr,'')
  825. return True
  826. async def remove_address(self,mmgen_or_coin_addr:str):
  827. "remove an address from tracking wallet"
  828. from .tw import TrackingWallet
  829. ret = await (await TrackingWallet(self.proto,mode='w')).remove_address(mmgen_or_coin_addr) # returns None on failure
  830. if ret:
  831. msg("Address '{}' deleted from tracking wallet".format(ret))
  832. return ret
  833. class MMGenToolCmdMonero(MMGenToolCmds):
  834. """
  835. Monero wallet utilities
  836. Note that the use of these commands requires private data to be exposed on
  837. a network-connected machine in order to unlock the Monero wallets. This is
  838. a violation of good security practice.
  839. """
  840. _monero_chain_height = None
  841. monerod_args = []
  842. @property
  843. def monero_chain_height(self):
  844. if self._monero_chain_height == None:
  845. from .daemon import CoinDaemon
  846. port = CoinDaemon('xmr',test_suite=g.test_suite).rpc_port
  847. cmd = ['monerod','--rpc-bind-port={}'.format(port)] + self.monerod_args + ['status']
  848. from subprocess import run,PIPE,DEVNULL
  849. cp = run(cmd,stdout=PIPE,stderr=DEVNULL,check=True)
  850. import re
  851. m = re.search(r'Height: (\d+)/\d+ ',cp.stdout.decode())
  852. if not m:
  853. die(1,'Unable to connect to monerod!')
  854. self._monero_chain_height = int(m.group(1))
  855. msg('Chain height: {}'.format(self._monero_chain_height))
  856. return self._monero_chain_height
  857. def keyaddrlist2monerowallets( self,
  858. xmr_keyaddrfile:str,
  859. blockheight:'(default: current height)' = 0,
  860. addrs:'(integer range or list)' = ''):
  861. "create Monero wallets from a key-address list"
  862. return self.monero_wallet_ops( infile = xmr_keyaddrfile,
  863. op = 'create',
  864. blockheight = blockheight,
  865. addrs = addrs)
  866. def syncmonerowallets(self,xmr_keyaddrfile:str,addrs:'(integer range or list)'=''):
  867. "sync Monero wallets from a key-address list"
  868. return self.monero_wallet_ops(infile=xmr_keyaddrfile,op='sync',addrs=addrs)
  869. def monero_wallet_ops(self,infile:str,op:str,blockheight=0,addrs='',monerod_args=[]):
  870. if monerod_args:
  871. self.monerod_args = monerod_args
  872. async def create(n,d,fn,c,m):
  873. try: os.stat(fn)
  874. except: pass
  875. else:
  876. ymsg("Wallet '{}' already exists!".format(fn))
  877. return False
  878. gmsg(m)
  879. from .baseconv import baseconv
  880. ret = await c.call(
  881. 'restore_deterministic_wallet',
  882. filename = os.path.basename(fn),
  883. password = d.wallet_passwd,
  884. seed = baseconv.fromhex(d.sec,'xmrseed',tostr=True),
  885. restore_height = blockheight,
  886. language = 'English' )
  887. pp_msg(ret) if opt.debug else msg(' Address: {}'.format(ret['address']))
  888. return True
  889. async def sync(n,d,fn,c,m):
  890. try:
  891. os.stat(fn)
  892. except:
  893. ymsg("Wallet '{}' does not exist!".format(fn))
  894. return False
  895. chain_height = self.monero_chain_height
  896. gmsg(m)
  897. import time
  898. t_start = time.time()
  899. msg_r(' Opening wallet...')
  900. await c.call(
  901. 'open_wallet',
  902. filename=os.path.basename(fn),
  903. password=d.wallet_passwd )
  904. msg('done')
  905. msg_r(' Getting wallet height...')
  906. wallet_height = (await c.call('get_height'))['height']
  907. msg('\r Wallet height: {} '.format(wallet_height))
  908. behind = chain_height - wallet_height
  909. if behind > 1000:
  910. m = ' Wallet is {} blocks behind chain tip. Please be patient. Syncing...'
  911. msg_r(m.format(behind))
  912. ret = await c.call('refresh')
  913. if behind > 1000:
  914. msg('done')
  915. if ret['received_money']:
  916. msg(' Wallet has received funds')
  917. t_elapsed = int(time.time() - t_start)
  918. ret = await c.call('get_balance') # account_index=0, address_indices=[0,1]
  919. from .obj import XMRAmt
  920. bals[fn] = tuple([XMRAmt(ret[k],from_unit='min_coin_unit') for k in ('balance','unlocked_balance')])
  921. if opt.debug:
  922. pp_msg(ret)
  923. else:
  924. msg(' Balance: {} Unlocked balance: {}'.format(*[b.hl() for b in bals[fn]]))
  925. msg(' Wallet height: {}'.format((await c.call('get_height'))['height']))
  926. msg(' Sync time: {:02}:{:02}'.format(t_elapsed//60,t_elapsed%60))
  927. await c.call('close_wallet')
  928. return True
  929. async def process_wallets(op):
  930. opt.accept_defaults = opt.accept_defaults or op.accept_defaults
  931. from .protocol import init_proto
  932. proto = init_proto('xmr',network='mainnet')
  933. from .addr import AddrList
  934. al = KeyAddrList(proto,infile)
  935. data = [d for d in al.data if addrs == '' or d.idx in AddrIdxList(addrs)]
  936. dl = len(data)
  937. assert dl,"No addresses in addrfile within range '{}'".format(addrs)
  938. gmsg('\n{}ing {} wallet{}'.format(op.desc,dl,suf(dl)))
  939. from .daemon import MoneroWalletDaemon
  940. wd = MoneroWalletDaemon(opt.outdir or '.',test_suite=g.test_suite)
  941. wd.restart()
  942. from .rpc import MoneroWalletRPCClient
  943. c = MoneroWalletRPCClient(
  944. host = g.monero_wallet_rpc_host,
  945. port = wd.rpc_port,
  946. user = g.monero_wallet_rpc_user,
  947. passwd = g.monero_wallet_rpc_password)
  948. wallets_processed = 0
  949. for n,d in enumerate(data): # [d.sec,d.wallet_passwd,d.viewkey,d.addr]
  950. fn = os.path.join(
  951. opt.outdir or '.','{}-{}-MoneroWallet{}'.format(
  952. al.al_id.sid,
  953. d.idx,
  954. '-α' if g.debug_utf8 else ''))
  955. info = '\n{}ing wallet {}/{} ({})'.format(op.action,n+1,dl,fn)
  956. wallets_processed += await op.func(n,d,fn,c,info)
  957. wd.stop()
  958. gmsg('\n{} wallet{} {}ed'.format(wallets_processed,suf(wallets_processed),op.desc.lower()))
  959. if wallets_processed and op.name == 'sync':
  960. col1_w = max(map(len,bals)) + 1
  961. fs = '{:%s} {} {}' % col1_w
  962. msg('\n'+fs.format('Wallet','Balance ','Unlocked Balance '))
  963. from .obj import XMRAmt
  964. tbals = [XMRAmt('0'),XMRAmt('0')]
  965. for bal in bals:
  966. for i in (0,1): tbals[i] += bals[bal][i]
  967. msg(fs.format(bal+':',*[XMRAmt(b).fmt(fs='5.12',color=True) for b in bals[bal]]))
  968. msg(fs.format('-'*col1_w,'-'*18,'-'*18))
  969. msg(fs.format('TOTAL:',*[XMRAmt(b).fmt(fs='5.12',color=True) for b in tbals]))
  970. if blockheight < 0:
  971. blockheight = 0 # TODO: handle the non-zero case
  972. bals = {} # locked,unlocked
  973. from collections import namedtuple
  974. wo = namedtuple('mwo',['name','desc','action','func','accept_defaults'])
  975. op = { # reusing name!
  976. 'create': wo('create', 'Creat', 'Generat', create, False),
  977. 'sync': wo('sync', 'Sync', 'Sync', sync, True) }[op]
  978. try:
  979. run_session(process_wallets(op))
  980. except KeyboardInterrupt:
  981. rdie(1,'\nUser interrupt\n')
  982. except EOFError:
  983. rdie(2,'\nEnd of file\n')
  984. except Exception as e:
  985. try:
  986. die(1,'Error: {}'.format(e.args[0]))
  987. except:
  988. rdie(1,'Error: {!r}'.format(e.args[0]))
  989. return True
  990. class tool_api(
  991. MMGenToolCmdUtil,
  992. MMGenToolCmdCoin,
  993. MMGenToolCmdMnemonic,
  994. ):
  995. """
  996. API providing access to a subset of methods from the mmgen.tool module
  997. Example:
  998. from mmgen.tool import tool_api
  999. tool = tool_api()
  1000. # Set the coin and network:
  1001. tool.init_coin('btc','mainnet')
  1002. # Print available address types:
  1003. tool.print_addrtypes()
  1004. # Set the address type:
  1005. tool.addrtype = 'segwit'
  1006. # Disable user entropy gathering (optional, reduces security):
  1007. tool.usr_randchars = 0
  1008. # Generate a random BTC segwit keypair:
  1009. wif,addr = tool.randpair()
  1010. # Set coin, network and address type:
  1011. tool.init_coin('ltc','testnet')
  1012. tool.addrtype = 'bech32'
  1013. # Generate a random LTC testnet Bech32 keypair:
  1014. wif,addr = tool.randpair()
  1015. """
  1016. def __init__(self):
  1017. """
  1018. Initializer - takes no arguments
  1019. """
  1020. super().__init__()
  1021. if not hasattr(opt,'version'):
  1022. opts.init()
  1023. opt.use_old_ed25519 = None
  1024. opt.type = None
  1025. def init_coin(self,coinsym,network):
  1026. """
  1027. Initialize a coin/network pair
  1028. Valid choices for coins: one of the symbols returned by the 'coins' attribute
  1029. Valid choices for network: 'mainnet','testnet','regtest'
  1030. """
  1031. from .protocol import init_proto,init_genonly_altcoins
  1032. altcoin_trust_level = init_genonly_altcoins(coinsym,testnet=network in ('testnet','regtest'))
  1033. warn_altcoins(coinsym,altcoin_trust_level)
  1034. self.proto = init_proto(coinsym,network=network) # FIXME
  1035. return self.proto
  1036. @property
  1037. def coins(self):
  1038. """The available coins"""
  1039. from .protocol import CoinProtocol
  1040. from .altcoin import CoinInfo
  1041. return sorted(set(
  1042. [c.upper() for c in CoinProtocol.coins]
  1043. + [c.symbol for c in CoinInfo.get_supported_coins(self.proto.network)]
  1044. ))
  1045. @property
  1046. def coin(self):
  1047. """The currently configured coin"""
  1048. return self.proto.coin
  1049. @property
  1050. def network(self):
  1051. """The currently configured network"""
  1052. return self.proto.network
  1053. @property
  1054. def addrtypes(self):
  1055. """
  1056. The available address types for current coin/network pair. The
  1057. first-listed is the default
  1058. """
  1059. return [MMGenAddrType(proto=proto,id_str=id_str).name for id_str in self.proto.mmtypes]
  1060. def print_addrtypes(self):
  1061. """
  1062. Print the available address types for current coin/network pair along with
  1063. a description. The first-listed is the default
  1064. """
  1065. for t in [MMGenAddrType(proto=proto,id_str=id_str).name for id_str in self.proto.mmtypes]:
  1066. print('{:<12} - {}'.format(t.name,t.desc))
  1067. @property
  1068. def addrtype(self):
  1069. """The currently configured address type (is assignable)"""
  1070. return opt.type
  1071. @addrtype.setter
  1072. def addrtype(self,val):
  1073. opt.type = val
  1074. @property
  1075. def usr_randchars(self):
  1076. """
  1077. The number of keystrokes of entropy to be gathered from the user.
  1078. Setting to zero disables user entropy gathering.
  1079. """
  1080. return opt.usr_randchars
  1081. @usr_randchars.setter
  1082. def usr_randchars(self,val):
  1083. opt.usr_randchars = val