cfg.py 29 KB

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