cfg.py 28 KB

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