opts.py 20 KB

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