main_tool.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2022 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. mmgen-tool: Perform various MMGen- and cryptocoin-related operations.
  20. Part of the MMGen suite
  21. """
  22. import os,importlib
  23. from .common import *
  24. opts_data = {
  25. 'text': {
  26. 'desc': f'Perform various {g.proj_name}- and cryptocoin-related operations',
  27. 'usage': '[opts] <command> <command args>',
  28. 'options': """
  29. -d, --outdir= d Specify an alternate directory 'd' for output
  30. -h, --help Print this help message
  31. --, --longhelp Print help message for long options (common options)
  32. -e, --echo-passphrase Echo passphrase or mnemonic to screen upon entry
  33. -k, --use-internal-keccak-module Force use of the internal keccak module
  34. -K, --keygen-backend=n Use backend 'n' for public key generation. Options
  35. for {coin_id}: {kgs}
  36. -l, --list List available commands
  37. -p, --hash-preset= p Use the scrypt hash parameters defined by preset 'p'
  38. for password hashing (default: '{g.dfl_hash_preset}')
  39. -P, --passwd-file= f Get passphrase from file 'f'.
  40. -q, --quiet Produce quieter output
  41. -r, --usr-randchars=n Get 'n' characters of additional randomness from
  42. user (min={g.min_urandchars}, max={g.max_urandchars})
  43. -t, --type=t Specify address type (valid choices: 'legacy',
  44. 'compressed', 'segwit', 'bech32', 'zcash_z')
  45. -v, --verbose Produce more verbose output
  46. -X, --cached-balances Use cached balances (Ethereum only)
  47. -y, --yes Answer 'yes' to prompts, suppress non-essential output
  48. """,
  49. 'notes': """
  50. COMMANDS
  51. {ch}
  52. Type ‘{pn} help <command>’ for help on a particular command
  53. """
  54. },
  55. 'code': {
  56. 'options': lambda s, help_notes: s.format(
  57. kgs=help_notes('keygen_backends'),
  58. coin_id=help_notes('coin_id'),
  59. g=g,
  60. ),
  61. 'notes': lambda s, help_notes: s.format(
  62. ch=help_notes('tool_help'),
  63. pn=g.prog_name)
  64. }
  65. }
  66. # NB: Command groups and commands are displayed on the help screen in the following order,
  67. # so keep the command names sorted
  68. mods = {
  69. 'help': (
  70. 'help',
  71. 'usage',
  72. ),
  73. 'util': (
  74. 'b32tohex',
  75. 'b58chktohex',
  76. 'b58tobytes',
  77. 'b58tohex',
  78. 'b6dtohex',
  79. 'bytespec',
  80. 'bytestob58',
  81. 'hash160',
  82. 'hash256',
  83. 'hexdump',
  84. 'hexlify',
  85. 'hexreverse',
  86. 'hextob32',
  87. 'hextob58',
  88. 'hextob58chk',
  89. 'hextob6d',
  90. 'id6',
  91. 'id8',
  92. 'randb58',
  93. 'randhex',
  94. 'str2id6',
  95. 'to_bytespec',
  96. 'unhexdump',
  97. 'unhexlify',
  98. ),
  99. 'coin': (
  100. 'addr2pubhash',
  101. 'addr2scriptpubkey',
  102. 'eth_checksummed_addr',
  103. 'hex2wif',
  104. 'privhex2addr',
  105. 'privhex2pubhex',
  106. 'pubhash2addr',
  107. 'pubhex2addr',
  108. 'pubhex2redeem_script',
  109. 'randpair',
  110. 'randwif',
  111. 'redeem_script2addr',
  112. 'scriptpubkey2addr',
  113. 'wif2addr',
  114. 'wif2hex',
  115. 'wif2redeem_script',
  116. 'wif2segwit_pair',
  117. ),
  118. 'mnemonic': (
  119. 'hex2mn',
  120. 'mn2hex',
  121. 'mn2hex_interactive',
  122. 'mn_printlist',
  123. 'mn_rand128',
  124. 'mn_rand192',
  125. 'mn_rand256',
  126. 'mn_stats',
  127. ),
  128. 'file': (
  129. 'addrfile_chksum',
  130. 'keyaddrfile_chksum',
  131. 'passwdfile_chksum',
  132. 'txview',
  133. ),
  134. 'filecrypt': (
  135. 'decrypt',
  136. 'encrypt',
  137. ),
  138. 'fileutil': (
  139. 'extract_key_from_geth_wallet',
  140. 'find_incog_data',
  141. 'rand2file',
  142. ),
  143. 'wallet': (
  144. 'gen_addr',
  145. 'gen_key',
  146. 'get_subseed',
  147. 'get_subseed_by_seed_id',
  148. 'list_shares',
  149. 'list_subseeds',
  150. ),
  151. 'rpc': (
  152. 'add_label',
  153. 'daemon_version',
  154. 'getbalance',
  155. 'listaddress',
  156. 'listaddresses',
  157. 'remove_address',
  158. 'remove_label',
  159. 'rescan_address',
  160. 'rescan_blockchain',
  161. 'resolve_address',
  162. 'twexport',
  163. 'twimport',
  164. 'twview',
  165. 'txhist',
  166. ),
  167. }
  168. def create_call_sig(cmd,cls,as_string=False):
  169. m = getattr(cls,cmd)
  170. if 'varargs_call_sig' in m.__code__.co_varnames: # hack
  171. flag = 'VAR_ARGS'
  172. va = m.__defaults__[0]
  173. args,dfls,ann = va['args'],va['dfls'],va['annots']
  174. else:
  175. flag = None
  176. args = m.__code__.co_varnames[1:m.__code__.co_argcount]
  177. dfls = m.__defaults__ or ()
  178. ann = m.__annotations__
  179. nargs = len(args) - len(dfls)
  180. dfl_types = tuple(
  181. ann[a] if a in ann and isinstance(ann[a],type) else type(dfls[i])
  182. for i,a in enumerate(args[nargs:]) )
  183. if as_string:
  184. get_type_from_ann = lambda x: 'str or STDIN' if ann[x] == 'sstr' else ann[x].__name__
  185. return ' '.join(
  186. [f'{a} [{get_type_from_ann(a)}]' for a in args[:nargs]] +
  187. ['{a} [{b}={c!r}]'.format(
  188. a = a,
  189. b = dfl_types[n].__name__,
  190. c = dfls[n] )
  191. for n,a in enumerate(args[nargs:])] )
  192. else:
  193. get_type_from_ann = lambda x: 'str' if ann[x] == 'sstr' else ann[x].__name__
  194. return (
  195. [(a,get_type_from_ann(a)) for a in args[:nargs]], # c_args
  196. dict([(a,dfls[n]) for n,a in enumerate(args[nargs:])]), # c_kwargs
  197. dict([(a,dfl_types[n]) for n,a in enumerate(args[nargs:])]), # c_kwargs_types
  198. ('STDIN_OK' if nargs and ann[args[0]] == 'sstr' else flag), # flag
  199. ann ) # ann
  200. def process_args(cmd,cmd_args,cls):
  201. c_args,c_kwargs,c_kwargs_types,flag,ann = create_call_sig(cmd,cls)
  202. have_stdin_input = False
  203. def usage_die(s):
  204. msg(s)
  205. from .tool.help import usage
  206. usage(cmd)
  207. if flag != 'VAR_ARGS':
  208. if len(cmd_args) < len(c_args):
  209. usage_die(f'Command requires exactly {len(c_args)} non-keyword argument{suf(c_args)}')
  210. u_args = cmd_args[:len(c_args)]
  211. # If we're reading from a pipe, replace '-' with output of previous command
  212. if flag == 'STDIN_OK' and u_args and u_args[0] == '-':
  213. if sys.stdin.isatty():
  214. die( 'BadFilename', "Standard input is a TTY. Can't use '-' as a filename" )
  215. else:
  216. from .util2 import parse_bytespec
  217. max_dlen_spec = '10kB' # limit input to 10KB for now
  218. max_dlen = parse_bytespec(max_dlen_spec)
  219. u_args[0] = os.read(0,max_dlen)
  220. have_stdin_input = True
  221. if len(u_args[0]) >= max_dlen:
  222. die(2,f'Maximum data input for this command is {max_dlen_spec}')
  223. if not u_args[0]:
  224. die(2,f'{cmd}: ERROR: no output from previous command in pipe')
  225. u_nkwargs = len(cmd_args) - len(c_args)
  226. u_kwargs = {}
  227. if flag == 'VAR_ARGS':
  228. cmd_args = ['dummy_arg'] + cmd_args
  229. t = [a.split('=',1) for a in cmd_args if '=' in a]
  230. tk = [a[0] for a in t]
  231. tk_bad = [a for a in tk if a not in c_kwargs]
  232. if set(tk_bad) != set(tk[:len(tk_bad)]): # permit non-kw args to contain '='
  233. die(1,f'{tk_bad[-1]!r}: illegal keyword argument')
  234. u_kwargs = dict(t[len(tk_bad):])
  235. u_args = cmd_args[:-len(u_kwargs) or None]
  236. elif u_nkwargs > 0:
  237. u_kwargs = dict([a.split('=',1) for a in cmd_args[len(c_args):] if '=' in a])
  238. if len(u_kwargs) != u_nkwargs:
  239. usage_die(f'Command requires exactly {len(c_args)} non-keyword argument{suf(c_args)}')
  240. if len(u_kwargs) > len(c_kwargs):
  241. usage_die(f'Command accepts no more than {len(c_kwargs)} keyword argument{suf(c_kwargs)}')
  242. for k in u_kwargs:
  243. if k not in c_kwargs:
  244. usage_die(f'{k!r}: invalid keyword argument')
  245. def conv_type(arg,arg_name,arg_type):
  246. if arg_type == 'bytes' and type(arg) != bytes:
  247. die(1,"'Binary input data must be supplied via STDIN")
  248. if have_stdin_input and arg_type == 'str' and isinstance(arg,bytes):
  249. from .globalvars import g
  250. NL = '\r\n' if g.platform == 'win' else '\n'
  251. arg = arg.decode()
  252. if arg[-len(NL):] == NL: # rstrip one newline
  253. arg = arg[:-len(NL)]
  254. if arg_type == 'bool':
  255. if arg.lower() in ('true','yes','1','on'):
  256. arg = True
  257. elif arg.lower() in ('false','no','0','off'):
  258. arg = False
  259. else:
  260. usage_die(f'{arg!r}: invalid boolean value for keyword argument')
  261. try:
  262. return __builtins__[arg_type](arg)
  263. except:
  264. die(1,f'{arg!r}: Invalid argument for argument {arg_name} ({arg_type!r} required)')
  265. if flag == 'VAR_ARGS':
  266. args = [conv_type(u_args[i],c_args[0][0],c_args[0][1]) for i in range(len(u_args))]
  267. else:
  268. args = [conv_type(u_args[i],c_args[i][0],c_args[i][1]) for i in range(len(c_args))]
  269. kwargs = {k:conv_type(u_kwargs[k],k,c_kwargs_types[k].__name__) for k in u_kwargs}
  270. return ( args, kwargs )
  271. def process_result(ret,pager=False,print_result=False):
  272. """
  273. Convert result to something suitable for output to screen and return it.
  274. If result is bytes and not convertible to utf8, output as binary using os.write().
  275. If 'print_result' is True, send the converted result directly to screen or
  276. pager instead of returning it.
  277. """
  278. from .util import Msg,die
  279. def triage_result(o):
  280. if print_result:
  281. if pager:
  282. from .ui import do_pager
  283. do_pager(o)
  284. else:
  285. Msg(o)
  286. else:
  287. return o
  288. if ret == True:
  289. return True
  290. elif ret in (False,None):
  291. die(2,f'tool command returned {ret!r}')
  292. elif isinstance(ret,str):
  293. return triage_result(ret)
  294. elif isinstance(ret,int):
  295. return triage_result(str(ret))
  296. elif isinstance(ret,tuple):
  297. return triage_result('\n'.join([r.decode() if isinstance(r,bytes) else r for r in ret]))
  298. elif isinstance(ret,bytes):
  299. try:
  300. return triage_result(ret.decode())
  301. except:
  302. # don't add NL to binary data if it can't be converted to utf8
  303. if print_result:
  304. return os.write(1,ret)
  305. else:
  306. return ret
  307. else:
  308. die(2,f'tool.py: can’t handle return value of type {type(ret).__name__!r}')
  309. def get_cmd_cls(cmd):
  310. for modname,cmdlist in mods.items():
  311. if cmd in cmdlist:
  312. return getattr(importlib.import_module(f'mmgen.tool.{modname}'),'tool_cmd')
  313. else:
  314. return False
  315. def get_mod_cls(modname):
  316. return getattr(importlib.import_module(f'mmgen.tool.{modname}'),'tool_cmd')
  317. if g.prog_name == 'mmgen-tool' and not opt._lock:
  318. po = opts.init( opts_data, parse_only=True )
  319. if po.user_opts.get('list'):
  320. def gen():
  321. for mod,cmdlist in mods.items():
  322. if mod == 'help':
  323. continue
  324. yield capfirst( get_mod_cls(mod).__doc__.lstrip().split('\n')[0] ) + ':'
  325. for cmd in cmdlist:
  326. yield ' ' + cmd
  327. yield ''
  328. Msg('\n'.join(gen()).rstrip())
  329. sys.exit(0)
  330. if len(po.cmd_args) < 1:
  331. opts.usage()
  332. cls = get_cmd_cls(po.cmd_args[0])
  333. if not cls:
  334. die(1,f'{po.cmd_args[0]!r}: no such command')
  335. cmd,*args = opts.init( opts_data, parsed_opts=po, need_proto=cls.need_proto )
  336. if cmd in ('help','usage') and args:
  337. args[0] = 'command_name=' + args[0]
  338. args,kwargs = process_args(cmd,args,cls)
  339. ret = getattr(cls(cmdname=cmd),cmd)(*args,**kwargs)
  340. if type(ret).__name__ == 'coroutine':
  341. ret = async_run(ret)
  342. process_result(
  343. ret,
  344. pager = kwargs.get('pager'),
  345. print_result = True )