cfg.py 25 KB

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