cfg.py 25 KB

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