opts.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. #!/usr/bin/env python
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2016 Philemon <mmgen-py@yandex.com>
  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. opts.py: MMGen-specific options processing after generic processing by share.Opts
  20. """
  21. import sys,os
  22. class opt(object): pass
  23. from mmgen.globalvars import g
  24. import mmgen.share.Opts
  25. from mmgen.util import *
  26. pw_note = """
  27. For passphrases all combinations of whitespace are equal and leading and
  28. trailing space is ignored. This permits reading passphrase or brainwallet
  29. data from a multi-line file with free spacing and indentation.
  30. """.strip()
  31. bw_note = """
  32. BRAINWALLET NOTE:
  33. To thwart dictionary attacks, it's recommended to use a strong hash preset
  34. with brainwallets. For a brainwallet passphrase to generate the correct
  35. seed, the same seed length and hash preset parameters must always be used.
  36. """.strip()
  37. version_info = """
  38. {pgnm_uc} version {g.version}
  39. Part of the {pnm} suite, a Bitcoin cold-storage solution for the command line.
  40. Copyright (C) {g.Cdates} {g.author} {g.email}
  41. """.format(pnm=g.proj_name, g=g, pgnm_uc=g.prog_name.upper()).strip()
  42. def usage(): Die(2,'USAGE: %s %s' % (g.prog_name, usage_txt))
  43. def die_on_incompatible_opts(incompat_list):
  44. for group in incompat_list:
  45. bad = [k for k in opt.__dict__ if opt.__dict__[k] and k in group]
  46. if len(bad) > 1:
  47. die(1,'Conflicting options: %s' % ', '.join([fmt_opt(b) for b in bad]))
  48. def fmt_opt(o): return '--' + o.replace('_','-')
  49. def _show_hash_presets():
  50. fs = ' {:<7} {:<6} {:<3} {}'
  51. msg('Available parameters for scrypt.hash():')
  52. msg(fs.format('Preset','N','r','p'))
  53. for i in sorted(g.hash_presets.keys()):
  54. msg(fs.format("'%s'" % i, *g.hash_presets[i]))
  55. msg('N = memory usage (power of two), p = iterations (rounds)')
  56. common_opts_data = """
  57. --, --color=c Set to '0' to disable color output, '1' to enable
  58. --, --data-dir=d Specify the location of {pnm}'s data directory
  59. --, --no-license Suppress the GPL license prompt
  60. --, --rpc-host=h Communicate with bitcoind running on host 'h'
  61. --, --testnet=1 Set to '1' use testnet, '0' to force mainnet
  62. --, --skip-cfg-file Skip reading the configuration file
  63. --, --version Print version information and exit
  64. """.format(pnm=g.proj_name)
  65. def opt_preproc_debug(short_opts,long_opts,skipped_opts,uopts,args):
  66. d = (
  67. ('Cmdline', ' '.join(sys.argv)),
  68. ('Short opts', short_opts),
  69. ('Long opts', long_opts),
  70. ('Skipped opts', skipped_opts),
  71. ('User-selected opts', uopts),
  72. ('Cmd args', args),
  73. )
  74. Msg('\n=== opts.py debug ===')
  75. for e in d: Msg(' {:<20}: {}'.format(*e))
  76. def opt_postproc_debug():
  77. opt.verbose,opt.quiet = True,None
  78. a = [k for k in dir(opt) if k[:2] != '__' and getattr(opt,k) != None]
  79. b = [k for k in dir(opt) if k[:2] != '__' and getattr(opt,k) == None]
  80. Msg(' Opts after processing:')
  81. for k in a:
  82. v = getattr(opt,k)
  83. Msg(' %-18s: %-6s [%s]' % (k,v,type(v).__name__))
  84. Msg(" Opts set to 'None':")
  85. Msg(' %s\n' % '\n '.join(b))
  86. Msg(' Global vars:')
  87. for e in [d for d in dir(g) if d[:2] != '__']:
  88. Msg(' {:<20}: {}'.format(e, getattr(g,e)))
  89. Msg('\n=== end opts.py debug ===')
  90. def opt_postproc_actions():
  91. from mmgen.term import set_terminal_vars
  92. set_terminal_vars()
  93. # testnet data_dir differs from data_dir_root, so check or create
  94. from mmgen.util import msg,die,check_or_create_dir
  95. check_or_create_dir(g.data_dir) # dies on error
  96. def set_data_dir_root():
  97. g.data_dir_root = os.path.normpath(os.path.expanduser(opt.data_dir)) if opt.data_dir else \
  98. (os.path.join(g.home_dir,'Application Data',g.proj_name),
  99. os.path.join(g.home_dir,'.'+g.proj_name.lower()))[bool(os.getenv('HOME'))]
  100. # mainnet and testnet share cfg file, as with Core
  101. g.cfg_file = os.path.join(g.data_dir_root,'{}.cfg'.format(g.proj_name.lower()))
  102. def get_data_from_config_file():
  103. from mmgen.util import msg,die,check_or_create_dir
  104. check_or_create_dir(g.data_dir_root) # dies on error
  105. # https://wiki.debian.org/Python:
  106. # Debian (Ubuntu) sys.prefix is '/usr' rather than '/usr/local, so add 'local'
  107. # TODO - test for Windows
  108. # This must match the configuration in setup.py
  109. data = u''
  110. try:
  111. with open(g.cfg_file,'rb') as f: data = f.read().decode('utf8')
  112. except:
  113. cfg_template = os.path.join(*([sys.prefix]
  114. + (['share'],['local','share'])[g.platform=='linux']
  115. + [g.proj_name.lower(),os.path.basename(g.cfg_file)]))
  116. try:
  117. with open(cfg_template,'rb') as f: template_data = f.read()
  118. except:
  119. msg("WARNING: configuration template not found at '{}'".format(cfg_template))
  120. else:
  121. try:
  122. with open(g.cfg_file,'wb') as f: f.write(template_data)
  123. os.chmod(g.cfg_file,0600)
  124. except:
  125. die(2,"ERROR: unable to write to datadir '{}'".format(g.data_dir))
  126. return data
  127. def override_from_cfg_file(cfg_data):
  128. from mmgen.util import die,strip_comments,set_for_type
  129. import re
  130. for n,l in enumerate(cfg_data.splitlines(),1): # DOS-safe
  131. l = strip_comments(l)
  132. if l == '': continue
  133. m = re.match(r'(\w+)\s+(\S+)$',l)
  134. if not m: die(2,"Parse error in file '{}', line {}".format(g.cfg_file,n))
  135. name,val = m.groups()
  136. if name in g.cfg_file_opts:
  137. setattr(g,name,set_for_type(val,getattr(g,name),name,src=g.cfg_file))
  138. else:
  139. die(2,"'{}': unrecognized option in '{}'".format(name,g.cfg_file))
  140. def override_from_env():
  141. from mmgen.util import set_for_type
  142. for name in g.env_opts:
  143. idx,invert_bool = ((6,False),(14,True))[name[:14]=='MMGEN_DISABLE_']
  144. val = os.getenv(name) # os.getenv() returns None if env var is unset
  145. if val: # exclude empty string values too
  146. gname = name[idx:].lower()
  147. setattr(g,gname,set_for_type(val,getattr(g,gname),name,invert_bool))
  148. def init(opts_data,add_opts=[],opt_filter=None):
  149. opts_data['long_options'] = common_opts_data
  150. uopts,args,short_opts,long_opts,skipped_opts = \
  151. mmgen.share.Opts.parse_opts(sys.argv,opts_data,opt_filter=opt_filter)
  152. if g.debug: opt_preproc_debug(short_opts,long_opts,skipped_opts,uopts,args)
  153. # Save this for usage()
  154. global usage_txt
  155. usage_txt = opts_data['usage']
  156. # We don't need this data anymore
  157. del mmgen.share.Opts
  158. for k in 'prog_name','desc','usage','options','notes':
  159. if k in opts_data: del opts_data[k]
  160. # Transfer uopts into opt, setting program's opts + required opts to None if not set by user
  161. for o in tuple([s.rstrip('=') for s in long_opts] + add_opts + skipped_opts) + \
  162. g.required_opts + g.common_opts:
  163. setattr(opt,o,uopts[o] if o in uopts else None)
  164. if opt.version: Die(0,version_info)
  165. # === Interaction with global vars begins here ===
  166. # cfg file is in g.data_dir_root, wallet and other data are in g.data_dir
  167. # Must set g.data_dir_root and g.cfg_file from cmdline before processing cfg file
  168. set_data_dir_root()
  169. if not opt.skip_cfg_file:
  170. cfg_data = get_data_from_config_file()
  171. override_from_cfg_file(cfg_data)
  172. override_from_env()
  173. # User opt sets global var - do these here, before opt is set from g.global_sets_opt
  174. for k in g.common_opts:
  175. val = getattr(opt,k)
  176. if val != None: setattr(g,k,set_for_type(val,getattr(g,k),'--'+k))
  177. # Global vars are now final, including g.testnet, so we can set g.data_dir
  178. g.data_dir=os.path.normpath(os.path.join(g.data_dir_root,('',g.testnet_name)[g.testnet]))
  179. # If user opt is set, convert its type based on value in mmgen.globalvars (g)
  180. # If unset, set it to default value in mmgen.globalvars (g)
  181. setattr(opt,'set_by_user',[])
  182. for k in g.global_sets_opt:
  183. if k in opt.__dict__ and getattr(opt,k) != None:
  184. # _typeconvert_from_dfl(k)
  185. setattr(opt,k,set_for_type(getattr(opt,k),getattr(g,k),'--'+k))
  186. opt.set_by_user.append(k)
  187. else:
  188. setattr(opt,k,g.__dict__[k])
  189. # Check user-set opts without modifying them
  190. if not check_opts(uopts):
  191. sys.exit(1)
  192. if opt.show_hash_presets:
  193. _show_hash_presets()
  194. sys.exit()
  195. if g.debug: opt_postproc_debug()
  196. if opt.verbose: opt.quiet = None
  197. die_on_incompatible_opts(g.incompatible_opts)
  198. opt_postproc_actions()
  199. return args
  200. def check_opts(usr_opts): # Returns false if any check fails
  201. def opt_splits(val,sep,n,desc):
  202. sepword = 'comma' if sep == ',' else 'colon' if sep == ':' else "'%s'" % sep
  203. try: l = val.split(sep)
  204. except:
  205. msg("'%s': invalid %s (not %s-separated list)" % (val,desc,sepword))
  206. return False
  207. if len(l) == n: return True
  208. else:
  209. msg("'%s': invalid %s (%s %s-separated items required)" %
  210. (val,desc,n,sepword))
  211. return False
  212. def opt_compares(val,op,target,desc,what=''):
  213. if what: what += ' '
  214. if not eval('%s %s %s' % (val, op, target)):
  215. msg('%s: invalid %s (%snot %s %s)' % (val,desc,what,op,target))
  216. return False
  217. return True
  218. def opt_is_int(val,desc):
  219. try: int(val)
  220. except:
  221. msg("'%s': invalid %s (not an integer)" % (val,desc))
  222. return False
  223. return True
  224. def opt_is_in_list(val,lst,desc):
  225. if val not in lst:
  226. q,sep = (('',','),("'","','"))[type(lst[0]) == str]
  227. msg('{q}{v}{q}: invalid {w}\nValid choices: {q}{o}{q}'.format(
  228. v=val,w=desc,q=q,
  229. o=sep.join([str(i) for i in sorted(lst)])
  230. ))
  231. return False
  232. return True
  233. def opt_unrecognized(key,val,desc):
  234. msg("'%s': unrecognized %s for option '%s'"
  235. % (val,desc,fmt_opt(key)))
  236. return False
  237. def opt_display(key,val='',beg='For selected',end=':\n'):
  238. s = '%s=%s' % (fmt_opt(key),val) if val else fmt_opt(key)
  239. msg_r("%s option '%s'%s" % (beg,s,end))
  240. global opt
  241. for key,val in [(k,getattr(opt,k)) for k in usr_opts]:
  242. desc = "parameter for '%s' option" % fmt_opt(key)
  243. from mmgen.util import check_infile,check_outfile,check_outdir
  244. # Check for file existence and readability
  245. if key in ('keys_from_file','mmgen_keys_from_file',
  246. 'passwd_file','keysforaddrs','comment_file'):
  247. check_infile(val) # exits on error
  248. continue
  249. if key == 'outdir':
  250. check_outdir(val) # exits on error
  251. # # NEW
  252. elif key in ('in_fmt','out_fmt'):
  253. from mmgen.seed import SeedSource,IncogWallet,Brainwallet,IncogWalletHidden
  254. sstype = SeedSource.fmt_code_to_type(val)
  255. if not sstype:
  256. return opt_unrecognized(key,val,'format code')
  257. if key == 'out_fmt':
  258. p = 'hidden_incog_output_params'
  259. if sstype == IncogWalletHidden and not getattr(opt,p):
  260. die(1,'Hidden incog format output requested. You must supply'
  261. + " a file and offset with the '%s' option" % fmt_opt(p))
  262. if issubclass(sstype,IncogWallet) and opt.old_incog_fmt:
  263. opt_display(key,val,beg='Selected',end=' ')
  264. opt_display('old_incog_fmt',beg='conflicts with',end=':\n')
  265. die(1,'Export to old incog wallet format unsupported')
  266. elif issubclass(sstype,Brainwallet):
  267. die(1,'Output to brainwallet format unsupported')
  268. elif key in ('hidden_incog_input_params','hidden_incog_output_params'):
  269. a = val.split(',')
  270. if len(a) < 2:
  271. opt_display(key,val)
  272. msg('Option requires two comma-separated arguments')
  273. return False
  274. fn,ofs = ','.join(a[:-1]),a[-1] # permit comma in filename
  275. if not opt_is_int(ofs,desc): return False
  276. if key == 'hidden_incog_input_params':
  277. check_infile(fn,blkdev_ok=True)
  278. key2 = 'in_fmt'
  279. else:
  280. try: os.stat(fn)
  281. except:
  282. b = os.path.dirname(fn)
  283. if b: check_outdir(b)
  284. else: check_outfile(fn,blkdev_ok=True)
  285. key2 = 'out_fmt'
  286. if hasattr(opt,key2):
  287. val2 = getattr(opt,key2)
  288. from mmgen.seed import IncogWalletHidden
  289. if val2 and val2 not in IncogWalletHidden.fmt_codes:
  290. die(1,
  291. 'Option conflict:\n %s, with\n %s=%s' % (
  292. fmt_opt(key),fmt_opt(key2),val2
  293. ))
  294. elif key == 'seed_len':
  295. if not opt_is_int(val,desc): return False
  296. if not opt_is_in_list(int(val),g.seed_lens,desc): return False
  297. elif key == 'hash_preset':
  298. if not opt_is_in_list(val,g.hash_presets.keys(),desc): return False
  299. elif key == 'brain_params':
  300. a = val.split(',')
  301. if len(a) != 2:
  302. opt_display(key,val)
  303. msg('Option requires two comma-separated arguments')
  304. return False
  305. d = 'seed length ' + desc
  306. if not opt_is_int(a[0],d): return False
  307. if not opt_is_in_list(int(a[0]),g.seed_lens,d): return False
  308. d = 'hash preset ' + desc
  309. if not opt_is_in_list(a[1],g.hash_presets.keys(),d): return False
  310. elif key == 'usr_randchars':
  311. if val == 0: continue
  312. if not opt_is_int(val,desc): return False
  313. if not opt_compares(val,'>=',g.min_urandchars,desc): return False
  314. if not opt_compares(val,'<=',g.max_urandchars,desc): return False
  315. elif key == 'key_generator':
  316. if not opt_compares(val,'<=',len(g.key_generators),desc): return False
  317. if not opt_compares(val,'>',0,desc): return False
  318. else:
  319. if g.debug: Msg("check_opts(): No test for opt '%s'" % key)
  320. return True