cfg.py 26 KB

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