opts.py 22 KB

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