opts.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2020 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. opts.py: MMGen-specific options processing after generic processing by share.Opts
  20. """
  21. import sys,os,stat
  22. from .exception import UserOptError
  23. from .globalvars import g
  24. from .base_obj import Lockable
  25. import mmgen.share.Opts
  26. class UserOpts(Lockable):
  27. _set_ok = ('usr_randchars',)
  28. _reset_ok = ('quiet','verbose','yes')
  29. opt = UserOpts()
  30. from .util import *
  31. def usage():
  32. Die(1,f'USAGE: {g.prog_name} {usage_txt}')
  33. def version():
  34. Die(0,fmt("""
  35. {pn} version {g.version}
  36. Part of the {g.proj_name} suite, an online/offline cryptocurrency wallet for the
  37. command line. Copyright (C){g.Cdates} {g.author} {g.email}
  38. """.format(g=g,pn=g.prog_name.upper()),indent=' ').rstrip())
  39. def print_help(po,opts_data,opt_filter):
  40. if not 'code' in opts_data:
  41. opts_data['code'] = {}
  42. from .protocol import init_proto_from_opts
  43. proto = init_proto_from_opts()
  44. if getattr(opt,'longhelp',None):
  45. opts_data['code']['long_options'] = common_opts_data['code']
  46. def remove_unneeded_long_opts():
  47. d = opts_data['text']['long_options']
  48. if g.prog_name != 'mmgen-tool':
  49. d = '\n'.join(''+i for i in d.split('\n') if not '--monero-wallet' in i)
  50. if proto.base_proto != 'Ethereum':
  51. d = '\n'.join(''+i for i in d.split('\n') if not '--token' in i)
  52. opts_data['text']['long_options'] = d
  53. remove_unneeded_long_opts()
  54. mmgen.share.Opts.print_help( # exits
  55. proto,
  56. po,
  57. opts_data,
  58. opt_filter )
  59. def fmt_opt(o):
  60. return '--' + o.replace('_','-')
  61. def die_on_incompatible_opts(incompat_list):
  62. for group in incompat_list:
  63. bad = [k for k in opt.__dict__ if k in group and getattr(opt,k) != None]
  64. if len(bad) > 1:
  65. die(1,'Conflicting options: {}'.format(', '.join(map(fmt_opt,bad))))
  66. def _show_hash_presets():
  67. fs = ' {:<7} {:<6} {:<3} {}'
  68. msg('Available parameters for scrypt.hash():')
  69. msg(fs.format('Preset','N','r','p'))
  70. for i in sorted(g.hash_presets.keys()):
  71. msg(fs.format(i,*g.hash_presets[i]))
  72. msg('N = memory usage (power of two), p = iterations (rounds)')
  73. sys.exit(0)
  74. def opt_preproc_debug(po):
  75. d = (
  76. ('Cmdline', ' '.join(sys.argv)),
  77. ('Opts', po.opts),
  78. ('Skipped opts', po.skipped_opts),
  79. ('User-selected opts', po.user_opts),
  80. ('Cmd args', po.cmd_args),
  81. )
  82. Msg('\n=== opts.py debug ===')
  83. for e in d:
  84. Msg(' {:<20}: {}'.format(*e))
  85. def opt_postproc_debug():
  86. a = [k for k in dir(opt) if k[:2] != '__' and getattr(opt,k) != None]
  87. b = [k for k in dir(opt) if k[:2] != '__' and getattr(opt,k) == None]
  88. Msg(' Opts after processing:')
  89. for k in a:
  90. v = getattr(opt,k)
  91. Msg(' {:18}: {!r:<6} [{}]'.format(k,v,type(v).__name__))
  92. Msg(" Opts set to 'None':")
  93. Msg(' {}\n'.format('\n '.join(b)))
  94. Msg(' Global vars:')
  95. for e in [d for d in dir(g) if d[:2] != '__']:
  96. Msg(' {:<20}: {}'.format(e, getattr(g,e)))
  97. Msg('\n=== end opts.py debug ===\n')
  98. def init_term_and_color():
  99. from .term import init_term
  100. init_term()
  101. if g.color: # MMGEN_DISABLE_COLOR sets this to False
  102. from .color import start_mscolor,init_color
  103. if g.platform == 'win':
  104. start_mscolor()
  105. init_color(num_colors=('auto',256)[bool(g.force_256_color)])
  106. def override_globals_from_cfg_file(ucfg):
  107. from .protocol import CoinProtocol,init_proto
  108. for d in ucfg.parse():
  109. val = d.value
  110. if d.name in g.cfg_file_opts:
  111. ns = d.name.split('_')
  112. if ns[0] in CoinProtocol.coins:
  113. nse,tn = (ns[2:],True) if len(ns) > 2 and ns[1] == 'testnet' else (ns[1:],False)
  114. cls = init_proto(ns[0],tn)
  115. attr = '_'.join(nse)
  116. else:
  117. cls = g
  118. attr = d.name
  119. refval = getattr(cls,attr)
  120. if type(refval) is dict and type(val) is str: # hack - catch single colon-separated value
  121. try:
  122. val = dict([val.split(':')])
  123. except:
  124. raise CfgFileParseError(f'Parse error in file {ucfg.fn!r}, line {d.lineno}')
  125. val_conv = set_for_type(val,refval,attr,src=ucfg.fn)
  126. setattr(cls,attr,val_conv)
  127. else:
  128. raise CfgFileParseError(f'{d.name!r}: unrecognized option in {ucfg.fn!r}, line {d.lineno}')
  129. def override_globals_and_set_opts_from_env(opt):
  130. for name in g.env_opts:
  131. if name == 'MMGEN_DEBUG_ALL':
  132. continue
  133. disable = name[:14] == 'MMGEN_DISABLE_'
  134. val = os.getenv(name) # os.getenv() returns None if env var is unset
  135. if val: # exclude empty string values; string value of '0' or 'false' sets variable to False
  136. gname = name[(6,14)[disable]:].lower()
  137. if hasattr(g,gname):
  138. setattr(g,gname,set_for_type(val,getattr(g,gname),name,disable))
  139. elif hasattr(opt,gname):
  140. if getattr(opt,gname) is None: # env must not override cmdline!
  141. setattr(opt,gname,val)
  142. else:
  143. raise ValueError(f'Name {gname} not present in globals or opts')
  144. def show_common_opts_diff():
  145. def common_opts_data_to_list():
  146. for l in common_opts_data['text'].splitlines():
  147. if l.startswith('--,'):
  148. yield l.split()[1].split('=')[0][2:].replace('-','_')
  149. def do_fmt(set_data):
  150. return fmt_list(['--'+s.replace('_','-') for s in set_data],fmt='col',indent=' ')
  151. a = set(g.common_opts)
  152. b = set(common_opts_data_to_list())
  153. m1 = 'g.common_opts - common_opts_data:\n {}\n'
  154. msg(m1.format(do_fmt(a-b) if a-b else 'None'))
  155. m2 = 'common_opts_data - g.common_opts (these do not set global var):\n{}\n'
  156. msg(m2.format(do_fmt(b-a)))
  157. m3 = 'common_opts_data ^ g.common_opts (these set global var):\n{}\n'
  158. msg(m3.format(do_fmt(b.intersection(a))))
  159. sys.exit(0)
  160. common_opts_data = {
  161. # Most but not all of these set the corresponding global var
  162. # View differences with show_common_opts_diff()
  163. 'text': """
  164. --, --accept-defaults Accept defaults at all prompts
  165. --, --coin=c Choose coin unit. Default: BTC. Current choice: {cu_dfl}
  166. --, --token=t Specify an ERC20 token by address or symbol
  167. --, --color=0|1 Disable or enable color output
  168. --, --force-256-color Force 256-color output when color is enabled
  169. --, --data-dir=path Specify {pnm} data directory location
  170. --, --daemon-data-dir=path Specify {dn} data directory location
  171. --, --no-license Suppress the GPL license prompt
  172. --, --rpc-host=host Communicate with {dn} running on host 'host'
  173. --, --rpc-port=port Communicate with {dn} listening on port 'port'
  174. --, --rpc-user=user Authenticate to {dn} using username 'user'
  175. --, --rpc-password=pass Authenticate to {dn} using password 'pass'
  176. --, --rpc-backend=backend Use backend 'backend' for JSON-RPC communications
  177. --, --aiohttp-rpc-queue-len=N Use 'N' simultaneous RPC connections with aiohttp
  178. --, --monero-wallet-rpc-host=host Specify Monero wallet daemon host
  179. --, --monero-wallet-rpc-user=user Specify Monero wallet daemon username
  180. --, --monero-wallet-rpc-password=pass Specify Monero wallet daemon password
  181. --, --regtest=0|1 Disable or enable regtest mode
  182. --, --testnet=0|1 Disable or enable testnet
  183. --, --skip-cfg-file Skip reading the configuration file
  184. --, --version Print version information and exit
  185. --, --bob Switch to user "Bob" in MMGen regtest setup
  186. --, --alice Switch to user "Alice" in MMGen regtest setup
  187. """,
  188. 'code': lambda help_notes,proto,s: s.format(
  189. pnm = g.proj_name,
  190. dn = help_notes('coind_exec'),
  191. cu_dfl = proto.coin,
  192. )
  193. }
  194. opts_data_dfl = {
  195. 'text': {
  196. 'desc': '',
  197. 'usage':'',
  198. 'options': """
  199. -h, --help Print this help message
  200. --, --longhelp Print help message for long (common) options
  201. """
  202. }
  203. }
  204. def init(opts_data=None,add_opts=None,init_opts=None,opt_filter=None,parse_only=False):
  205. if opts_data is None:
  206. opts_data = opts_data_dfl
  207. opts_data['text']['long_options'] = common_opts_data['text']
  208. # po: (user_opts,cmd_args,opts,skipped_opts)
  209. po = mmgen.share.Opts.parse_opts(opts_data,opt_filter=opt_filter,parse_only=parse_only)
  210. if init_opts: # allow programs to preload user opts
  211. for uopt,val in init_opts.items():
  212. if uopt not in po.user_opts:
  213. po.user_opts[uopt] = val
  214. if parse_only:
  215. return po
  216. if g.debug_opts:
  217. opt_preproc_debug(po)
  218. # Copy parsed opts to opt, setting values to None if not set by user
  219. for o in set(
  220. po.opts
  221. + po.skipped_opts
  222. + tuple(add_opts or [])
  223. + tuple(init_opts or [])
  224. + g.required_opts
  225. + g.common_opts ):
  226. setattr(opt,o,po.user_opts[o] if o in po.user_opts else None)
  227. # Make this available to usage()
  228. global usage_txt
  229. usage_txt = opts_data['text']['usage']
  230. if opt.version:
  231. version() # exits
  232. # === begin global var initialization === #
  233. """
  234. NB: user opt --data-dir is actually data_dir_root
  235. - data_dir is data_dir_root plus optionally 'regtest' or 'testnet', so for mainnet
  236. data_dir == data_dir_root
  237. - As with Bitcoin Core, cfg file is in data_dir_root, wallets and other data are
  238. in data_dir
  239. - Since cfg file is in data_dir_root, data_dir_root must be finalized before we
  240. can process cfg file
  241. - Since data_dir depends on the values of g.testnet and g.regtest, these must be
  242. finalized before setting data_dir
  243. """
  244. if opt.data_dir:
  245. g.data_dir_root = os.path.normpath(os.path.expanduser(opt.data_dir))
  246. elif os.getenv('MMGEN_TEST_SUITE'):
  247. from test.include.common import get_data_dir
  248. g.data_dir_root = get_data_dir()
  249. else:
  250. g.data_dir_root = os.path.join(g.home_dir,'.'+g.proj_name.lower())
  251. check_or_create_dir(g.data_dir_root)
  252. init_term_and_color()
  253. if not opt.skip_cfg_file:
  254. from .cfg import cfg_file
  255. cfg_file('sample') # check for changes in system template file
  256. override_globals_from_cfg_file(cfg_file('usr'))
  257. override_globals_and_set_opts_from_env(opt)
  258. # Set globals from opts, setting type from original global value
  259. # Do here, before opts are set from globals below
  260. for k in (g.common_opts + g.opt_sets_global):
  261. if hasattr(opt,k):
  262. val = getattr(opt,k)
  263. if val != None and hasattr(g,k):
  264. setattr(g,k,set_for_type(val,getattr(g,k),'--'+k))
  265. """
  266. g.testnet and g.regtest are finalized, so we can set g.data_dir
  267. """
  268. g.data_dir = os.path.normpath(os.path.join(
  269. g.data_dir_root,
  270. ('regtest' if g.regtest else 'testnet' if g.testnet else '') ))
  271. # Set user opts from globals:
  272. # - if opt is unset, set it to global value
  273. # - if opt is set, convert its type to that of global value
  274. for k in g.global_sets_opt:
  275. if hasattr(opt,k) and getattr(opt,k) != None:
  276. setattr(opt,k,set_for_type(getattr(opt,k),getattr(g,k),'--'+k))
  277. else:
  278. setattr(opt,k,getattr(g,k))
  279. if opt.show_hash_presets: # exits
  280. _show_hash_presets()
  281. g.coin = g.coin.upper() or 'BTC'
  282. g.token = g.token.upper() or None
  283. if g.bob or g.alice:
  284. g.regtest = True
  285. g.rpc_host = 'localhost'
  286. g.data_dir = os.path.join(g.data_dir_root,'regtest',g.coin.lower(),('alice','bob')[g.bob])
  287. from .regtest import MMGenRegtest
  288. g.rpc_user = MMGenRegtest.rpc_user
  289. g.rpc_password = MMGenRegtest.rpc_password
  290. g.rpc_port = MMGenRegtest(g.coin).d.rpc_port
  291. from .protocol import init_genonly_altcoins
  292. altcoin_trust_level = init_genonly_altcoins(
  293. g.coin,
  294. testnet = g.testnet or g.regtest )
  295. # === end global var initialization === #
  296. # print help screen only after global vars are initialized:
  297. if getattr(opt,'help',None) or getattr(opt,'longhelp',None):
  298. print_help(po,opts_data,opt_filter) # exits
  299. warn_altcoins(g.coin,altcoin_trust_level)
  300. die_on_incompatible_opts(g.incompatible_opts)
  301. check_or_create_dir(g.data_dir) # g.data_dir is finalized, so we can create it
  302. # Check user-set opts without modifying them
  303. check_usr_opts(po.user_opts)
  304. # Check all opts against g.autoset_opts, setting if unset
  305. check_and_set_autoset_opts()
  306. set_auto_typeset_opts()
  307. if opt.verbose:
  308. opt.quiet = None
  309. if g.debug and g.prog_name != 'test.py':
  310. opt.verbose,opt.quiet = (True,None)
  311. if g.debug_opts:
  312. opt_postproc_debug()
  313. # We don't need this data anymore
  314. del mmgen.share.Opts
  315. for k in ('text','notes','code'):
  316. if k in opts_data:
  317. del opts_data[k]
  318. g.lock()
  319. opt.lock()
  320. return po.cmd_args
  321. # DISABLED
  322. def opt_is_tx_fee(key,val,desc): # 'key' must remain a placeholder
  323. # contract data or non-standard startgas: disable fee checking
  324. if hasattr(opt,'contract_data') and opt.contract_data:
  325. return
  326. if hasattr(opt,'tx_gas') and opt.tx_gas:
  327. return
  328. from .tx import MMGenTX
  329. from .protocol import init_proto_from_opts
  330. tx = MMGenTX.New(init_proto_from_opts())
  331. # Size of 224 is just a ball-park figure to eliminate the most extreme cases at startup
  332. # This check will be performed again once we know the true size
  333. ret = tx.process_fee_spec(val,224)
  334. if ret == False:
  335. raise UserOptError('{!r}: invalid {}\n(not a {} amount or {} specification)'.format(
  336. val,desc,tx.proto.coin.upper(),tx.rel_fee_desc))
  337. if ret > tx.proto.max_tx_fee:
  338. raise UserOptError('{!r}: invalid {}\n({} > max_tx_fee ({} {}))'.format(
  339. val,desc,ret.fmt(fs='1.1'),tx.proto.max_tx_fee,tx.proto.coin.upper()))
  340. def check_usr_opts(usr_opts): # Raises an exception if any check fails
  341. def opt_splits(val,sep,n,desc):
  342. sepword = 'comma' if sep == ',' else 'colon' if sep == ':' else repr(sep)
  343. try:
  344. l = val.split(sep)
  345. except:
  346. raise UserOptError('{!r}: invalid {} (not {}-separated list)'.format(val,desc,sepword))
  347. if len(l) != n:
  348. raise UserOptError('{!r}: invalid {} ({} {}-separated items required)'.format(val,desc,n,sepword))
  349. def opt_compares(val,op_str,target,desc,desc2=''):
  350. import operator as o
  351. op_f = { '<':o.lt, '<=':o.le, '>':o.gt, '>=':o.ge, '=':o.eq }[op_str]
  352. if not op_f(val,target):
  353. d2 = desc2 + ' ' if desc2 else ''
  354. raise UserOptError('{}: invalid {} ({}not {} {})'.format(val,desc,d2,op_str,target))
  355. def opt_is_int(val,desc):
  356. if not is_int(val):
  357. raise UserOptError('{!r}: invalid {} (not an integer)'.format(val,desc))
  358. def opt_is_float(val,desc):
  359. try:
  360. float(val)
  361. except:
  362. raise UserOptError('{!r}: invalid {} (not a floating-point number)'.format(val,desc))
  363. def opt_is_in_list(val,tlist,desc):
  364. if val not in tlist:
  365. q,sep = (('',','),("'","','"))[type(tlist[0]) == str]
  366. fs = '{q}{v}{q}: invalid {w}\nValid choices: {q}{o}{q}'
  367. raise UserOptError(fs.format(v=val,w=desc,q=q,o=sep.join(map(str,sorted(tlist)))))
  368. def opt_unrecognized(key,val,desc='value'):
  369. raise UserOptError('{!r}: unrecognized {} for option {!r}'.format(val,desc,fmt_opt(key)))
  370. def opt_display(key,val='',beg='For selected',end=':\n'):
  371. s = '{}={}'.format(fmt_opt(key),val) if val else fmt_opt(key)
  372. msg_r('{} option {!r}{}'.format(beg,s,end))
  373. def chk_in_fmt(key,val,desc):
  374. from .wallet import Wallet,IncogWallet,Brainwallet,IncogWalletHidden
  375. sstype = Wallet.fmt_code_to_type(val)
  376. if not sstype:
  377. opt_unrecognized(key,val)
  378. if key == 'out_fmt':
  379. p = 'hidden_incog_output_params'
  380. if sstype == IncogWalletHidden and not getattr(opt,p):
  381. m1 = 'Hidden incog format output requested. '
  382. m2 = 'You must supply a file and offset with the {!r} option'
  383. raise UserOptError(m1+m2.format(fmt_opt(p)))
  384. if issubclass(sstype,IncogWallet) and opt.old_incog_fmt:
  385. opt_display(key,val,beg='Selected',end=' ')
  386. opt_display('old_incog_fmt',beg='conflicts with',end=':\n')
  387. raise UserOptError('Export to old incog wallet format unsupported')
  388. elif issubclass(sstype,Brainwallet):
  389. raise UserOptError('Output to brainwallet format unsupported')
  390. chk_out_fmt = chk_in_fmt
  391. def chk_hidden_incog_input_params(key,val,desc):
  392. a = val.rsplit(',',1) # permit comma in filename
  393. if len(a) != 2:
  394. opt_display(key,val)
  395. raise UserOptError('Option requires two comma-separated arguments')
  396. fn,offset = a
  397. opt_is_int(offset,desc)
  398. if key == 'hidden_incog_input_params':
  399. check_infile(fn,blkdev_ok=True)
  400. key2 = 'in_fmt'
  401. else:
  402. try: os.stat(fn)
  403. except:
  404. b = os.path.dirname(fn)
  405. if b: check_outdir(b)
  406. else:
  407. check_outfile(fn,blkdev_ok=True)
  408. key2 = 'out_fmt'
  409. if hasattr(opt,key2):
  410. val2 = getattr(opt,key2)
  411. from .wallet import IncogWalletHidden
  412. if val2 and val2 not in IncogWalletHidden.fmt_codes:
  413. fs = 'Option conflict:\n {}, with\n {}={}'
  414. raise UserOptError(fs.format(fmt_opt(key),fmt_opt(key2),val2))
  415. chk_hidden_incog_output_params = chk_hidden_incog_input_params
  416. def chk_seed_len(key,val,desc):
  417. opt_is_int(val,desc)
  418. opt_is_in_list(int(val),g.seed_lens,desc)
  419. def chk_hash_preset(key,val,desc):
  420. opt_is_in_list(val,list(g.hash_presets.keys()),desc)
  421. def chk_brain_params(key,val,desc):
  422. a = val.split(',')
  423. if len(a) != 2:
  424. opt_display(key,val)
  425. raise UserOptError('Option requires two comma-separated arguments')
  426. opt_is_int(a[0],'seed length '+desc)
  427. opt_is_in_list(int(a[0]),g.seed_lens,'seed length '+desc)
  428. opt_is_in_list(a[1],list(g.hash_presets.keys()),'hash preset '+desc)
  429. def chk_usr_randchars(key,val,desc):
  430. if val == 0:
  431. return
  432. opt_is_int(val,desc)
  433. opt_compares(val,'>=',g.min_urandchars,desc)
  434. opt_compares(val,'<=',g.max_urandchars,desc)
  435. def chk_tx_fee(key,val,desc):
  436. pass
  437. # opt_is_tx_fee(key,val,desc) # TODO: move this check elsewhere
  438. def chk_tx_confs(key,val,desc):
  439. opt_is_int(val,desc)
  440. opt_compares(val,'>=',1,desc)
  441. def chk_vsize_adj(key,val,desc):
  442. opt_is_float(val,desc)
  443. ymsg('Adjusting transaction vsize by a factor of {:1.2f}'.format(float(val)))
  444. def chk_key_generator(key,val,desc):
  445. opt_compares(val,'<=',len(g.key_generators),desc)
  446. opt_compares(val,'>',0,desc)
  447. def chk_coin(key,val,desc):
  448. from .protocol import CoinProtocol
  449. opt_is_in_list(val.lower(),CoinProtocol.coins,'coin')
  450. # TODO: move this check elsewhere
  451. # def chk_rbf(key,val,desc):
  452. # if not proto.cap('rbf'):
  453. # m = '--rbf requested, but {} does not support replace-by-fee transactions'
  454. # raise UserOptError(m.format(proto.coin))
  455. def chk_bob(key,val,desc):
  456. m = "Regtest (Bob and Alice) mode not set up yet. Run '{}-regtest setup' to initialize."
  457. from .regtest import MMGenRegtest
  458. try:
  459. os.stat(os.path.join(MMGenRegtest(g.coin).d.datadir,'regtest','debug.log'))
  460. except:
  461. raise UserOptError(m.format(g.proj_name.lower()))
  462. chk_alice = chk_bob
  463. def chk_locktime(key,val,desc):
  464. opt_is_int(val,desc)
  465. opt_compares(int(val),'>',0,desc)
  466. # TODO: move this check elsewhere
  467. # def chk_token(key,val,desc):
  468. # if not 'token' in proto.caps:
  469. # raise UserOptError('Coin {!r} does not support the --token option'.format(tx.coin))
  470. # if len(val) == 40 and is_hex_str(val):
  471. # return
  472. # if len(val) > 20 or not all(s.isalnum() for s in val):
  473. # raise UserOptError('{!r}: invalid parameter for --token option'.format(val))
  474. cfuncs = { k:v for k,v in locals().items() if k.startswith('chk_') }
  475. for key in usr_opts:
  476. val = getattr(opt,key)
  477. desc = 'parameter for {!r} option'.format(fmt_opt(key))
  478. if key in g.infile_opts:
  479. check_infile(val) # file exists and is readable - dies on error
  480. elif key == 'outdir':
  481. check_outdir(val) # dies on error
  482. elif 'chk_'+key in cfuncs:
  483. cfuncs['chk_'+key](key,val,desc)
  484. elif g.debug:
  485. Msg('check_usr_opts(): No test for opt {!r}'.format(key))
  486. def set_auto_typeset_opts():
  487. for key,ref_type in g.auto_typeset_opts.items():
  488. if hasattr(opt,key):
  489. val = getattr(opt,key)
  490. if val is not None: # typeset only if opt is set
  491. setattr(opt,key,ref_type(val))
  492. def check_and_set_autoset_opts(): # Raises exception if any check fails
  493. def nocase_str(key,val,asd):
  494. try:
  495. return asd.choices.index(val)
  496. except:
  497. return 'one of'
  498. def nocase_pfx(key,val,asd):
  499. cs = [s.startswith(val.lower()) for s in asd.choices]
  500. if cs.count(True) == 1:
  501. return cs.index(True)
  502. else:
  503. return 'unique substring of'
  504. for key,asd in g.autoset_opts.items():
  505. if hasattr(opt,key):
  506. val = getattr(opt,key)
  507. if val is None:
  508. setattr(opt,key,asd.choices[0])
  509. else:
  510. ret = locals()[asd.type](key,val,asd)
  511. if type(ret) is str:
  512. m = '{!r}: invalid parameter for option --{} (not {}: {})'
  513. raise UserOptError(m.format(val,key.replace('_','-'),ret,fmt_list(asd.choices)))
  514. elif ret is True:
  515. setattr(opt,key,val)
  516. else:
  517. setattr(opt,key,asd.choices[ret])