cfg.py 29 KB

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