tool.py 42 KB

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