opts.py 21 KB

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