tool.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071
  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(bytes.fromhex(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).hex()
  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. def hextob6d(self,hexstr:'sstr',pad=0,add_spaces=True):
  298. "convert a hexadecimal number to die roll base6 (base6d)"
  299. ret = baseconv.fromhex(hexstr,'b6d',pad,tostr=True)
  300. return block_format(ret,gw=5,cols=None).strip() if add_spaces else ret
  301. def b6dtohex(self,b6d_num:'sstr',pad=0):
  302. "convert a die roll base6 (base6d) number to hexadecimal"
  303. return baseconv.tohex(remove_whitespace(b6d_num),'b6d',pad)
  304. class MMGenToolCmdCoin(MMGenToolCmdBase):
  305. """
  306. cryptocoin key/address utilities
  307. May require use of the '--coin', '--type' and/or '--testnet' options
  308. Examples:
  309. mmgen-tool --coin=ltc --type=bech32 wif2addr <wif key>
  310. mmgen-tool --coin=zec --type=zcash_z randpair
  311. """
  312. def randwif(self):
  313. "generate a random private key in WIF format"
  314. init_generators('at')
  315. return PrivKey(get_random(32),pubkey_type=at.pubkey_type,compressed=at.compressed).wif
  316. def randpair(self):
  317. "generate a random private key/address pair"
  318. init_generators()
  319. privhex = PrivKey(get_random(32),pubkey_type=at.pubkey_type,compressed=at.compressed)
  320. addr = ag.to_addr(kg.to_pubhex(privhex))
  321. return (privhex.wif,addr)
  322. def wif2hex(self,wifkey:'sstr'):
  323. "convert a private key from WIF to hex format"
  324. return PrivKey(wif=wifkey)
  325. def hex2wif(self,privhex:'sstr'):
  326. "convert a private key from hex to WIF format"
  327. init_generators('at')
  328. return g.proto.hex2wif(privhex,pubkey_type=at.pubkey_type,compressed=at.compressed)
  329. def wif2addr(self,wifkey:'sstr'):
  330. "generate a coin address from a key in WIF format"
  331. init_generators()
  332. privhex = PrivKey(wif=wifkey)
  333. addr = ag.to_addr(kg.to_pubhex(privhex))
  334. return addr
  335. def wif2redeem_script(self,wifkey:'sstr'): # new
  336. "convert a WIF private key to a Segwit P2SH-P2WPKH redeem script"
  337. assert opt.type == 'segwit','This command is meaningful only for --type=segwit'
  338. init_generators()
  339. privhex = PrivKey(wif=wifkey)
  340. return ag.to_segwit_redeem_script(kg.to_pubhex(privhex))
  341. def wif2segwit_pair(self,wifkey:'sstr'):
  342. "generate both a Segwit P2SH-P2WPKH redeem script and address from WIF"
  343. assert opt.type == 'segwit','This command is meaningful only for --type=segwit'
  344. init_generators()
  345. pubhex = kg.to_pubhex(PrivKey(wif=wifkey))
  346. addr = ag.to_addr(pubhex)
  347. rs = ag.to_segwit_redeem_script(pubhex)
  348. return (rs,addr)
  349. def privhex2addr(self,privhex:'sstr',output_pubhex=False):
  350. "generate coin address from raw private key data in hexadecimal format"
  351. init_generators()
  352. pk = PrivKey(bytes.fromhex(privhex),compressed=at.compressed,pubkey_type=at.pubkey_type)
  353. ph = kg.to_pubhex(pk)
  354. return ph if output_pubhex else ag.to_addr(ph)
  355. def privhex2pubhex(self,privhex:'sstr'): # new
  356. "generate a hex public key from a hex private key"
  357. return self.privhex2addr(privhex,output_pubhex=True)
  358. def pubhex2addr(self,pubkeyhex:'sstr'):
  359. "convert a hex pubkey to an address"
  360. if opt.type == 'segwit':
  361. return g.proto.pubhex2segwitaddr(pubkeyhex)
  362. else:
  363. return self.pubhash2addr(hash160(pubkeyhex))
  364. def pubhex2redeem_script(self,pubkeyhex:'sstr'): # new
  365. "convert a hex pubkey to a Segwit P2SH-P2WPKH redeem script"
  366. assert opt.type == 'segwit','This command is meaningful only for --type=segwit'
  367. return g.proto.pubhex2redeem_script(pubkeyhex)
  368. def redeem_script2addr(self,redeem_scripthex:'sstr'): # new
  369. "convert a Segwit P2SH-P2WPKH redeem script to an address"
  370. assert opt.type == 'segwit','This command is meaningful only for --type=segwit'
  371. assert redeem_scripthex[:4] == '0014','{!r}: invalid redeem script'.format(redeem_scripthex)
  372. assert len(redeem_scripthex) == 44,'{} bytes: invalid redeem script length'.format(len(redeem_scripthex)//2)
  373. return self.pubhash2addr(self.hash160(redeem_scripthex))
  374. def pubhash2addr(self,pubhashhex:'sstr'):
  375. "convert public key hash to address"
  376. if opt.type == 'bech32':
  377. return g.proto.pubhash2bech32addr(pubhashhex)
  378. else:
  379. init_generators('at')
  380. return g.proto.pubhash2addr(pubhashhex,at.addr_fmt=='p2sh')
  381. def addr2pubhash(self,addr:'sstr'):
  382. "convert coin address to public key hash"
  383. from mmgen.tx import addr2pubhash
  384. return addr2pubhash(CoinAddr(addr))
  385. def addr2scriptpubkey(self,addr:'sstr'):
  386. "convert coin address to scriptPubKey"
  387. from mmgen.tx import addr2scriptPubKey
  388. return addr2scriptPubKey(CoinAddr(addr))
  389. def scriptpubkey2addr(self,hexstr:'sstr'):
  390. "convert scriptPubKey to coin address"
  391. from mmgen.tx import scriptPubKey2addr
  392. return scriptPubKey2addr(hexstr)[0]
  393. class MMGenToolCmdMnemonic(MMGenToolCmdBase):
  394. """
  395. seed phrase utilities (valid formats: 'mmgen' (default), 'bip39')
  396. IMPORTANT NOTE: MMGen's default seed phrase format uses the Electrum
  397. wordlist, however seed phrases are computed using a different algorithm
  398. and are NOT Electrum-compatible!
  399. BIP39 support is fully compatible with the standard, allowing users to
  400. import and export seed entropy from BIP39-compatible wallets. However,
  401. users should be aware that BIP39 support does not imply BIP32 support!
  402. MMGen uses its own key derivation scheme differing from the one described
  403. by the BIP32 protocol.
  404. """
  405. def _do_random_mn(self,nbytes:int,fmt:str):
  406. assert nbytes in (16,24,32), 'nbytes must be 16, 24 or 32'
  407. hexrand = get_random(nbytes).hex()
  408. Vmsg('Seed: {}'.format(hexrand))
  409. return self.hex2mn(hexrand,fmt=fmt)
  410. def mn_rand128(self, fmt:mn_opts_disp = dfl_mnemonic_fmt ):
  411. "generate random 128-bit mnemonic seed phrase"
  412. return self._do_random_mn(16,fmt)
  413. def mn_rand192(self, fmt:mn_opts_disp = dfl_mnemonic_fmt ):
  414. "generate random 192-bit mnemonic seed phrase"
  415. return self._do_random_mn(24,fmt)
  416. def mn_rand256(self, fmt:mn_opts_disp = dfl_mnemonic_fmt ):
  417. "generate random 256-bit mnemonic seed phrase"
  418. return self._do_random_mn(32,fmt)
  419. def _get_mnemonic_fmt(self,fmt):
  420. if fmt not in mnemonic_fmts:
  421. m = '{!r}: invalid format (valid options: {})'
  422. die(1,m.format(fmt,', '.join(mnemonic_fmts)))
  423. return mnemonic_fmts[fmt]['fmt']
  424. def hex2mn( self, hexstr:'sstr', fmt:mn_opts_disp = dfl_mnemonic_fmt ):
  425. "convert a 16, 24 or 32-byte hexadecimal number to a mnemonic seed phrase"
  426. opt.out_fmt = self._get_mnemonic_fmt(fmt)
  427. from mmgen.seed import SeedSource
  428. s = SeedSource(seed_bin=bytes.fromhex(hexstr))
  429. s._format()
  430. return ' '.join(s.ssdata.mnemonic)
  431. def mn2hex( self, seed_mnemonic:'sstr', fmt:mn_opts_disp = dfl_mnemonic_fmt ):
  432. "convert a 12, 18 or 24-word mnemonic seed phrase to a hexadecimal number"
  433. in_fmt = self._get_mnemonic_fmt(fmt)
  434. opt.quiet = True
  435. from mmgen.seed import SeedSource
  436. return SeedSource(in_data=seed_mnemonic,in_fmt=in_fmt).seed.hexdata
  437. def mn_stats(self, fmt:mn_opts_disp = dfl_mnemonic_fmt ):
  438. "show stats for mnemonic wordlist"
  439. conv_cls = mnemonic_fmts[fmt]['conv_cls']()
  440. conv_cls.check_wordlist(fmt)
  441. return True
  442. def mn_printlist( self, fmt:mn_opts_disp = dfl_mnemonic_fmt, enum=False, pager=False ):
  443. "print mnemonic wordlist"
  444. conv_cls = mnemonic_fmts[fmt]['conv_cls']()
  445. ret = conv_cls.get_wordlist(fmt)
  446. if enum:
  447. ret = ['{:>4} {}'.format(n,e) for n,e in enumerate(ret)]
  448. return '\n'.join(ret)
  449. class MMGenToolCmdFile(MMGenToolCmdBase):
  450. "utilities for viewing/checking MMGen address and transaction files"
  451. def _file_chksum(self,mmgen_addrfile,objname):
  452. opt.yes = True
  453. opt.quiet = True
  454. from mmgen.addr import AddrList,KeyAddrList,PasswordList
  455. ret = locals()[objname](mmgen_addrfile)
  456. if opt.verbose:
  457. if ret.al_id.mmtype.name == 'password':
  458. fs = 'Passwd fmt: {}\nPasswd len: {}\nID string: {}'
  459. msg(fs.format(capfirst(ret.pw_info[ret.pw_fmt].desc),ret.pw_len,ret.pw_id_str))
  460. else:
  461. msg('Base coin: {} {}'.format(ret.base_coin,('Mainnet','Testnet')[ret.is_testnet]))
  462. msg('MMType: {}'.format(capfirst(ret.al_id.mmtype.name)))
  463. msg('List length: {}'.format(len(ret.data)))
  464. return ret.chksum
  465. def addrfile_chksum(self,mmgen_addrfile:str):
  466. "compute checksum for MMGen address file"
  467. return self._file_chksum(mmgen_addrfile,'AddrList')
  468. def keyaddrfile_chksum(self,mmgen_keyaddrfile:str):
  469. "compute checksum for MMGen key-address file"
  470. return self._file_chksum(mmgen_keyaddrfile,'KeyAddrList')
  471. def passwdfile_chksum(self,mmgen_passwdfile:str):
  472. "compute checksum for MMGen password file"
  473. return self._file_chksum(mmgen_passwdfile,'PasswordList')
  474. def txview( varargs_call_sig = { # hack to allow for multiple filenames
  475. 'args': (
  476. 'mmgen_tx_file(s)',
  477. 'pager',
  478. 'terse',
  479. 'sort',
  480. 'filesort' ),
  481. 'dfls': ( False, False, 'addr', 'mtime' ),
  482. 'annots': {
  483. 'mmgen_tx_file(s)': str,
  484. 'sort': '(valid options: addr,raw)',
  485. 'filesort': '(valid options: mtime,ctime,atime)'
  486. } },
  487. *infiles,**kwargs):
  488. "show raw/signed MMGen transaction in human-readable form"
  489. terse = bool(kwargs.get('terse'))
  490. tx_sort = kwargs.get('sort') or 'addr'
  491. file_sort = kwargs.get('filesort') or 'mtime'
  492. from mmgen.filename import MMGenFileList
  493. from mmgen.tx import MMGenTX
  494. flist = MMGenFileList(infiles,ftype=MMGenTX)
  495. flist.sort_by_age(key=file_sort) # in-place sort
  496. sep = '—'*77+'\n'
  497. return sep.join(
  498. [MMGenTX(fn,offline=True).format_view(terse=terse,sort=tx_sort) for fn in flist.names()]
  499. ).rstrip()
  500. class MMGenToolCmdFileCrypt(MMGenToolCmdBase):
  501. """
  502. file encryption and decryption
  503. MMGen encryption suite:
  504. * Key: Scrypt (user-configurable hash parameters, 32-byte salt)
  505. * Enc: AES256_CTR, 16-byte rand IV, sha256 hash + 32-byte nonce + data
  506. * The encrypted file is indistinguishable from random data
  507. """
  508. def encrypt(self,infile:str,outfile='',hash_preset=''):
  509. "encrypt a file"
  510. data = get_data_from_file(infile,'data for encryption',binary=True)
  511. enc_d = mmgen_encrypt(data,'user data',hash_preset)
  512. if not outfile:
  513. outfile = '{}.{}'.format(os.path.basename(infile),g.mmenc_ext)
  514. write_data_to_file(outfile,enc_d,'encrypted data',binary=True)
  515. return True
  516. def decrypt(self,infile:str,outfile='',hash_preset=''):
  517. "decrypt a file"
  518. enc_d = get_data_from_file(infile,'encrypted data',binary=True)
  519. while True:
  520. dec_d = mmgen_decrypt(enc_d,'user data',hash_preset)
  521. if dec_d: break
  522. msg('Trying again...')
  523. if not outfile:
  524. o = os.path.basename(infile)
  525. outfile = remove_extension(o,g.mmenc_ext)
  526. if outfile == o: outfile += '.dec'
  527. write_data_to_file(outfile,dec_d,'decrypted data',binary=True)
  528. return True
  529. class MMGenToolCmdFileUtil(MMGenToolCmdBase):
  530. "file utilities"
  531. def find_incog_data(self,filename:str,incog_id:str,keep_searching=False):
  532. "Use an Incog ID to find hidden incognito wallet data"
  533. ivsize,bsize,mod = g.aesctr_iv_len,4096,4096*8
  534. n,carry = 0,b' '*ivsize
  535. flgs = os.O_RDONLY|os.O_BINARY if g.platform == 'win' else os.O_RDONLY
  536. f = os.open(filename,flgs)
  537. for ch in incog_id:
  538. if ch not in '0123456789ABCDEF':
  539. die(2,"'{}': invalid Incog ID".format(incog_id))
  540. while True:
  541. d = os.read(f,bsize)
  542. if not d: break
  543. d = carry + d
  544. for i in range(bsize):
  545. if sha256(d[i:i+ivsize]).hexdigest()[:8].upper() == incog_id:
  546. if n+i < ivsize: continue
  547. msg('\rIncog data for ID {} found at offset {}'.format(incog_id,n+i-ivsize))
  548. if not keep_searching: sys.exit(0)
  549. carry = d[len(d)-ivsize:]
  550. n += bsize
  551. if not n % mod:
  552. msg_r('\rSearched: {} bytes'.format(n))
  553. msg('')
  554. os.close(f)
  555. return True
  556. def rand2file(self,outfile:str,nbytes:str,threads=4,silent=False):
  557. "write 'n' bytes of random data to specified file"
  558. from threading import Thread
  559. from queue import Queue
  560. from cryptography.hazmat.primitives.ciphers import Cipher,algorithms,modes
  561. from cryptography.hazmat.backends import default_backend
  562. def encrypt_worker(wid):
  563. ctr_init_val = os.urandom(g.aesctr_iv_len)
  564. c = Cipher(algorithms.AES(key),modes.CTR(ctr_init_val),backend=default_backend())
  565. encryptor = c.encryptor()
  566. while True:
  567. q2.put(encryptor.update(q1.get()))
  568. q1.task_done()
  569. def output_worker():
  570. while True:
  571. f.write(q2.get())
  572. q2.task_done()
  573. nbytes = parse_bytespec(nbytes)
  574. if opt.outdir:
  575. outfile = make_full_path(opt.outdir,outfile)
  576. f = open(outfile,'wb')
  577. key = get_random(32)
  578. q1,q2 = Queue(),Queue()
  579. for i in range(max(1,threads-2)):
  580. t = Thread(target=encrypt_worker,args=[i])
  581. t.daemon = True
  582. t.start()
  583. t = Thread(target=output_worker)
  584. t.daemon = True
  585. t.start()
  586. blk_size = 1024 * 1024
  587. for i in range(nbytes // blk_size):
  588. if not i % 4:
  589. msg_r('\rRead: {} bytes'.format(i * blk_size))
  590. q1.put(os.urandom(blk_size))
  591. if nbytes % blk_size:
  592. q1.put(os.urandom(nbytes % blk_size))
  593. q1.join()
  594. q2.join()
  595. f.close()
  596. fsize = os.stat(outfile).st_size
  597. if fsize != nbytes:
  598. die(3,'{}: incorrect random file size (should be {})'.format(fsize,nbytes))
  599. if not silent:
  600. msg('\rRead: {} bytes'.format(nbytes))
  601. qmsg("\r{} byte{} of random data written to file '{}'".format(nbytes,suf(nbytes),outfile))
  602. return True
  603. class MMGenToolCmdWallet(MMGenToolCmdBase):
  604. "key, address or subseed generation from an MMGen wallet"
  605. def get_subseed(self,subseed_idx:str,wallet=''):
  606. "get the Seed ID of a single subseed by Subseed Index for default or specified wallet"
  607. opt.quiet = True
  608. sf = get_seed_file([wallet] if wallet else [],1)
  609. from mmgen.seed import SeedSource
  610. return SeedSource(sf).seed.subseed(subseed_idx).sid
  611. def get_subseed_by_seed_id(self,seed_id:str,wallet='',last_idx=g.subseeds):
  612. "get the Subseed Index of a single subseed by Seed ID 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. ret = SeedSource(sf).seed.subseed_by_seed_id(seed_id,last_idx)
  617. return ret.ss_idx if ret else None
  618. def list_subseeds(self,subseed_idx_range:str,wallet=''):
  619. "list a range of subseed Seed IDs for default or specified wallet"
  620. opt.quiet = True
  621. sf = get_seed_file([wallet] if wallet else [],1)
  622. from mmgen.seed import SeedSource
  623. return SeedSource(sf).seed.subseeds.format(*SubSeedIdxRange(subseed_idx_range))
  624. def list_shares(self,
  625. share_count:int,
  626. id_str='default',
  627. master_share:"(min:1, max:{}, 0=no master share)".format(MasterShareIdx.max_val)=0,
  628. wallet=''):
  629. "list the Seed IDs of the shares resulting from a split of default or specified wallet"
  630. opt.quiet = True
  631. sf = get_seed_file([wallet] if wallet else [],1)
  632. from mmgen.seed import SeedSource
  633. return SeedSource(sf).seed.split(share_count,id_str,master_share).format()
  634. def gen_key(self,mmgen_addr:str,wallet=''):
  635. "generate a single MMGen WIF key from default or specified wallet"
  636. return self.gen_addr(mmgen_addr,wallet,target='wif')
  637. def gen_addr(self,mmgen_addr:str,wallet='',target='addr'):
  638. "generate a single MMGen address from default or specified wallet"
  639. addr = MMGenID(mmgen_addr)
  640. opt.quiet = True
  641. sf = get_seed_file([wallet] if wallet else [],1)
  642. from mmgen.seed import SeedSource
  643. ss = SeedSource(sf)
  644. if ss.seed.sid != addr.sid:
  645. m = 'Seed ID of requested address ({}) does not match wallet ({})'
  646. die(1,m.format(addr.sid,ss.seed.sid))
  647. al = AddrList(seed=ss.seed,addr_idxs=AddrIdxList(str(addr.idx)),mmtype=addr.mmtype)
  648. d = al.data[0]
  649. ret = d.sec.wif if target=='wif' else d.addr
  650. return ret
  651. class MMGenToolCmdRPC(MMGenToolCmdBase):
  652. "tracking wallet commands using the JSON-RPC interface"
  653. def getbalance(self,minconf=1,quiet=False,pager=False):
  654. "list confirmed/unconfirmed, spendable/unspendable balances in tracking wallet"
  655. from mmgen.tw import TwGetBalance
  656. return TwGetBalance(minconf,quiet).format()
  657. def listaddress(self,
  658. mmgen_addr:str,
  659. minconf = 1,
  660. pager = False,
  661. showempty = True,
  662. showbtcaddr = True,
  663. age_fmt:'(valid options: days,confs)' = ''):
  664. "list the specified MMGen address and its balance"
  665. return self.listaddresses( mmgen_addrs = mmgen_addr,
  666. minconf = minconf,
  667. pager = pager,
  668. showempty = showempty,
  669. showbtcaddrs = showbtcaddr,
  670. age_fmt = age_fmt)
  671. def listaddresses( self,
  672. mmgen_addrs:'(range or list)' = '',
  673. minconf = 1,
  674. showempty = False,
  675. pager = False,
  676. showbtcaddrs = True,
  677. all_labels = False,
  678. sort:'(valid options: reverse,age)' = '',
  679. age_fmt:'(valid options: days,confs)' = ''):
  680. "list MMGen addresses and their balances"
  681. show_age = bool(age_fmt)
  682. if sort:
  683. sort = set(sort.split(','))
  684. sort_params = {'reverse','age'}
  685. if not sort.issubset(sort_params):
  686. die(1,"The sort option takes the following parameters: '{}'".format("','".join(sort_params)))
  687. usr_addr_list = []
  688. if mmgen_addrs:
  689. a = mmgen_addrs.rsplit(':',1)
  690. if len(a) != 2:
  691. m = "'{}': invalid address list argument (must be in form <seed ID>:[<type>:]<idx list>)"
  692. die(1,m.format(mmgen_addrs))
  693. usr_addr_list = [MMGenID('{}:{}'.format(a[0],i)) for i in AddrIdxList(a[1])]
  694. rpc_init()
  695. from mmgen.tw import TwAddrList
  696. al = TwAddrList(usr_addr_list,minconf,showempty,showbtcaddrs,all_labels)
  697. if not al:
  698. die(0,('No tracked addresses with balances!','No tracked addresses!')[showempty])
  699. return al.format(showbtcaddrs,sort,show_age,age_fmt or 'days')
  700. def twview( self,
  701. pager = False,
  702. reverse = False,
  703. wide = False,
  704. minconf = 1,
  705. sort = 'age',
  706. age_fmt:'(valid options: days,confs)' = 'days',
  707. show_mmid = True):
  708. "view tracking wallet"
  709. rpc_init()
  710. from mmgen.tw import TwUnspentOutputs
  711. twuo = TwUnspentOutputs(minconf=minconf)
  712. twuo.do_sort(sort,reverse=reverse)
  713. twuo.age_fmt = age_fmt
  714. twuo.show_mmid = show_mmid
  715. ret = twuo.format_for_printing(color=True) if wide else twuo.format_for_display()
  716. del twuo.wallet
  717. return ret
  718. def add_label(self,mmgen_or_coin_addr:str,label:str):
  719. "add descriptive label for address in tracking wallet"
  720. rpc_init()
  721. from mmgen.tw import TrackingWallet
  722. TrackingWallet(mode='w').add_label(mmgen_or_coin_addr,label,on_fail='raise')
  723. return True
  724. def remove_label(self,mmgen_or_coin_addr:str):
  725. "remove descriptive label for address in tracking wallet"
  726. self.add_label(mmgen_or_coin_addr,'')
  727. return True
  728. def remove_address(self,mmgen_or_coin_addr:str):
  729. "remove an address from tracking wallet"
  730. from mmgen.tw import TrackingWallet
  731. tw = TrackingWallet(mode='w')
  732. ret = tw.remove_address(mmgen_or_coin_addr) # returns None on failure
  733. if ret:
  734. msg("Address '{}' deleted from tracking wallet".format(ret))
  735. return ret
  736. class MMGenToolCmdMonero(MMGenToolCmdBase):
  737. "Monero wallet utilities"
  738. def keyaddrlist2monerowallets( self,
  739. xmr_keyaddrfile:str,
  740. blockheight:'(default: current height)' = 0,
  741. addrs:'(integer range or list)' = ''):
  742. "create Monero wallets from key-address list"
  743. return self.monero_wallet_ops( infile = xmr_keyaddrfile,
  744. op = 'create',
  745. blockheight = blockheight,
  746. addrs = addrs)
  747. def syncmonerowallets(self,xmr_keyaddrfile:str,addrs:'(integer range or list)'=''):
  748. "sync Monero wallets from key-address list"
  749. return self.monero_wallet_ops(infile=xmr_keyaddrfile,op='sync',addrs=addrs)
  750. def monero_wallet_ops(self,infile:str,op:str,blockheight=0,addrs=''):
  751. exit_if_mswin('Monero wallet operations')
  752. def run_cmd(cmd):
  753. from subprocess import run,PIPE,DEVNULL
  754. return run(cmd,stdout=PIPE,stderr=DEVNULL,check=True)
  755. def test_rpc():
  756. cp = run_cmd(['monero-wallet-cli','--version'])
  757. if not b'Monero' in cp.stdout:
  758. die(1,"Unable to run 'monero-wallet-cli'!")
  759. cp = run_cmd(['monerod','status'])
  760. import re
  761. m = re.search(r'Height: (\d+)/\d+ ',cp.stdout.decode())
  762. if not m:
  763. die(1,'Unable to connect to monerod!')
  764. return int(m.group(1))
  765. def my_expect(p,m,s,regex=False):
  766. if m: msg_r(' {}...'.format(m))
  767. ret = (p.expect_exact,p.expect)[regex](s)
  768. vmsg("\nexpect: '{}' => {}".format(s,ret))
  769. if g.debug:
  770. pmsg('p.before:',p.before)
  771. pmsg('p.after:',p.after)
  772. if not (ret == 0 or (type(s) == list and ret in (0,1))):
  773. die(2,"Expect failed: '{}' (return value: {})".format(s,ret))
  774. if m: msg('OK')
  775. return ret
  776. def my_sendline(p,m,s,usr_ret):
  777. if m: msg_r(' {}...'.format(m))
  778. ret = p.sendline(s)
  779. if g.debug:
  780. pmsg('p.before:',p.before)
  781. pmsg('p.after:',p.after)
  782. if ret != usr_ret:
  783. die(2,"Unable to send line '{}' (return value {})".format(s,ret))
  784. if m: msg('OK')
  785. vmsg("sendline: '{}' => {}".format(s,ret))
  786. def create(n,d,fn):
  787. try: os.stat(fn)
  788. except: pass
  789. else: die(1,"Wallet '{}' already exists!".format(fn))
  790. p = pexpect.spawn('monero-wallet-cli --generate-from-spend-key {}'.format(fn))
  791. # if g.debug: p.logfile = sys.stdout # TODO: Error: 'write() argument must be str, not bytes'
  792. my_expect(p,'Awaiting initial prompt','Secret spend key: ')
  793. my_sendline(p,'',d.sec,65)
  794. my_expect(p,'','Enter.* new.* password.*: ',regex=True)
  795. my_sendline(p,'Sending password',d.wallet_passwd,33)
  796. my_expect(p,'','Confirm password: ')
  797. my_sendline(p,'Sending password again',d.wallet_passwd,33)
  798. my_expect(p,'','of your choice: ')
  799. my_sendline(p,'','1',2)
  800. my_expect(p,'monerod generating wallet','Generated new wallet: ')
  801. my_expect(p,'','\n')
  802. if d.addr not in p.before.decode():
  803. die(3,'Addresses do not match!\n MMGen: {}\n Monero: {}'.format(d.addr,p.before.decode()))
  804. my_expect(p,'','View key: ')
  805. my_expect(p,'','\n')
  806. if d.viewkey not in p.before.decode():
  807. die(3,'View keys do not match!\n MMGen: {}\n Monero: {}'.format(d.viewkey,p.before.decode()))
  808. my_expect(p,'','(YYYY-MM-DD): ')
  809. h = str(blockheight or cur_height-1)
  810. my_sendline(p,'',h,len(h)+1)
  811. ret = my_expect(p,'',['Starting refresh','Still apply restore height? (Y/Yes/N/No): '])
  812. if ret == 1:
  813. my_sendline(p,'','Y',2)
  814. m = ' Warning: {}: blockheight argument is higher than current blockheight'
  815. ymsg(m.format(blockheight))
  816. elif blockheight:
  817. p.logfile = sys.stderr
  818. my_expect(p,'Syncing wallet','\[wallet.*$',regex=True)
  819. p.logfile = None
  820. my_sendline(p,'Exiting','exit',5)
  821. p.read()
  822. def sync(n,d,fn):
  823. import time
  824. try: os.stat(fn)
  825. except: die(1,"Wallet '{}' does not exist!".format(fn))
  826. p = pexpect.spawn('monero-wallet-cli --wallet-file={}'.format(fn))
  827. # if g.debug: p.logfile = sys.stdout # TODO: Error: 'write() argument must be str, not bytes'
  828. my_expect(p,'Awaiting password prompt','Wallet password: ')
  829. my_sendline(p,'Sending password',d.wallet_passwd,33)
  830. msg(' Starting refresh...')
  831. height = None
  832. while True:
  833. ret = p.expect([r'Height\s+\S+\s+/\s+\S+',r'\[wallet.*:.*'])
  834. if ret == 0: # TODO: coverage
  835. d = p.after.decode().split()
  836. msg_r('\r Block {} / {}'.format(d[1],d[3]))
  837. height = d[3]
  838. time.sleep(0.5)
  839. elif ret == 1:
  840. if height:
  841. msg('\r Block {h} / {h} (wallet in sync)'.format(h=height))
  842. else:
  843. msg(' Wallet in sync')
  844. my_sendline(p,'Requesting account info','account',8)
  845. my_expect(p,'Getting totals','Total\s+.*\n',regex=True)
  846. b = p.after.decode().strip().split()[1:]
  847. msg(' Balance: {} Unlocked balance: {}'.format(*b))
  848. from mmgen.obj import XMRAmt
  849. bals[fn] = tuple(map(XMRAmt,b))
  850. my_sendline(p,'Exiting','exit',5)
  851. p.read()
  852. break
  853. else:
  854. die(2,"\nExpect failed: (return value: {})".format(ret))
  855. def process_wallets():
  856. m = { 'create': ('Creat','Generat',create,False),
  857. 'sync': ('Sync', 'Sync', sync, True) }
  858. opt.accept_defaults = opt.accept_defaults or m[op][3]
  859. from mmgen.protocol import init_coin
  860. init_coin('xmr')
  861. from mmgen.addr import AddrList
  862. al = KeyAddrList(infile)
  863. data = [d for d in al.data if addrs == '' or d.idx in AddrIdxList(addrs)]
  864. dl = len(data)
  865. assert dl,"No addresses in addrfile within range '{}'".format(addrs)
  866. gmsg('\n{}ing {} wallet{}'.format(m[op][0],dl,suf(dl)))
  867. for n,d in enumerate(data): # [d.sec,d.wallet_passwd,d.viewkey,d.addr]
  868. fn = os.path.join(
  869. opt.outdir or '','{}-{}-MoneroWallet{}'.format(
  870. al.al_id.sid,
  871. d.idx,
  872. '-α' if g.debug_utf8 else ''))
  873. gmsg('\n{}ing wallet {}/{} ({})'.format(m[op][1],n+1,dl,fn))
  874. m[op][2](n,d,fn)
  875. gmsg('\n{} wallet{} {}ed'.format(dl,suf(dl),m[op][0].lower()))
  876. if op == 'sync':
  877. col1_w = max(map(len,bals)) + 1
  878. fs = '{:%s} {} {}' % col1_w
  879. msg('\n'+fs.format('Wallet','Balance ','Unlocked Balance '))
  880. from mmgen.obj import XMRAmt
  881. tbals = [XMRAmt('0'),XMRAmt('0')]
  882. for bal in bals:
  883. for i in (0,1): tbals[i] += bals[bal][i]
  884. msg(fs.format(bal+':',*[XMRAmt(b).fmt(fs='5.12',color=True) for b in bals[bal]]))
  885. msg(fs.format('-'*col1_w,'-'*18,'-'*18))
  886. msg(fs.format('TOTAL:',*[XMRAmt(b).fmt(fs='5.12',color=True) for b in tbals]))
  887. os.environ['LANG'] = 'C'
  888. import pexpect
  889. if blockheight < 0:
  890. blockheight = 0 # TODO: handle the non-zero case
  891. cur_height = test_rpc() # empty blockchain returns 1
  892. from collections import OrderedDict
  893. bals = OrderedDict() # locked,unlocked
  894. try:
  895. process_wallets()
  896. except KeyboardInterrupt:
  897. rdie(1,'\nUser interrupt\n')
  898. except EOFError:
  899. rdie(2,'\nEnd of file\n')
  900. except Exception as e:
  901. try:
  902. die(1,'Error: {}'.format(e.args[0]))
  903. except:
  904. rdie(1,'Error: {!r}'.format(e.args[0]))
  905. return True
  906. class MMGenToolCmd(
  907. MMGenToolCmdMisc,
  908. MMGenToolCmdUtil,
  909. MMGenToolCmdCoin,
  910. MMGenToolCmdMnemonic,
  911. MMGenToolCmdFile,
  912. MMGenToolCmdFileCrypt,
  913. MMGenToolCmdFileUtil,
  914. MMGenToolCmdWallet,
  915. MMGenToolCmdRPC,
  916. MMGenToolCmdMonero,
  917. ): pass