cfg.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907
  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'):
  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','quiet','verbose','yes')
  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_QUIET',
  281. 'MMGEN_NO_LICENSE',
  282. 'MMGEN_RPC_HOST',
  283. 'MMGEN_RPC_FAIL_ON_COMMAND',
  284. 'MMGEN_TESTNET',
  285. 'MMGEN_REGTEST',
  286. 'MMGEN_EXEC_WRAPPER',
  287. 'MMGEN_IGNORE_TEST_PY_EXCEPTION',
  288. 'MMGEN_RPC_BACKEND',
  289. 'MMGEN_IGNORE_DAEMON_VERSION',
  290. 'MMGEN_USE_STANDALONE_SCRYPT_MODULE',
  291. 'MMGEN_ENABLE_ERIGON',
  292. 'MMGEN_DISABLE_COLOR',
  293. )
  294. _infile_opts = (
  295. 'keys_from_file',
  296. 'mmgen_keys_from_file',
  297. 'passwd_file',
  298. 'keysforaddrs',
  299. 'comment_file',
  300. 'contract_data',
  301. )
  302. # Auto-typechecked and auto-set opts - first value in list is the default
  303. _ov = namedtuple('autoset_opt_info',['type','choices'])
  304. _autoset_opts = {
  305. 'fee_estimate_mode': _ov('nocase_pfx', ['conservative','economical']),
  306. 'rpc_backend': _ov('nocase_pfx', ['auto','httplib','curl','aiohttp','requests']),
  307. }
  308. _auto_typeset_opts = {
  309. 'seed_len': int,
  310. 'subseeds': int,
  311. 'vsize_adj': float,
  312. }
  313. # test suite:
  314. err_disp_timeout = 0.7
  315. short_disp_timeout = 0.3
  316. stdin_tty = sys.stdin.isatty()
  317. if os.getenv('MMGEN_TEST_SUITE'):
  318. min_urandchars = 3
  319. err_disp_timeout = 0.1
  320. short_disp_timeout = 0.1
  321. if os.getenv('MMGEN_TEST_SUITE_POPEN_SPAWN'):
  322. stdin_tty = True
  323. if gc.prog_name == 'unit_tests.py':
  324. _set_ok += ('debug_subseed',)
  325. _reset_ok += ('force_standalone_scrypt_module',)
  326. if os.getenv('MMGEN_DEBUG_ALL'):
  327. for name in _env_opts:
  328. if name[:11] == 'MMGEN_DEBUG':
  329. os.environ[name] = '1'
  330. @property
  331. def data_dir_root(self):
  332. """
  333. location of mmgen.cfg
  334. """
  335. if not hasattr(self,'_data_dir_root'):
  336. if self._data_dir_root_override:
  337. self._data_dir_root = os.path.normpath(os.path.abspath(self._data_dir_root_override))
  338. elif self.test_suite:
  339. self._data_dir_root = self.test_datadir
  340. else:
  341. self._data_dir_root = os.path.join(gc.home_dir,'.'+gc.proj_name.lower())
  342. return self._data_dir_root
  343. @property
  344. def data_dir(self):
  345. """
  346. location of wallet and other data - same as data_dir_root for mainnet
  347. """
  348. if not hasattr(self,'_data_dir'):
  349. self._data_dir = os.path.normpath(os.path.join(*{
  350. 'regtest': (self.data_dir_root, 'regtest', self.coin.lower(), (self.regtest_user or 'none') ),
  351. 'testnet': (self.data_dir_root, 'testnet'),
  352. 'mainnet': (self.data_dir_root,),
  353. }[self.network] ))
  354. return self._data_dir
  355. def __init__(
  356. self,
  357. cfg = None,
  358. opts_data = None,
  359. init_opts = None,
  360. opt_filter = None,
  361. parse_only = False,
  362. parsed_opts = None,
  363. need_proto = True,
  364. need_amt = True,
  365. do_post_init = False,
  366. process_opts = False ):
  367. # Step 1: get user-supplied configuration data from
  368. # a) command line, or
  369. # b) first argument to constructor;
  370. # save to self._uopts:
  371. self._cloned = {}
  372. if opts_data or parsed_opts or process_opts:
  373. assert cfg is None, (
  374. 'Config(): ‘cfg’ cannot be used simultaneously with ' +
  375. '‘opts_data’, ‘parsed_opts’ or ‘process_opts’' )
  376. from .opts import UserOpts
  377. UserOpts(
  378. cfg = self,
  379. opts_data = opts_data,
  380. init_opts = init_opts,
  381. opt_filter = opt_filter,
  382. parse_only = parse_only,
  383. parsed_opts = parsed_opts )
  384. self._uopt_desc = 'command-line option'
  385. else:
  386. if cfg is None:
  387. self._uopts = {}
  388. else:
  389. if '_clone' in cfg:
  390. assert isinstance( cfg['_clone'], Config )
  391. self._cloned = cfg['_clone'].__dict__
  392. for k,v in self._cloned.items():
  393. if not k.startswith('_'):
  394. setattr(self,k,v)
  395. del cfg['_clone']
  396. self._uopts = cfg
  397. self._uopt_desc = 'configuration option'
  398. self._data_dir_root_override = self._cloned.pop(
  399. '_data_dir_root_override',
  400. self._uopts.pop('data_dir',None))
  401. if parse_only and not any(k in self._uopts for k in ['help','longhelp']):
  402. return
  403. # Step 2: set cfg from user-supplied data, skipping auto opts; set type from corresponding
  404. # class attribute, if it exists:
  405. auto_opts = tuple(self._autoset_opts) + tuple(self._auto_typeset_opts)
  406. for key,val in self._uopts.items():
  407. assert key.isascii() and key.isidentifier() and key[0] != '_', '{key!r}: malformed configuration option'
  408. assert key not in self._forbidden_opts, '{key!r}: forbidden configuration option'
  409. if key not in auto_opts:
  410. if hasattr(type(self), key):
  411. setattr(
  412. self,
  413. key,
  414. getattr(type(self), key) if val is None else
  415. conv_type(key, val, getattr(type(self), key), self._uopt_desc))
  416. elif val is None:
  417. if hasattr(self, key):
  418. delattr(self, key)
  419. else:
  420. setattr(self, key, val)
  421. # Step 3: set cfg from environment, skipping already-set opts; save names set from environment:
  422. self._envopts = tuple(self._set_cfg_from_env()) if self._use_env else ()
  423. from .term import init_term
  424. init_term(self) # requires ‘hold_protect_disable’ (set from env)
  425. from .fileutil import check_or_create_dir
  426. check_or_create_dir(self.data_dir_root)
  427. from .util import wrap_ripemd160
  428. wrap_ripemd160() # ripemd160 required by mmgen_cfg_file() in _set_cfg_from_cfg_file()
  429. # Step 4: set cfg from cfgfile, skipping already-set opts and auto opts; save set opts and auto
  430. # opts to be set:
  431. # requires ‘data_dir_root’, ‘test_suite_cfgtest’
  432. self._cfgfile_opts = self._set_cfg_from_cfg_file( self._envopts, need_proto )
  433. # Step 5: set autoset opts from user-supplied data, cfgfile data, or default values, in that order:
  434. self._set_autoset_opts( self._cfgfile_opts.autoset )
  435. # Step 6: set auto typeset opts from user-supplied data or cfgfile data, in that order:
  436. self._set_auto_typeset_opts( self._cfgfile_opts.auto_typeset )
  437. if self.regtest or self.bob or self.alice or self.carol or gc.prog_name == 'mmgen-regtest':
  438. self.network = 'regtest'
  439. self.regtest_user = 'bob' if self.bob else 'alice' if self.alice else 'carol' if self.carol else None
  440. else:
  441. self.network = 'testnet' if self.testnet else 'mainnet'
  442. self.coin = self.coin.upper()
  443. self.token = self.token.upper() if self.token else None
  444. # self.color is finalized, so initialize color:
  445. if self.color: # MMGEN_DISABLE_COLOR sets this to False
  446. from .color import init_color
  447. init_color(num_colors=256 if self.force_256_color else 'auto')
  448. self._die_on_incompatible_opts()
  449. check_or_create_dir(self.data_dir)
  450. if self.debug and gc.prog_name != 'cmdtest.py':
  451. self.verbose = True
  452. self.quiet = False
  453. if self.debug_opts:
  454. opt_postproc_debug(self)
  455. from .util import Util
  456. self._util = Util(self)
  457. del self._cloned
  458. self._lock()
  459. if need_proto:
  460. from .protocol import warn_trustlevel,init_proto_from_cfg
  461. warn_trustlevel(self)
  462. # requires the default-to-none behavior, so do after the lock:
  463. self._proto = init_proto_from_cfg(self,need_amt=need_amt)
  464. if self._opts and not do_post_init:
  465. self._opts.init_bottom(self)
  466. # Check user-set opts without modifying them
  467. check_opts(self)
  468. def _set_cfg_from_env(self):
  469. for name,val in ((k,v) for k,v in os.environ.items() if k.startswith('MMGEN_')):
  470. if name == 'MMGEN_DEBUG_ALL':
  471. continue
  472. elif name in self._env_opts:
  473. if val: # ignore empty string values; string value of '0' or 'false' sets variable to False
  474. disable = name.startswith('MMGEN_DISABLE_')
  475. gname = name[(6,14)[disable]:].lower()
  476. if gname in self._uopts: # don’t touch attr if already set by user
  477. continue
  478. elif hasattr(self,gname):
  479. setattr(
  480. self,
  481. gname,
  482. conv_type( name, val, getattr(self,gname), 'environment var', invert_bool=disable ))
  483. yield gname
  484. else:
  485. raise ValueError(f'Name {gname!r} not present in globals')
  486. else:
  487. raise ValueError(f'{name!r} is not a valid MMGen environment variable')
  488. def _set_cfg_from_cfg_file(
  489. self,
  490. env_cfg,
  491. need_proto ):
  492. _ret = namedtuple('cfgfile_opts',['non_auto','autoset','auto_typeset'])
  493. if not self._use_cfg_file:
  494. return _ret( (), {}, {} )
  495. # check for changes in system template file (term must be initialized)
  496. from .cfgfile import mmgen_cfg_file
  497. mmgen_cfg_file(self,'sample')
  498. ucfg = mmgen_cfg_file(self,'usr')
  499. self._cfgfile_fn = ucfg.fn
  500. if need_proto:
  501. from .protocol import init_proto
  502. autoset_opts = {}
  503. auto_typeset_opts = {}
  504. non_auto_opts = []
  505. already_set = tuple(self._uopts) + env_cfg
  506. for d in ucfg.get_lines():
  507. if d.name in self._cfg_file_opts:
  508. ns = d.name.split('_')
  509. if ns[0] in gc.core_coins:
  510. if not need_proto:
  511. continue
  512. nse,tn = (
  513. (ns[2:],ns[1]=='testnet') if len(ns) > 2 and ns[1] in ('mainnet','testnet') else
  514. (ns[1:],False)
  515. )
  516. # no instance yet, so override _class_ attr:
  517. cls = init_proto(self, ns[0], tn, need_amt=True, return_cls=True)
  518. attr = '_'.join(nse)
  519. else:
  520. cls = self
  521. attr = d.name
  522. refval = getattr(cls,attr)
  523. val = ucfg.parse_value(d.value,refval)
  524. if not val:
  525. die( 'CfgFileParseError', f'Parse error in file {ucfg.fn!r}, line {d.lineno}' )
  526. val_conv = conv_type( attr, val, refval, 'configuration file option', src=ucfg.fn )
  527. if not attr in already_set:
  528. setattr(cls,attr,val_conv)
  529. non_auto_opts.append(attr)
  530. elif d.name in self._autoset_opts:
  531. autoset_opts[d.name] = d.value
  532. elif d.name in self._auto_typeset_opts:
  533. auto_typeset_opts[d.name] = d.value
  534. else:
  535. die( 'CfgFileParseError', f'{d.name!r}: unrecognized option in {ucfg.fn!r}, line {d.lineno}' )
  536. return _ret( tuple(non_auto_opts), autoset_opts, auto_typeset_opts )
  537. def _set_autoset_opts(self,cfgfile_autoset_opts):
  538. def get_autoset_opt(key,val,src):
  539. def die_on_err(desc):
  540. from .util import fmt_list
  541. die(
  542. 'UserOptError',
  543. '{a!r}: invalid {b} (not {c}: {d})'.format(
  544. a = val,
  545. b = {
  546. 'cmdline': f'parameter for option --{key.replace("_","-")}',
  547. 'cfgfile': f'value for cfg file option {key!r}'
  548. }[src],
  549. c = desc,
  550. d = fmt_list(data.choices) ))
  551. class opt_type:
  552. def nocase_str():
  553. if val.lower() in data.choices:
  554. return val.lower()
  555. else:
  556. die_on_err('one of')
  557. def nocase_pfx():
  558. cs = [s for s in data.choices if s.startswith(val.lower())]
  559. if len(cs) == 1:
  560. return cs[0]
  561. else:
  562. die_on_err('unique substring of')
  563. data = self._autoset_opts[key]
  564. return getattr(opt_type,data.type)()
  565. # Check autoset opts, setting if unset
  566. for key in self._autoset_opts:
  567. if key in self._cloned:
  568. continue
  569. assert not hasattr(self,key), f'autoset opt {key!r} is already set, but it shouldn’t be!'
  570. if key in self._uopts:
  571. val,src = (self._uopts[key],'cmdline')
  572. elif key in cfgfile_autoset_opts:
  573. val,src = (cfgfile_autoset_opts[key],'cfgfile')
  574. else:
  575. val = None
  576. if val is None:
  577. setattr(self, key, self._autoset_opts[key].choices[0])
  578. else:
  579. setattr(self, key, get_autoset_opt(key,val,src=src))
  580. def _set_auto_typeset_opts(self,cfgfile_auto_typeset_opts):
  581. def do_set(key,val,ref_type):
  582. assert not hasattr(self,key), f'{key!r} is in cfg!'
  583. setattr(self,key,None if val is None else ref_type(val))
  584. for key,ref_type in self._auto_typeset_opts.items():
  585. if key in self._uopts:
  586. do_set(key, self._uopts[key], ref_type)
  587. elif key in cfgfile_auto_typeset_opts:
  588. do_set(key, cfgfile_auto_typeset_opts[key], ref_type)
  589. def _post_init(self):
  590. return self._opts.init_bottom(self)
  591. def _die_on_incompatible_opts(self):
  592. for group in self._incompatible_opts:
  593. bad = [k for k in self.__dict__ if k in group and getattr(self,k) is not None]
  594. if len(bad) > 1:
  595. die(1,'Conflicting options: {}'.format(', '.join(map(fmt_opt,bad))))
  596. def check_opts(cfg): # Raises exception if any check fails
  597. from .util import is_int,Msg
  598. def get_desc(desc_pfx=''):
  599. return (
  600. (desc_pfx + ' ' if desc_pfx else '')
  601. + (
  602. f'parameter for command-line option {fmt_opt(name)!r}'
  603. if name in cfg._uopts and 'command-line' in cfg._uopt_desc else
  604. f'value for configuration option {name!r}'
  605. )
  606. + ( ' from environment' if name in cfg._envopts else '')
  607. + (f' in {cfg._cfgfile_fn!r}' if name in cfg._cfgfile_opts.non_auto else '')
  608. )
  609. def display_opt(name,val='',beg='For selected',end=':\n'):
  610. from .util import msg_r
  611. msg_r('{} option {!r}{}'.format(
  612. beg,
  613. f'{fmt_opt(name)}={val}' if val else fmt_opt(name),
  614. end ))
  615. def opt_compares(val,op_str,target):
  616. import operator
  617. if not {
  618. '<': operator.lt,
  619. '<=': operator.le,
  620. '>': operator.gt,
  621. '>=': operator.ge,
  622. '=': operator.eq,
  623. }[op_str](val,target):
  624. die( 'UserOptError', f'{val}: invalid {get_desc()} (not {op_str} {target})' )
  625. def opt_is_int(val,desc_pfx=''):
  626. if not is_int(val):
  627. die( 'UserOptError', f'{val!r}: invalid {get_desc(desc_pfx)} (not an integer)' )
  628. def opt_is_in_list(val,tlist,desc_pfx=''):
  629. if val not in tlist:
  630. q,sep = (('',','),("'","','"))[isinstance(tlist[0],str)]
  631. die( 'UserOptError', '{q}{v}{q}: invalid {w}\nValid choices: {q}{o}{q}'.format(
  632. v = val,
  633. w = get_desc(desc_pfx),
  634. q = q,
  635. o = sep.join(map(str,sorted(tlist))) ))
  636. def opt_unrecognized():
  637. die( 'UserOptError', f'{val!r}: unrecognized {get_desc()}' )
  638. class check_funcs:
  639. def in_fmt():
  640. from .wallet import get_wallet_data
  641. wd = get_wallet_data(fmt_code=val)
  642. if not wd:
  643. opt_unrecognized()
  644. if name == 'out_fmt':
  645. p = 'hidden_incog_output_params'
  646. if wd.type == 'incog_hidden' and not getattr(cfg,p):
  647. die( 'UserOptError',
  648. 'Hidden incog format output requested. ' +
  649. f'You must supply a file and offset with the {fmt_opt(p)!r} option' )
  650. if wd.base_type == 'incog_base' and cfg.old_incog_fmt:
  651. display_opt(name,val,beg='Selected',end=' ')
  652. display_opt('old_incog_fmt',beg='conflicts with',end=':\n')
  653. die( 'UserOptError', 'Export to old incog wallet format unsupported' )
  654. elif wd.type == 'brain':
  655. die( 'UserOptError', 'Output to brainwallet format unsupported' )
  656. out_fmt = in_fmt
  657. def hidden_incog_input_params():
  658. a = val.rsplit(',',1) # permit comma in filename
  659. if len(a) != 2:
  660. display_opt(name,val)
  661. die( 'UserOptError', 'Option requires two comma-separated arguments' )
  662. fn,offset = a
  663. opt_is_int(offset)
  664. from .fileutil import check_infile,check_outdir,check_outfile
  665. if name == 'hidden_incog_input_params':
  666. check_infile(fn,blkdev_ok=True)
  667. key2 = 'in_fmt'
  668. else:
  669. try:
  670. os.stat(fn)
  671. except:
  672. b = os.path.dirname(fn)
  673. if b:
  674. check_outdir(b)
  675. else:
  676. check_outfile(fn,blkdev_ok=True)
  677. key2 = 'out_fmt'
  678. if hasattr(cfg,key2):
  679. val2 = getattr(cfg,key2)
  680. from .wallet import get_wallet_data
  681. wd = get_wallet_data('incog_hidden')
  682. if val2 and val2 not in wd.fmt_codes:
  683. die( 'UserOptError', f'Option conflict:\n {fmt_opt(name)}, with\n {fmt_opt(key2)}={val2}' )
  684. hidden_incog_output_params = hidden_incog_input_params
  685. def subseeds():
  686. from .subseed import SubSeedIdxRange
  687. opt_compares(val,'>=',SubSeedIdxRange.min_idx)
  688. opt_compares(val,'<=',SubSeedIdxRange.max_idx)
  689. def seed_len():
  690. from .seed import Seed
  691. opt_is_in_list(int(val),Seed.lens)
  692. def hash_preset():
  693. from .crypto import Crypto
  694. opt_is_in_list(val,list(Crypto.hash_presets.keys()))
  695. def brain_params():
  696. a = val.split(',')
  697. if len(a) != 2:
  698. display_opt(name,val)
  699. die( 'UserOptError', 'Option requires two comma-separated arguments' )
  700. opt_is_int( a[0], desc_pfx='seed length' )
  701. from .seed import Seed
  702. opt_is_in_list( int(a[0]), Seed.lens, desc_pfx='seed length' )
  703. from .crypto import Crypto
  704. opt_is_in_list( a[1], list(Crypto.hash_presets.keys()), desc_pfx='hash preset' )
  705. def usr_randchars():
  706. if val != 0:
  707. opt_compares(val,'>=',cfg.min_urandchars)
  708. opt_compares(val,'<=',cfg.max_urandchars)
  709. def tx_confs():
  710. opt_is_int(val)
  711. opt_compares(int(val),'>=',1)
  712. def vsize_adj():
  713. from .util import ymsg
  714. ymsg(f'Adjusting transaction vsize by a factor of {val:1.2f}')
  715. def daemon_id():
  716. from .daemon import CoinDaemon
  717. opt_is_in_list(val,CoinDaemon.all_daemon_ids())
  718. def locktime():
  719. opt_is_int(val)
  720. opt_compares(int(val),'>',0)
  721. def columns():
  722. opt_compares(val,'>',10)
  723. # TODO: add checks for token, rbf, tx_fee
  724. check_funcs_names = tuple(check_funcs.__dict__)
  725. for name in tuple(cfg._uopts) + cfg._envopts + cfg._cfgfile_opts.non_auto:
  726. val = getattr(cfg,name)
  727. if name in cfg._infile_opts:
  728. from .fileutil import check_infile
  729. check_infile(val) # file exists and is readable - dies on error
  730. elif name == 'outdir':
  731. from .fileutil import check_outdir
  732. check_outdir(val) # dies on error
  733. elif name in check_funcs_names:
  734. getattr(check_funcs,name)()
  735. elif cfg.debug:
  736. Msg(f'check_opts(): No test for config opt {name!r}')
  737. def fmt_opt(o):
  738. return '--' + o.replace('_','-')
  739. def opt_postproc_debug(cfg):
  740. none_opts = [k for k in dir(cfg) if k[:2] != '__' and getattr(cfg,k) is None]
  741. from .util import Msg
  742. Msg('\n Configuration opts:')
  743. for e in [d for d in dir(cfg) if d[:2] != '__']:
  744. Msg(f' {e:<20}: {getattr(cfg,e)}')
  745. Msg(" Configuration opts set to 'None':")
  746. Msg(' {}\n'.format('\n '.join(none_opts)))
  747. Msg('\n=== end opts.py debug ===\n')
  748. def conv_type(
  749. name,
  750. val,
  751. refval,
  752. desc,
  753. invert_bool = False,
  754. src = None ):
  755. def do_fail():
  756. die(1,'{a!r}: invalid value for {b} {c!r}{d} (must be of type {e!r})'.format(
  757. a = val,
  758. b = desc,
  759. c = fmt_opt(name) if 'command-line' in desc else name,
  760. d = f' in {src!r}' if src else '',
  761. e = type(refval).__name__ ))
  762. if type(refval) is bool:
  763. v = str(val).lower()
  764. ret = (
  765. True if v in ('true','yes','1','on') else
  766. False if v in ('false','no','none','0','off','') else
  767. None
  768. )
  769. return do_fail() if ret is None else (not ret) if invert_bool else ret
  770. else:
  771. try:
  772. return type(refval)(not val if invert_bool else val)
  773. except:
  774. do_fail()