tool.py 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2019 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. from mmgen.bip39 import bip39
  26. NL = ('\n','\r\n')[g.platform=='win']
  27. def _create_call_sig(cmd,parsed=False):
  28. m = getattr(MMGenToolCmd,cmd)
  29. if 'varargs_call_sig' in m.__code__.co_varnames: # hack
  30. flag = 'VAR_ARGS'
  31. va = m.__defaults__[0]
  32. args,dfls,ann = va['args'],va['dfls'],va['annots']
  33. else:
  34. flag = None
  35. args = m.__code__.co_varnames[1:m.__code__.co_argcount]
  36. dfls = m.__defaults__ or ()
  37. ann = m.__annotations__
  38. nargs = len(args) - len(dfls)
  39. def get_type_from_ann(arg):
  40. return ann[arg][1:] + (' or STDIN','')[parsed] if ann[arg] == 'sstr' else ann[arg].__name__
  41. if parsed:
  42. c_args = [(a,get_type_from_ann(a)) for a in args[:nargs]]
  43. c_kwargs = [(a,dfls[n]) for n,a in enumerate(args[nargs:])]
  44. return c_args,dict(c_kwargs),'STDIN_OK' if c_args and ann[args[0]] == 'sstr' else flag
  45. else:
  46. c_args = ['{} [{}]'.format(a,get_type_from_ann(a)) for a in args[:nargs]]
  47. c_kwargs = ['"{}" [{}={!r}{}]'.format(
  48. a, type(dfls[n]).__name__, dfls[n],
  49. (' ' + ann[a] if a in ann else ''))
  50. for n,a in enumerate(args[nargs:])]
  51. return ' '.join(c_args + c_kwargs)
  52. def _usage(cmd=None,exit_val=1):
  53. m1=('USAGE INFORMATION FOR MMGEN-TOOL COMMANDS:\n\n'
  54. ' Unquoted arguments are mandatory\n'
  55. ' Quoted arguments are optional, default values will be used\n'
  56. ' Argument types and default values are shown in square brackets\n')
  57. m2=(' To force a command to read from STDIN instead of file (for commands taking\n'
  58. ' a filename as their first argument), substitute "-" for the filename.\n\n'
  59. 'EXAMPLES:\n\n'
  60. ' Generate a random Bech32 public/private keypair for LTC:\n'
  61. ' $ mmgen-tool -r0 --coin=ltc --type=bech32 randpair\n\n'
  62. ' Generate a well-known burn address:\n'
  63. ' $ mmgen-tool hextob58chk 000000000000000000000000000000000000000000\n\n'
  64. ' Generate a random 12-word seed phrase:\n'
  65. ' $ mmgen-tool -r0 mn_rand128\n\n'
  66. ' Same as above, but get additional entropy from user:\n'
  67. ' $ mmgen-tool mn_rand128\n\n'
  68. ' Convert a string to base 58:\n'
  69. ' $ mmgen-tool bytestob58 /etc/timezone pad=20\n\n'
  70. ' Reverse a hex string:\n'
  71. ' $ mmgen-tool hexreverse "deadbeefcafe"\n\n'
  72. ' Same as above, but use a pipe:\n'
  73. ' $ echo "deadbeefcafe" | mmgen-tool hexreverse -')
  74. if not cmd:
  75. Msg(m1)
  76. for bc in MMGenToolCmd.__bases__:
  77. cls_info = bc.__doc__.strip().split('\n')[0]
  78. Msg(' {}{}\n'.format(cls_info[0].upper(),cls_info[1:]))
  79. ucmds = bc._user_commands()
  80. max_w = max(map(len,ucmds))
  81. for cmd in ucmds:
  82. if getattr(MMGenToolCmd,cmd).__doc__:
  83. Msg(' {:{w}} {}'.format(cmd,_create_call_sig(cmd),w=max_w))
  84. Msg('')
  85. Msg(m2)
  86. elif cmd in MMGenToolCmd._user_commands():
  87. docstr = getattr(MMGenToolCmd,cmd).__doc__.strip()
  88. msg('{}'.format(capfirst(docstr)))
  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. # try: u_args[0] = u_args[0].decode()
  111. # except: pass
  112. have_stdin_input = True
  113. if len(u_args[0]) >= max_dlen:
  114. die(2,'Maximum data input for this command is {}'.format(max_dlen_spec))
  115. if not u_args[0]:
  116. die(2,'{}: ERROR: no output from previous command in pipe'.format(cmd))
  117. u_nkwargs = len(cmd_args) - len(c_args)
  118. u_kwargs = {}
  119. if flag == 'VAR_ARGS':
  120. t = [a.split('=',1) for a in cmd_args if '=' in a]
  121. tk = [a[0] for a in t]
  122. tk_bad = [a for a in tk if a not in c_kwargs]
  123. if set(tk_bad) != set(tk[:len(tk_bad)]): # permit non-kw args to contain '='
  124. die(1,"'{}': illegal keyword argument".format(tk_bad[-1]))
  125. u_kwargs = dict(t[len(tk_bad):])
  126. u_args = cmd_args[:-len(u_kwargs) or None]
  127. elif u_nkwargs > 0:
  128. u_kwargs = dict([a.split('=',1) for a in cmd_args[len(c_args):] if '=' in a])
  129. if len(u_kwargs) != u_nkwargs:
  130. msg('Command requires exactly {} non-keyword argument{}'.format(len(c_args),suf(c_args)))
  131. _usage(cmd)
  132. if len(u_kwargs) > len(c_kwargs):
  133. msg('Command accepts no more than {} keyword argument{}'.format(len(c_kwargs),suf(c_kwargs)))
  134. _usage(cmd)
  135. for k in u_kwargs:
  136. if k not in c_kwargs:
  137. msg("'{}': invalid keyword argument".format(k))
  138. _usage(cmd)
  139. def conv_type(arg,arg_name,arg_type):
  140. if arg_type == 'bytes' and type(arg) != bytes:
  141. die(1,"'Binary input data must be supplied via STDIN")
  142. if have_stdin_input and arg_type == 'str' and isinstance(arg,bytes):
  143. arg = arg.decode()
  144. if arg[-len(NL):] == NL: # rstrip one newline
  145. arg = arg[:-len(NL)]
  146. if arg_type == 'bool':
  147. if arg.lower() in ('true','yes','1','on'): arg = True
  148. elif arg.lower() in ('false','no','0','off'): arg = False
  149. else:
  150. msg("'{}': invalid boolean value for keyword argument".format(arg))
  151. _usage(cmd)
  152. try:
  153. return __builtins__[arg_type](arg)
  154. except:
  155. die(1,"'{}': Invalid argument for argument {} ('{}' required)".format(arg,arg_name,arg_type))
  156. if flag == 'VAR_ARGS':
  157. args = [conv_type(u_args[i],c_args[0][0],c_args[0][1]) for i in range(len(u_args))]
  158. else:
  159. args = [conv_type(u_args[i],c_args[i][0],c_args[i][1]) for i in range(len(c_args))]
  160. kwargs = {k:conv_type(u_kwargs[k],k,type(c_kwargs[k]).__name__) for k in u_kwargs}
  161. return args,kwargs
  162. def _process_result(ret,pager=False,print_result=False):
  163. """
  164. Convert result to something suitable for output to screen and return it.
  165. If result is bytes and not convertible to utf8, output as binary using os.write().
  166. If 'print_result' is True, send the converted result directly to screen or
  167. pager instead of returning it.
  168. """
  169. def triage_result(o):
  170. return o if not print_result else do_pager(o) if pager else Msg(o)
  171. if ret == True:
  172. return True
  173. elif ret in (False,None):
  174. ydie(1,"tool command returned '{}'".format(ret))
  175. elif isinstance(ret,str):
  176. return triage_result(ret)
  177. elif isinstance(ret,int):
  178. return triage_result(str(ret))
  179. elif isinstance(ret,tuple):
  180. return triage_result('\n'.join([r.decode() if isinstance(r,bytes) else r for r in ret]))
  181. elif isinstance(ret,bytes):
  182. try:
  183. o = ret.decode()
  184. return o if not print_result else do_pager(o) if pager else Msg(o)
  185. except:
  186. # don't add NL to binary data if it can't be converted to utf8
  187. return ret if not print_result else os.write(1,ret)
  188. else:
  189. ydie(1,"tool.py: can't handle return value of type '{}'".format(type(ret).__name__))
  190. from mmgen.obj import MMGenAddrType
  191. def init_generators(arg=None):
  192. global at,kg,ag
  193. at = MMGenAddrType((hasattr(opt,'type') and opt.type) or g.proto.dfl_mmtype)
  194. if arg != 'at':
  195. kg = KeyGenerator(at)
  196. ag = AddrGenerator(at)
  197. dfl_mnemonic_fmt = 'mmgen'
  198. mnemonic_fmts = {
  199. 'mmgen': { 'fmt': 'words', 'conv_cls': baseconv },
  200. 'bip39': { 'fmt': 'bip39', 'conv_cls': bip39 },
  201. }
  202. mn_opts_disp = "(valid options: '{}')".format("', '".join(mnemonic_fmts))
  203. class MMGenToolCmdBase(object):
  204. @classmethod
  205. def _user_commands(cls):
  206. return [e for e in dir(cls) if e[0] != '_' and getattr(cls,e).__doc__]
  207. class MMGenToolCmdMisc(MMGenToolCmdBase):
  208. "miscellaneous commands"
  209. def help(self,command_name=''):
  210. "display usage information for a single command or all commands"
  211. _usage(command_name,exit_val=0)
  212. usage = help
  213. class MMGenToolCmdUtil(MMGenToolCmdBase):
  214. "general string conversion and hashing utilities"
  215. def bytespec(self,dd_style_byte_specifier:str):
  216. "convert a byte specifier such as '1GB' into an integer"
  217. return parse_bytespec(dd_style_byte_specifier)
  218. def randhex(self,nbytes='32'):
  219. "print 'n' bytes (default 32) of random data in hex format"
  220. return get_random(int(nbytes)).hex()
  221. def hexreverse(self,hexstr:'sstr'):
  222. "reverse bytes of a hexadecimal string"
  223. return bytes.fromhex(hexstr.strip())[::-1].hex()
  224. def hexlify(self,infile:str):
  225. "convert bytes in file to hexadecimal (use '-' for stdin)"
  226. data = get_data_from_file(infile,dash=True,quiet=True,binary=True)
  227. return data.hex()
  228. def unhexlify(self,hexstr:'sstr'):
  229. "convert hexadecimal value to bytes (warning: outputs binary data)"
  230. return bytes.fromhex(hexstr)
  231. def hexdump(self,infile:str,cols=8,line_nums=True):
  232. "create hexdump of data from file (use '-' for stdin)"
  233. data = get_data_from_file(infile,dash=True,quiet=True,binary=True)
  234. return pretty_hexdump(data,cols=cols,line_nums=line_nums).rstrip()
  235. def unhexdump(self,infile:str):
  236. "decode hexdump from file (use '-' for stdin) (warning: outputs binary data)"
  237. if g.platform == 'win':
  238. import msvcrt
  239. msvcrt.setmode(sys.stdout.fileno(),os.O_BINARY)
  240. hexdata = get_data_from_file(infile,dash=True,quiet=True)
  241. return decode_pretty_hexdump(hexdata)
  242. def hash160(self,hexstr:'sstr'):
  243. "compute ripemd160(sha256(data)) (convert hex pubkey to hex addr)"
  244. return hash160(hexstr)
  245. def hash256(self,string_or_bytes:str,file_input=False,hex_input=False): # TODO: handle stdin
  246. "compute sha256(sha256(data)) (double sha256)"
  247. from hashlib import sha256
  248. if file_input: b = get_data_from_file(string_or_bytes,binary=True)
  249. elif hex_input: b = decode_pretty_hexdump(string_or_bytes)
  250. else: b = string_or_bytes
  251. return sha256(sha256(b.encode()).digest()).hexdigest()
  252. def id6(self,infile:str):
  253. "generate 6-character MMGen ID for a file (use '-' for stdin)"
  254. return make_chksum_6(
  255. get_data_from_file(infile,dash=True,quiet=True,binary=True))
  256. def str2id6(self,string:'sstr'): # retain ignoring of space for backwards compat
  257. "generate 6-character MMGen ID for a string, ignoring spaces"
  258. return make_chksum_6(''.join(string.split()))
  259. def id8(self,infile:str):
  260. "generate 8-character MMGen ID for a file (use '-' for stdin)"
  261. return make_chksum_8(
  262. get_data_from_file(infile,dash=True,quiet=True,binary=True))
  263. def randb58(self,nbytes=32,pad=True):
  264. "generate random data (default: 32 bytes) and convert it to base 58"
  265. return baseconv.b58encode(get_random(nbytes),pad=pad)
  266. def bytestob58(self,infile:str,pad=0):
  267. "convert bytes to base 58 (supply data via STDIN)"
  268. data = get_data_from_file(infile,dash=True,quiet=True,binary=True)
  269. return baseconv.fromhex(data.hex(),'b58',pad=pad,tostr=True)
  270. def b58tobytes(self,b58num:'sstr',pad=0):
  271. "convert a base 58 number to bytes (warning: outputs binary data)"
  272. return bytes.fromhex(baseconv.tohex(b58num,'b58',pad=pad))
  273. def hextob58(self,hexstr:'sstr',pad=0):
  274. "convert a hexadecimal number to base 58"
  275. return baseconv.fromhex(hexstr,'b58',pad=pad,tostr=True)
  276. def b58tohex(self,b58num:'sstr',pad=0):
  277. "convert a base 58 number to hexadecimal"
  278. return baseconv.tohex(b58num,'b58',pad=pad)
  279. def hextob58chk(self,hexstr:'sstr'):
  280. "convert a hexadecimal number to base58-check encoding"
  281. from mmgen.protocol import _b58chk_encode
  282. return _b58chk_encode(hexstr)
  283. def b58chktohex(self,b58chk_num:'sstr'):
  284. "convert a base58-check encoded number to hexadecimal"
  285. from mmgen.protocol import _b58chk_decode
  286. return _b58chk_decode(b58chk_num)
  287. def hextob32(self,hexstr:'sstr',pad=0):
  288. "convert a hexadecimal number to MMGen's flavor of base 32"
  289. return baseconv.fromhex(hexstr,'b32',pad,tostr=True)
  290. def b32tohex(self,b32num:'sstr',pad=0):
  291. "convert an MMGen-flavor base 32 number to hexadecimal"
  292. return baseconv.tohex(b32num.upper(),'b32',pad)
  293. class MMGenToolCmdCoin(MMGenToolCmdBase):
  294. """
  295. cryptocoin key/address utilities
  296. May require use of the '--coin', '--type' and/or '--testnet' options
  297. Examples:
  298. mmgen-tool --coin=ltc --type=bech32 wif2addr <wif key>
  299. mmgen-tool --coin=zec --type=zcash_z randpair
  300. """
  301. def randwif(self):
  302. "generate a random private key in WIF format"
  303. init_generators('at')
  304. return PrivKey(get_random(32),pubkey_type=at.pubkey_type,compressed=at.compressed).wif
  305. def randpair(self):
  306. "generate a random private key/address pair"
  307. init_generators()
  308. privhex = PrivKey(get_random(32),pubkey_type=at.pubkey_type,compressed=at.compressed)
  309. addr = ag.to_addr(kg.to_pubhex(privhex))
  310. return (privhex.wif,addr)
  311. def wif2hex(self,wifkey:'sstr'):
  312. "convert a private key from WIF to hex format"
  313. return PrivKey(wif=wifkey)
  314. def hex2wif(self,privhex:'sstr'):
  315. "convert a private key from hex to WIF format"
  316. init_generators('at')
  317. return g.proto.hex2wif(privhex,pubkey_type=at.pubkey_type,compressed=at.compressed)
  318. def wif2addr(self,wifkey:'sstr'):
  319. "generate a coin address from a key in WIF format"
  320. init_generators()
  321. privhex = PrivKey(wif=wifkey)
  322. addr = ag.to_addr(kg.to_pubhex(privhex))
  323. return addr
  324. def wif2redeem_script(self,wifkey:'sstr'): # new
  325. "convert a WIF private key to a Segwit P2SH-P2WPKH redeem script"
  326. assert opt.type == 'segwit','This command is meaningful only for --type=segwit'
  327. init_generators()
  328. privhex = PrivKey(wif=wifkey)
  329. return ag.to_segwit_redeem_script(kg.to_pubhex(privhex))
  330. def wif2segwit_pair(self,wifkey:'sstr'):
  331. "generate both a Segwit P2SH-P2WPKH redeem script and address from WIF"
  332. assert opt.type == 'segwit','This command is meaningful only for --type=segwit'
  333. init_generators()
  334. pubhex = kg.to_pubhex(PrivKey(wif=wifkey))
  335. addr = ag.to_addr(pubhex)
  336. rs = ag.to_segwit_redeem_script(pubhex)
  337. return (rs,addr)
  338. def privhex2addr(self,privhex:'sstr',output_pubhex=False):
  339. "generate coin address from private key in hex format"
  340. init_generators()
  341. pk = PrivKey(bytes.fromhex(privhex),compressed=at.compressed,pubkey_type=at.pubkey_type)
  342. ph = kg.to_pubhex(pk)
  343. return ph if output_pubhex else ag.to_addr(ph)
  344. def privhex2pubhex(self,privhex:'sstr'): # new
  345. "generate a hex public key from a hex private key"
  346. return self.privhex2addr(privhex,output_pubhex=True)
  347. def pubhex2addr(self,pubkeyhex:'sstr'):
  348. "convert a hex pubkey to an address"
  349. if opt.type == 'segwit':
  350. return g.proto.pubhex2segwitaddr(pubkeyhex)
  351. else:
  352. return self.pubhash2addr(hash160(pubkeyhex))
  353. def pubhex2redeem_script(self,pubkeyhex:'sstr'): # new
  354. "convert a hex pubkey to a Segwit P2SH-P2WPKH redeem script"
  355. assert opt.type == 'segwit','This command is meaningful only for --type=segwit'
  356. return g.proto.pubhex2redeem_script(pubkeyhex)
  357. def redeem_script2addr(self,redeem_scripthex:'sstr'): # new
  358. "convert a Segwit P2SH-P2WPKH redeem script to an address"
  359. assert opt.type == 'segwit','This command is meaningful only for --type=segwit'
  360. assert redeem_scripthex[:4] == '0014','{!r}: invalid redeem script'.format(redeem_scripthex)
  361. assert len(redeem_scripthex) == 44,'{} bytes: invalid redeem script length'.format(len(redeem_scripthex)//2)
  362. return self.pubhash2addr(self.hash160(redeem_scripthex))
  363. def pubhash2addr(self,pubhashhex:'sstr'):
  364. "convert public key hash to address"
  365. if opt.type == 'bech32':
  366. return g.proto.pubhash2bech32addr(pubhashhex)
  367. else:
  368. init_generators('at')
  369. return g.proto.pubhash2addr(pubhashhex,at.addr_fmt=='p2sh')
  370. def addr2pubhash(self,addr:'sstr'):
  371. "convert coin address to public key hash"
  372. from mmgen.tx import addr2pubhash
  373. return addr2pubhash(CoinAddr(addr))
  374. def addr2scriptpubkey(self,addr:'sstr'):
  375. "convert coin address to scriptPubKey"
  376. from mmgen.tx import addr2scriptPubKey
  377. return addr2scriptPubKey(CoinAddr(addr))
  378. def scriptpubkey2addr(self,hexstr:'sstr'):
  379. "convert scriptPubKey to coin address"
  380. from mmgen.tx import scriptPubKey2addr
  381. return scriptPubKey2addr(hexstr)[0]
  382. class MMGenToolCmdMnemonic(MMGenToolCmdBase):
  383. """
  384. seed phrase utilities (valid formats: 'mmgen' (default), 'bip39')
  385. IMPORTANT NOTE: MMGen's default seed phrase format uses the Electrum
  386. wordlist, however seed phrases are computed using a different algorithm
  387. and are NOT Electrum-compatible!
  388. BIP39 support is fully compatible with the standard, allowing users to
  389. import and export seed entropy from BIP39-compatible wallets. However,
  390. users should be aware that BIP39 support does not imply BIP32 support!
  391. MMGen uses its own key derivation scheme differing from the one described
  392. by the BIP32 protocol.
  393. """
  394. def _do_random_mn(self,nbytes:int,fmt:str):
  395. assert nbytes in (16,24,32), 'nbytes must be 16, 24 or 32'
  396. hexrand = get_random(nbytes).hex()
  397. Vmsg('Seed: {}'.format(hexrand))
  398. return self.hex2mn(hexrand,fmt=fmt)
  399. def mn_rand128(self, fmt:mn_opts_disp = dfl_mnemonic_fmt ):
  400. "generate random 128-bit mnemonic seed phrase"
  401. return self._do_random_mn(16,fmt)
  402. def mn_rand192(self, fmt:mn_opts_disp = dfl_mnemonic_fmt ):
  403. "generate random 192-bit mnemonic seed phrase"
  404. return self._do_random_mn(24,fmt)
  405. def mn_rand256(self, fmt:mn_opts_disp = dfl_mnemonic_fmt ):
  406. "generate random 256-bit mnemonic seed phrase"
  407. return self._do_random_mn(32,fmt)
  408. def _get_mnemonic_fmt(self,fmt):
  409. if fmt not in mnemonic_fmts:
  410. m = '{!r}: invalid format (valid options: {})'
  411. die(1,m.format(fmt,', '.join(mnemonic_fmts)))
  412. return mnemonic_fmts[fmt]['fmt']
  413. def hex2mn( self, hexstr:'sstr', fmt:mn_opts_disp = dfl_mnemonic_fmt ):
  414. "convert a 16, 24 or 32-byte hexadecimal number to a mnemonic seed phrase"
  415. opt.out_fmt = self._get_mnemonic_fmt(fmt)
  416. from mmgen.seed import SeedSource
  417. s = SeedSource(seed_bin=bytes.fromhex(hexstr))
  418. s._format()
  419. return ' '.join(s.ssdata.mnemonic)
  420. def mn2hex( self, seed_mnemonic:'sstr', fmt:mn_opts_disp = dfl_mnemonic_fmt ):
  421. "convert a 12, 18 or 24-word mnemonic seed phrase to a hexadecimal number"
  422. in_fmt = self._get_mnemonic_fmt(fmt)
  423. opt.quiet = True
  424. from mmgen.seed import SeedSource
  425. return SeedSource(in_data=seed_mnemonic,in_fmt=in_fmt).seed.hexdata
  426. def mn_stats(self, fmt:mn_opts_disp = dfl_mnemonic_fmt ):
  427. "show stats for mnemonic wordlist"
  428. conv_cls = mnemonic_fmts[fmt]['conv_cls']
  429. fmt in conv_cls.digits or die(1,"'{}': not a valid format".format(fmt))
  430. conv_cls.check_wordlist(fmt)
  431. return True
  432. def mn_printlist( self, fmt:mn_opts_disp = dfl_mnemonic_fmt, enum=False, pager=False ):
  433. "print mnemonic wordlist"
  434. self._get_mnemonic_fmt(fmt) # perform check
  435. ret = mnemonic_fmts[fmt]['conv_cls'].digits[fmt]
  436. if enum:
  437. ret = ['{:>4} {}'.format(n,e) for n,e in enumerate(ret)]
  438. return '\n'.join(ret)
  439. class MMGenToolCmdFile(MMGenToolCmdBase):
  440. "utilities for viewing/checking MMGen address and transaction files"
  441. def addrfile_chksum(self,mmgen_addrfile:str):
  442. "compute checksum for MMGen address file"
  443. opt.yes = True
  444. opt.quiet = True
  445. from mmgen.addr import AddrList
  446. return AddrList(mmgen_addrfile).chksum
  447. def keyaddrfile_chksum(self,mmgen_keyaddrfile:str):
  448. "compute checksum for MMGen key-address file"
  449. opt.yes = True
  450. opt.quiet = True
  451. from mmgen.addr import KeyAddrList
  452. return KeyAddrList(mmgen_keyaddrfile).chksum
  453. def passwdfile_chksum(self,mmgen_passwdfile:str):
  454. "compute checksum for MMGen password file"
  455. from mmgen.addr import PasswordList
  456. return PasswordList(infile=mmgen_passwdfile).chksum
  457. def txview( varargs_call_sig = { # hack to allow for multiple filenames
  458. 'args': (
  459. 'mmgen_tx_file(s)',
  460. 'pager',
  461. 'terse',
  462. 'sort',
  463. 'filesort' ),
  464. 'dfls': ( False, False, 'addr', 'mtime' ),
  465. 'annots': {
  466. 'mmgen_tx_file(s)': str,
  467. 'sort': '(valid options: addr,raw)',
  468. 'filesort': '(valid options: mtime,ctime,atime)'
  469. } },
  470. *infiles,**kwargs):
  471. "show raw/signed MMGen transaction in human-readable form"
  472. terse = bool(kwargs.get('terse'))
  473. tx_sort = kwargs.get('sort') or 'addr'
  474. file_sort = kwargs.get('filesort') or 'mtime'
  475. from mmgen.filename import MMGenFileList
  476. from mmgen.tx import MMGenTX
  477. flist = MMGenFileList(infiles,ftype=MMGenTX)
  478. flist.sort_by_age(key=file_sort) # in-place sort
  479. sep = '—'*77+'\n'
  480. return sep.join(
  481. [MMGenTX(fn,offline=True).format_view(terse=terse,sort=tx_sort) for fn in flist.names()]
  482. ).rstrip()
  483. class MMGenToolCmdFileCrypt(MMGenToolCmdBase):
  484. """
  485. file encryption and decryption
  486. MMGen encryption suite:
  487. * Key: Scrypt (user-configurable hash parameters, 32-byte salt)
  488. * Enc: AES256_CTR, 16-byte rand IV, sha256 hash + 32-byte nonce + data
  489. * The encrypted file is indistinguishable from random data
  490. """
  491. def encrypt(self,infile:str,outfile='',hash_preset=''):
  492. "encrypt a file"
  493. data = get_data_from_file(infile,'data for encryption',binary=True)
  494. enc_d = mmgen_encrypt(data,'user data',hash_preset)
  495. if not outfile:
  496. outfile = '{}.{}'.format(os.path.basename(infile),g.mmenc_ext)
  497. write_data_to_file(outfile,enc_d,'encrypted data',binary=True)
  498. return True
  499. def decrypt(self,infile:str,outfile='',hash_preset=''):
  500. "decrypt a file"
  501. enc_d = get_data_from_file(infile,'encrypted data',binary=True)
  502. while True:
  503. dec_d = mmgen_decrypt(enc_d,'user data',hash_preset)
  504. if dec_d: break
  505. msg('Trying again...')
  506. if not outfile:
  507. o = os.path.basename(infile)
  508. outfile = remove_extension(o,g.mmenc_ext)
  509. if outfile == o: outfile += '.dec'
  510. write_data_to_file(outfile,dec_d,'decrypted data',binary=True)
  511. return True
  512. class MMGenToolCmdFileUtil(MMGenToolCmdBase):
  513. "file utilities"
  514. def find_incog_data(self,filename:str,incog_id:str,keep_searching=False):
  515. "Use an Incog ID to find hidden incognito wallet data"
  516. ivsize,bsize,mod = g.aesctr_iv_len,4096,4096*8
  517. n,carry = 0,b' '*ivsize
  518. flgs = os.O_RDONLY|os.O_BINARY if g.platform == 'win' else os.O_RDONLY
  519. f = os.open(filename,flgs)
  520. for ch in incog_id:
  521. if ch not in '0123456789ABCDEF':
  522. die(2,"'{}': invalid Incog ID".format(incog_id))
  523. while True:
  524. d = os.read(f,bsize)
  525. if not d: break
  526. d = carry + d
  527. for i in range(bsize):
  528. if sha256(d[i:i+ivsize]).hexdigest()[:8].upper() == incog_id:
  529. if n+i < ivsize: continue
  530. msg('\rIncog data for ID {} found at offset {}'.format(incog_id,n+i-ivsize))
  531. if not keep_searching: sys.exit(0)
  532. carry = d[len(d)-ivsize:]
  533. n += bsize
  534. if not n % mod:
  535. msg_r('\rSearched: {} bytes'.format(n))
  536. msg('')
  537. os.close(f)
  538. return True
  539. def rand2file(self,outfile:str,nbytes:str,threads=4,silent=False):
  540. "write 'n' bytes of random data to specified file"
  541. from threading import Thread
  542. from queue import Queue
  543. from cryptography.hazmat.primitives.ciphers import Cipher,algorithms,modes
  544. from cryptography.hazmat.backends import default_backend
  545. def encrypt_worker(wid):
  546. ctr_init_val = os.urandom(g.aesctr_iv_len)
  547. c = Cipher(algorithms.AES(key),modes.CTR(ctr_init_val),backend=default_backend())
  548. encryptor = c.encryptor()
  549. while True:
  550. q2.put(encryptor.update(q1.get()))
  551. q1.task_done()
  552. def output_worker():
  553. while True:
  554. f.write(q2.get())
  555. q2.task_done()
  556. nbytes = parse_bytespec(nbytes)
  557. if opt.outdir:
  558. outfile = make_full_path(opt.outdir,outfile)
  559. f = open(outfile,'wb')
  560. key = get_random(32)
  561. q1,q2 = Queue(),Queue()
  562. for i in range(max(1,threads-2)):
  563. t = Thread(target=encrypt_worker,args=[i])
  564. t.daemon = True
  565. t.start()
  566. t = Thread(target=output_worker)
  567. t.daemon = True
  568. t.start()
  569. blk_size = 1024 * 1024
  570. for i in range(nbytes // blk_size):
  571. if not i % 4:
  572. msg_r('\rRead: {} bytes'.format(i * blk_size))
  573. q1.put(os.urandom(blk_size))
  574. if nbytes % blk_size:
  575. q1.put(os.urandom(nbytes % blk_size))
  576. q1.join()
  577. q2.join()
  578. f.close()
  579. fsize = os.stat(outfile).st_size
  580. if fsize != nbytes:
  581. die(3,'{}: incorrect random file size (should be {})'.format(fsize,nbytes))
  582. if not silent:
  583. msg('\rRead: {} bytes'.format(nbytes))
  584. qmsg("\r{} byte{} of random data written to file '{}'".format(nbytes,suf(nbytes),outfile))
  585. return True
  586. class MMGenToolCmdWallet(MMGenToolCmdBase):
  587. "key, address or subseed generation from an MMGen wallet"
  588. def get_subseed(self,subseed_idx:str,wallet=''):
  589. "get the Seed ID of a single subseed by Subseed Index for default or specified wallet"
  590. opt.quiet = True
  591. sf = get_seed_file([wallet] if wallet else [],1)
  592. from mmgen.seed import SeedSource
  593. return SeedSource(sf).seed.subseed(subseed_idx).sid
  594. def get_subseed_by_seed_id(self,seed_id:str,wallet='',last_idx=g.subseeds):
  595. "get the Subseed Index of a single subseed by Seed ID for default or specified wallet"
  596. opt.quiet = True
  597. sf = get_seed_file([wallet] if wallet else [],1)
  598. from mmgen.seed import SeedSource
  599. ret = SeedSource(sf).seed.subseed_by_seed_id(seed_id,last_idx)
  600. return ret.ss_idx if ret else None
  601. def list_subseeds(self,subseed_idx_range:str,wallet=''):
  602. "list a range of subseed Seed IDs for default or specified wallet"
  603. opt.quiet = True
  604. sf = get_seed_file([wallet] if wallet else [],1)
  605. from mmgen.seed import SeedSource
  606. return SeedSource(sf).seed.subseeds.format(*SubSeedIdxRange(subseed_idx_range))
  607. def gen_key(self,mmgen_addr:str,wallet=''):
  608. "generate a single MMGen WIF key from default or specified wallet"
  609. return self.gen_addr(mmgen_addr,wallet,target='wif')
  610. def gen_addr(self,mmgen_addr:str,wallet='',target='addr'):
  611. "generate a single MMGen address from default or specified wallet"
  612. addr = MMGenID(mmgen_addr)
  613. opt.quiet = True
  614. sf = get_seed_file([wallet] if wallet else [],1)
  615. from mmgen.seed import SeedSource
  616. ss = SeedSource(sf)
  617. if ss.seed.sid != addr.sid:
  618. m = 'Seed ID of requested address ({}) does not match wallet ({})'
  619. die(1,m.format(addr.sid,ss.seed.sid))
  620. al = AddrList(seed=ss.seed,addr_idxs=AddrIdxList(str(addr.idx)),mmtype=addr.mmtype)
  621. d = al.data[0]
  622. ret = d.sec.wif if target=='wif' else d.addr
  623. return ret
  624. class MMGenToolCmdRPC(MMGenToolCmdBase):
  625. "tracking wallet commands using the JSON-RPC interface"
  626. def getbalance(self,minconf=1,quiet=False,pager=False):
  627. "list confirmed/unconfirmed, spendable/unspendable balances in tracking wallet"
  628. from mmgen.tw import TwGetBalance
  629. return TwGetBalance(minconf,quiet).format()
  630. def listaddress(self,
  631. mmgen_addr:str,
  632. minconf = 1,
  633. pager = False,
  634. showempty = True,
  635. showbtcaddr = True,
  636. age_fmt:'(valid options: days,confs)' = ''):
  637. "list the specified MMGen address and its balance"
  638. return self.listaddresses( mmgen_addrs = mmgen_addr,
  639. minconf = minconf,
  640. pager = pager,
  641. showempty = showempty,
  642. showbtcaddrs = showbtcaddr,
  643. age_fmt = age_fmt)
  644. def listaddresses( self,
  645. mmgen_addrs:'(range or list)' = '',
  646. minconf = 1,
  647. showempty = False,
  648. pager = False,
  649. showbtcaddrs = True,
  650. all_labels = False,
  651. sort:'(valid options: reverse,age)' = '',
  652. age_fmt:'(valid options: days,confs)' = ''):
  653. "list MMGen addresses and their balances"
  654. show_age = bool(age_fmt)
  655. if sort:
  656. sort = set(sort.split(','))
  657. sort_params = {'reverse','age'}
  658. if not sort.issubset(sort_params):
  659. die(1,"The sort option takes the following parameters: '{}'".format("','".join(sort_params)))
  660. usr_addr_list = []
  661. if mmgen_addrs:
  662. a = mmgen_addrs.rsplit(':',1)
  663. if len(a) != 2:
  664. m = "'{}': invalid address list argument (must be in form <seed ID>:[<type>:]<idx list>)"
  665. die(1,m.format(mmgen_addrs))
  666. usr_addr_list = [MMGenID('{}:{}'.format(a[0],i)) for i in AddrIdxList(a[1])]
  667. rpc_init()
  668. from mmgen.tw import TwAddrList
  669. al = TwAddrList(usr_addr_list,minconf,showempty,showbtcaddrs,all_labels)
  670. if not al:
  671. die(0,('No tracked addresses with balances!','No tracked addresses!')[showempty])
  672. return al.format(showbtcaddrs,sort,show_age,age_fmt or 'days')
  673. def twview( self,
  674. pager = False,
  675. reverse = False,
  676. wide = False,
  677. minconf = 1,
  678. sort = 'age',
  679. age_fmt:'(valid options: days,confs)' = 'days',
  680. show_mmid = True):
  681. "view tracking wallet"
  682. rpc_init()
  683. from mmgen.tw import TwUnspentOutputs
  684. twuo = TwUnspentOutputs(minconf=minconf)
  685. twuo.do_sort(sort,reverse=reverse)
  686. twuo.age_fmt = age_fmt
  687. twuo.show_mmid = show_mmid
  688. ret = twuo.format_for_printing(color=True) if wide else twuo.format_for_display()
  689. del twuo.wallet
  690. return ret
  691. def add_label(self,mmgen_or_coin_addr:str,label:str):
  692. "add descriptive label for address in tracking wallet"
  693. rpc_init()
  694. from mmgen.tw import TrackingWallet
  695. TrackingWallet(mode='w').add_label(mmgen_or_coin_addr,label,on_fail='raise')
  696. return True
  697. def remove_label(self,mmgen_or_coin_addr:str):
  698. "remove descriptive label for address in tracking wallet"
  699. self.add_label(mmgen_or_coin_addr,'')
  700. return True
  701. def remove_address(self,mmgen_or_coin_addr:str):
  702. "remove an address from tracking wallet"
  703. from mmgen.tw import TrackingWallet
  704. tw = TrackingWallet(mode='w')
  705. ret = tw.remove_address(mmgen_or_coin_addr) # returns None on failure
  706. if ret:
  707. msg("Address '{}' deleted from tracking wallet".format(ret))
  708. return ret
  709. class MMGenToolCmdMonero(MMGenToolCmdBase):
  710. "Monero wallet utilities"
  711. def keyaddrlist2monerowallets( self,
  712. xmr_keyaddrfile:str,
  713. blockheight:'(default: current height)' = 0,
  714. addrs:'(integer range or list)' = ''):
  715. "create Monero wallets from key-address list"
  716. return self.monero_wallet_ops( infile = xmr_keyaddrfile,
  717. op = 'create',
  718. blockheight = blockheight,
  719. addrs = addrs)
  720. def syncmonerowallets(self,xmr_keyaddrfile:str,addrs:'(integer range or list)'=''):
  721. "sync Monero wallets from key-address list"
  722. return self.monero_wallet_ops(infile=xmr_keyaddrfile,op='sync',addrs=addrs)
  723. def monero_wallet_ops(self,infile:str,op:str,blockheight=0,addrs=''):
  724. exit_if_mswin('Monero wallet operations')
  725. def run_cmd(cmd):
  726. import subprocess as sp
  727. p = sp.Popen(cmd,stdin=sp.PIPE,stdout=sp.PIPE,stderr=sp.PIPE)
  728. return p
  729. def test_rpc():
  730. p = run_cmd(['monero-wallet-cli','--version'])
  731. if not b'Monero' in p.stdout.read():
  732. die(1,"Unable to run 'monero-wallet-cli'!")
  733. p = run_cmd(['monerod','status'])
  734. import re
  735. m = re.search(r'Height: (\d+)/\d+ ',p.stdout.read().decode())
  736. if not m:
  737. die(1,'Unable to connect to monerod!')
  738. return int(m.group(1))
  739. def my_expect(p,m,s,regex=False):
  740. if m: msg_r(' {}...'.format(m))
  741. ret = (p.expect_exact,p.expect)[regex](s)
  742. vmsg("\nexpect: '{}' => {}".format(s,ret))
  743. if g.debug:
  744. pmsg('p.before:',p.before)
  745. pmsg('p.after:',p.after)
  746. if not (ret == 0 or (type(s) == list and ret in (0,1))):
  747. die(2,"Expect failed: '{}' (return value: {})".format(s,ret))
  748. if m: msg('OK')
  749. return ret
  750. def my_sendline(p,m,s,usr_ret):
  751. if m: msg_r(' {}...'.format(m))
  752. ret = p.sendline(s)
  753. if g.debug:
  754. pmsg('p.before:',p.before)
  755. pmsg('p.after:',p.after)
  756. if ret != usr_ret:
  757. die(2,"Unable to send line '{}' (return value {})".format(s,ret))
  758. if m: msg('OK')
  759. vmsg("sendline: '{}' => {}".format(s,ret))
  760. def create(n,d,fn):
  761. try: os.stat(fn)
  762. except: pass
  763. else: die(1,"Wallet '{}' already exists!".format(fn))
  764. p = pexpect.spawn('monero-wallet-cli --generate-from-spend-key {}'.format(fn))
  765. # if g.debug: p.logfile = sys.stdout # TODO: Error: 'write() argument must be str, not bytes'
  766. my_expect(p,'Awaiting initial prompt','Secret spend key: ')
  767. my_sendline(p,'',d.sec,65)
  768. my_expect(p,'','Enter.* new.* password.*: ',regex=True)
  769. my_sendline(p,'Sending password',d.wallet_passwd,33)
  770. my_expect(p,'','Confirm password: ')
  771. my_sendline(p,'Sending password again',d.wallet_passwd,33)
  772. my_expect(p,'','of your choice: ')
  773. my_sendline(p,'','1',2)
  774. my_expect(p,'monerod generating wallet','Generated new wallet: ')
  775. my_expect(p,'','\n')
  776. if d.addr not in p.before.decode():
  777. die(3,'Addresses do not match!\n MMGen: {}\n Monero: {}'.format(d.addr,p.before.decode()))
  778. my_expect(p,'','View key: ')
  779. my_expect(p,'','\n')
  780. if d.viewkey not in p.before.decode():
  781. die(3,'View keys do not match!\n MMGen: {}\n Monero: {}'.format(d.viewkey,p.before.decode()))
  782. my_expect(p,'','(YYYY-MM-DD): ')
  783. h = str(blockheight or cur_height-1)
  784. my_sendline(p,'',h,len(h)+1)
  785. ret = my_expect(p,'',['Starting refresh','Still apply restore height? (Y/Yes/N/No): '])
  786. if ret == 1:
  787. my_sendline(p,'','Y',2)
  788. m = ' Warning: {}: blockheight argument is higher than current blockheight'
  789. ymsg(m.format(blockheight))
  790. elif blockheight:
  791. p.logfile = sys.stderr
  792. my_expect(p,'Syncing wallet','\[wallet.*$',regex=True)
  793. p.logfile = None
  794. my_sendline(p,'Exiting','exit',5)
  795. p.read()
  796. def sync(n,d,fn):
  797. import time
  798. try: os.stat(fn)
  799. except: die(1,"Wallet '{}' does not exist!".format(fn))
  800. p = pexpect.spawn('monero-wallet-cli --wallet-file={}'.format(fn))
  801. # if g.debug: p.logfile = sys.stdout # TODO: Error: 'write() argument must be str, not bytes'
  802. my_expect(p,'Awaiting password prompt','Wallet password: ')
  803. my_sendline(p,'Sending password',d.wallet_passwd,33)
  804. msg(' Starting refresh...')
  805. height = None
  806. while True:
  807. ret = p.expect([r'Height\s+\S+\s+/\s+\S+',r'\[wallet.*:.*'])
  808. if ret == 0: # TODO: coverage
  809. d = p.after.decode().split()
  810. msg_r('\r Block {} / {}'.format(d[1],d[3]))
  811. height = d[3]
  812. time.sleep(0.5)
  813. elif ret == 1:
  814. if height:
  815. msg('\r Block {h} / {h} (wallet in sync)'.format(h=height))
  816. else:
  817. msg(' Wallet in sync')
  818. my_sendline(p,'Requesting account info','account',8)
  819. my_expect(p,'Getting totals','Total\s+.*\n',regex=True)
  820. b = p.after.decode().strip().split()[1:]
  821. msg(' Balance: {} Unlocked balance: {}'.format(*b))
  822. from mmgen.obj import XMRAmt
  823. bals[fn] = tuple(map(XMRAmt,b))
  824. my_sendline(p,'Exiting','exit',5)
  825. p.read()
  826. break
  827. else:
  828. die(2,"\nExpect failed: (return value: {})".format(ret))
  829. def process_wallets():
  830. m = { 'create': ('Creat','Generat',create,False),
  831. 'sync': ('Sync', 'Sync', sync, True) }
  832. opt.accept_defaults = opt.accept_defaults or m[op][3]
  833. from mmgen.protocol import init_coin
  834. init_coin('xmr')
  835. from mmgen.addr import AddrList
  836. al = KeyAddrList(infile)
  837. data = [d for d in al.data if addrs == '' or d.idx in AddrIdxList(addrs)]
  838. dl = len(data)
  839. assert dl,"No addresses in addrfile within range '{}'".format(addrs)
  840. gmsg('\n{}ing {} wallet{}'.format(m[op][0],dl,suf(dl)))
  841. for n,d in enumerate(data): # [d.sec,d.wallet_passwd,d.viewkey,d.addr]
  842. fn = os.path.join(
  843. opt.outdir or '','{}-{}-MoneroWallet{}'.format(
  844. al.al_id.sid,
  845. d.idx,
  846. '-α' if g.debug_utf8 else ''))
  847. gmsg('\n{}ing wallet {}/{} ({})'.format(m[op][1],n+1,dl,fn))
  848. m[op][2](n,d,fn)
  849. gmsg('\n{} wallet{} {}ed'.format(dl,suf(dl),m[op][0].lower()))
  850. if op == 'sync':
  851. col1_w = max(map(len,bals)) + 1
  852. fs = '{:%s} {} {}' % col1_w
  853. msg('\n'+fs.format('Wallet','Balance ','Unlocked Balance '))
  854. from mmgen.obj import XMRAmt
  855. tbals = [XMRAmt('0'),XMRAmt('0')]
  856. for bal in bals:
  857. for i in (0,1): tbals[i] += bals[bal][i]
  858. msg(fs.format(bal+':',*[XMRAmt(b).fmt(fs='5.12',color=True) for b in bals[bal]]))
  859. msg(fs.format('-'*col1_w,'-'*18,'-'*18))
  860. msg(fs.format('TOTAL:',*[XMRAmt(b).fmt(fs='5.12',color=True) for b in tbals]))
  861. os.environ['LANG'] = 'C'
  862. import pexpect
  863. if blockheight < 0:
  864. blockheight = 0 # TODO: handle the non-zero case
  865. cur_height = test_rpc() # empty blockchain returns 1
  866. from collections import OrderedDict
  867. bals = OrderedDict() # locked,unlocked
  868. try:
  869. process_wallets()
  870. except KeyboardInterrupt:
  871. rdie(1,'\nUser interrupt\n')
  872. except EOFError:
  873. rdie(2,'\nEnd of file\n')
  874. except Exception as e:
  875. try:
  876. die(1,'Error: {}'.format(e.args[0]))
  877. except:
  878. rdie(1,'Error: {!r}'.format(e.args[0]))
  879. return True
  880. class MMGenToolCmd(
  881. MMGenToolCmdMisc,
  882. MMGenToolCmdUtil,
  883. MMGenToolCmdCoin,
  884. MMGenToolCmdMnemonic,
  885. MMGenToolCmdFile,
  886. MMGenToolCmdFileCrypt,
  887. MMGenToolCmdFileUtil,
  888. MMGenToolCmdWallet,
  889. MMGenToolCmdRPC,
  890. MMGenToolCmdMonero,
  891. ): pass