cfg.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2023 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. cfg: Configuration classes for the MMGen suite
  20. """
  21. import sys,os
  22. from collections import namedtuple
  23. from .base_obj import Lockable
  24. def die(*args,**kwargs):
  25. from .util import die
  26. die(*args,**kwargs)
  27. def die2(exit_val,s):
  28. sys.stderr.write(s+'\n')
  29. sys.exit(exit_val)
  30. class GlobalConstants(Lockable):
  31. """
  32. These values are non-configurable. They’re constant for a given machine,
  33. user, executable and MMGen release.
  34. """
  35. _autolock = True
  36. proj_name = 'MMGen'
  37. proj_url = 'https://github.com/mmgen/mmgen'
  38. author = 'The MMGen Project'
  39. email = '<mmgen@tuta.io>'
  40. Cdates = '2013-2023'
  41. dfl_hash_preset = '3'
  42. passwd_max_tries = 5
  43. min_screen_width = 80
  44. min_time_precision = 18
  45. # must match CoinProtocol.coins
  46. core_coins = ('btc','bch','ltc','eth','etc','zec','xmr')
  47. prog_name = os.path.basename(sys.argv[0])
  48. is_txprog = prog_name == 'mmgen-regtest' or prog_name.startswith('mmgen-tx')
  49. for k in ('linux','win','msys'):
  50. if sys.platform.startswith(k):
  51. platform = { 'linux':'linux', 'win':'win', 'msys':'win' }[k]
  52. break
  53. else:
  54. die2(1,f'{sys.platform!r}: platform not supported by {proj_name}')
  55. if os.getenv('HOME'): # Linux or MSYS2
  56. home_dir = os.getenv('HOME')
  57. elif platform == 'win': # Windows without MSYS2 - not supported
  58. die2(1,f'$HOME not set! {proj_name} for Windows must be run in MSYS2 environment')
  59. else:
  60. die2(2,'$HOME is not set! Unable to determine home directory')
  61. def get_mmgen_data_file(self,filename,package='mmgen'):
  62. """
  63. this is an expensive import, so do only when required
  64. """
  65. # Resource will be unpacked and then cleaned up if necessary, see:
  66. # https://docs.python.org/3/library/importlib.html:
  67. # Note: This module provides functionality similar to pkg_resources Basic
  68. # Resource Access without the performance overhead of that package.
  69. # https://importlib-resources.readthedocs.io/en/latest/migration.html
  70. # https://setuptools.readthedocs.io/en/latest/pkg_resources.html
  71. try:
  72. from importlib.resources import files # Python 3.9
  73. except ImportError:
  74. from importlib_resources import files
  75. return files(package).joinpath('data',filename).read_text()
  76. @property
  77. def version(self):
  78. return self.get_mmgen_data_file(
  79. filename = 'version',
  80. package = 'mmgen_node_tools' if self.prog_name.startswith('mmnode-') else 'mmgen'
  81. ).strip()
  82. @property
  83. def release_date(self):
  84. return self.get_mmgen_data_file(filename='release_date').strip()
  85. gc = GlobalConstants()
  86. class GlobalVars:
  87. """
  88. These are used only by the test suite to redirect msg() and friends to /dev/null
  89. """
  90. stdout = sys.stdout
  91. stderr = sys.stderr
  92. gv = GlobalVars()
  93. class Config(Lockable):
  94. """
  95. These values are configurable - RHS values are defaults
  96. Globals are overridden with the following precedence:
  97. 1 - command line
  98. 2 - environmental vars
  99. 3 - config file
  100. """
  101. _autolock = False
  102. _set_ok = ('usr_randchars','_proto')
  103. _reset_ok = ('accept_defaults','quiet','verbose','yes')
  104. _use_class_attr = True
  105. _default_to_none = True
  106. # general
  107. coin = 'BTC'
  108. token = ''
  109. outdir = ''
  110. passwd_file = ''
  111. network = 'mainnet'
  112. testnet = False
  113. regtest = False
  114. # verbosity / prompting behavior
  115. quiet = False
  116. verbose = False
  117. yes = False
  118. accept_defaults = False
  119. no_license = False
  120. # limits
  121. http_timeout = 60
  122. usr_randchars = 30
  123. fee_adjust = 1.0
  124. fee_estimate_confs = 3
  125. minconf = 1
  126. max_tx_file_size = 100000
  127. max_input_size = 1024 * 1024
  128. min_urandchars = 10
  129. max_urandchars = 80
  130. # debug
  131. debug = False
  132. debug_daemon = False
  133. debug_opts = False
  134. debug_rpc = False
  135. debug_addrlist = False
  136. debug_subseed = False
  137. debug_tw = False
  138. devtools = False
  139. # rpc:
  140. rpc_host = ''
  141. rpc_port = 0
  142. rpc_user = ''
  143. rpc_password = ''
  144. monero_wallet_rpc_user = 'monero'
  145. monero_wallet_rpc_password = ''
  146. aiohttp_rpc_queue_len = 16
  147. cached_balances = False
  148. # daemons
  149. daemon_data_dir = '' # set by user
  150. daemon_id = ''
  151. blacklisted_daemons = ''
  152. ignore_daemon_version = False
  153. # display:
  154. test_suite_enable_color = False # placeholder
  155. force_256_color = False
  156. scroll = False
  157. pager = False
  158. columns = 0
  159. color = bool(
  160. ( sys.stdout.isatty() and not os.getenv('MMGEN_TEST_SUITE_PEXPECT') ) or
  161. os.getenv('MMGEN_TEST_SUITE_ENABLE_COLOR')
  162. )
  163. # miscellaneous features:
  164. use_internal_keccak_module = False
  165. force_standalone_scrypt_module = False
  166. enable_erigon = False
  167. autochg_ignore_labels = False
  168. # regtest:
  169. bob = False
  170. alice = False
  171. carol = False
  172. regtest_user = ''
  173. # test suite:
  174. bogus_send = False
  175. bogus_unspent_data = ''
  176. debug_utf8 = False
  177. exec_wrapper = False
  178. test_suite = False
  179. test_suite_autosign_led_simulate = False
  180. test_suite_xmr_autosign = False
  181. test_suite_cfgtest = False
  182. test_suite_deterministic = False
  183. test_suite_pexpect = False
  184. test_suite_popen_spawn = False
  185. hold_protect_disable = False
  186. no_daemon_autostart = False
  187. names = False
  188. no_timings = False
  189. exit_after = ''
  190. resuming = False
  191. skipping_deps = False
  192. test_datadir = os.path.join('test','data_dir' + ('','-α')[bool(os.getenv('MMGEN_DEBUG_UTF8'))])
  193. mnemonic_entry_modes = {}
  194. # external use:
  195. _opts = None
  196. _proto = None
  197. # internal use:
  198. _use_cfg_file = False
  199. _use_env = False
  200. _forbidden_opts = (
  201. 'data_dir_root',
  202. )
  203. _incompatible_opts = (
  204. ('help','longhelp'),
  205. ('bob','alice','carol'),
  206. ('label','keep_label'),
  207. ('tx_id','info'),
  208. ('tx_id','terse_info'),
  209. )
  210. _cfg_file_opts = (
  211. 'autochg_ignore_labels',
  212. 'color',
  213. 'daemon_data_dir',
  214. 'debug',
  215. 'fee_adjust',
  216. 'force_256_color',
  217. 'hash_preset',
  218. 'http_timeout',
  219. 'max_input_size',
  220. 'max_tx_file_size',
  221. 'mnemonic_entry_modes',
  222. 'monero_wallet_rpc_password',
  223. 'monero_wallet_rpc_user',
  224. 'no_license',
  225. 'quiet',
  226. 'regtest',
  227. 'rpc_host',
  228. 'rpc_password',
  229. 'rpc_port',
  230. 'rpc_user',
  231. 'scroll',
  232. 'subseeds',
  233. 'testnet',
  234. 'usr_randchars',
  235. 'bch_max_tx_fee',
  236. 'btc_max_tx_fee',
  237. 'eth_max_tx_fee',
  238. 'ltc_max_tx_fee',
  239. 'bch_ignore_daemon_version',
  240. 'btc_ignore_daemon_version',
  241. 'etc_ignore_daemon_version',
  242. 'eth_ignore_daemon_version',
  243. 'ltc_ignore_daemon_version',
  244. 'xmr_ignore_daemon_version',
  245. 'eth_mainnet_chain_names',
  246. 'eth_testnet_chain_names' )
  247. # Supported environmental vars
  248. # The corresponding attributes (lowercase, without 'mmgen_') must exist in the class.
  249. # The 'MMGEN_DISABLE_' prefix sets the corresponding attribute to False.
  250. _env_opts = (
  251. 'MMGEN_DEBUG_ALL', # special: there is no `debug_all` attribute
  252. 'MMGEN_COLUMNS',
  253. 'MMGEN_TEST_SUITE',
  254. 'MMGEN_TEST_SUITE_AUTOSIGN_LED_SIMULATE',
  255. 'MMGEN_TEST_SUITE_XMR_AUTOSIGN',
  256. 'MMGEN_TEST_SUITE_CFGTEST',
  257. 'MMGEN_TEST_SUITE_DETERMINISTIC',
  258. 'MMGEN_TEST_SUITE_ENABLE_COLOR',
  259. 'MMGEN_TEST_SUITE_PEXPECT',
  260. 'MMGEN_TEST_SUITE_POPEN_SPAWN',
  261. 'MMGEN_BLACKLIST_DAEMONS',
  262. 'MMGEN_BOGUS_SEND',
  263. 'MMGEN_BOGUS_UNSPENT_DATA',
  264. 'MMGEN_DEBUG',
  265. 'MMGEN_DEBUG_DAEMON',
  266. 'MMGEN_DEBUG_OPTS',
  267. 'MMGEN_DEBUG_RPC',
  268. 'MMGEN_DEBUG_ADDRLIST',
  269. 'MMGEN_DEBUG_TW',
  270. 'MMGEN_DEBUG_UTF8',
  271. 'MMGEN_DEBUG_SUBSEED',
  272. 'MMGEN_DEVTOOLS',
  273. 'MMGEN_FORCE_256_COLOR',
  274. 'MMGEN_HOLD_PROTECT_DISABLE',
  275. 'MMGEN_QUIET',
  276. 'MMGEN_NO_LICENSE',
  277. 'MMGEN_RPC_HOST',
  278. 'MMGEN_RPC_FAIL_ON_COMMAND',
  279. 'MMGEN_TESTNET',
  280. 'MMGEN_REGTEST',
  281. 'MMGEN_EXEC_WRAPPER',
  282. 'MMGEN_RPC_BACKEND',
  283. 'MMGEN_IGNORE_DAEMON_VERSION',
  284. 'MMGEN_USE_STANDALONE_SCRYPT_MODULE',
  285. 'MMGEN_ENABLE_ERIGON',
  286. 'MMGEN_DISABLE_COLOR',
  287. )
  288. _infile_opts = (
  289. 'keys_from_file',
  290. 'mmgen_keys_from_file',
  291. 'passwd_file',
  292. 'keysforaddrs',
  293. 'comment_file',
  294. 'contract_data',
  295. )
  296. # Auto-typechecked and auto-set opts - first value in list is the default
  297. _ov = namedtuple('autoset_opt_info',['type','choices'])
  298. _autoset_opts = {
  299. 'fee_estimate_mode': _ov('nocase_pfx', ['conservative','economical']),
  300. 'rpc_backend': _ov('nocase_pfx', ['auto','httplib','curl','aiohttp','requests']),
  301. }
  302. _auto_typeset_opts = {
  303. 'seed_len': int,
  304. 'subseeds': int,
  305. 'vsize_adj': float,
  306. }
  307. # test suite:
  308. err_disp_timeout = 0.7
  309. short_disp_timeout = 0.3
  310. stdin_tty = sys.stdin.isatty()
  311. if os.getenv('MMGEN_TEST_SUITE'):
  312. min_urandchars = 3
  313. err_disp_timeout = 0.1
  314. short_disp_timeout = 0.1
  315. if os.getenv('MMGEN_TEST_SUITE_POPEN_SPAWN'):
  316. stdin_tty = True
  317. if gc.prog_name == 'unit_tests.py':
  318. _set_ok += ('debug_subseed',)
  319. _reset_ok += ('force_standalone_scrypt_module',)
  320. if os.getenv('MMGEN_DEBUG_ALL'):
  321. for name in _env_opts:
  322. if name[:11] == 'MMGEN_DEBUG':
  323. os.environ[name] = '1'
  324. @property
  325. def data_dir_root(self):
  326. """
  327. location of mmgen.cfg
  328. """
  329. if hasattr(self,'_data_dir_root'):
  330. return self._data_dir_root
  331. else:
  332. if self._data_dir_root_override:
  333. self._data_dir_root = os.path.normpath(os.path.abspath(self._data_dir_root_override))
  334. elif self.test_suite:
  335. self._data_dir_root = self.test_datadir
  336. else:
  337. self._data_dir_root = os.path.join(gc.home_dir,'.'+gc.proj_name.lower())
  338. return self._data_dir_root
  339. @property
  340. def data_dir(self):
  341. """
  342. location of wallet and other data - same as data_dir_root for mainnet
  343. """
  344. if hasattr(self,'_data_dir'):
  345. return self._data_dir
  346. else:
  347. self._data_dir = os.path.normpath(os.path.join(*{
  348. 'regtest': (self.data_dir_root, 'regtest', self.coin.lower(), (self.regtest_user or 'none') ),
  349. 'testnet': (self.data_dir_root, 'testnet'),
  350. 'mainnet': (self.data_dir_root,),
  351. }[self.network] ))
  352. return self._data_dir
  353. def __init__(
  354. self,
  355. cfg = None,
  356. opts_data = None,
  357. init_opts = None,
  358. opt_filter = None,
  359. parse_only = False,
  360. parsed_opts = None,
  361. need_proto = True,
  362. need_amt = True,
  363. do_post_init = False,
  364. process_opts = False ):
  365. # Step 1: get user-supplied configuration data from a) command line, or b) first argument
  366. # to constructor; save to self._uopts:
  367. self._cloned = {}
  368. if opts_data or parsed_opts or process_opts:
  369. assert cfg is None, (
  370. 'Config(): ‘cfg’ cannot be used simultaneously with ' +
  371. '‘opts_data’, ‘parsed_opts’ or ‘process_opts’' )
  372. from mmgen.opts import UserOpts
  373. UserOpts(
  374. cfg = self,
  375. opts_data = opts_data,
  376. init_opts = init_opts,
  377. opt_filter = opt_filter,
  378. parse_only = parse_only,
  379. parsed_opts = parsed_opts )
  380. self._uopt_desc = 'command-line option'
  381. else:
  382. if cfg is None:
  383. self._uopts = {}
  384. else:
  385. if '_clone' in cfg:
  386. assert isinstance( cfg['_clone'], Config )
  387. self._cloned = cfg['_clone'].__dict__
  388. for k,v in self._cloned.items():
  389. if not k.startswith('_'):
  390. setattr(self,k,v)
  391. del cfg['_clone']
  392. self._uopts = cfg
  393. self._uopt_desc = 'configuration option'
  394. self._data_dir_root_override = self._cloned.pop(
  395. '_data_dir_root_override',
  396. self._uopts.pop('data_dir',None))
  397. if parse_only and not any(k in self._uopts for k in ['help','longhelp']):
  398. return
  399. # Step 2: set cfg from user-supplied data, skipping auto opts; set type from corresponding
  400. # class attribute, if it exists:
  401. auto_opts = tuple(self._autoset_opts) + tuple(self._auto_typeset_opts)
  402. for key,val in self._uopts.items():
  403. assert key.isascii() and key.isidentifier() and key[0] != '_', '{key!r}: malformed configuration option'
  404. assert key not in self._forbidden_opts, '{key!r}: forbidden configuration option'
  405. if key not in auto_opts:
  406. setattr(
  407. self,
  408. key,
  409. conv_type(key, val, getattr(self,key), self._uopt_desc ) if hasattr(self,key) else val )
  410. # Step 3: set cfg from environment, skipping already-set opts; save names set from environment:
  411. self._envopts = tuple(self._set_cfg_from_env()) if self._use_env else ()
  412. from .term import init_term
  413. init_term(self) # requires ‘hold_protect_disable’ (set from env)
  414. from .fileutil import check_or_create_dir
  415. check_or_create_dir(self.data_dir_root)
  416. from .util import wrap_ripemd160
  417. wrap_ripemd160() # ripemd160 required by mmgen_cfg_file() in _set_cfg_from_cfg_file()
  418. # Step 4: set cfg from cfgfile, skipping already-set opts and auto opts; save set opts and auto
  419. # opts to be set:
  420. # requires ‘data_dir_root’, ‘test_suite_cfgtest’
  421. self._cfgfile_opts = self._set_cfg_from_cfg_file( self._envopts, need_proto )
  422. # Step 5: set autoset opts from user-supplied data, cfgfile data, or default values, in that order:
  423. self._set_autoset_opts( self._cfgfile_opts.autoset )
  424. # Step 6: set auto typeset opts from user-supplied data or cfgfile data, in that order:
  425. self._set_auto_typeset_opts( self._cfgfile_opts.auto_typeset )
  426. if self.regtest or self.bob or self.alice or self.carol or gc.prog_name == 'mmgen-regtest':
  427. self.network = 'regtest'
  428. self.regtest_user = 'bob' if self.bob else 'alice' if self.alice else 'carol' if self.carol else None
  429. else:
  430. self.network = 'testnet' if self.testnet else 'mainnet'
  431. self.coin = self.coin.upper()
  432. self.token = self.token.upper() if self.token else None
  433. # self.color is finalized, so initialize color:
  434. if self.color: # MMGEN_DISABLE_COLOR sets this to False
  435. from .color import init_color
  436. init_color(num_colors=256 if self.force_256_color else 'auto')
  437. self._die_on_incompatible_opts()
  438. check_or_create_dir(self.data_dir)
  439. if self.debug and gc.prog_name != 'test.py':
  440. self.verbose = True
  441. self.quiet = False
  442. if self.debug_opts:
  443. opt_postproc_debug(self)
  444. from .util import Util
  445. self._util = Util(self)
  446. del self._cloned
  447. self._lock()
  448. if need_proto:
  449. from .protocol import warn_trustlevel,init_proto_from_cfg
  450. warn_trustlevel(self)
  451. # requires the default-to-none behavior, so do after the lock:
  452. self._proto = init_proto_from_cfg(self,need_amt=need_amt)
  453. if self._opts and not do_post_init:
  454. self._opts.init_bottom(self)
  455. # Check user-set opts without modifying them
  456. check_opts(self)
  457. def _set_cfg_from_env(self):
  458. for name,val in ((k,v) for k,v in os.environ.items() if k.startswith('MMGEN_')):
  459. if name == 'MMGEN_DEBUG_ALL':
  460. continue
  461. elif name in self._env_opts:
  462. if val: # ignore empty string values; string value of '0' or 'false' sets variable to False
  463. disable = name.startswith('MMGEN_DISABLE_')
  464. gname = name[(6,14)[disable]:].lower()
  465. if gname in self._uopts: # don’t touch attr if already set by user
  466. continue
  467. elif hasattr(self,gname):
  468. setattr(
  469. self,
  470. gname,
  471. conv_type( name, val, getattr(self,gname), 'environment var', invert_bool=disable ))
  472. yield gname
  473. else:
  474. raise ValueError(f'Name {gname!r} not present in globals')
  475. else:
  476. raise ValueError(f'{name!r} is not a valid MMGen environment variable')
  477. def _set_cfg_from_cfg_file(
  478. self,
  479. env_cfg,
  480. need_proto ):
  481. _ret = namedtuple('cfgfile_opts',['non_auto','autoset','auto_typeset'])
  482. if not self._use_cfg_file:
  483. return _ret( (), {}, {} )
  484. # check for changes in system template file (term must be initialized)
  485. from .cfgfile import mmgen_cfg_file
  486. mmgen_cfg_file(self,'sample')
  487. ucfg = mmgen_cfg_file(self,'usr')
  488. self._cfgfile_fn = ucfg.fn
  489. if need_proto:
  490. from .protocol import init_proto
  491. autoset_opts = {}
  492. auto_typeset_opts = {}
  493. non_auto_opts = []
  494. already_set = tuple(self._uopts) + env_cfg
  495. for d in ucfg.get_lines():
  496. if d.name in self._cfg_file_opts:
  497. ns = d.name.split('_')
  498. if ns[0] in gc.core_coins:
  499. if not need_proto:
  500. continue
  501. nse,tn = (
  502. (ns[2:],ns[1]=='testnet') if len(ns) > 2 and ns[1] in ('mainnet','testnet') else
  503. (ns[1:],False)
  504. )
  505. cls = type(init_proto( self, ns[0], tn, need_amt=True )) # no instance yet, so override _class_ attr
  506. attr = '_'.join(nse)
  507. else:
  508. cls = self
  509. attr = d.name
  510. refval = getattr(cls,attr)
  511. val = ucfg.parse_value(d.value,refval)
  512. if not val:
  513. die( 'CfgFileParseError', f'Parse error in file {ucfg.fn!r}, line {d.lineno}' )
  514. val_conv = conv_type( attr, val, refval, 'configuration file option', src=ucfg.fn )
  515. if not attr in already_set:
  516. setattr(cls,attr,val_conv)
  517. non_auto_opts.append(attr)
  518. elif d.name in self._autoset_opts:
  519. autoset_opts[d.name] = d.value
  520. elif d.name in self._auto_typeset_opts:
  521. auto_typeset_opts[d.name] = d.value
  522. else:
  523. die( 'CfgFileParseError', f'{d.name!r}: unrecognized option in {ucfg.fn!r}, line {d.lineno}' )
  524. return _ret( tuple(non_auto_opts), autoset_opts, auto_typeset_opts )
  525. def _set_autoset_opts(self,cfgfile_autoset_opts):
  526. def get_autoset_opt(key,val,src):
  527. def die_on_err(desc):
  528. from .util import fmt_list
  529. die(
  530. 'UserOptError',
  531. '{a!r}: invalid {b} (not {c}: {d})'.format(
  532. a = val,
  533. b = {
  534. 'cmdline': 'parameter for option --{}'.format(key.replace('_','-')),
  535. 'cfgfile': 'value for cfg file option {!r}'.format(key)
  536. }[src],
  537. c = desc,
  538. d = fmt_list(data.choices) ))
  539. class opt_type:
  540. def nocase_str():
  541. if val.lower() in data.choices:
  542. return val.lower()
  543. else:
  544. die_on_err('one of')
  545. def nocase_pfx():
  546. cs = [s for s in data.choices if s.startswith(val.lower())]
  547. if len(cs) == 1:
  548. return cs[0]
  549. else:
  550. die_on_err('unique substring of')
  551. data = self._autoset_opts[key]
  552. return getattr(opt_type,data.type)()
  553. # Check autoset opts, setting if unset
  554. for key in self._autoset_opts:
  555. if key in self._cloned:
  556. continue
  557. assert not hasattr(self,key), f'autoset opt {key!r} is already set, but it shouldn’t be!'
  558. if key in self._uopts:
  559. val,src = (self._uopts[key],'cmdline')
  560. elif key in cfgfile_autoset_opts:
  561. val,src = (cfgfile_autoset_opts[key],'cfgfile')
  562. else:
  563. val = None
  564. if val is None:
  565. setattr(self, key, self._autoset_opts[key].choices[0])
  566. else:
  567. setattr(self, key, get_autoset_opt(key,val,src=src))
  568. def _set_auto_typeset_opts(self,cfgfile_auto_typeset_opts):
  569. def do_set(key,val,ref_type):
  570. assert not hasattr(self,key), f'{key!r} is in cfg!'
  571. setattr(self,key,None if val is None else ref_type(val))
  572. for key,ref_type in self._auto_typeset_opts.items():
  573. if key in self._uopts:
  574. do_set(key, self._uopts[key], ref_type)
  575. elif key in cfgfile_auto_typeset_opts:
  576. do_set(key, cfgfile_auto_typeset_opts[key], ref_type)
  577. def _post_init(self):
  578. return self._opts.init_bottom(self)
  579. def _die_on_incompatible_opts(self):
  580. for group in self._incompatible_opts:
  581. bad = [k for k in self.__dict__ if k in group and getattr(self,k) != None]
  582. if len(bad) > 1:
  583. die(1,'Conflicting options: {}'.format(', '.join(map(fmt_opt,bad))))
  584. def check_opts(cfg): # Raises exception if any check fails
  585. from .util import is_int,Msg
  586. def get_desc(desc_pfx=''):
  587. return (
  588. (desc_pfx + ' ' if desc_pfx else '')
  589. + (
  590. f'parameter for command-line option {fmt_opt(name)!r}'
  591. if name in cfg._uopts and 'command-line' in cfg._uopt_desc else
  592. f'value for configuration option {name!r}'
  593. )
  594. + ( ' from environment' if name in cfg._envopts else '')
  595. + (f' in {cfg._cfgfile_fn!r}' if name in cfg._cfgfile_opts.non_auto else '')
  596. )
  597. def display_opt(name,val='',beg='For selected',end=':\n'):
  598. from .util import msg_r
  599. msg_r('{} option {!r}{}'.format(
  600. beg,
  601. f'{fmt_opt(name)}={val}' if val else fmt_opt(name),
  602. end ))
  603. def opt_compares(val,op_str,target):
  604. import operator
  605. if not {
  606. '<': operator.lt,
  607. '<=': operator.le,
  608. '>': operator.gt,
  609. '>=': operator.ge,
  610. '=': operator.eq,
  611. }[op_str](val,target):
  612. die( 'UserOptError', f'{val}: invalid {get_desc()} (not {op_str} {target})' )
  613. def opt_is_int(val,desc_pfx=''):
  614. if not is_int(val):
  615. die( 'UserOptError', f'{val!r}: invalid {get_desc(desc_pfx)} (not an integer)' )
  616. def opt_is_in_list(val,tlist,desc_pfx=''):
  617. if val not in tlist:
  618. q,sep = (('',','),("'","','"))[type(tlist[0]) == str]
  619. die( 'UserOptError', '{q}{v}{q}: invalid {w}\nValid choices: {q}{o}{q}'.format(
  620. v = val,
  621. w = get_desc(desc_pfx),
  622. q = q,
  623. o = sep.join(map(str,sorted(tlist))) ))
  624. def opt_unrecognized():
  625. die( 'UserOptError', f'{val!r}: unrecognized {get_desc()}' )
  626. class check_funcs:
  627. def in_fmt():
  628. from .wallet import get_wallet_data
  629. wd = get_wallet_data(fmt_code=val)
  630. if not wd:
  631. opt_unrecognized()
  632. if name == 'out_fmt':
  633. p = 'hidden_incog_output_params'
  634. if wd.type == 'incog_hidden' and not getattr(cfg,p):
  635. die( 'UserOptError',
  636. 'Hidden incog format output requested. ' +
  637. f'You must supply a file and offset with the {fmt_opt(p)!r} option' )
  638. if wd.base_type == 'incog_base' and cfg.old_incog_fmt:
  639. display_opt(name,val,beg='Selected',end=' ')
  640. display_opt('old_incog_fmt',beg='conflicts with',end=':\n')
  641. die( 'UserOptError', 'Export to old incog wallet format unsupported' )
  642. elif wd.type == 'brain':
  643. die( 'UserOptError', 'Output to brainwallet format unsupported' )
  644. out_fmt = in_fmt
  645. def hidden_incog_input_params():
  646. a = val.rsplit(',',1) # permit comma in filename
  647. if len(a) != 2:
  648. display_opt(name,val)
  649. die( 'UserOptError', 'Option requires two comma-separated arguments' )
  650. fn,offset = a
  651. opt_is_int(offset)
  652. from .fileutil import check_infile,check_outdir,check_outfile
  653. if name == 'hidden_incog_input_params':
  654. check_infile(fn,blkdev_ok=True)
  655. key2 = 'in_fmt'
  656. else:
  657. try: os.stat(fn)
  658. except:
  659. b = os.path.dirname(fn)
  660. if b:
  661. check_outdir(b)
  662. else:
  663. check_outfile(fn,blkdev_ok=True)
  664. key2 = 'out_fmt'
  665. if hasattr(cfg,key2):
  666. val2 = getattr(cfg,key2)
  667. from .wallet import get_wallet_data
  668. wd = get_wallet_data('incog_hidden')
  669. if val2 and val2 not in wd.fmt_codes:
  670. die( 'UserOptError', f'Option conflict:\n {fmt_opt(name)}, with\n {fmt_opt(key2)}={val2}' )
  671. hidden_incog_output_params = hidden_incog_input_params
  672. def subseeds():
  673. from .subseed import SubSeedIdxRange
  674. opt_compares(val,'>=',SubSeedIdxRange.min_idx)
  675. opt_compares(val,'<=',SubSeedIdxRange.max_idx)
  676. def seed_len():
  677. from .seed import Seed
  678. opt_is_in_list(int(val),Seed.lens)
  679. def hash_preset():
  680. from .crypto import Crypto
  681. opt_is_in_list(val,list(Crypto.hash_presets.keys()))
  682. def brain_params():
  683. a = val.split(',')
  684. if len(a) != 2:
  685. display_opt(name,val)
  686. die( 'UserOptError', 'Option requires two comma-separated arguments' )
  687. opt_is_int( a[0], desc_pfx='seed length' )
  688. from .seed import Seed
  689. opt_is_in_list( int(a[0]), Seed.lens, desc_pfx='seed length' )
  690. from .crypto import Crypto
  691. opt_is_in_list( a[1], list(Crypto.hash_presets.keys()), desc_pfx='hash preset' )
  692. def usr_randchars():
  693. if val != 0:
  694. opt_compares(val,'>=',cfg.min_urandchars)
  695. opt_compares(val,'<=',cfg.max_urandchars)
  696. def tx_confs():
  697. opt_is_int(val)
  698. opt_compares(int(val),'>=',1)
  699. def vsize_adj():
  700. from .util import ymsg
  701. ymsg(f'Adjusting transaction vsize by a factor of {val:1.2f}')
  702. def daemon_id():
  703. from .daemon import CoinDaemon
  704. opt_is_in_list(val,CoinDaemon.all_daemon_ids())
  705. def locktime():
  706. opt_is_int(val)
  707. opt_compares(int(val),'>',0)
  708. def columns():
  709. opt_compares(val,'>',10)
  710. # TODO: add checks for token, rbf, tx_fee
  711. check_funcs_names = tuple(check_funcs.__dict__)
  712. for name in tuple(cfg._uopts) + cfg._envopts + cfg._cfgfile_opts.non_auto:
  713. val = getattr(cfg,name)
  714. if name in cfg._infile_opts:
  715. from .fileutil import check_infile
  716. check_infile(val) # file exists and is readable - dies on error
  717. elif name == 'outdir':
  718. from .fileutil import check_outdir
  719. check_outdir(val) # dies on error
  720. elif name in check_funcs_names:
  721. getattr(check_funcs,name)()
  722. elif cfg.debug:
  723. Msg(f'check_opts(): No test for config opt {name!r}')
  724. def fmt_opt(o):
  725. return '--' + o.replace('_','-')
  726. def opt_postproc_debug(cfg):
  727. a = [k for k in dir(cfg) if k[:2] != '__' and getattr(cfg,k) != None]
  728. b = [k for k in dir(cfg) if k[:2] != '__' and getattr(cfg,k) == None]
  729. from .util import Msg
  730. Msg('\n Configuration opts:')
  731. for e in [d for d in dir(cfg) if d[:2] != '__']:
  732. Msg(' {:<20}: {}'.format(e, getattr(cfg,e)))
  733. Msg(" Configuration opts set to 'None':")
  734. Msg(' {}\n'.format('\n '.join(b)))
  735. Msg('\n=== end opts.py debug ===\n')
  736. def conv_type(
  737. name,
  738. val,
  739. refval,
  740. desc,
  741. invert_bool = False,
  742. src = None ):
  743. def do_fail():
  744. die(1,'{a!r}: invalid value for {b} {c!r}{d} (must be of type {e!r})'.format(
  745. a = val,
  746. b = desc,
  747. c = fmt_opt(name) if 'command-line' in desc else name,
  748. d = f' in {src!r}' if src else '',
  749. e = type(refval).__name__ ))
  750. if type(refval) == bool:
  751. v = str(val).lower()
  752. ret = (
  753. True if v in ('true','yes','1','on') else
  754. False if v in ('false','no','none','0','off','') else
  755. None
  756. )
  757. return do_fail() if ret is None else (not ret) if invert_bool else ret
  758. else:
  759. try:
  760. return type(refval)(not val if invert_bool else val)
  761. except:
  762. do_fail()