cfg.py 26 KB

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