cfg.py 30 KB

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