opts.py 21 KB

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