cfg.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889
  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'
  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. for k in ('linux','win','msys'):
  50. if sys.platform.startswith(k):
  51. platform = { 'linux':'linux', 'win':'win', 'msys':'win' }[k]
  52. break
  53. else:
  54. die2(1,f'{sys.platform!r}: platform not supported by {proj_name}')
  55. if os.getenv('HOME'): # Linux or MSYS2
  56. home_dir = os.getenv('HOME')
  57. elif platform == 'win': # Windows without MSYS2 - not supported
  58. die2(1,f'$HOME not set! {proj_name} for Windows must be run in MSYS2 environment')
  59. else:
  60. die2(2,'$HOME is not set! Unable to determine home directory')
  61. def get_mmgen_data_file(self,filename,package='mmgen'):
  62. """
  63. this is an expensive import, so do only when required
  64. """
  65. # Resource will be unpacked and then cleaned up if necessary, see:
  66. # https://docs.python.org/3/library/importlib.html:
  67. # Note: This module provides functionality similar to pkg_resources Basic
  68. # Resource Access without the performance overhead of that package.
  69. # https://importlib-resources.readthedocs.io/en/latest/migration.html
  70. # https://setuptools.readthedocs.io/en/latest/pkg_resources.html
  71. try:
  72. from importlib.resources import files # Python 3.9
  73. except ImportError:
  74. from importlib_resources import files
  75. return files(package).joinpath('data',filename).read_text()
  76. @property
  77. def version(self):
  78. return self.get_mmgen_data_file(
  79. filename = 'version',
  80. package = 'mmgen_node_tools' if self.prog_name.startswith('mmnode-') else 'mmgen'
  81. ).strip()
  82. @property
  83. def release_date(self):
  84. return self.get_mmgen_data_file(filename='release_date').strip()
  85. gc = GlobalConstants()
  86. class GlobalVars:
  87. """
  88. These are used only by the test suite to redirect msg() and friends to /dev/null
  89. """
  90. stdout = sys.stdout
  91. stderr = sys.stderr
  92. gv = GlobalVars()
  93. class Config(Lockable):
  94. """
  95. These values are configurable - RHS values are defaults
  96. Globals are overridden with the following precedence:
  97. 1 - command line
  98. 2 - environmental vars
  99. 3 - config file
  100. """
  101. _autolock = False
  102. _set_ok = ('usr_randchars','_proto')
  103. _reset_ok = ('accept_defaults','quiet','verbose','yes')
  104. _use_class_attr = True
  105. _default_to_none = True
  106. # general
  107. coin = 'BTC'
  108. token = ''
  109. outdir = ''
  110. passwd_file = ''
  111. network = 'mainnet'
  112. testnet = False
  113. regtest = False
  114. # verbosity / prompting behavior
  115. quiet = False
  116. verbose = False
  117. yes = False
  118. accept_defaults = False
  119. no_license = False
  120. # limits
  121. http_timeout = 60
  122. usr_randchars = 30
  123. fee_adjust = 1.0
  124. fee_estimate_confs = 3
  125. minconf = 1
  126. max_tx_file_size = 100000
  127. max_input_size = 1024 * 1024
  128. min_urandchars = 10
  129. max_urandchars = 80
  130. # debug
  131. debug = False
  132. debug_opts = False
  133. debug_rpc = False
  134. debug_addrlist = False
  135. debug_subseed = False
  136. debug_tw = False
  137. # rpc:
  138. rpc_host = ''
  139. rpc_port = 0
  140. rpc_user = ''
  141. rpc_password = ''
  142. monero_wallet_rpc_user = 'monero'
  143. monero_wallet_rpc_password = ''
  144. aiohttp_rpc_queue_len = 16
  145. cached_balances = False
  146. # daemons
  147. daemon_data_dir = '' # set by user
  148. daemon_id = ''
  149. blacklisted_daemons = ''
  150. ignore_daemon_version = False
  151. # display:
  152. force_color = False # placeholder
  153. force_256_color = False
  154. scroll = False
  155. pager = False
  156. columns = 0
  157. color = bool(
  158. ( sys.stdout.isatty() and not os.getenv('MMGEN_TEST_SUITE_PEXPECT') ) or
  159. os.getenv('MMGEN_FORCE_COLOR')
  160. )
  161. # miscellaneous features:
  162. use_internal_keccak_module = False
  163. force_standalone_scrypt_module = False
  164. enable_erigon = False
  165. autochg_ignore_labels = False
  166. # regtest:
  167. bob = False
  168. alice = False
  169. carol = False
  170. regtest_user = ''
  171. # test suite:
  172. bogus_send = False
  173. bogus_unspent_data = ''
  174. debug_utf8 = False
  175. exec_wrapper = False
  176. test_suite = False
  177. test_suite_autosign_led_simulate = False
  178. test_suite_xmr_autosign = False
  179. test_suite_cfgtest = False
  180. test_suite_deterministic = False
  181. test_suite_pexpect = False
  182. test_suite_popen_spawn = False
  183. hold_protect_disable = False
  184. no_daemon_autostart = False
  185. names = False
  186. no_timings = False
  187. exit_after = ''
  188. resuming = False
  189. skipping_deps = False
  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_PEXPECT',
  256. 'MMGEN_TEST_SUITE_POPEN_SPAWN',
  257. 'MMGEN_BLACKLIST_DAEMONS',
  258. 'MMGEN_BOGUS_SEND',
  259. 'MMGEN_BOGUS_UNSPENT_DATA',
  260. 'MMGEN_DEBUG',
  261. 'MMGEN_DEBUG_OPTS',
  262. 'MMGEN_DEBUG_RPC',
  263. 'MMGEN_DEBUG_ADDRLIST',
  264. 'MMGEN_DEBUG_TW',
  265. 'MMGEN_DEBUG_UTF8',
  266. 'MMGEN_DEBUG_SUBSEED',
  267. 'MMGEN_FORCE_COLOR',
  268. 'MMGEN_FORCE_256_COLOR',
  269. 'MMGEN_HOLD_PROTECT_DISABLE',
  270. 'MMGEN_QUIET',
  271. 'MMGEN_NO_LICENSE',
  272. 'MMGEN_RPC_HOST',
  273. 'MMGEN_RPC_FAIL_ON_COMMAND',
  274. 'MMGEN_TESTNET',
  275. 'MMGEN_REGTEST',
  276. 'MMGEN_EXEC_WRAPPER',
  277. 'MMGEN_RPC_BACKEND',
  278. 'MMGEN_IGNORE_DAEMON_VERSION',
  279. 'MMGEN_USE_STANDALONE_SCRYPT_MODULE',
  280. 'MMGEN_ENABLE_ERIGON',
  281. 'MMGEN_DISABLE_COLOR',
  282. )
  283. _infile_opts = (
  284. 'keys_from_file',
  285. 'mmgen_keys_from_file',
  286. 'passwd_file',
  287. 'keysforaddrs',
  288. 'comment_file',
  289. 'contract_data',
  290. )
  291. # Auto-typechecked and auto-set opts - first value in list is the default
  292. _ov = namedtuple('autoset_opt_info',['type','choices'])
  293. _autoset_opts = {
  294. 'fee_estimate_mode': _ov('nocase_pfx', ['conservative','economical']),
  295. 'rpc_backend': _ov('nocase_pfx', ['auto','httplib','curl','aiohttp','requests']),
  296. }
  297. _auto_typeset_opts = {
  298. 'seed_len': int,
  299. 'subseeds': int,
  300. 'vsize_adj': float,
  301. }
  302. # test suite:
  303. err_disp_timeout = 0.7
  304. short_disp_timeout = 0.3
  305. stdin_tty = sys.stdin.isatty()
  306. if os.getenv('MMGEN_TEST_SUITE'):
  307. min_urandchars = 3
  308. err_disp_timeout = 0.1
  309. short_disp_timeout = 0.1
  310. if os.getenv('MMGEN_TEST_SUITE_POPEN_SPAWN'):
  311. stdin_tty = True
  312. if gc.prog_name == 'unit_tests.py':
  313. _set_ok += ('debug_subseed',)
  314. _reset_ok += ('force_standalone_scrypt_module',)
  315. if os.getenv('MMGEN_DEBUG_ALL'):
  316. for name in _env_opts:
  317. if name[:11] == 'MMGEN_DEBUG':
  318. os.environ[name] = '1'
  319. @property
  320. def data_dir_root(self):
  321. """
  322. location of mmgen.cfg
  323. """
  324. if hasattr(self,'_data_dir_root'):
  325. return self._data_dir_root
  326. else:
  327. if self._data_dir_root_override:
  328. self._data_dir_root = os.path.normpath(os.path.abspath(self._data_dir_root_override))
  329. elif self.test_suite:
  330. from test.include.common import get_test_data_dir
  331. self._data_dir_root = get_test_data_dir()
  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 hasattr(self,'_data_dir'):
  341. return self._data_dir
  342. else:
  343. self._data_dir = os.path.normpath(os.path.join(*{
  344. 'regtest': (self.data_dir_root, 'regtest', self.coin.lower(), (self.regtest_user or 'none') ),
  345. 'testnet': (self.data_dir_root, 'testnet'),
  346. 'mainnet': (self.data_dir_root,),
  347. }[self.network] ))
  348. return self._data_dir
  349. def __init__(
  350. self,
  351. cfg = None,
  352. opts_data = None,
  353. init_opts = None,
  354. opt_filter = None,
  355. parse_only = False,
  356. parsed_opts = None,
  357. need_proto = True,
  358. need_amt = True,
  359. do_post_init = False,
  360. process_opts = False ):
  361. # Step 1: get user-supplied configuration data from a) command line, or b) first argument
  362. # to constructor; 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 mmgen.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 != 'test.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. cls = type(init_proto( self, ns[0], tn, need_amt=True )) # no instance yet, so override _class_ attr
  502. attr = '_'.join(nse)
  503. else:
  504. cls = self
  505. attr = d.name
  506. refval = getattr(cls,attr)
  507. val = ucfg.parse_value(d.value,refval)
  508. if not val:
  509. die( 'CfgFileParseError', f'Parse error in file {ucfg.fn!r}, line {d.lineno}' )
  510. val_conv = conv_type( attr, val, refval, 'configuration file option', src=ucfg.fn )
  511. if not attr in already_set:
  512. setattr(cls,attr,val_conv)
  513. non_auto_opts.append(attr)
  514. elif d.name in self._autoset_opts:
  515. autoset_opts[d.name] = d.value
  516. elif d.name in self._auto_typeset_opts:
  517. auto_typeset_opts[d.name] = d.value
  518. else:
  519. die( 'CfgFileParseError', f'{d.name!r}: unrecognized option in {ucfg.fn!r}, line {d.lineno}' )
  520. return _ret( tuple(non_auto_opts), autoset_opts, auto_typeset_opts )
  521. def _set_autoset_opts(self,cfgfile_autoset_opts):
  522. def get_autoset_opt(key,val,src):
  523. def die_on_err(desc):
  524. from .util import fmt_list
  525. die(
  526. 'UserOptError',
  527. '{a!r}: invalid {b} (not {c}: {d})'.format(
  528. a = val,
  529. b = {
  530. 'cmdline': 'parameter for option --{}'.format(key.replace('_','-')),
  531. 'cfgfile': 'value for cfg file option {!r}'.format(key)
  532. }[src],
  533. c = desc,
  534. d = fmt_list(data.choices) ))
  535. class opt_type:
  536. def nocase_str():
  537. if val.lower() in data.choices:
  538. return val.lower()
  539. else:
  540. die_on_err('one of')
  541. def nocase_pfx():
  542. cs = [s for s in data.choices if s.startswith(val.lower())]
  543. if len(cs) == 1:
  544. return cs[0]
  545. else:
  546. die_on_err('unique substring of')
  547. data = self._autoset_opts[key]
  548. return getattr(opt_type,data.type)()
  549. # Check autoset opts, setting if unset
  550. for key in self._autoset_opts:
  551. if key in self._cloned:
  552. continue
  553. assert not hasattr(self,key), f'autoset opt {key!r} is already set, but it shouldn’t be!'
  554. if key in self._uopts:
  555. val,src = (self._uopts[key],'cmdline')
  556. elif key in cfgfile_autoset_opts:
  557. val,src = (cfgfile_autoset_opts[key],'cfgfile')
  558. else:
  559. val = None
  560. if val is None:
  561. setattr(self, key, self._autoset_opts[key].choices[0])
  562. else:
  563. setattr(self, key, get_autoset_opt(key,val,src=src))
  564. def _set_auto_typeset_opts(self,cfgfile_auto_typeset_opts):
  565. def do_set(key,val,ref_type):
  566. assert not hasattr(self,key), f'{key!r} is in cfg!'
  567. setattr(self,key,None if val is None else ref_type(val))
  568. for key,ref_type in self._auto_typeset_opts.items():
  569. if key in self._uopts:
  570. do_set(key, self._uopts[key], ref_type)
  571. elif key in cfgfile_auto_typeset_opts:
  572. do_set(key, cfgfile_auto_typeset_opts[key], ref_type)
  573. def _post_init(self):
  574. return self._opts.init_bottom(self)
  575. def _die_on_incompatible_opts(self):
  576. for group in self._incompatible_opts:
  577. bad = [k for k in self.__dict__ if k in group and getattr(self,k) != None]
  578. if len(bad) > 1:
  579. die(1,'Conflicting options: {}'.format(', '.join(map(fmt_opt,bad))))
  580. def check_opts(cfg): # Raises exception if any check fails
  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 = (('',','),("'","','"))[type(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: os.stat(fn)
  653. except:
  654. b = os.path.dirname(fn)
  655. if b:
  656. check_outdir(b)
  657. else:
  658. check_outfile(fn,blkdev_ok=True)
  659. key2 = 'out_fmt'
  660. if hasattr(cfg,key2):
  661. val2 = getattr(cfg,key2)
  662. from .wallet import get_wallet_data
  663. wd = get_wallet_data('incog_hidden')
  664. if val2 and val2 not in wd.fmt_codes:
  665. die( 'UserOptError', f'Option conflict:\n {fmt_opt(name)}, with\n {fmt_opt(key2)}={val2}' )
  666. hidden_incog_output_params = hidden_incog_input_params
  667. def subseeds():
  668. from .subseed import SubSeedIdxRange
  669. opt_compares(val,'>=',SubSeedIdxRange.min_idx)
  670. opt_compares(val,'<=',SubSeedIdxRange.max_idx)
  671. def seed_len():
  672. from .seed import Seed
  673. opt_is_in_list(int(val),Seed.lens)
  674. def hash_preset():
  675. from .crypto import Crypto
  676. opt_is_in_list(val,list(Crypto.hash_presets.keys()))
  677. def brain_params():
  678. a = val.split(',')
  679. if len(a) != 2:
  680. display_opt(name,val)
  681. die( 'UserOptError', 'Option requires two comma-separated arguments' )
  682. opt_is_int( a[0], desc_pfx='seed length' )
  683. from .seed import Seed
  684. opt_is_in_list( int(a[0]), Seed.lens, desc_pfx='seed length' )
  685. from .crypto import Crypto
  686. opt_is_in_list( a[1], list(Crypto.hash_presets.keys()), desc_pfx='hash preset' )
  687. def usr_randchars():
  688. if val != 0:
  689. opt_compares(val,'>=',cfg.min_urandchars)
  690. opt_compares(val,'<=',cfg.max_urandchars)
  691. def tx_confs():
  692. opt_is_int(val)
  693. opt_compares(int(val),'>=',1)
  694. def vsize_adj():
  695. from .util import ymsg
  696. ymsg(f'Adjusting transaction vsize by a factor of {val:1.2f}')
  697. def daemon_id():
  698. from .daemon import CoinDaemon
  699. opt_is_in_list(val,CoinDaemon.all_daemon_ids())
  700. def locktime():
  701. opt_is_int(val)
  702. opt_compares(int(val),'>',0)
  703. def columns():
  704. opt_compares(val,'>',10)
  705. from .util import is_int,Msg
  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. a = [k for k in dir(cfg) if k[:2] != '__' and getattr(cfg,k) != None]
  724. b = [k for k in dir(cfg) if k[:2] != '__' and getattr(cfg,k) == None]
  725. from .util import Msg
  726. Msg('\n Configuration opts:')
  727. for e in [d for d in dir(cfg) if d[:2] != '__']:
  728. Msg(' {:<20}: {}'.format(e, getattr(cfg,e)))
  729. Msg(" Configuration opts set to 'None':")
  730. Msg(' {}\n'.format('\n '.join(b)))
  731. Msg('\n=== end opts.py debug ===\n')
  732. def conv_type(
  733. name,
  734. val,
  735. refval,
  736. desc,
  737. invert_bool = False,
  738. src = None ):
  739. def do_fail():
  740. die(1,'{a!r}: invalid value for {b} {c!r}{d} (must be of type {e!r})'.format(
  741. a = val,
  742. b = desc,
  743. c = fmt_opt(name) if 'command-line' in desc else name,
  744. d = f' in {src!r}' if src else '',
  745. e = type(refval).__name__ ))
  746. if type(refval) == bool:
  747. v = str(val).lower()
  748. ret = (
  749. True if v in ('true','yes','1','on') else
  750. False if v in ('false','no','none','0','off','') else
  751. None
  752. )
  753. return do_fail() if ret is None else (not ret) if invert_bool else ret
  754. else:
  755. try:
  756. return type(refval)(not val if invert_bool else val)
  757. except:
  758. do_fail()