tool.py 37 KB

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