cfg.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991
  1. #!/usr/bin/env python3
  2. #
  3. # MMGen Wallet, a terminal-based cryptocurrency wallet
  4. # Copyright (C)2013-2025 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-runtime-configurable. They’re constant for a given machine,
  33. user, executable and MMGen Wallet version
  34. """
  35. _autolock = True
  36. proj_name = 'MMGen'
  37. proj_id = 'mmgen'
  38. proj_url = 'https://github.com/mmgen/mmgen-wallet'
  39. author = 'The MMGen Project'
  40. email = '<mmgen@tuta.io>'
  41. Cdates = '2013-2025'
  42. dfl_hash_preset = '3'
  43. passwd_max_tries = 5
  44. min_screen_width = 80
  45. min_time_precision = 18
  46. # must match CoinProtocol.coins
  47. core_coins = ('btc', 'bch', 'ltc', 'eth', 'etc', 'zec', 'xmr')
  48. rpc_coins = ('btc', 'bch', 'ltc', 'eth', 'etc', 'xmr')
  49. btc_fork_rpc_coins = ('btc', 'bch', 'ltc')
  50. eth_fork_coins = ('eth', 'etc')
  51. # ‘use_coin_opt’ must be False if ‘coin_codes’ is set
  52. _cc = namedtuple('cmd_cap', ['proto', 'rpc', 'use_coin_opt', 'coin_codes', 'caps', 'platforms'])
  53. cmd_caps_data = {
  54. 'addrgen': _cc(True, False, True, None, [], 'lmw'),
  55. 'addrimport': _cc(True, True, True, None, ['tw'], 'lmw'),
  56. 'autosign': _cc(True, True, False, '-rRb', ['rpc'], 'lm'),
  57. 'cli': _cc(True, True, True, None, ['tw'], 'lmw'),
  58. 'keygen': _cc(True, False, True, None, [], 'lmw'),
  59. 'msg': _cc(True, True, True, None, ['msg'], 'lmw'),
  60. 'passchg': _cc(False, False, False, None, [], 'lmw'),
  61. 'passgen': _cc(False, False, False, None, [], 'lmw'),
  62. 'regtest': _cc(True, True, True, None, ['tw'], 'lmw'),
  63. 'seedjoin': _cc(False, False, False, None, [], 'lmw'),
  64. 'seedsplit': _cc(False, False, False, None, [], 'lmw'),
  65. 'subwalletgen': _cc(False, False, False, None, [], 'lmw'),
  66. 'swaptxcreate': _cc(True, True, False, '-rRb', ['tw'], 'lmw'),
  67. 'swaptxdo': _cc(True, True, False, '-rRb', ['tw'], 'lmw'),
  68. 'tool': _cc(True, True, True, None, [], 'lmw'),
  69. 'txbump': _cc(True, True, True, None, ['tw'], 'lmw'),
  70. 'txcreate': _cc(True, True, True, None, ['tw'], 'lmw'),
  71. 'txdo': _cc(True, True, True, None, ['tw'], 'lmw'),
  72. 'txsend': _cc(True, True, False, '-rRb', ['tw'], 'lmw'),
  73. 'txsign': _cc(True, True, False, '-rRb', ['tw'], 'lmw'),
  74. 'walletchk': _cc(False, False, False, None, [], 'lmw'),
  75. 'walletconv': _cc(False, False, False, None, [], 'lmw'),
  76. 'walletgen': _cc(False, False, False, None, [], 'lmw'),
  77. 'xmrwallet': _cc(True, True, False, '-r', ['rpc'], 'lmw'),
  78. }
  79. prog_name = os.path.basename(sys.argv[0])
  80. prog_id = prog_name.removeprefix(f'{proj_id}-')
  81. cmd_caps = cmd_caps_data.get(prog_id)
  82. if sys.platform not in ('linux', 'win32', 'darwin'):
  83. die2(1, f'{sys.platform!r}: platform not supported by {proj_name}')
  84. if os.getenv('HOME'): # Linux, MSYS2, or macOS
  85. home_dir = os.getenv('HOME')
  86. elif sys.platform == 'win32': # Windows without MSYS2 - not supported
  87. die2(1, f'$HOME not set! {proj_name} for Windows must be run in MSYS2 environment')
  88. else:
  89. die2(2, '$HOME is not set! Unable to determine home directory')
  90. def get_mmgen_data_file(self, *, filename, package='mmgen'):
  91. """
  92. this is an expensive import, so do only when required
  93. """
  94. # Resource will be unpacked and then cleaned up if necessary, see:
  95. # https://docs.python.org/3/library/importlib.html:
  96. # Note: This module provides functionality similar to pkg_resources Basic
  97. # Resource Access without the performance overhead of that package.
  98. # https://importlib-resources.readthedocs.io/en/latest/migration.html
  99. # https://setuptools.readthedocs.io/en/latest/pkg_resources.html
  100. try:
  101. from importlib.resources import files # Python 3.9 and above
  102. except ImportError:
  103. from importlib_resources import files
  104. return files(package).joinpath('data', filename).read_text()
  105. @property
  106. def version(self):
  107. return self.get_mmgen_data_file(
  108. filename = 'version',
  109. package = 'mmgen_node_tools' if self.prog_name.startswith('mmnode-') else 'mmgen'
  110. ).strip()
  111. @property
  112. def release_date(self):
  113. return self.get_mmgen_data_file(filename='release_date').strip()
  114. gc = GlobalConstants()
  115. class GlobalVars:
  116. """
  117. These are used only by the test suite to redirect msg() and friends to /dev/null
  118. """
  119. stdout = sys.stdout
  120. stderr = sys.stderr
  121. gv = GlobalVars()
  122. class Config(Lockable):
  123. """
  124. These values are configurable - RHS values are defaults
  125. Globals are overridden with the following precedence:
  126. 1 - command line
  127. 2 - environmental vars
  128. 3 - config file
  129. """
  130. _autolock = False
  131. _set_ok = ('usr_randchars', '_proto')
  132. _reset_ok = ('accept_defaults',)
  133. _delete_ok = ('_opts',)
  134. _use_class_attr = True
  135. _default_to_none = True
  136. # general
  137. coin = 'BTC'
  138. token = ''
  139. outdir = ''
  140. passwd_file = ''
  141. network = 'mainnet'
  142. testnet = False
  143. regtest = False
  144. # verbosity / prompting behavior
  145. quiet = False
  146. verbose = False
  147. yes = False
  148. accept_defaults = False
  149. no_license = False
  150. # limits
  151. http_timeout = 60
  152. usr_randchars = 30
  153. fee_adjust = 1.0
  154. fee_estimate_confs = 3
  155. minconf = 1
  156. max_tx_file_size = 100000
  157. max_input_size = 1024 * 1024
  158. min_urandchars = 10
  159. max_urandchars = 80
  160. macos_autosign_ramdisk_size = 10 # see MacOSRamDisk
  161. # debug
  162. debug = False
  163. debug_daemon = False
  164. debug_evm = False
  165. debug_opts = False
  166. debug_rpc = False
  167. debug_addrlist = False
  168. debug_subseed = False
  169. debug_tw = False
  170. devtools = False
  171. traceback = False
  172. # rpc:
  173. rpc_host = ''
  174. rpc_port = 0
  175. rpc_user = ''
  176. rpc_password = ''
  177. aiohttp_rpc_queue_len = 16
  178. cached_balances = False
  179. # daemons
  180. daemon_data_dir = '' # set by user
  181. daemon_id = ''
  182. blacklisted_daemons = ''
  183. ignore_daemon_version = False
  184. # display:
  185. test_suite_enable_color = False # placeholder
  186. force_256_color = False
  187. scroll = False
  188. pager = False
  189. columns = 0
  190. color = bool(
  191. (sys.stdout.isatty() and not os.getenv('MMGEN_TEST_SUITE_PEXPECT')) or
  192. os.getenv('MMGEN_TEST_SUITE_ENABLE_COLOR')
  193. )
  194. # miscellaneous features:
  195. use_internal_keccak_module = False
  196. force_standalone_scrypt_module = False
  197. enable_erigon = False
  198. autochg_ignore_labels = False
  199. autosign = False
  200. # regtest:
  201. bob = False
  202. alice = False
  203. carol = False
  204. regtest_user = ''
  205. # altcoin:
  206. cashaddr = True
  207. # Monero:
  208. monero_wallet_rpc_user = 'monero'
  209. monero_wallet_rpc_password = ''
  210. priority = 0
  211. # test suite:
  212. bogus_send = False
  213. bogus_unspent_data = ''
  214. debug_utf8 = False
  215. exec_wrapper = False
  216. ignore_test_py_exception = False
  217. test_suite = False
  218. test_suite_autosign_led_simulate = False
  219. test_suite_autosign_threaded = False
  220. test_suite_xmr_autosign = False
  221. test_suite_cfgtest = False
  222. test_suite_deterministic = False
  223. test_suite_pexpect = False
  224. test_suite_popen_spawn = False
  225. test_suite_root_pfx = ''
  226. hold_protect_disable = False
  227. no_daemon_autostart = False
  228. names = False
  229. no_timings = False
  230. exit_after = ''
  231. resuming = False
  232. skipping_deps = False
  233. test_datadir = os.path.join('test', 'data_dir' + ('', '-α')[bool(os.getenv('MMGEN_DEBUG_UTF8'))])
  234. mnemonic_entry_modes = {}
  235. # external use:
  236. _opts = None
  237. _proto = None
  238. # internal use:
  239. _use_cfg_file = False
  240. _use_env = False
  241. _forbidden_opts = (
  242. 'data_dir_root',
  243. )
  244. _incompatible_opts = (
  245. ('help', 'longhelp'),
  246. ('bob', 'alice', 'carol'),
  247. ('label', 'keep_label'),
  248. ('tx_id', 'info'),
  249. ('tx_id', 'terse_info'),
  250. ('autosign', 'outdir'),
  251. )
  252. # proto-specific only: eth_mainnet_chain_names eth_testnet_chain_names
  253. # coin-specific only: bch_cashaddr (alias of cashaddr)
  254. _cfg_file_opts = (
  255. 'autochg_ignore_labels',
  256. 'autosign',
  257. 'color',
  258. 'daemon_data_dir',
  259. 'daemon_id', # also coin-specific
  260. 'debug',
  261. 'fee_adjust',
  262. 'force_256_color',
  263. 'hash_preset',
  264. 'http_timeout',
  265. 'ignore_daemon_version', # also coin-specific
  266. 'macos_autosign_ramdisk_size',
  267. 'max_input_size',
  268. 'max_tx_file_size',
  269. 'mnemonic_entry_modes',
  270. 'monero_wallet_rpc_password',
  271. 'monero_wallet_rpc_user',
  272. 'no_license',
  273. 'quiet',
  274. 'regtest',
  275. 'rpc_host', # also coin-specific
  276. 'rpc_password', # also coin-specific
  277. 'rpc_port', # also coin-specific
  278. 'rpc_user', # also coin-specific
  279. 'scroll',
  280. 'subseeds',
  281. 'testnet',
  282. 'tw_name', # also coin-specific
  283. 'usr_randchars')
  284. # Supported environmental vars
  285. # The corresponding attributes (lowercase, without 'mmgen_') must exist in the class.
  286. # The 'MMGEN_DISABLE_' prefix sets the corresponding attribute to False.
  287. _env_opts = (
  288. 'MMGEN_DEBUG_ALL', # special: there is no `debug_all` attribute
  289. 'MMGEN_COLUMNS',
  290. 'MMGEN_TEST_SUITE',
  291. 'MMGEN_TEST_SUITE_AUTOSIGN_LED_SIMULATE',
  292. 'MMGEN_TEST_SUITE_AUTOSIGN_THREADED',
  293. 'MMGEN_TEST_SUITE_XMR_AUTOSIGN',
  294. 'MMGEN_TEST_SUITE_CFGTEST',
  295. 'MMGEN_TEST_SUITE_DETERMINISTIC',
  296. 'MMGEN_TEST_SUITE_ENABLE_COLOR',
  297. 'MMGEN_TEST_SUITE_PEXPECT',
  298. 'MMGEN_TEST_SUITE_POPEN_SPAWN',
  299. 'MMGEN_TEST_SUITE_ROOT_PFX',
  300. 'MMGEN_TRACEBACK',
  301. 'MMGEN_BLACKLIST_DAEMONS',
  302. 'MMGEN_BOGUS_SEND',
  303. 'MMGEN_BOGUS_UNSPENT_DATA',
  304. 'MMGEN_DEBUG',
  305. 'MMGEN_DEBUG_DAEMON',
  306. 'MMGEN_DEBUG_EVM',
  307. 'MMGEN_DEBUG_OPTS',
  308. 'MMGEN_DEBUG_RPC',
  309. 'MMGEN_DEBUG_ADDRLIST',
  310. 'MMGEN_DEBUG_TW',
  311. 'MMGEN_DEBUG_UTF8',
  312. 'MMGEN_DEBUG_SUBSEED',
  313. 'MMGEN_DEVTOOLS',
  314. 'MMGEN_FORCE_256_COLOR',
  315. 'MMGEN_HOLD_PROTECT_DISABLE',
  316. 'MMGEN_HTTP_TIMEOUT',
  317. 'MMGEN_QUIET',
  318. 'MMGEN_NO_LICENSE',
  319. 'MMGEN_RPC_HOST',
  320. 'MMGEN_RPC_FAIL_ON_COMMAND',
  321. 'MMGEN_TESTNET',
  322. 'MMGEN_REGTEST',
  323. 'MMGEN_EXEC_WRAPPER',
  324. 'MMGEN_IGNORE_TEST_PY_EXCEPTION',
  325. 'MMGEN_RPC_BACKEND',
  326. 'MMGEN_IGNORE_DAEMON_VERSION',
  327. 'MMGEN_USE_STANDALONE_SCRYPT_MODULE',
  328. 'MMGEN_ENABLE_ERIGON',
  329. 'MMGEN_DISABLE_COLOR',
  330. )
  331. _infile_opts = (
  332. 'keys_from_file',
  333. 'mmgen_keys_from_file',
  334. 'passwd_file',
  335. 'keysforaddrs',
  336. 'comment_file',
  337. 'contract_data',
  338. )
  339. # Auto-typechecked and auto-set opts - first value in list is the default
  340. _ov = namedtuple('autoset_opt_info', ['type', 'choices'])
  341. _autoset_opts = {
  342. 'fee_estimate_mode': _ov('nocase_pfx', ['conservative', 'economical']),
  343. 'rpc_backend': _ov('nocase_pfx', ['auto', 'httplib', 'curl', 'aiohttp', 'requests']),
  344. 'swap_proto': _ov('nocase_pfx', ['thorchain']),
  345. 'tx_proxy': _ov('nocase_pfx', ['etherscan']) # , 'blockchair'
  346. }
  347. _dfl_none_autoset_opts = ('tx_proxy',)
  348. _auto_typeset_opts = {
  349. 'seed_len': int,
  350. 'subseeds': int,
  351. 'vsize_adj': float,
  352. }
  353. # test suite:
  354. err_disp_timeout = 0.7
  355. short_disp_timeout = 0.3
  356. stdin_tty = sys.stdin.isatty()
  357. if os.getenv('MMGEN_TEST_SUITE'):
  358. min_urandchars = 3
  359. err_disp_timeout = 0.1
  360. short_disp_timeout = 0.1
  361. if os.getenv('MMGEN_TEST_SUITE_POPEN_SPAWN'):
  362. stdin_tty = True
  363. if gc.prog_name == 'modtest.py':
  364. _set_ok += ('debug_subseed',)
  365. _reset_ok += ('force_standalone_scrypt_module',)
  366. if os.getenv('MMGEN_DEBUG_ALL'):
  367. for name in _env_opts:
  368. if name[:11] == 'MMGEN_DEBUG':
  369. os.environ[name] = '1'
  370. @property
  371. def data_dir_root(self):
  372. """
  373. location of mmgen.cfg
  374. """
  375. if not hasattr(self, '_data_dir_root'):
  376. if self._data_dir_root_override:
  377. self._data_dir_root = os.path.normpath(os.path.abspath(self._data_dir_root_override))
  378. elif self.test_suite:
  379. self._data_dir_root = self.test_datadir
  380. else:
  381. self._data_dir_root = os.path.join(gc.home_dir, '.'+gc.proj_name.lower())
  382. return self._data_dir_root
  383. @property
  384. def data_dir(self):
  385. """
  386. location of wallet and other data - same as data_dir_root for mainnet
  387. """
  388. if not hasattr(self, '_data_dir'):
  389. self._data_dir = os.path.normpath(os.path.join(*{
  390. 'regtest': (self.data_dir_root, 'regtest', (self.regtest_user or 'none')),
  391. 'testnet': (self.data_dir_root, 'testnet'),
  392. 'mainnet': (self.data_dir_root,),
  393. }[self.network]))
  394. return self._data_dir
  395. def __init__(
  396. self,
  397. cfg = None,
  398. *,
  399. opts_data = None,
  400. init_opts = None,
  401. parse_only = False,
  402. parsed_opts = None,
  403. need_proto = True,
  404. need_amt = True,
  405. caller_post_init = False,
  406. process_opts = False):
  407. # Step 1: get user-supplied configuration data from
  408. # a) command line, or
  409. # b) first argument to constructor;
  410. # save to self._uopts:
  411. self._cloned = {}
  412. if opts_data or parsed_opts or process_opts:
  413. assert cfg is None, (
  414. 'Config(): ‘cfg’ cannot be used simultaneously with ' +
  415. '‘opts_data’, ‘parsed_opts’ or ‘process_opts’')
  416. from .opts import UserOpts
  417. UserOpts(
  418. cfg = self,
  419. opts_data = opts_data,
  420. init_opts = init_opts,
  421. parsed_opts = parsed_opts,
  422. need_proto = need_proto)
  423. self._uopt_src = 'cmdline'
  424. else:
  425. if cfg is None:
  426. self._uopts = {}
  427. else:
  428. if '_clone' in cfg:
  429. assert isinstance(cfg['_clone'], Config)
  430. self._cloned = cfg['_clone'].__dict__
  431. for k, v in self._cloned.items():
  432. if not k.startswith('_'):
  433. setattr(self, k, v)
  434. del cfg['_clone']
  435. self._uopts = cfg
  436. self._uopt_src = 'cfg'
  437. self._data_dir_root_override = self._cloned.pop(
  438. '_data_dir_root_override',
  439. self._uopts.pop('data_dir', None))
  440. if parse_only and not any(k in self._uopts for k in ['help', 'longhelp', 'usage']):
  441. return
  442. # Step 2: set cfg from user-supplied data, skipping auto opts; set type from corresponding
  443. # class attribute, if it exists:
  444. auto_opts = tuple(self._autoset_opts) + tuple(self._auto_typeset_opts)
  445. for key, val in self._uopts.items():
  446. assert key.isascii() and key.isidentifier() and key[0] != '_', (
  447. f'{key!r}: malformed configuration option')
  448. assert key not in self._forbidden_opts, (
  449. f'{key!r}: forbidden configuration option')
  450. if key not in auto_opts:
  451. if hasattr(type(self), key):
  452. setattr(
  453. self,
  454. key,
  455. getattr(type(self), key) if val is None else
  456. conv_type(key, val, getattr(type(self), key), src=self._uopt_src))
  457. elif val is None:
  458. if hasattr(self, key):
  459. delattr(self, key)
  460. else:
  461. setattr(self, key, val)
  462. # Step 3: set cfg from environment, skipping already-set opts; save names set from environment:
  463. self._envopts = tuple(self._set_cfg_from_env()) if self._use_env else ()
  464. from .term import init_term
  465. init_term(self) # requires ‘hold_protect_disable’ (set from env)
  466. from .fileutil import check_or_create_dir
  467. check_or_create_dir(self.data_dir_root)
  468. from .util import wrap_ripemd160
  469. wrap_ripemd160() # ripemd160 required by mmgen_cfg_file() in _set_cfg_from_cfg_file()
  470. # Step 4: set cfg from cfgfile, skipping already-set opts and auto opts; save set opts and auto
  471. # opts to be set:
  472. # requires ‘data_dir_root’, ‘test_suite_cfgtest’
  473. self._cfgfile_opts = self._set_cfg_from_cfg_file(self._envopts, need_proto=need_proto)
  474. # Step 5: set autoset opts from user-supplied data, cfgfile data, or default values, in that order:
  475. self._set_autoset_opts(self._cfgfile_opts.autoset)
  476. # Step 6: set auto typeset opts from user-supplied data or cfgfile data, in that order:
  477. self._set_auto_typeset_opts(self._cfgfile_opts.auto_typeset)
  478. # Step 7: set opts_data['sets'] opts:
  479. if opts_data and 'sets' in opts_data:
  480. self._set_opts_data_sets_opts(opts_data)
  481. if self.regtest or self.bob or self.alice or self.carol or gc.prog_name == f'{gc.proj_id}-regtest':
  482. self.network = 'regtest'
  483. self.regtest_user = 'bob' if self.bob else 'alice' if self.alice else 'carol' if self.carol else None
  484. else:
  485. self.network = 'testnet' if self.testnet else 'mainnet'
  486. self.coin = self.coin.upper()
  487. self.token = self.token.upper() if self.token else None
  488. if 'usage' in self._uopts: # requires self.coin
  489. import importlib
  490. getattr(importlib.import_module(UserOpts.help_pkg), 'usage')(self) # exits
  491. # self.color is finalized, so initialize color:
  492. if self.color: # MMGEN_DISABLE_COLOR sets this to False
  493. from .color import init_color
  494. init_color(num_colors=256 if self.force_256_color else 'auto')
  495. self._die_on_incompatible_opts()
  496. check_or_create_dir(self.data_dir)
  497. if self.debug and gc.prog_name != 'cmdtest.py':
  498. self.verbose = True
  499. self.quiet = False
  500. if self.debug_opts:
  501. opt_postproc_debug(self)
  502. from .util import Util
  503. self._util = Util(self)
  504. del self._cloned
  505. if hasattr(self, 'bch_cashaddr') and not hasattr(self, 'cashaddr'):
  506. self.cashaddr = self.bch_cashaddr
  507. self._lock()
  508. if need_proto:
  509. from .protocol import init_proto_from_cfg, warn_trustlevel
  510. # requires the default-to-none behavior, so do after the lock:
  511. self._proto = init_proto_from_cfg(self, need_amt=need_amt)
  512. if self._opts and not caller_post_init:
  513. self._post_init()
  514. # Check user-set opts without modifying them
  515. check_opts(self)
  516. if need_proto:
  517. warn_trustlevel(self) # do this only after proto is initialized
  518. def _post_init(self):
  519. if self.help or self.longhelp:
  520. from .help import print_help
  521. print_help(self, self._opts) # exits
  522. del self._opts
  523. def _usage(self):
  524. from .help import make_usage_str
  525. print(make_usage_str(self, caller='user'))
  526. sys.exit(1) # called only on bad invocation
  527. def _set_cfg_from_env(self):
  528. for name, val in ((k, v) for k, v in os.environ.items() if k.startswith('MMGEN_')):
  529. if name == 'MMGEN_DEBUG_ALL':
  530. continue
  531. if name in self._env_opts:
  532. if val: # ignore empty string values; string value of '0' or 'false' sets variable to False
  533. disable = name.startswith('MMGEN_DISABLE_')
  534. gname = name[(6, 14)[disable]:].lower()
  535. if gname in self._uopts: # don’t touch attr if already set by user
  536. continue
  537. if hasattr(self, gname):
  538. setattr(
  539. self,
  540. gname,
  541. conv_type(name, val, getattr(self, gname), src='env', invert_bool=disable))
  542. yield gname
  543. else:
  544. raise ValueError(f'Name {gname!r} not present in globals')
  545. else:
  546. raise ValueError(f'{name!r} is not a valid MMGen environment variable')
  547. def _set_cfg_from_cfg_file(self, env_cfg, *, need_proto):
  548. _ret = namedtuple('cfgfile_opts', ['non_auto', 'autoset', 'auto_typeset'])
  549. if not self._use_cfg_file:
  550. return _ret((), {}, {})
  551. # check for changes in system template file (term must be initialized)
  552. from .cfgfile import mmgen_cfg_file
  553. mmgen_cfg_file(self, 'sample')
  554. ucfg = mmgen_cfg_file(self, 'usr')
  555. self._cfgfile_fn = ucfg.fn
  556. if need_proto:
  557. from .protocol import init_proto
  558. autoset_opts = {}
  559. auto_typeset_opts = {}
  560. non_auto_opts = []
  561. already_set = tuple(self._uopts) + env_cfg
  562. def set_opt(d, obj, name, refval):
  563. val = ucfg.parse_value(d.value, refval)
  564. if not val:
  565. die('CfgFileParseError', f'Parse error in file {ucfg.fn!r}, line {d.lineno}')
  566. val_conv = conv_type(name, val, refval, src=ucfg.fn)
  567. setattr(obj, name, val_conv)
  568. non_auto_opts.append(name)
  569. for d in ucfg.get_lines():
  570. if d.name in self._cfg_file_opts:
  571. if not d.name in already_set:
  572. set_opt(d, self, d.name, getattr(self, d.name))
  573. elif d.name in self._autoset_opts:
  574. autoset_opts[d.name] = d.value
  575. elif d.name in self._auto_typeset_opts:
  576. auto_typeset_opts[d.name] = d.value
  577. elif any(d.name.startswith(coin + '_') for coin in gc.rpc_coins):
  578. if need_proto and not d.name in already_set:
  579. try:
  580. refval = init_proto(self, d.name.split('_', 1)[0]).get_opt_clsval(self, d.name)
  581. except AttributeError:
  582. die('CfgFileParseError', f'{d.name!r}: unrecognized option in {ucfg.fn!r}, line {d.lineno}')
  583. set_opt(d, self, d.name, refval)
  584. else:
  585. die('CfgFileParseError', f'{d.name!r}: unrecognized option in {ucfg.fn!r}, line {d.lineno}')
  586. return _ret(tuple(non_auto_opts), autoset_opts, auto_typeset_opts)
  587. def _set_autoset_opts(self, cfgfile_autoset_opts):
  588. def get_autoset_opt(key, val, src):
  589. def die_on_err(desc):
  590. from .util import fmt_list
  591. die(
  592. 'UserOptError',
  593. '{a!r}: invalid {b} (not {c}: {d})'.format(
  594. a = val,
  595. b = {
  596. 'cmdline': f'parameter for option --{key.replace("_", "-")}',
  597. 'cfgfile': f'value for cfg file option {key!r}'
  598. }[src],
  599. c = desc,
  600. d = fmt_list(data.choices)))
  601. class opt_type:
  602. def nocase_str():
  603. if val.lower() in data.choices:
  604. return val.lower()
  605. else:
  606. die_on_err('one of')
  607. def nocase_pfx():
  608. cs = [s for s in data.choices if s.startswith(val.lower())]
  609. if len(cs) == 1:
  610. return cs[0]
  611. else:
  612. die_on_err('unique substring of')
  613. data = self._autoset_opts[key]
  614. return getattr(opt_type, data.type)()
  615. # Check autoset opts, setting if unset
  616. for key in self._autoset_opts:
  617. if key in self._cloned:
  618. continue
  619. assert not hasattr(self, key), f'autoset opt {key!r} is already set, but it shouldn’t be!'
  620. if key in self._uopts:
  621. val, src = (self._uopts[key], 'cmdline')
  622. elif key in cfgfile_autoset_opts:
  623. val, src = (cfgfile_autoset_opts[key], 'cfgfile')
  624. else:
  625. val = None
  626. if val is None:
  627. if key not in self._dfl_none_autoset_opts:
  628. setattr(self, key, self._autoset_opts[key].choices[0])
  629. else:
  630. setattr(self, key, get_autoset_opt(key, val, src=src))
  631. def _set_auto_typeset_opts(self, cfgfile_auto_typeset_opts):
  632. def do_set(key, val, ref_type):
  633. assert not hasattr(self, key), f'{key!r} is in cfg!'
  634. setattr(self, key, None if val is None else ref_type(val))
  635. for key, ref_type in self._auto_typeset_opts.items():
  636. if key in self._uopts:
  637. do_set(key, self._uopts[key], ref_type)
  638. elif key in cfgfile_auto_typeset_opts:
  639. do_set(key, cfgfile_auto_typeset_opts[key], ref_type)
  640. def _set_opts_data_sets_opts(self, opts_data):
  641. for a_opt, a_val, b_opt, b_val in opts_data['sets']:
  642. if (usr_a_val := getattr(self, a_opt, None)) not in (None, False):
  643. if a_val == bool or usr_a_val == a_val:
  644. if ((usr_b_val := getattr(self, b_opt, None)) in (None, False)) or usr_b_val == b_val:
  645. setattr(self, b_opt, b_val)
  646. else:
  647. die(1, 'Option --{}={} conflicts with option --{}={}\n'.format(
  648. b_opt.replace('_', '-'),
  649. usr_b_val,
  650. a_opt.replace('_', '-'),
  651. usr_a_val))
  652. def _die_on_incompatible_opts(self):
  653. for group in self._incompatible_opts:
  654. bad = [k for k in self.__dict__ if k in group and getattr(self, k) is not None]
  655. if len(bad) > 1:
  656. die(1, 'Conflicting options: {}'.format(', '.join(map(fmt_opt, bad))))
  657. def _set_quiet(self, val):
  658. from .util import Util
  659. self.__dict__['quiet'] = val
  660. self.__dict__['_util'] = Util(self) # qmsg, qmsg_r
  661. def check_opts(cfg): # Raises exception if any check fails
  662. from .util import is_int, Msg
  663. def get_desc(desc_pfx=''):
  664. return (
  665. (desc_pfx + ' ' if desc_pfx else '')
  666. + (
  667. f'parameter for command-line option {fmt_opt(name)!r}'
  668. if name in cfg._uopts and cfg._uopt_src == 'cmdline' else
  669. f'value for configuration option {name!r}'
  670. )
  671. + (' from environment' if name in cfg._envopts else '')
  672. + (f' in {cfg._cfgfile_fn!r}' if name in cfg._cfgfile_opts.non_auto else '')
  673. )
  674. def display_opt(name, val='', *, beg='For selected', end=':\n'):
  675. from .util import msg_r
  676. msg_r('{} option {!r}{}'.format(
  677. beg,
  678. f'{fmt_opt(name)}={val}' if val else fmt_opt(name),
  679. end))
  680. def opt_compares(val, op_str, target):
  681. import operator
  682. if not {
  683. '<': operator.lt,
  684. '<=': operator.le,
  685. '>': operator.gt,
  686. '>=': operator.ge,
  687. '=': operator.eq,
  688. }[op_str](val, target):
  689. die('UserOptError', f'{val}: invalid {get_desc()} (not {op_str} {target})')
  690. def opt_is_int(val, *, desc_pfx=''):
  691. if not is_int(val):
  692. die('UserOptError', f'{val!r}: invalid {get_desc(desc_pfx)} (not an integer)')
  693. def opt_is_in_list(val, tlist, *, desc_pfx=''):
  694. if val not in tlist:
  695. q, sep = (('', ','), ("'", "','"))[isinstance(tlist[0], str)]
  696. die('UserOptError', '{q}{v}{q}: invalid {w}\nValid choices: {q}{o}{q}'.format(
  697. v = val,
  698. w = get_desc(desc_pfx),
  699. q = q,
  700. o = sep.join(map(str, sorted(tlist)))))
  701. def opt_unrecognized():
  702. die('UserOptError', f'{val!r}: unrecognized {get_desc()}')
  703. class check_funcs:
  704. def in_fmt():
  705. from .wallet import get_wallet_data
  706. wd = get_wallet_data(fmt_code=val)
  707. if not wd:
  708. opt_unrecognized()
  709. if name == 'out_fmt':
  710. p = 'hidden_incog_output_params'
  711. if wd.type == 'incog_hidden' and not getattr(cfg, p):
  712. die('UserOptError',
  713. 'Hidden incog format output requested. ' +
  714. f'You must supply a file and offset with the {fmt_opt(p)!r} option')
  715. if wd.base_type == 'incog_base' and cfg.old_incog_fmt:
  716. display_opt(name, val, beg='Selected', end=' ')
  717. display_opt('old_incog_fmt', beg='conflicts with', end=':\n')
  718. die('UserOptError', 'Export to old incog wallet format unsupported')
  719. elif wd.type == 'brain':
  720. die('UserOptError', 'Output to brainwallet format unsupported')
  721. out_fmt = in_fmt
  722. def hidden_incog_input_params():
  723. a = val.rsplit(',', 1) # permit comma in filename
  724. if len(a) != 2:
  725. display_opt(name, val)
  726. die('UserOptError', 'Option requires two comma-separated arguments')
  727. fn, offset = a
  728. opt_is_int(offset)
  729. from .fileutil import check_infile, check_outdir, check_outfile
  730. if name == 'hidden_incog_input_params':
  731. check_infile(fn, blkdev_ok=True)
  732. key2 = 'in_fmt'
  733. else:
  734. try:
  735. os.stat(fn)
  736. except:
  737. b = os.path.dirname(fn)
  738. if b:
  739. check_outdir(b)
  740. else:
  741. check_outfile(fn, blkdev_ok=True)
  742. key2 = 'out_fmt'
  743. if hasattr(cfg, key2):
  744. val2 = getattr(cfg, key2)
  745. from .wallet import get_wallet_data
  746. wd = get_wallet_data(wtype='incog_hidden')
  747. if val2 and val2 not in wd.fmt_codes:
  748. die('UserOptError',
  749. f'Option {fmt_opt(name)} conflicts with option {fmt_opt(key2)}={val2}')
  750. hidden_incog_output_params = hidden_incog_input_params
  751. def subseeds():
  752. from .subseed import SubSeedIdxRange
  753. opt_compares(val, '>=', SubSeedIdxRange.min_idx)
  754. opt_compares(val, '<=', SubSeedIdxRange.max_idx)
  755. def seed_len():
  756. from .seed import Seed
  757. opt_is_in_list(int(val), Seed.lens)
  758. def hash_preset():
  759. from .crypto import Crypto
  760. opt_is_in_list(val, list(Crypto.hash_presets.keys()))
  761. def brain_params():
  762. a = val.split(',')
  763. if len(a) != 2:
  764. display_opt(name, val)
  765. die('UserOptError', 'Option requires two comma-separated arguments')
  766. opt_is_int(a[0], desc_pfx='seed length')
  767. from .seed import Seed
  768. opt_is_in_list(int(a[0]), Seed.lens, desc_pfx='seed length')
  769. from .crypto import Crypto
  770. opt_is_in_list(a[1], list(Crypto.hash_presets.keys()), desc_pfx='hash preset')
  771. def usr_randchars():
  772. if val != 0:
  773. opt_compares(val, '>=', cfg.min_urandchars)
  774. opt_compares(val, '<=', cfg.max_urandchars)
  775. def tx_confs():
  776. opt_is_int(val)
  777. opt_compares(int(val), '>=', 1)
  778. def vsize_adj():
  779. from .util import ymsg
  780. ymsg(f'Adjusting transaction vsize by a factor of {val:1.2f}')
  781. def daemon_id():
  782. from .daemon import CoinDaemon
  783. opt_is_in_list(val, CoinDaemon.all_daemon_ids())
  784. def locktime():
  785. opt_is_int(val)
  786. opt_compares(int(val), '>', 0)
  787. def columns():
  788. opt_compares(val, '>', 10)
  789. # TODO: add checks for token, rbf, tx_fee
  790. check_funcs_names = tuple(check_funcs.__dict__)
  791. for name in tuple(cfg._uopts) + cfg._envopts + cfg._cfgfile_opts.non_auto:
  792. val = getattr(cfg, name)
  793. if name in cfg._infile_opts:
  794. from .fileutil import check_infile
  795. check_infile(val) # file exists and is readable - dies on error
  796. elif name == 'outdir':
  797. from .fileutil import check_outdir
  798. check_outdir(val) # dies on error
  799. elif name in check_funcs_names:
  800. getattr(check_funcs, name)()
  801. elif cfg.debug:
  802. Msg(f'check_opts(): No test for config opt {name!r}')
  803. def fmt_opt(o):
  804. return '--' + o.replace('_', '-')
  805. def opt_postproc_debug(cfg):
  806. none_opts = [k for k in dir(cfg) if k[:2] != '__' and getattr(cfg, k) is None]
  807. from .util import Msg
  808. Msg('\n Configuration opts:')
  809. for e in [d for d in dir(cfg) if d[:2] != '__']:
  810. Msg(f' {e:<20}: {getattr(cfg, e)}')
  811. Msg(" Configuration opts set to 'None':")
  812. Msg(' {}\n'.format('\n '.join(none_opts)))
  813. Msg('\n=== end opts.py debug ===\n')
  814. def conv_type(name, val, refval, *, src, invert_bool=False):
  815. def do_fail():
  816. desc = {
  817. 'cmdline': 'command-line',
  818. 'cfg': 'Config',
  819. 'env': 'environment var',
  820. }
  821. die(1, '{a!r}: invalid value for {b} option {c!r}{d} (must be of type {e!r})'.format(
  822. a = val,
  823. b = desc.get(src, 'config file'),
  824. c = fmt_opt(name) if src == 'cmdline' else name,
  825. d = '' if src in ('cmdline', 'cfg', 'env') else f' in {src!r}',
  826. e = type(refval).__name__))
  827. # refval is None = boolean opt with no cmdline parameter
  828. if type(refval) is bool or refval is None:
  829. v = str(val).lower()
  830. ret = (
  831. True if v in ('true', 'yes', '1', 'on') else
  832. False if v in ('false', 'no', 'none', '0', 'off', '') else
  833. None
  834. )
  835. return do_fail() if ret is None else (not ret) if invert_bool else ret
  836. elif isinstance(refval, (list, tuple)):
  837. if src == 'cmdline':
  838. return type(refval)(val.split(','))
  839. else:
  840. assert isinstance(val, (list, tuple)), f'{val}: not a list or tuple'
  841. return type(refval)(val)
  842. else:
  843. try:
  844. return type(refval)(not val if invert_bool else val)
  845. except:
  846. do_fail()