opts.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. #!/usr/bin/env python
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2017 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. def usage(): Die(2,'USAGE: %s %s' % (g.prog_name, usage_txt))
  27. def die_on_incompatible_opts(incompat_list):
  28. for group in incompat_list:
  29. bad = [k for k in opt.__dict__ if opt.__dict__[k] and k in group]
  30. if len(bad) > 1:
  31. die(1,'Conflicting options: %s' % ', '.join([fmt_opt(b) for b in bad]))
  32. def fmt_opt(o): return '--' + o.replace('_','-')
  33. def _show_hash_presets():
  34. fs = ' {:<7} {:<6} {:<3} {}'
  35. msg('Available parameters for scrypt.hash():')
  36. msg(fs.format('Preset','N','r','p'))
  37. for i in sorted(g.hash_presets.keys()):
  38. msg(fs.format("'%s'" % i, *g.hash_presets[i]))
  39. msg('N = memory usage (power of two), p = iterations (rounds)')
  40. def opt_preproc_debug(short_opts,long_opts,skipped_opts,uopts,args):
  41. d = (
  42. ('Cmdline', ' '.join(sys.argv)),
  43. ('Short opts', short_opts),
  44. ('Long opts', long_opts),
  45. ('Skipped opts', skipped_opts),
  46. ('User-selected opts', uopts),
  47. ('Cmd args', args),
  48. )
  49. Msg('\n=== opts.py debug ===')
  50. for e in d: Msg(' {:<20}: {}'.format(*e))
  51. def opt_postproc_debug():
  52. opt.verbose,opt.quiet = True,None
  53. a = [k for k in dir(opt) if k[:2] != '__' and getattr(opt,k) != None]
  54. b = [k for k in dir(opt) if k[:2] != '__' and getattr(opt,k) == None]
  55. Msg(' Opts after processing:')
  56. for k in a:
  57. v = getattr(opt,k)
  58. Msg(' %-18s: %-6s [%s]' % (k,v,type(v).__name__))
  59. Msg(" Opts set to 'None':")
  60. Msg(' %s\n' % '\n '.join(b))
  61. Msg(' Global vars:')
  62. for e in [d for d in dir(g) if d[:2] != '__']:
  63. Msg(' {:<20}: {}'.format(e, getattr(g,e)))
  64. Msg('\n=== end opts.py debug ===\n')
  65. def opt_postproc_initializations():
  66. from mmgen.term import set_terminal_vars
  67. set_terminal_vars()
  68. # testnet data_dir differs from data_dir_root, so check or create
  69. from mmgen.util import msg,die,check_or_create_dir
  70. check_or_create_dir(g.data_dir) # dies on error
  71. from mmgen.color import init_color
  72. init_color(enable_color=g.color,num_colors=('auto',256)[bool(g.force_256_color)])
  73. if g.platform == 'win': start_mscolor()
  74. g.coin = g.coin.upper() # allow user to use lowercase
  75. def set_data_dir_root():
  76. g.data_dir_root = os.path.normpath(os.path.expanduser(opt.data_dir)) if opt.data_dir else \
  77. os.path.join(g.home_dir,'.'+g.proj_name.lower())
  78. # mainnet and testnet share cfg file, as with Core
  79. g.cfg_file = os.path.join(g.data_dir_root,'{}.cfg'.format(g.proj_name.lower()))
  80. def get_cfg_template_data():
  81. # https://wiki.debian.org/Python:
  82. # Debian (Ubuntu) sys.prefix is '/usr' rather than '/usr/local, so add 'local'
  83. # TODO - test for Windows
  84. # This must match the configuration in setup.py
  85. cfg_template = os.path.join(*([sys.prefix]
  86. + (['share'],['local','share'])[g.platform=='linux']
  87. + [g.proj_name.lower(),os.path.basename(g.cfg_file)]))
  88. try:
  89. with open(cfg_template,'rb') as f:
  90. return f.read()
  91. except:
  92. msg("WARNING: configuration template not found at '{}'".format(cfg_template))
  93. return u''
  94. def get_data_from_cfg_file():
  95. from mmgen.util import msg,die,check_or_create_dir
  96. check_or_create_dir(g.data_dir_root) # dies on error
  97. template_data = get_cfg_template_data()
  98. data = {}
  99. def copy_template_data(fn):
  100. try:
  101. with open(fn,'wb') as f: f.write(template_data)
  102. os.chmod(fn,0600)
  103. except:
  104. die(2,"ERROR: unable to write to datadir '{}'".format(g.data_dir))
  105. for k,suf in (('cfg',''),('sample','.sample')):
  106. try:
  107. with open(g.cfg_file+suf,'rb') as f:
  108. data[k] = f.read().decode('utf8')
  109. except:
  110. if template_data:
  111. copy_template_data(g.cfg_file+suf)
  112. data[k] = template_data
  113. else:
  114. data[k] = u''
  115. if template_data and data['sample'] != template_data:
  116. g.cfg_options_changed = True
  117. copy_template_data(g.cfg_file+'.sample')
  118. return data['cfg']
  119. def override_from_cfg_file(cfg_data):
  120. from mmgen.util import die,strip_comments,set_for_type
  121. import re
  122. from mmgen.protocol import CoinProtocol
  123. for n,l in enumerate(cfg_data.splitlines(),1): # DOS-safe
  124. l = strip_comments(l)
  125. if l == '': continue
  126. m = re.match(r'(\w+)\s+(\S+)$',l)
  127. if not m: die(2,"Parse error in file '{}', line {}".format(g.cfg_file,n))
  128. name,val = m.groups()
  129. if name in g.cfg_file_opts:
  130. pfx,cfg_var = name.split('_',1)
  131. if pfx in CoinProtocol.coins:
  132. cls,attr = CoinProtocol(pfx,False),cfg_var
  133. else:
  134. cls,attr = g,name
  135. setattr(cls,attr,set_for_type(val,getattr(cls,attr),attr,src=g.cfg_file))
  136. # pmsg(cls,attr,getattr(cls,attr))
  137. else:
  138. die(2,"'{}': unrecognized option in '{}'".format(name,g.cfg_file))
  139. # pdie('xxx')
  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 warn_altcoins(trust_level):
  149. if trust_level == None: return
  150. tl = (red('COMPLETELY UNTESTED'),red('LOW'),yellow('MEDIUM'),green('HIGH'))
  151. m = """
  152. Support for coin '{}' is EXPERIMENTAL. The {pn} project assumes no
  153. responsibility for any loss of funds you may incur.
  154. This coin's {pn} testing status: {}
  155. Are you sure you want to continue?
  156. """.strip().format(g.coin,tl[trust_level],pn=g.proj_name)
  157. if os.getenv('MMGEN_TEST_SUITE'):
  158. msg(m); return
  159. if not keypress_confirm(m,default_yes=True):
  160. sys.exit(0)
  161. def init(opts_f,add_opts=[],opt_filter=None):
  162. from mmgen.protocol import CoinProtocol,BitcoinProtocol,init_genonly_altcoins
  163. g.proto = BitcoinProtocol # this must be initialized to something before opts_f is called
  164. # most, but not all, of these set the corresponding global var
  165. common_opts_data = """
  166. --, --accept-defaults Accept defaults at all prompts
  167. --, --coin=c Choose coin unit. Default: {cu_dfl}. Options: {cu_all}
  168. --, --color=0|1 Disable or enable color output
  169. --, --force-256-color Force 256-color output when color is enabled
  170. --, --daemon-data-dir=d Specify coin daemon data directory location 'd'
  171. --, --data-dir=d Specify {pnm} data directory location 'd'
  172. --, --no-license Suppress the GPL license prompt
  173. --, --rpc-host=h Communicate with {dn} running on host 'h'
  174. --, --rpc-port=p Communicate with {dn} listening on port 'p'
  175. --, --rpc-user=user Override 'rpcuser' in {pn}.conf
  176. --, --rpc-password=pass Override 'rpcpassword' in {pn}.conf
  177. --, --regtest=0|1 Disable or enable regtest mode
  178. --, --testnet=0|1 Disable or enable testnet
  179. --, --skip-cfg-file Skip reading the configuration file
  180. --, --version Print version information and exit
  181. --, --bob Switch to user "Bob" in MMGen regtest setup
  182. --, --alice Switch to user "Alice" in MMGen regtest setup
  183. """.format( pnm=g.proj_name,pn=g.proto.name,dn=g.proto.daemon_name,
  184. cu_dfl=g.coin,
  185. cu_all=' '.join(CoinProtocol.coins))
  186. opts_data = opts_f()
  187. opts_data['long_options'] = common_opts_data
  188. version_info = """
  189. {pgnm_uc} version {g.version}
  190. Part of the {pnm} suite, an online/offline cryptocoin wallet for the command line.
  191. Copyright (C) {g.Cdates} {g.author} {g.email}
  192. """.format(pnm=g.proj_name, g=g, pgnm_uc=g.prog_name.upper()).strip()
  193. uopts,args,short_opts,long_opts,skipped_opts,do_help = \
  194. mmgen.share.Opts.parse_opts(sys.argv,opts_data,opt_filter=opt_filter,defer_help=True)
  195. if g.debug: opt_preproc_debug(short_opts,long_opts,skipped_opts,uopts,args)
  196. # Save this for usage()
  197. global usage_txt
  198. usage_txt = opts_data['usage']
  199. # Transfer uopts into opt, setting program's opts + required opts to None if not set by user
  200. for o in tuple([s.rstrip('=') for s in long_opts] + add_opts + skipped_opts) + \
  201. g.required_opts + g.common_opts:
  202. setattr(opt,o,uopts[o] if o in uopts else None)
  203. if opt.version: Die(0,version_info)
  204. # === Interaction with global vars begins here ===
  205. # NB: user opt --data-dir is actually g.data_dir_root
  206. # cfg file is in g.data_dir_root, wallet and other data are in g.data_dir
  207. # We must set g.data_dir_root and g.cfg_file from cmdline before processing cfg file
  208. set_data_dir_root()
  209. if not opt.skip_cfg_file:
  210. override_from_cfg_file(get_data_from_cfg_file())
  211. override_from_env()
  212. # User opt sets global var - do these here, before opt is set from g.global_sets_opt
  213. for k in g.common_opts:
  214. val = getattr(opt,k)
  215. if val != None: setattr(g,k,set_for_type(val,getattr(g,k),'--'+k))
  216. if g.regtest: g.testnet = True # These are equivalent for now
  217. altcoin_trust_level = init_genonly_altcoins(opt.coin)
  218. # g.testnet is set, so we can set g.proto
  219. g.proto = CoinProtocol(g.coin,g.testnet)
  220. # global sets proto
  221. if g.daemon_data_dir: g.proto.daemon_data_dir = g.daemon_data_dir
  222. # g.proto is set, so we can set g.data_dir
  223. g.data_dir = os.path.normpath(os.path.join(g.data_dir_root,g.proto.data_subdir))
  224. # If user opt is set, convert its type based on value in mmgen.globalvars (g)
  225. # If unset, set it to default value in mmgen.globalvars (g)
  226. setattr(opt,'set_by_user',[])
  227. for k in g.global_sets_opt:
  228. if k in opt.__dict__ and getattr(opt,k) != None:
  229. setattr(opt,k,set_for_type(getattr(opt,k),getattr(g,k),'--'+k))
  230. opt.set_by_user.append(k)
  231. else:
  232. setattr(opt,k,g.__dict__[k])
  233. if opt.show_hash_presets:
  234. _show_hash_presets()
  235. sys.exit(0)
  236. if opt.verbose: opt.quiet = None
  237. die_on_incompatible_opts(g.incompatible_opts)
  238. opt_postproc_initializations()
  239. if do_help: # print help screen only after global vars are initialized
  240. opts_data = opts_f()
  241. opts_data['long_options'] = common_opts_data
  242. mmgen.share.Opts.parse_opts(sys.argv,opts_data,opt_filter=opt_filter)
  243. if g.bob or g.alice:
  244. g.testnet = True
  245. g.proto = CoinProtocol(g.coin,g.testnet)
  246. g.data_dir = os.path.join(g.data_dir_root,'regtest',g.coin.lower(),('alice','bob')[g.bob])
  247. check_or_create_dir(g.data_dir)
  248. import regtest as rt
  249. g.rpc_host = 'localhost'
  250. g.rpc_port = rt.rpc_port
  251. g.rpc_user = rt.rpc_user
  252. g.rpc_password = rt.rpc_password
  253. # Check user-set opts without modifying them
  254. if not check_opts(uopts):
  255. sys.exit(1)
  256. if hasattr(g,'cfg_options_changed'):
  257. ymsg("Warning: config file options have changed! See '{}' for details".format(g.cfg_file+'.sample'))
  258. my_raw_input('Hit ENTER to continue: ')
  259. if g.debug: opt_postproc_debug()
  260. # We don't need this data anymore
  261. del mmgen.share.Opts
  262. del opts_f
  263. for k in ('prog_name','desc','usage','options','notes'):
  264. if k in opts_data: del opts_data[k]
  265. warn_altcoins(altcoin_trust_level)
  266. return args
  267. def opt_is_tx_fee(val,desc):
  268. from mmgen.tx import MMGenTX
  269. ret = MMGenTX().convert_fee_spec(val,224,on_fail='return')
  270. if ret == False:
  271. msg("'{}': invalid {} (not a {} amount or satoshis-per-byte specification)".format(
  272. val,desc,g.coin.upper()))
  273. elif ret != None and ret > g.proto.max_tx_fee:
  274. msg("'{}': invalid {} (> max_tx_fee ({} {}))".format(
  275. val,desc,g.proto.max_tx_fee,g.coin.upper()))
  276. else:
  277. return True
  278. return False
  279. def check_opts(usr_opts): # Returns false if any check fails
  280. def opt_splits(val,sep,n,desc):
  281. sepword = 'comma' if sep == ',' else 'colon' if sep == ':' else "'%s'" % sep
  282. try: l = val.split(sep)
  283. except:
  284. msg("'%s': invalid %s (not %s-separated list)" % (val,desc,sepword))
  285. return False
  286. if len(l) == n: return True
  287. else:
  288. msg("'%s': invalid %s (%s %s-separated items required)" %
  289. (val,desc,n,sepword))
  290. return False
  291. def opt_compares(val,op,target,desc,what=''):
  292. if what: what += ' '
  293. if not eval('%s %s %s' % (val, op, target)):
  294. msg('%s: invalid %s (%snot %s %s)' % (val,desc,what,op,target))
  295. return False
  296. return True
  297. def opt_is_int(val,desc):
  298. try: int(val)
  299. except:
  300. msg("'%s': invalid %s (not an integer)" % (val,desc))
  301. return False
  302. return True
  303. def opt_is_in_list(val,lst,desc):
  304. if val not in lst:
  305. q,sep = (('',','),("'","','"))[type(lst[0]) == str]
  306. msg('{q}{v}{q}: invalid {w}\nValid choices: {q}{o}{q}'.format(
  307. v=val,w=desc,q=q,
  308. o=sep.join([str(i) for i in sorted(lst)])
  309. ))
  310. return False
  311. return True
  312. def opt_unrecognized(key,val,desc):
  313. msg("'%s': unrecognized %s for option '%s'"
  314. % (val,desc,fmt_opt(key)))
  315. return False
  316. def opt_display(key,val='',beg='For selected',end=':\n'):
  317. s = '%s=%s' % (fmt_opt(key),val) if val else fmt_opt(key)
  318. msg_r("%s option '%s'%s" % (beg,s,end))
  319. global opt
  320. for key,val in [(k,getattr(opt,k)) for k in usr_opts]:
  321. desc = "parameter for '%s' option" % fmt_opt(key)
  322. from mmgen.util import check_infile,check_outfile,check_outdir
  323. # Check for file existence and readability
  324. if key in ('keys_from_file','mmgen_keys_from_file',
  325. 'passwd_file','keysforaddrs','comment_file'):
  326. check_infile(val) # exits on error
  327. continue
  328. if key == 'outdir':
  329. check_outdir(val) # exits on error
  330. # # NEW
  331. elif key in ('in_fmt','out_fmt'):
  332. from mmgen.seed import SeedSource,IncogWallet,Brainwallet,IncogWalletHidden
  333. sstype = SeedSource.fmt_code_to_type(val)
  334. if not sstype:
  335. return opt_unrecognized(key,val,'format code')
  336. if key == 'out_fmt':
  337. p = 'hidden_incog_output_params'
  338. if sstype == IncogWalletHidden and not getattr(opt,p):
  339. die(1,'Hidden incog format output requested. You must supply'
  340. + " a file and offset with the '%s' option" % fmt_opt(p))
  341. if issubclass(sstype,IncogWallet) and opt.old_incog_fmt:
  342. opt_display(key,val,beg='Selected',end=' ')
  343. opt_display('old_incog_fmt',beg='conflicts with',end=':\n')
  344. die(1,'Export to old incog wallet format unsupported')
  345. elif issubclass(sstype,Brainwallet):
  346. die(1,'Output to brainwallet format unsupported')
  347. elif key in ('hidden_incog_input_params','hidden_incog_output_params'):
  348. a = val.split(',')
  349. if len(a) < 2:
  350. opt_display(key,val)
  351. msg('Option requires two comma-separated arguments')
  352. return False
  353. fn,ofs = ','.join(a[:-1]),a[-1] # permit comma in filename
  354. if not opt_is_int(ofs,desc): return False
  355. if key == 'hidden_incog_input_params':
  356. check_infile(fn,blkdev_ok=True)
  357. key2 = 'in_fmt'
  358. else:
  359. try: os.stat(fn)
  360. except:
  361. b = os.path.dirname(fn)
  362. if b: check_outdir(b)
  363. else: check_outfile(fn,blkdev_ok=True)
  364. key2 = 'out_fmt'
  365. if hasattr(opt,key2):
  366. val2 = getattr(opt,key2)
  367. from mmgen.seed import IncogWalletHidden
  368. if val2 and val2 not in IncogWalletHidden.fmt_codes:
  369. die(1,
  370. 'Option conflict:\n %s, with\n %s=%s' % (
  371. fmt_opt(key),fmt_opt(key2),val2
  372. ))
  373. elif key == 'seed_len':
  374. if not opt_is_int(val,desc): return False
  375. if not opt_is_in_list(int(val),g.seed_lens,desc): return False
  376. elif key == 'hash_preset':
  377. if not opt_is_in_list(val,g.hash_presets.keys(),desc): return False
  378. elif key == 'brain_params':
  379. a = val.split(',')
  380. if len(a) != 2:
  381. opt_display(key,val)
  382. msg('Option requires two comma-separated arguments')
  383. return False
  384. d = 'seed length ' + desc
  385. if not opt_is_int(a[0],d): return False
  386. if not opt_is_in_list(int(a[0]),g.seed_lens,d): return False
  387. d = 'hash preset ' + desc
  388. if not opt_is_in_list(a[1],g.hash_presets.keys(),d): return False
  389. elif key == 'usr_randchars':
  390. if val == 0: continue
  391. if not opt_is_int(val,desc): return False
  392. if not opt_compares(val,'>=',g.min_urandchars,desc): return False
  393. if not opt_compares(val,'<=',g.max_urandchars,desc): return False
  394. elif key == 'tx_fee':
  395. if not opt_is_tx_fee(val,desc): return False
  396. elif key == 'tx_confs':
  397. if not opt_is_int(val,desc): return False
  398. if not opt_compares(val,'>=',1,desc): return False
  399. elif key == 'key_generator':
  400. if not opt_compares(val,'<=',len(g.key_generators),desc): return False
  401. if not opt_compares(val,'>',0,desc): return False
  402. elif key == 'coin':
  403. from mmgen.protocol import CoinProtocol
  404. if not opt_is_in_list(val.lower(),CoinProtocol.coins.keys(),'coin'): return False
  405. elif key == 'rbf':
  406. if not g.proto.cap('rbf'):
  407. die(1,'--rbf requested, but {} does not support replace-by-fee transactions'.format(g.coin))
  408. elif key in ('bob','alice'):
  409. from mmgen.regtest import daemon_dir
  410. m = "Regtest (Bob and Alice) mode not set up yet. Run '{}-regtest setup' to initialize."
  411. try: os.stat(daemon_dir)
  412. except: die(1,m.format(g.proj_name.lower()))
  413. elif key == 'locktime':
  414. if not opt_is_int(val,desc): return False
  415. if not opt_compares(val,'>',0,desc): return False
  416. else:
  417. if g.debug: Msg("check_opts(): No test for opt '%s'" % key)
  418. return True