From ef95be334f3aec671346372b64606e0fd390979a Mon Sep 17 00:00:00 2001 From: TheCharlatan Date: Thu, 4 May 2023 23:04:35 +0200 Subject: refactor: Add stop_at_height option in ChainstateManager Remove access to the global gArgs for the stopatheight argument and replace it by adding a field to the existing ChainstateManager Options struct. This should eventually allow users of the ChainstateManager to not rely on the global gArgs and instead pass in their own options. --- src/kernel/chainstatemanager_opts.h | 2 ++ src/node/chainstatemanager_args.cpp | 2 ++ src/validation.cpp | 3 +-- src/validation.h | 3 +-- 4 files changed, 6 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/kernel/chainstatemanager_opts.h b/src/kernel/chainstatemanager_opts.h index 917f7d226c..035a913d10 100644 --- a/src/kernel/chainstatemanager_opts.h +++ b/src/kernel/chainstatemanager_opts.h @@ -21,6 +21,7 @@ class CChainParams; static constexpr bool DEFAULT_CHECKPOINTS_ENABLED{true}; static constexpr auto DEFAULT_MAX_TIP_AGE{24h}; +static constexpr int DEFAULT_STOPATHEIGHT{0}; namespace kernel { @@ -45,6 +46,7 @@ struct ChainstateManagerOpts { DBOptions coins_db{}; CoinsViewOptions coins_view{}; Notifications& notifications; + int stop_at_height{DEFAULT_STOPATHEIGHT}; }; } // namespace kernel diff --git a/src/node/chainstatemanager_args.cpp b/src/node/chainstatemanager_args.cpp index 87d9238c18..a7f7303348 100644 --- a/src/node/chainstatemanager_args.cpp +++ b/src/node/chainstatemanager_args.cpp @@ -37,6 +37,8 @@ util::Result ApplyArgsManOptions(const ArgsManager& args, ChainstateManage if (auto value{args.GetIntArg("-maxtipage")}) opts.max_tip_age = std::chrono::seconds{*value}; + if (auto value{args.GetIntArg("-stopatheight")}) opts.stop_at_height = *value; + ReadDatabaseArgs(args, opts.block_tree_db); ReadDatabaseArgs(args, opts.coins_db); ReadCoinsViewArgs(args, opts.coins_view); diff --git a/src/validation.cpp b/src/validation.cpp index 5fd2d05447..49c512fa54 100644 --- a/src/validation.cpp +++ b/src/validation.cpp @@ -3104,7 +3104,6 @@ bool Chainstate::ActivateBestChain(BlockValidationState& state, std::shared_ptr< CBlockIndex *pindexMostWork = nullptr; CBlockIndex *pindexNewTip = nullptr; - int nStopAtHeight = gArgs.GetIntArg("-stopatheight", DEFAULT_STOPATHEIGHT); do { // Block until the validation queue drains. This should largely // never happen in normal operation, however may happen during @@ -3179,7 +3178,7 @@ bool Chainstate::ActivateBestChain(BlockValidationState& state, std::shared_ptr< } // When we reach this point, we switched to a new tip (stored in pindexNewTip). - if (nStopAtHeight && pindexNewTip && pindexNewTip->nHeight >= nStopAtHeight) StartShutdown(); + if (m_chainman.StopAtHeight() && pindexNewTip && pindexNewTip->nHeight >= m_chainman.StopAtHeight()) StartShutdown(); if (WITH_LOCK(::cs_main, return m_disabled)) { // Background chainstate has reached the snapshot base block, so exit. diff --git a/src/validation.h b/src/validation.h index 444fe72db4..48a1b075b8 100644 --- a/src/validation.h +++ b/src/validation.h @@ -65,8 +65,6 @@ struct Params; static const int MAX_SCRIPTCHECK_THREADS = 15; /** -par default (number of script-checking threads, 0 = auto) */ static const int DEFAULT_SCRIPTCHECK_THREADS = 0; -/** Default for -stopatheight */ -static const int DEFAULT_STOPATHEIGHT = 0; /** Block files containing a block-height within MIN_BLOCKS_TO_KEEP of ActiveChain().Tip() will not be pruned. */ static const unsigned int MIN_BLOCKS_TO_KEEP = 288; static const signed int DEFAULT_CHECKBLOCKS = 6; @@ -960,6 +958,7 @@ public: const arith_uint256& MinimumChainWork() const { return *Assert(m_options.minimum_chain_work); } const uint256& AssumedValidBlock() const { return *Assert(m_options.assumed_valid_block); } kernel::Notifications& GetNotifications() const { return m_options.notifications; }; + int StopAtHeight() const { return m_options.stop_at_height; }; /** * Alias for ::cs_main. -- cgit v1.2.3 From 8789b11114b4bd6c7ee727dffbc75a6bdf20dd27 Mon Sep 17 00:00:00 2001 From: TheCharlatan Date: Thu, 4 May 2023 23:19:58 +0200 Subject: refactor: Add path argument to FindSnapshotChainstateDir Remove access to the global gArgs for getting the directory in utxo_snapshot. This is done in the context of the libbitcoinkernel project, wherein reliance of libbitcoinkernel code on the global gArgs is incrementally removed. --- src/node/utxo_snapshot.cpp | 5 ++--- src/node/utxo_snapshot.h | 2 +- src/test/validation_chainstatemanager_tests.cpp | 12 ++++++------ src/validation.cpp | 4 ++-- 4 files changed, 11 insertions(+), 12 deletions(-) (limited to 'src') diff --git a/src/node/utxo_snapshot.cpp b/src/node/utxo_snapshot.cpp index 3dae46fb84..036a25d0a5 100644 --- a/src/node/utxo_snapshot.cpp +++ b/src/node/utxo_snapshot.cpp @@ -4,7 +4,6 @@ #include -#include #include #include #include @@ -82,10 +81,10 @@ std::optional ReadSnapshotBaseBlockhash(fs::path chaindir) return base_blockhash; } -std::optional FindSnapshotChainstateDir() +std::optional FindSnapshotChainstateDir(const fs::path& data_dir) { fs::path possible_dir = - gArgs.GetDataDirNet() / fs::u8path(strprintf("chainstate%s", SNAPSHOT_CHAINSTATE_SUFFIX)); + data_dir / fs::u8path(strprintf("chainstate%s", SNAPSHOT_CHAINSTATE_SUFFIX)); if (fs::exists(possible_dir)) { return possible_dir; diff --git a/src/node/utxo_snapshot.h b/src/node/utxo_snapshot.h index 44ddd77dc3..a6dd3f3f13 100644 --- a/src/node/utxo_snapshot.h +++ b/src/node/utxo_snapshot.h @@ -67,7 +67,7 @@ constexpr std::string_view SNAPSHOT_CHAINSTATE_SUFFIX = "_snapshot"; //! Return a path to the snapshot-based chainstate dir, if one exists. -std::optional FindSnapshotChainstateDir(); +std::optional FindSnapshotChainstateDir(const fs::path& data_dir); } // namespace node diff --git a/src/test/validation_chainstatemanager_tests.cpp b/src/test/validation_chainstatemanager_tests.cpp index 8ca4e62e27..a09a598332 100644 --- a/src/test/validation_chainstatemanager_tests.cpp +++ b/src/test/validation_chainstatemanager_tests.cpp @@ -184,7 +184,7 @@ struct SnapshotTestSetup : TestChain100Setup { { LOCK(::cs_main); BOOST_CHECK(!chainman.IsSnapshotValidated()); - BOOST_CHECK(!node::FindSnapshotChainstateDir()); + BOOST_CHECK(!node::FindSnapshotChainstateDir(m_args.GetDataDirNet())); } size_t initial_size; @@ -234,7 +234,7 @@ struct SnapshotTestSetup : TestChain100Setup { auto_infile >> coin; })); - BOOST_CHECK(!node::FindSnapshotChainstateDir()); + BOOST_CHECK(!node::FindSnapshotChainstateDir(m_args.GetDataDirNet())); BOOST_REQUIRE(!CreateAndActivateUTXOSnapshot( this, [](AutoFile& auto_infile, SnapshotMetadata& metadata) { @@ -258,7 +258,7 @@ struct SnapshotTestSetup : TestChain100Setup { })); BOOST_REQUIRE(CreateAndActivateUTXOSnapshot(this)); - BOOST_CHECK(fs::exists(*node::FindSnapshotChainstateDir())); + BOOST_CHECK(fs::exists(*node::FindSnapshotChainstateDir(m_args.GetDataDirNet()))); // Ensure our active chain is the snapshot chainstate. BOOST_CHECK(!chainman.ActiveChainstate().m_from_snapshot_blockhash->IsNull()); @@ -271,7 +271,7 @@ struct SnapshotTestSetup : TestChain100Setup { { LOCK(::cs_main); - fs::path found = *node::FindSnapshotChainstateDir(); + fs::path found = *node::FindSnapshotChainstateDir(m_args.GetDataDirNet()); // Note: WriteSnapshotBaseBlockhash() is implicitly tested above. BOOST_CHECK_EQUAL( @@ -491,7 +491,7 @@ BOOST_FIXTURE_TEST_CASE(chainstatemanager_snapshot_init, SnapshotTestSetup) this->SetupSnapshot(); - fs::path snapshot_chainstate_dir = *node::FindSnapshotChainstateDir(); + fs::path snapshot_chainstate_dir = *node::FindSnapshotChainstateDir(m_args.GetDataDirNet()); BOOST_CHECK(fs::exists(snapshot_chainstate_dir)); BOOST_CHECK_EQUAL(snapshot_chainstate_dir, gArgs.GetDataDirNet() / "chainstate_snapshot"); @@ -565,7 +565,7 @@ BOOST_FIXTURE_TEST_CASE(chainstatemanager_snapshot_completion, SnapshotTestSetup SnapshotCompletionResult res; auto mock_shutdown = [](bilingual_str msg) {}; - fs::path snapshot_chainstate_dir = *node::FindSnapshotChainstateDir(); + fs::path snapshot_chainstate_dir = *node::FindSnapshotChainstateDir(m_args.GetDataDirNet()); BOOST_CHECK(fs::exists(snapshot_chainstate_dir)); BOOST_CHECK_EQUAL(snapshot_chainstate_dir, gArgs.GetDataDirNet() / "chainstate_snapshot"); diff --git a/src/validation.cpp b/src/validation.cpp index 49c512fa54..080d426bc3 100644 --- a/src/validation.cpp +++ b/src/validation.cpp @@ -5107,7 +5107,7 @@ bool ChainstateManager::ActivateSnapshot( // PopulateAndValidateSnapshot can return (in error) before the leveldb datadir // has been created, so only attempt removal if we got that far. - if (auto snapshot_datadir = node::FindSnapshotChainstateDir()) { + if (auto snapshot_datadir = node::FindSnapshotChainstateDir(m_options.datadir)) { // We have to destruct leveldb::DB in order to release the db lock, otherwise // DestroyDB() (in DeleteCoinsDBFromDisk()) will fail. See `leveldb::~DBImpl()`. // Destructing the chainstate (and so resetting the coinsviews object) does this. @@ -5597,7 +5597,7 @@ ChainstateManager::~ChainstateManager() bool ChainstateManager::DetectSnapshotChainstate(CTxMemPool* mempool) { assert(!m_snapshot_chainstate); - std::optional path = node::FindSnapshotChainstateDir(); + std::optional path = node::FindSnapshotChainstateDir(m_options.datadir); if (!path) { return false; } -- cgit v1.2.3 From 05870b1c92f39d90e5ba6e0caf2f6c2b37955528 Mon Sep 17 00:00:00 2001 From: TheCharlatan Date: Thu, 4 May 2023 23:22:33 +0200 Subject: refactor: Remove gArgs access from validation.cpp This is done in the context of the libbitcoinkernel project, wherein reliance of libbitcoinkernel code on the global gArgs is incrementally removed. --- src/validation.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/validation.cpp b/src/validation.cpp index 080d426bc3..99495ae2f7 100644 --- a/src/validation.cpp +++ b/src/validation.cpp @@ -11,7 +11,6 @@ #include #include #include -#include #include #include #include @@ -2500,7 +2499,7 @@ bool Chainstate::FlushStateToDisk( // Write blocks and block index to disk. if (fDoFullFlush || fPeriodicWrite) { // Ensure we can write block index - if (!CheckDiskSpace(gArgs.GetBlocksDirPath())) { + if (!CheckDiskSpace(m_blockman.m_opts.blocks_dir)) { return AbortNode(state, "Disk space is too low!", _("Disk space is too low!")); } { @@ -2536,7 +2535,7 @@ bool Chainstate::FlushStateToDisk( // twice (once in the log, and once in the tables). This is already // an overestimation, as most will delete an existing entry or // overwrite one. Still, use a conservative safety factor of 2. - if (!CheckDiskSpace(gArgs.GetDataDirNet(), 48 * 2 * 2 * CoinsTip().GetCacheSize())) { + if (!CheckDiskSpace(m_chainman.m_options.datadir, 48 * 2 * 2 * CoinsTip().GetCacheSize())) { return AbortNode(state, "Disk space is too low!", _("Disk space is too low!")); } // Flush the chainstate (which may refer to block index entries). -- cgit v1.2.3 From c2dae5d7d89634fbd771755ce3909719f5462f63 Mon Sep 17 00:00:00 2001 From: TheCharlatan Date: Thu, 4 May 2023 23:26:52 +0200 Subject: kernel: Remove chainparams, chainparamsbase, args, settings from kernel library --- src/Makefile.am | 5 ----- src/bitcoin-chainstate.cpp | 17 +++++++---------- 2 files changed, 7 insertions(+), 15 deletions(-) (limited to 'src') diff --git a/src/Makefile.am b/src/Makefile.am index 0b25ef9c6b..77c36da658 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -912,12 +912,8 @@ libbitcoinkernel_la_SOURCES = \ kernel/bitcoinkernel.cpp \ arith_uint256.cpp \ chain.cpp \ - chainparamsbase.cpp \ - chainparams.cpp \ clientversion.cpp \ coins.cpp \ - common/args.cpp \ - common/config.cpp \ compressor.cpp \ consensus/merkle.cpp \ consensus/tx_check.cpp \ @@ -978,7 +974,6 @@ libbitcoinkernel_la_SOURCES = \ util/moneystr.cpp \ util/rbf.cpp \ util/serfloat.cpp \ - util/settings.cpp \ util/strencodings.cpp \ util/string.cpp \ util/syscall_sandbox.cpp \ diff --git a/src/bitcoin-chainstate.cpp b/src/bitcoin-chainstate.cpp index 5678d4a526..432bdc8e33 100644 --- a/src/bitcoin-chainstate.cpp +++ b/src/bitcoin-chainstate.cpp @@ -17,8 +17,6 @@ #include #include -#include -#include #include #include #include @@ -53,13 +51,9 @@ int main(int argc, char* argv[]) } std::filesystem::path abs_datadir = std::filesystem::absolute(argv[1]); std::filesystem::create_directories(abs_datadir); - gArgs.ForceSetArg("-datadir", abs_datadir.string()); - // SETUP: Misc Globals - SelectParams(ChainType::MAIN); - auto chainparams = CChainParams::Main(); - + // SETUP: Context kernel::Context kernel_context{}; // We can't use a goto here, but we can use an assert since none of the // things instantiated so far requires running the epilogue to be torn down @@ -106,16 +100,18 @@ int main(int argc, char* argv[]) }; auto notifications = std::make_unique(); + // SETUP: Chainstate + auto chainparams = CChainParams::Main(); const ChainstateManager::Options chainman_opts{ .chainparams = *chainparams, - .datadir = gArgs.GetDataDirNet(), + .datadir = abs_datadir, .adjusted_time_callback = NodeClock::now, .notifications = *notifications, }; const node::BlockManager::Options blockman_opts{ .chainparams = chainman_opts.chainparams, - .blocks_dir = gArgs.GetBlocksDirPath(), + .blocks_dir = abs_datadir / "blocks", }; ChainstateManager chainman{chainman_opts, blockman_opts}; @@ -148,7 +144,8 @@ int main(int argc, char* argv[]) // Main program logic starts here std::cout << "Hello! I'm going to print out some information about your datadir." << std::endl - << "\t" << "Path: " << gArgs.GetDataDirNet() << std::endl; + << "\t" + << "Path: " << abs_datadir << std::endl; { LOCK(chainman.GetMutex()); std::cout -- cgit v1.2.3 From c27e4bdc35bc7cedd1ee07e98a52c230241120d1 Mon Sep 17 00:00:00 2001 From: TheCharlatan Date: Wed, 24 May 2023 15:55:53 +0200 Subject: move-only: Move settings to the common library The background of this commit is an ongoing effort to decouple the libbitcoinkernel library from code that is not strictly required by it. The settings code belongs into the common library and namespace, since the kernel library should not depend on it. See doc/design/libraries.md for more information on this rationale. Changing the namespace of the moved functions is scripted in the following commit. --- src/Makefile.am | 4 +- src/addrdb.cpp | 2 +- src/common/args.cpp | 2 +- src/common/args.h | 2 +- src/common/config.cpp | 2 +- src/common/settings.cpp | 261 ++++++++++++++++++++++++++++++++++++++++++++ src/common/settings.h | 115 +++++++++++++++++++ src/interfaces/chain.h | 2 +- src/interfaces/node.h | 2 +- src/qt/test/optiontests.h | 2 +- src/test/fuzz/string.cpp | 2 +- src/test/getarg_tests.cpp | 2 +- src/test/settings_tests.cpp | 2 +- src/util/settings.cpp | 258 ------------------------------------------- src/util/settings.h | 114 ------------------- 15 files changed, 388 insertions(+), 384 deletions(-) create mode 100644 src/common/settings.cpp create mode 100644 src/common/settings.h delete mode 100644 src/util/settings.cpp delete mode 100644 src/util/settings.h (limited to 'src') diff --git a/src/Makefile.am b/src/Makefile.am index 77c36da658..b4ff556eb6 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -143,6 +143,7 @@ BITCOIN_CORE_H = \ compat/compat.h \ compat/cpuid.h \ compat/endian.h \ + common/settings.h \ common/system.h \ compressor.h \ consensus/consensus.h \ @@ -309,7 +310,6 @@ BITCOIN_CORE_H = \ util/readwritefile.h \ util/result.h \ util/serfloat.h \ - util/settings.h \ util/sock.h \ util/spanparsing.h \ util/string.h \ @@ -663,6 +663,7 @@ libbitcoin_common_a_SOURCES = \ common/init.cpp \ common/interfaces.cpp \ common/run_command.cpp \ + common/settings.cpp \ common/system.cpp \ compressor.cpp \ core_read.cpp \ @@ -733,7 +734,6 @@ libbitcoin_util_a_SOURCES = \ util/moneystr.cpp \ util/rbf.cpp \ util/readwritefile.cpp \ - util/settings.cpp \ util/thread.cpp \ util/threadinterrupt.cpp \ util/threadnames.cpp \ diff --git a/src/addrdb.cpp b/src/addrdb.cpp index 23f9600ea5..e86fc231a5 100644 --- a/src/addrdb.cpp +++ b/src/addrdb.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -21,7 +22,6 @@ #include #include #include -#include #include namespace { diff --git a/src/common/args.cpp b/src/common/args.cpp index c9af2d7f5e..289410ecbe 100644 --- a/src/common/args.cpp +++ b/src/common/args.cpp @@ -6,6 +6,7 @@ #include #include +#include #include #include #include @@ -14,7 +15,6 @@ #include #include #include -#include #include #ifdef WIN32 diff --git a/src/common/args.h b/src/common/args.h index 7569297a74..c4debb9c82 100644 --- a/src/common/args.h +++ b/src/common/args.h @@ -5,11 +5,11 @@ #ifndef BITCOIN_COMMON_ARGS_H #define BITCOIN_COMMON_ARGS_H +#include #include #include #include #include -#include #include #include diff --git a/src/common/config.cpp b/src/common/config.cpp index e25b4fe2df..d156f8e514 100644 --- a/src/common/config.cpp +++ b/src/common/config.cpp @@ -4,13 +4,13 @@ #include +#include #include #include #include #include #include #include -#include #include #include diff --git a/src/common/settings.cpp b/src/common/settings.cpp new file mode 100644 index 0000000000..7d08355b33 --- /dev/null +++ b/src/common/settings.cpp @@ -0,0 +1,261 @@ +// Copyright (c) 2019-2022 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace util { +namespace { + +enum class Source { + FORCED, + COMMAND_LINE, + RW_SETTINGS, + CONFIG_FILE_NETWORK_SECTION, + CONFIG_FILE_DEFAULT_SECTION +}; + +//! Merge settings from multiple sources in precedence order: +//! Forced config > command line > read-write settings file > config file network-specific section > config file default section +//! +//! This function is provided with a callback function fn that contains +//! specific logic for how to merge the sources. +template +static void MergeSettings(const Settings& settings, const std::string& section, const std::string& name, Fn&& fn) +{ + // Merge in the forced settings + if (auto* value = FindKey(settings.forced_settings, name)) { + fn(SettingsSpan(*value), Source::FORCED); + } + // Merge in the command-line options + if (auto* values = FindKey(settings.command_line_options, name)) { + fn(SettingsSpan(*values), Source::COMMAND_LINE); + } + // Merge in the read-write settings + if (const SettingsValue* value = FindKey(settings.rw_settings, name)) { + fn(SettingsSpan(*value), Source::RW_SETTINGS); + } + // Merge in the network-specific section of the config file + if (!section.empty()) { + if (auto* map = FindKey(settings.ro_config, section)) { + if (auto* values = FindKey(*map, name)) { + fn(SettingsSpan(*values), Source::CONFIG_FILE_NETWORK_SECTION); + } + } + } + // Merge in the default section of the config file + if (auto* map = FindKey(settings.ro_config, "")) { + if (auto* values = FindKey(*map, name)) { + fn(SettingsSpan(*values), Source::CONFIG_FILE_DEFAULT_SECTION); + } + } +} +} // namespace + +bool ReadSettings(const fs::path& path, std::map& values, std::vector& errors) +{ + values.clear(); + errors.clear(); + + // Ok for file to not exist + if (!fs::exists(path)) return true; + + std::ifstream file; + file.open(path); + if (!file.is_open()) { + errors.emplace_back(strprintf("%s. Please check permissions.", fs::PathToString(path))); + return false; + } + + SettingsValue in; + if (!in.read(std::string{std::istreambuf_iterator(file), std::istreambuf_iterator()})) { + errors.emplace_back(strprintf("Unable to parse settings file %s", fs::PathToString(path))); + return false; + } + + if (file.fail()) { + errors.emplace_back(strprintf("Failed reading settings file %s", fs::PathToString(path))); + return false; + } + file.close(); // Done with file descriptor. Release while copying data. + + if (!in.isObject()) { + errors.emplace_back(strprintf("Found non-object value %s in settings file %s", in.write(), fs::PathToString(path))); + return false; + } + + const std::vector& in_keys = in.getKeys(); + const std::vector& in_values = in.getValues(); + for (size_t i = 0; i < in_keys.size(); ++i) { + auto inserted = values.emplace(in_keys[i], in_values[i]); + if (!inserted.second) { + errors.emplace_back(strprintf("Found duplicate key %s in settings file %s", in_keys[i], fs::PathToString(path))); + values.clear(); + break; + } + } + return errors.empty(); +} + +bool WriteSettings(const fs::path& path, + const std::map& values, + std::vector& errors) +{ + SettingsValue out(SettingsValue::VOBJ); + for (const auto& value : values) { + out.__pushKV(value.first, value.second); + } + std::ofstream file; + file.open(path); + if (file.fail()) { + errors.emplace_back(strprintf("Error: Unable to open settings file %s for writing", fs::PathToString(path))); + return false; + } + file << out.write(/* prettyIndent= */ 4, /* indentLevel= */ 1) << std::endl; + file.close(); + return true; +} + +SettingsValue GetSetting(const Settings& settings, + const std::string& section, + const std::string& name, + bool ignore_default_section_config, + bool ignore_nonpersistent, + bool get_chain_type) +{ + SettingsValue result; + bool done = false; // Done merging any more settings sources. + MergeSettings(settings, section, name, [&](SettingsSpan span, Source source) { + // Weird behavior preserved for backwards compatibility: Apply negated + // setting even if non-negated setting would be ignored. A negated + // value in the default section is applied to network specific options, + // even though normal non-negated values there would be ignored. + const bool never_ignore_negated_setting = span.last_negated(); + + // Weird behavior preserved for backwards compatibility: Take first + // assigned value instead of last. In general, later settings take + // precedence over early settings, but for backwards compatibility in + // the config file the precedence is reversed for all settings except + // chain type settings. + const bool reverse_precedence = + (source == Source::CONFIG_FILE_NETWORK_SECTION || source == Source::CONFIG_FILE_DEFAULT_SECTION) && + !get_chain_type; + + // Weird behavior preserved for backwards compatibility: Negated + // -regtest and -testnet arguments which you would expect to override + // values set in the configuration file are currently accepted but + // silently ignored. It would be better to apply these just like other + // negated values, or at least warn they are ignored. + const bool skip_negated_command_line = get_chain_type; + + if (done) return; + + // Ignore settings in default config section if requested. + if (ignore_default_section_config && source == Source::CONFIG_FILE_DEFAULT_SECTION && + !never_ignore_negated_setting) { + return; + } + + // Ignore nonpersistent settings if requested. + if (ignore_nonpersistent && (source == Source::COMMAND_LINE || source == Source::FORCED)) return; + + // Skip negated command line settings. + if (skip_negated_command_line && span.last_negated()) return; + + if (!span.empty()) { + result = reverse_precedence ? span.begin()[0] : span.end()[-1]; + done = true; + } else if (span.last_negated()) { + result = false; + done = true; + } + }); + return result; +} + +std::vector GetSettingsList(const Settings& settings, + const std::string& section, + const std::string& name, + bool ignore_default_section_config) +{ + std::vector result; + bool done = false; // Done merging any more settings sources. + bool prev_negated_empty = false; + MergeSettings(settings, section, name, [&](SettingsSpan span, Source source) { + // Weird behavior preserved for backwards compatibility: Apply config + // file settings even if negated on command line. Negating a setting on + // command line will ignore earlier settings on the command line and + // ignore settings in the config file, unless the negated command line + // value is followed by non-negated value, in which case config file + // settings will be brought back from the dead (but earlier command + // line settings will still be ignored). + const bool add_zombie_config_values = + (source == Source::CONFIG_FILE_NETWORK_SECTION || source == Source::CONFIG_FILE_DEFAULT_SECTION) && + !prev_negated_empty; + + // Ignore settings in default config section if requested. + if (ignore_default_section_config && source == Source::CONFIG_FILE_DEFAULT_SECTION) return; + + // Add new settings to the result if isn't already complete, or if the + // values are zombies. + if (!done || add_zombie_config_values) { + for (const auto& value : span) { + if (value.isArray()) { + result.insert(result.end(), value.getValues().begin(), value.getValues().end()); + } else { + result.push_back(value); + } + } + } + + // If a setting was negated, or if a setting was forced, set + // done to true to ignore any later lower priority settings. + done |= span.negated() > 0 || source == Source::FORCED; + + // Update the negated and empty state used for the zombie values check. + prev_negated_empty |= span.last_negated() && result.empty(); + }); + return result; +} + +bool OnlyHasDefaultSectionSetting(const Settings& settings, const std::string& section, const std::string& name) +{ + bool has_default_section_setting = false; + bool has_other_setting = false; + MergeSettings(settings, section, name, [&](SettingsSpan span, Source source) { + if (span.empty()) return; + else if (source == Source::CONFIG_FILE_DEFAULT_SECTION) has_default_section_setting = true; + else has_other_setting = true; + }); + // If a value is set in the default section and not explicitly overwritten by the + // user on the command line or in a different section, then we want to enable + // warnings about the value being ignored. + return has_default_section_setting && !has_other_setting; +} + +SettingsSpan::SettingsSpan(const std::vector& vec) noexcept : SettingsSpan(vec.data(), vec.size()) {} +const SettingsValue* SettingsSpan::begin() const { return data + negated(); } +const SettingsValue* SettingsSpan::end() const { return data + size; } +bool SettingsSpan::empty() const { return size == 0 || last_negated(); } +bool SettingsSpan::last_negated() const { return size > 0 && data[size - 1].isFalse(); } +size_t SettingsSpan::negated() const +{ + for (size_t i = size; i > 0; --i) { + if (data[i - 1].isFalse()) return i; // Return number of negated values (position of last false value) + } + return 0; +} + +} // namespace util diff --git a/src/common/settings.h b/src/common/settings.h new file mode 100644 index 0000000000..4cec85ea1e --- /dev/null +++ b/src/common/settings.h @@ -0,0 +1,115 @@ +// Copyright (c) 2019-2022 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#ifndef BITCOIN_COMMON_SETTINGS_H +#define BITCOIN_COMMON_SETTINGS_H + +#include + +#include +#include +#include +#include + +class UniValue; + +namespace util { + +//! Settings value type (string/integer/boolean/null variant). +//! +//! @note UniValue is used here for convenience and because it can be easily +//! serialized in a readable format. But any other variant type that can +//! be assigned strings, int64_t, and bool values and has get_str(), +//! getInt(), get_bool(), isNum(), isBool(), isFalse(), isTrue() and +//! isNull() methods can be substituted if there's a need to move away +//! from UniValue. (An implementation with boost::variant was posted at +//! https://github.com/bitcoin/bitcoin/pull/15934/files#r337691812) +using SettingsValue = UniValue; + +//! Stored settings. This struct combines settings from the command line, a +//! read-only configuration file, and a read-write runtime settings file. +struct Settings { + //! Map of setting name to forced setting value. + std::map forced_settings; + //! Map of setting name to list of command line values. + std::map> command_line_options; + //! Map of setting name to read-write file setting value. + std::map rw_settings; + //! Map of config section name and setting name to list of config file values. + std::map>> ro_config; +}; + +//! Read settings file. +bool ReadSettings(const fs::path& path, + std::map& values, + std::vector& errors); + +//! Write settings file. +bool WriteSettings(const fs::path& path, + const std::map& values, + std::vector& errors); + +//! Get settings value from combined sources: forced settings, command line +//! arguments, runtime read-write settings, and the read-only config file. +//! +//! @param ignore_default_section_config - ignore values in the default section +//! of the config file (part before any +//! [section] keywords) +//! @param ignore_nonpersistent - ignore non-persistent settings values (forced +//! settings values and values specified on the +//! command line). Only return settings in the +//! read-only config and read-write settings +//! files. +//! @param get_chain_type - enable special backwards compatible behavior +//! for GetChainType +SettingsValue GetSetting(const Settings& settings, + const std::string& section, + const std::string& name, + bool ignore_default_section_config, + bool ignore_nonpersistent, + bool get_chain_type); + +//! Get combined setting value similar to GetSetting(), except if setting was +//! specified multiple times, return a list of all the values specified. +std::vector GetSettingsList(const Settings& settings, + const std::string& section, + const std::string& name, + bool ignore_default_section_config); + +//! Return true if a setting is set in the default config file section, and not +//! overridden by a higher priority command-line or network section value. +//! +//! This is used to provide user warnings about values that might be getting +//! ignored unintentionally. +bool OnlyHasDefaultSectionSetting(const Settings& settings, const std::string& section, const std::string& name); + +//! Accessor for list of settings that skips negated values when iterated over. +//! The last boolean `false` value in the list and all earlier values are +//! considered negated. +struct SettingsSpan { + explicit SettingsSpan() = default; + explicit SettingsSpan(const SettingsValue& value) noexcept : SettingsSpan(&value, 1) {} + explicit SettingsSpan(const SettingsValue* data, size_t size) noexcept : data(data), size(size) {} + explicit SettingsSpan(const std::vector& vec) noexcept; + const SettingsValue* begin() const; //!< Pointer to first non-negated value. + const SettingsValue* end() const; //!< Pointer to end of values. + bool empty() const; //!< True if there are any non-negated values. + bool last_negated() const; //!< True if the last value is negated. + size_t negated() const; //!< Number of negated values. + + const SettingsValue* data = nullptr; + size_t size = 0; +}; + +//! Map lookup helper. +template +auto FindKey(Map&& map, Key&& key) -> decltype(&map.at(key)) +{ + auto it = map.find(key); + return it == map.end() ? nullptr : &it->second; +} + +} // namespace util + +#endif // BITCOIN_COMMON_SETTINGS_H diff --git a/src/interfaces/chain.h b/src/interfaces/chain.h index 40bf0b680c..81b444fd33 100644 --- a/src/interfaces/chain.h +++ b/src/interfaces/chain.h @@ -6,8 +6,8 @@ #define BITCOIN_INTERFACES_CHAIN_H #include +#include #include // For CTransactionRef -#include // For util::SettingsValue #include #include diff --git a/src/interfaces/node.h b/src/interfaces/node.h index 7e87d5a523..432fa24ee7 100644 --- a/src/interfaces/node.h +++ b/src/interfaces/node.h @@ -5,13 +5,13 @@ #ifndef BITCOIN_INTERFACES_NODE_H #define BITCOIN_INTERFACES_NODE_H +#include #include // For CAmount #include // For NodeId #include // For banmap_t #include // For Network #include // For ConnectionDirection #include // For SecureString -#include // For util::SettingsValue #include #include diff --git a/src/qt/test/optiontests.h b/src/qt/test/optiontests.h index 0c458c97a6..f8c0f75c34 100644 --- a/src/qt/test/optiontests.h +++ b/src/qt/test/optiontests.h @@ -5,9 +5,9 @@ #ifndef BITCOIN_QT_TEST_OPTIONTESTS_H #define BITCOIN_QT_TEST_OPTIONTESTS_H +#include #include #include -#include #include diff --git a/src/test/fuzz/string.cpp b/src/test/fuzz/string.cpp index 75c78ce1bd..52cf546e10 100644 --- a/src/test/fuzz/string.cpp +++ b/src/test/fuzz/string.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -22,7 +23,6 @@ #include #include #include -#include #include #include #include diff --git a/src/test/getarg_tests.cpp b/src/test/getarg_tests.cpp index 715b6885f5..775d12508a 100644 --- a/src/test/getarg_tests.cpp +++ b/src/test/getarg_tests.cpp @@ -3,10 +3,10 @@ // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include +#include #include #include #include -#include #include #include diff --git a/src/test/settings_tests.cpp b/src/test/settings_tests.cpp index fff84d24f0..2b5f103fc6 100644 --- a/src/test/settings_tests.cpp +++ b/src/test/settings_tests.cpp @@ -2,7 +2,7 @@ // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. -#include +#include #include #include diff --git a/src/util/settings.cpp b/src/util/settings.cpp deleted file mode 100644 index db3d60046e..0000000000 --- a/src/util/settings.cpp +++ /dev/null @@ -1,258 +0,0 @@ -// Copyright (c) 2019-2022 The Bitcoin Core developers -// Distributed under the MIT software license, see the accompanying -// file COPYING or http://www.opensource.org/licenses/mit-license.php. - -#include -#include - -#include -#include - -#include -#include -#include -#include - -namespace util { -namespace { - -enum class Source { - FORCED, - COMMAND_LINE, - RW_SETTINGS, - CONFIG_FILE_NETWORK_SECTION, - CONFIG_FILE_DEFAULT_SECTION -}; - -//! Merge settings from multiple sources in precedence order: -//! Forced config > command line > read-write settings file > config file network-specific section > config file default section -//! -//! This function is provided with a callback function fn that contains -//! specific logic for how to merge the sources. -template -static void MergeSettings(const Settings& settings, const std::string& section, const std::string& name, Fn&& fn) -{ - // Merge in the forced settings - if (auto* value = FindKey(settings.forced_settings, name)) { - fn(SettingsSpan(*value), Source::FORCED); - } - // Merge in the command-line options - if (auto* values = FindKey(settings.command_line_options, name)) { - fn(SettingsSpan(*values), Source::COMMAND_LINE); - } - // Merge in the read-write settings - if (const SettingsValue* value = FindKey(settings.rw_settings, name)) { - fn(SettingsSpan(*value), Source::RW_SETTINGS); - } - // Merge in the network-specific section of the config file - if (!section.empty()) { - if (auto* map = FindKey(settings.ro_config, section)) { - if (auto* values = FindKey(*map, name)) { - fn(SettingsSpan(*values), Source::CONFIG_FILE_NETWORK_SECTION); - } - } - } - // Merge in the default section of the config file - if (auto* map = FindKey(settings.ro_config, "")) { - if (auto* values = FindKey(*map, name)) { - fn(SettingsSpan(*values), Source::CONFIG_FILE_DEFAULT_SECTION); - } - } -} -} // namespace - -bool ReadSettings(const fs::path& path, std::map& values, std::vector& errors) -{ - values.clear(); - errors.clear(); - - // Ok for file to not exist - if (!fs::exists(path)) return true; - - std::ifstream file; - file.open(path); - if (!file.is_open()) { - errors.emplace_back(strprintf("%s. Please check permissions.", fs::PathToString(path))); - return false; - } - - SettingsValue in; - if (!in.read(std::string{std::istreambuf_iterator(file), std::istreambuf_iterator()})) { - errors.emplace_back(strprintf("Unable to parse settings file %s", fs::PathToString(path))); - return false; - } - - if (file.fail()) { - errors.emplace_back(strprintf("Failed reading settings file %s", fs::PathToString(path))); - return false; - } - file.close(); // Done with file descriptor. Release while copying data. - - if (!in.isObject()) { - errors.emplace_back(strprintf("Found non-object value %s in settings file %s", in.write(), fs::PathToString(path))); - return false; - } - - const std::vector& in_keys = in.getKeys(); - const std::vector& in_values = in.getValues(); - for (size_t i = 0; i < in_keys.size(); ++i) { - auto inserted = values.emplace(in_keys[i], in_values[i]); - if (!inserted.second) { - errors.emplace_back(strprintf("Found duplicate key %s in settings file %s", in_keys[i], fs::PathToString(path))); - values.clear(); - break; - } - } - return errors.empty(); -} - -bool WriteSettings(const fs::path& path, - const std::map& values, - std::vector& errors) -{ - SettingsValue out(SettingsValue::VOBJ); - for (const auto& value : values) { - out.__pushKV(value.first, value.second); - } - std::ofstream file; - file.open(path); - if (file.fail()) { - errors.emplace_back(strprintf("Error: Unable to open settings file %s for writing", fs::PathToString(path))); - return false; - } - file << out.write(/* prettyIndent= */ 4, /* indentLevel= */ 1) << std::endl; - file.close(); - return true; -} - -SettingsValue GetSetting(const Settings& settings, - const std::string& section, - const std::string& name, - bool ignore_default_section_config, - bool ignore_nonpersistent, - bool get_chain_type) -{ - SettingsValue result; - bool done = false; // Done merging any more settings sources. - MergeSettings(settings, section, name, [&](SettingsSpan span, Source source) { - // Weird behavior preserved for backwards compatibility: Apply negated - // setting even if non-negated setting would be ignored. A negated - // value in the default section is applied to network specific options, - // even though normal non-negated values there would be ignored. - const bool never_ignore_negated_setting = span.last_negated(); - - // Weird behavior preserved for backwards compatibility: Take first - // assigned value instead of last. In general, later settings take - // precedence over early settings, but for backwards compatibility in - // the config file the precedence is reversed for all settings except - // chain type settings. - const bool reverse_precedence = - (source == Source::CONFIG_FILE_NETWORK_SECTION || source == Source::CONFIG_FILE_DEFAULT_SECTION) && - !get_chain_type; - - // Weird behavior preserved for backwards compatibility: Negated - // -regtest and -testnet arguments which you would expect to override - // values set in the configuration file are currently accepted but - // silently ignored. It would be better to apply these just like other - // negated values, or at least warn they are ignored. - const bool skip_negated_command_line = get_chain_type; - - if (done) return; - - // Ignore settings in default config section if requested. - if (ignore_default_section_config && source == Source::CONFIG_FILE_DEFAULT_SECTION && - !never_ignore_negated_setting) { - return; - } - - // Ignore nonpersistent settings if requested. - if (ignore_nonpersistent && (source == Source::COMMAND_LINE || source == Source::FORCED)) return; - - // Skip negated command line settings. - if (skip_negated_command_line && span.last_negated()) return; - - if (!span.empty()) { - result = reverse_precedence ? span.begin()[0] : span.end()[-1]; - done = true; - } else if (span.last_negated()) { - result = false; - done = true; - } - }); - return result; -} - -std::vector GetSettingsList(const Settings& settings, - const std::string& section, - const std::string& name, - bool ignore_default_section_config) -{ - std::vector result; - bool done = false; // Done merging any more settings sources. - bool prev_negated_empty = false; - MergeSettings(settings, section, name, [&](SettingsSpan span, Source source) { - // Weird behavior preserved for backwards compatibility: Apply config - // file settings even if negated on command line. Negating a setting on - // command line will ignore earlier settings on the command line and - // ignore settings in the config file, unless the negated command line - // value is followed by non-negated value, in which case config file - // settings will be brought back from the dead (but earlier command - // line settings will still be ignored). - const bool add_zombie_config_values = - (source == Source::CONFIG_FILE_NETWORK_SECTION || source == Source::CONFIG_FILE_DEFAULT_SECTION) && - !prev_negated_empty; - - // Ignore settings in default config section if requested. - if (ignore_default_section_config && source == Source::CONFIG_FILE_DEFAULT_SECTION) return; - - // Add new settings to the result if isn't already complete, or if the - // values are zombies. - if (!done || add_zombie_config_values) { - for (const auto& value : span) { - if (value.isArray()) { - result.insert(result.end(), value.getValues().begin(), value.getValues().end()); - } else { - result.push_back(value); - } - } - } - - // If a setting was negated, or if a setting was forced, set - // done to true to ignore any later lower priority settings. - done |= span.negated() > 0 || source == Source::FORCED; - - // Update the negated and empty state used for the zombie values check. - prev_negated_empty |= span.last_negated() && result.empty(); - }); - return result; -} - -bool OnlyHasDefaultSectionSetting(const Settings& settings, const std::string& section, const std::string& name) -{ - bool has_default_section_setting = false; - bool has_other_setting = false; - MergeSettings(settings, section, name, [&](SettingsSpan span, Source source) { - if (span.empty()) return; - else if (source == Source::CONFIG_FILE_DEFAULT_SECTION) has_default_section_setting = true; - else has_other_setting = true; - }); - // If a value is set in the default section and not explicitly overwritten by the - // user on the command line or in a different section, then we want to enable - // warnings about the value being ignored. - return has_default_section_setting && !has_other_setting; -} - -SettingsSpan::SettingsSpan(const std::vector& vec) noexcept : SettingsSpan(vec.data(), vec.size()) {} -const SettingsValue* SettingsSpan::begin() const { return data + negated(); } -const SettingsValue* SettingsSpan::end() const { return data + size; } -bool SettingsSpan::empty() const { return size == 0 || last_negated(); } -bool SettingsSpan::last_negated() const { return size > 0 && data[size - 1].isFalse(); } -size_t SettingsSpan::negated() const -{ - for (size_t i = size; i > 0; --i) { - if (data[i - 1].isFalse()) return i; // Return number of negated values (position of last false value) - } - return 0; -} - -} // namespace util diff --git a/src/util/settings.h b/src/util/settings.h deleted file mode 100644 index bb1fe585e1..0000000000 --- a/src/util/settings.h +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright (c) 2019-2022 The Bitcoin Core developers -// Distributed under the MIT software license, see the accompanying -// file COPYING or http://www.opensource.org/licenses/mit-license.php. - -#ifndef BITCOIN_UTIL_SETTINGS_H -#define BITCOIN_UTIL_SETTINGS_H - -#include - -#include -#include -#include - -class UniValue; - -namespace util { - -//! Settings value type (string/integer/boolean/null variant). -//! -//! @note UniValue is used here for convenience and because it can be easily -//! serialized in a readable format. But any other variant type that can -//! be assigned strings, int64_t, and bool values and has get_str(), -//! getInt(), get_bool(), isNum(), isBool(), isFalse(), isTrue() and -//! isNull() methods can be substituted if there's a need to move away -//! from UniValue. (An implementation with boost::variant was posted at -//! https://github.com/bitcoin/bitcoin/pull/15934/files#r337691812) -using SettingsValue = UniValue; - -//! Stored settings. This struct combines settings from the command line, a -//! read-only configuration file, and a read-write runtime settings file. -struct Settings { - //! Map of setting name to forced setting value. - std::map forced_settings; - //! Map of setting name to list of command line values. - std::map> command_line_options; - //! Map of setting name to read-write file setting value. - std::map rw_settings; - //! Map of config section name and setting name to list of config file values. - std::map>> ro_config; -}; - -//! Read settings file. -bool ReadSettings(const fs::path& path, - std::map& values, - std::vector& errors); - -//! Write settings file. -bool WriteSettings(const fs::path& path, - const std::map& values, - std::vector& errors); - -//! Get settings value from combined sources: forced settings, command line -//! arguments, runtime read-write settings, and the read-only config file. -//! -//! @param ignore_default_section_config - ignore values in the default section -//! of the config file (part before any -//! [section] keywords) -//! @param ignore_nonpersistent - ignore non-persistent settings values (forced -//! settings values and values specified on the -//! command line). Only return settings in the -//! read-only config and read-write settings -//! files. -//! @param get_chain_type - enable special backwards compatible behavior -//! for GetChainType -SettingsValue GetSetting(const Settings& settings, - const std::string& section, - const std::string& name, - bool ignore_default_section_config, - bool ignore_nonpersistent, - bool get_chain_type); - -//! Get combined setting value similar to GetSetting(), except if setting was -//! specified multiple times, return a list of all the values specified. -std::vector GetSettingsList(const Settings& settings, - const std::string& section, - const std::string& name, - bool ignore_default_section_config); - -//! Return true if a setting is set in the default config file section, and not -//! overridden by a higher priority command-line or network section value. -//! -//! This is used to provide user warnings about values that might be getting -//! ignored unintentionally. -bool OnlyHasDefaultSectionSetting(const Settings& settings, const std::string& section, const std::string& name); - -//! Accessor for list of settings that skips negated values when iterated over. -//! The last boolean `false` value in the list and all earlier values are -//! considered negated. -struct SettingsSpan { - explicit SettingsSpan() = default; - explicit SettingsSpan(const SettingsValue& value) noexcept : SettingsSpan(&value, 1) {} - explicit SettingsSpan(const SettingsValue* data, size_t size) noexcept : data(data), size(size) {} - explicit SettingsSpan(const std::vector& vec) noexcept; - const SettingsValue* begin() const; //!< Pointer to first non-negated value. - const SettingsValue* end() const; //!< Pointer to end of values. - bool empty() const; //!< True if there are any non-negated values. - bool last_negated() const; //!< True if the last value is negated. - size_t negated() const; //!< Number of negated values. - - const SettingsValue* data = nullptr; - size_t size = 0; -}; - -//! Map lookup helper. -template -auto FindKey(Map&& map, Key&& key) -> decltype(&map.at(key)) -{ - auto it = map.find(key); - return it == map.end() ? nullptr : &it->second; -} - -} // namespace util - -#endif // BITCOIN_UTIL_SETTINGS_H -- cgit v1.2.3 From db77f87c6365cb5f414036d6bfb1a12705772028 Mon Sep 17 00:00:00 2001 From: TheCharlatan Date: Wed, 24 May 2023 16:18:59 +0200 Subject: scripted-diff: move settings to common namespace -BEGIN VERIFY SCRIPT- sed -i 's/namespace\ util/namespace\ common/g' src/common/settings.cpp src/common/settings.h sed -i 's/util\:\:GetSetting/common\:\:GetSetting/g' $( git grep -l 'util\:\:GetSetting') sed -i 's/util\:\:Setting/common\:\:Setting/g' $( git grep -l 'util\:\:Setting') sed -i 's/util\:\:FindKey/common\:\:FindKey/g' $( git grep -l 'util\:\:FindKey') sed -i 's/util\:\:ReadSettings/common\:\:ReadSettings/g' $( git grep -l 'util\:\:ReadSettings') sed -i 's/util\:\:WriteSettings/common\:\:WriteSettings/g' $( git grep -l 'util\:\:WriteSettings') -END VERIFY SCRIPT- --- src/addrdb.cpp | 6 +++--- src/common/args.cpp | 48 ++++++++++++++++++++++----------------------- src/common/args.h | 24 +++++++++++------------ src/common/config.cpp | 12 ++++++------ src/common/settings.cpp | 4 ++-- src/common/settings.h | 4 ++-- src/interfaces/chain.h | 8 ++++---- src/interfaces/node.h | 6 +++--- src/node/interfaces.cpp | 32 +++++++++++++++--------------- src/qt/optionsmodel.cpp | 16 +++++++-------- src/qt/test/optiontests.cpp | 10 +++++----- src/qt/test/optiontests.h | 2 +- src/test/argsman_tests.cpp | 8 ++++---- src/test/fuzz/string.cpp | 2 +- src/test/getarg_tests.cpp | 4 ++-- src/test/settings_tests.cpp | 38 +++++++++++++++++------------------ src/wallet/load.cpp | 2 +- src/wallet/wallet.cpp | 14 ++++++------- 18 files changed, 120 insertions(+), 120 deletions(-) (limited to 'src') diff --git a/src/addrdb.cpp b/src/addrdb.cpp index e86fc231a5..cb1c49050e 100644 --- a/src/addrdb.cpp +++ b/src/addrdb.cpp @@ -132,7 +132,7 @@ CBanDB::CBanDB(fs::path ban_list_path) bool CBanDB::Write(const banmap_t& banSet) { std::vector errors; - if (util::WriteSettings(m_banlist_json, {{JSON_KEY, BanMapToJson(banSet)}}, errors)) { + if (common::WriteSettings(m_banlist_json, {{JSON_KEY, BanMapToJson(banSet)}}, errors)) { return true; } @@ -152,10 +152,10 @@ bool CBanDB::Read(banmap_t& banSet) return false; } - std::map settings; + std::map settings; std::vector errors; - if (!util::ReadSettings(m_banlist_json, settings, errors)) { + if (!common::ReadSettings(m_banlist_json, settings, errors)) { for (const auto& err : errors) { LogPrintf("Cannot load banlist %s: %s\n", fs::PathToString(m_banlist_json), err); } diff --git a/src/common/args.cpp b/src/common/args.cpp index 289410ecbe..643838399f 100644 --- a/src/common/args.cpp +++ b/src/common/args.cpp @@ -104,7 +104,7 @@ KeyInfo InterpretKey(std::string key) * @return parsed settings value if it is valid, otherwise nullopt accompanied * by a descriptive error string */ -std::optional InterpretValue(const KeyInfo& key, const std::string* value, +std::optional InterpretValue(const KeyInfo& key, const std::string* value, unsigned int flags, std::string& error) { // Return negated settings as false values. @@ -238,15 +238,15 @@ bool ArgsManager::ParseParameters(int argc, const char* const argv[], std::strin return false; } - std::optional value = InterpretValue(keyinfo, val ? &*val : nullptr, *flags, error); + std::optional value = InterpretValue(keyinfo, val ? &*val : nullptr, *flags, error); if (!value) return false; m_settings.command_line_options[keyinfo.name].push_back(*value); } // we do not allow -includeconf from command line, only -noincludeconf - if (auto* includes = util::FindKey(m_settings.command_line_options, "includeconf")) { - const util::SettingsSpan values{*includes}; + if (auto* includes = common::FindKey(m_settings.command_line_options, "includeconf")) { + const common::SettingsSpan values{*includes}; // Range may be empty if -noincludeconf was passed if (!values.empty()) { error = "-includeconf cannot be used from commandline; -includeconf=" + values.begin()->write(); @@ -361,7 +361,7 @@ std::optional ArgsManager::GetCommand() const std::vector ArgsManager::GetArgs(const std::string& strArg) const { std::vector result; - for (const util::SettingsValue& value : GetSettingsList(strArg)) { + for (const common::SettingsValue& value : GetSettingsList(strArg)) { result.push_back(value.isFalse() ? "0" : value.isTrue() ? "1" : value.get_str()); } return result; @@ -408,7 +408,7 @@ bool ArgsManager::ReadSettingsFile(std::vector* errors) LOCK(cs_args); m_settings.rw_settings.clear(); std::vector read_errors; - if (!util::ReadSettings(path, m_settings.rw_settings, read_errors)) { + if (!common::ReadSettings(path, m_settings.rw_settings, read_errors)) { SaveErrors(read_errors, errors); return false; } @@ -430,7 +430,7 @@ bool ArgsManager::WriteSettingsFile(std::vector* errors, bool backu LOCK(cs_args); std::vector write_errors; - if (!util::WriteSettings(path_tmp, m_settings.rw_settings, write_errors)) { + if (!common::WriteSettings(path_tmp, m_settings.rw_settings, write_errors)) { SaveErrors(write_errors, errors); return false; } @@ -441,10 +441,10 @@ bool ArgsManager::WriteSettingsFile(std::vector* errors, bool backu return true; } -util::SettingsValue ArgsManager::GetPersistentSetting(const std::string& name) const +common::SettingsValue ArgsManager::GetPersistentSetting(const std::string& name) const { LOCK(cs_args); - return util::GetSetting(m_settings, m_network, name, !UseDefaultSection("-" + name), + return common::GetSetting(m_settings, m_network, name, !UseDefaultSection("-" + name), /*ignore_nonpersistent=*/true, /*get_chain_type=*/false); } @@ -460,11 +460,11 @@ std::string ArgsManager::GetArg(const std::string& strArg, const std::string& st std::optional ArgsManager::GetArg(const std::string& strArg) const { - const util::SettingsValue value = GetSetting(strArg); + const common::SettingsValue value = GetSetting(strArg); return SettingToString(value); } -std::optional SettingToString(const util::SettingsValue& value) +std::optional SettingToString(const common::SettingsValue& value) { if (value.isNull()) return std::nullopt; if (value.isFalse()) return "0"; @@ -473,7 +473,7 @@ std::optional SettingToString(const util::SettingsValue& value) return value.get_str(); } -std::string SettingToString(const util::SettingsValue& value, const std::string& strDefault) +std::string SettingToString(const common::SettingsValue& value, const std::string& strDefault) { return SettingToString(value).value_or(strDefault); } @@ -485,11 +485,11 @@ int64_t ArgsManager::GetIntArg(const std::string& strArg, int64_t nDefault) cons std::optional ArgsManager::GetIntArg(const std::string& strArg) const { - const util::SettingsValue value = GetSetting(strArg); + const common::SettingsValue value = GetSetting(strArg); return SettingToInt(value); } -std::optional SettingToInt(const util::SettingsValue& value) +std::optional SettingToInt(const common::SettingsValue& value) { if (value.isNull()) return std::nullopt; if (value.isFalse()) return 0; @@ -498,7 +498,7 @@ std::optional SettingToInt(const util::SettingsValue& value) return LocaleIndependentAtoi(value.get_str()); } -int64_t SettingToInt(const util::SettingsValue& value, int64_t nDefault) +int64_t SettingToInt(const common::SettingsValue& value, int64_t nDefault) { return SettingToInt(value).value_or(nDefault); } @@ -510,18 +510,18 @@ bool ArgsManager::GetBoolArg(const std::string& strArg, bool fDefault) const std::optional ArgsManager::GetBoolArg(const std::string& strArg) const { - const util::SettingsValue value = GetSetting(strArg); + const common::SettingsValue value = GetSetting(strArg); return SettingToBool(value); } -std::optional SettingToBool(const util::SettingsValue& value) +std::optional SettingToBool(const common::SettingsValue& value) { if (value.isNull()) return std::nullopt; if (value.isBool()) return value.get_bool(); return InterpretBool(value.get_str()); } -bool SettingToBool(const util::SettingsValue& value, bool fDefault) +bool SettingToBool(const common::SettingsValue& value, bool fDefault) { return SettingToBool(value).value_or(fDefault); } @@ -738,7 +738,7 @@ std::variant ArgsManager::GetChainArg() const { auto get_net = [&](const std::string& arg) { LOCK(cs_args); - util::SettingsValue value = util::GetSetting(m_settings, /* section= */ "", SettingName(arg), + common::SettingsValue value = common::GetSetting(m_settings, /* section= */ "", SettingName(arg), /* ignore_default_section_config= */ false, /*ignore_nonpersistent=*/false, /* get_chain_type= */ true); @@ -769,24 +769,24 @@ bool ArgsManager::UseDefaultSection(const std::string& arg) const return m_network == ChainTypeToString(ChainType::MAIN) || m_network_only_args.count(arg) == 0; } -util::SettingsValue ArgsManager::GetSetting(const std::string& arg) const +common::SettingsValue ArgsManager::GetSetting(const std::string& arg) const { LOCK(cs_args); - return util::GetSetting( + return common::GetSetting( m_settings, m_network, SettingName(arg), !UseDefaultSection(arg), /*ignore_nonpersistent=*/false, /*get_chain_type=*/false); } -std::vector ArgsManager::GetSettingsList(const std::string& arg) const +std::vector ArgsManager::GetSettingsList(const std::string& arg) const { LOCK(cs_args); - return util::GetSettingsList(m_settings, m_network, SettingName(arg), !UseDefaultSection(arg)); + return common::GetSettingsList(m_settings, m_network, SettingName(arg), !UseDefaultSection(arg)); } void ArgsManager::logArgsPrefix( const std::string& prefix, const std::string& section, - const std::map>& args) const + const std::map>& args) const { std::string section_str = section.empty() ? "" : "[" + section + "] "; for (const auto& arg : args) { diff --git a/src/common/args.h b/src/common/args.h index c4debb9c82..ae3ed02bc7 100644 --- a/src/common/args.h +++ b/src/common/args.h @@ -75,7 +75,7 @@ struct KeyInfo { KeyInfo InterpretKey(std::string key); -std::optional InterpretValue(const KeyInfo& key, const std::string* value, +std::optional InterpretValue(const KeyInfo& key, const std::string* value, unsigned int flags, std::string& error); struct SectionInfo { @@ -84,14 +84,14 @@ struct SectionInfo { int m_line; }; -std::string SettingToString(const util::SettingsValue&, const std::string&); -std::optional SettingToString(const util::SettingsValue&); +std::string SettingToString(const common::SettingsValue&, const std::string&); +std::optional SettingToString(const common::SettingsValue&); -int64_t SettingToInt(const util::SettingsValue&, int64_t); -std::optional SettingToInt(const util::SettingsValue&); +int64_t SettingToInt(const common::SettingsValue&, int64_t); +std::optional SettingToInt(const common::SettingsValue&); -bool SettingToBool(const util::SettingsValue&, bool); -std::optional SettingToBool(const util::SettingsValue&); +bool SettingToBool(const common::SettingsValue&, bool); +std::optional SettingToBool(const common::SettingsValue&); class ArgsManager { @@ -130,7 +130,7 @@ protected: }; mutable RecursiveMutex cs_args; - util::Settings m_settings GUARDED_BY(cs_args); + common::Settings m_settings GUARDED_BY(cs_args); std::vector m_command GUARDED_BY(cs_args); std::string m_network GUARDED_BY(cs_args); std::set m_network_only_args GUARDED_BY(cs_args); @@ -159,12 +159,12 @@ protected: * false if "-nosetting" argument was passed, and a string if a "-setting=value" * argument was passed. */ - util::SettingsValue GetSetting(const std::string& arg) const; + common::SettingsValue GetSetting(const std::string& arg) const; /** * Get list of setting values. */ - std::vector GetSettingsList(const std::string& arg) const; + std::vector GetSettingsList(const std::string& arg) const; ArgsManager(); ~ArgsManager(); @@ -394,7 +394,7 @@ protected: * Get current setting from config file or read/write settings file, * ignoring nonpersistent command line or forced settings values. */ - util::SettingsValue GetPersistentSetting(const std::string& name) const; + common::SettingsValue GetPersistentSetting(const std::string& name) const; /** * Access settings with lock held. @@ -433,7 +433,7 @@ private: void logArgsPrefix( const std::string& prefix, const std::string& section, - const std::map>& args) const; + const std::map>& args) const; }; extern ArgsManager gArgs; diff --git a/src/common/config.cpp b/src/common/config.cpp index d156f8e514..1c85273f69 100644 --- a/src/common/config.cpp +++ b/src/common/config.cpp @@ -98,7 +98,7 @@ bool ArgsManager::ReadConfigStream(std::istream& stream, const std::string& file std::optional flags = GetArgFlags('-' + key.name); if (!IsConfSupported(key, error)) return false; if (flags) { - std::optional value = InterpretValue(key, &option.second, *flags, error); + std::optional value = InterpretValue(key, &option.second, *flags, error); if (!value) { return false; } @@ -142,9 +142,9 @@ bool ArgsManager::ReadConfigFiles(std::string& error, bool ignore_invalid_keys) bool use_conf_file{true}; { LOCK(cs_args); - if (auto* includes = util::FindKey(m_settings.command_line_options, "includeconf")) { + if (auto* includes = common::FindKey(m_settings.command_line_options, "includeconf")) { // ParseParameters() fails if a non-negated -includeconf is passed on the command-line - assert(util::SettingsSpan(*includes).last_negated()); + assert(common::SettingsSpan(*includes).last_negated()); use_conf_file = false; } } @@ -155,9 +155,9 @@ bool ArgsManager::ReadConfigFiles(std::string& error, bool ignore_invalid_keys) auto add_includes = [&](const std::string& network, size_t skip = 0) { size_t num_values = 0; LOCK(cs_args); - if (auto* section = util::FindKey(m_settings.ro_config, network)) { - if (auto* values = util::FindKey(*section, "includeconf")) { - for (size_t i = std::max(skip, util::SettingsSpan(*values).negated()); i < values->size(); ++i) { + if (auto* section = common::FindKey(m_settings.ro_config, network)) { + if (auto* values = common::FindKey(*section, "includeconf")) { + for (size_t i = std::max(skip, common::SettingsSpan(*values).negated()); i < values->size(); ++i) { conf_file_names.push_back((*values)[i].get_str()); } num_values = values->size(); diff --git a/src/common/settings.cpp b/src/common/settings.cpp index 7d08355b33..9187f242eb 100644 --- a/src/common/settings.cpp +++ b/src/common/settings.cpp @@ -16,7 +16,7 @@ #include #include -namespace util { +namespace common { namespace { enum class Source { @@ -258,4 +258,4 @@ size_t SettingsSpan::negated() const return 0; } -} // namespace util +} // namespace common diff --git a/src/common/settings.h b/src/common/settings.h index 4cec85ea1e..0e9d376e23 100644 --- a/src/common/settings.h +++ b/src/common/settings.h @@ -14,7 +14,7 @@ class UniValue; -namespace util { +namespace common { //! Settings value type (string/integer/boolean/null variant). //! @@ -110,6 +110,6 @@ auto FindKey(Map&& map, Key&& key) -> decltype(&map.at(key)) return it == map.end() ? nullptr : &it->second; } -} // namespace util +} // namespace common #endif // BITCOIN_COMMON_SETTINGS_H diff --git a/src/interfaces/chain.h b/src/interfaces/chain.h index 81b444fd33..dd664165d3 100644 --- a/src/interfaces/chain.h +++ b/src/interfaces/chain.h @@ -300,17 +300,17 @@ public: virtual int rpcSerializationFlags() = 0; //! Get settings value. - virtual util::SettingsValue getSetting(const std::string& arg) = 0; + virtual common::SettingsValue getSetting(const std::string& arg) = 0; //! Get list of settings values. - virtual std::vector getSettingsList(const std::string& arg) = 0; + virtual std::vector getSettingsList(const std::string& arg) = 0; //! Return /settings.json setting value. - virtual util::SettingsValue getRwSetting(const std::string& name) = 0; + virtual common::SettingsValue getRwSetting(const std::string& name) = 0; //! Write a setting to /settings.json. Optionally just update the //! setting in memory and do not write the file. - virtual bool updateRwSetting(const std::string& name, const util::SettingsValue& value, bool write=true) = 0; + virtual bool updateRwSetting(const std::string& name, const common::SettingsValue& value, bool write=true) = 0; //! Synchronously send transactionAddedToMempool notifications about all //! current mempool transactions to the specified handler and return after diff --git a/src/interfaces/node.h b/src/interfaces/node.h index 432fa24ee7..479c585b88 100644 --- a/src/interfaces/node.h +++ b/src/interfaces/node.h @@ -103,14 +103,14 @@ public: virtual bool isSettingIgnored(const std::string& name) = 0; //! Return setting value from /settings.json or bitcoin.conf. - virtual util::SettingsValue getPersistentSetting(const std::string& name) = 0; + virtual common::SettingsValue getPersistentSetting(const std::string& name) = 0; //! Update a setting in /settings.json. - virtual void updateRwSetting(const std::string& name, const util::SettingsValue& value) = 0; + virtual void updateRwSetting(const std::string& name, const common::SettingsValue& value) = 0; //! Force a setting value to be applied, overriding any other configuration //! source, but not being persisted. - virtual void forceSetting(const std::string& name, const util::SettingsValue& value) = 0; + virtual void forceSetting(const std::string& name, const common::SettingsValue& value) = 0; //! Clear all settings in /settings.json and store a backup of //! previous settings in /settings.json.bak. diff --git a/src/node/interfaces.cpp b/src/node/interfaces.cpp index 6e39ccf34e..57c0d302fd 100644 --- a/src/node/interfaces.cpp +++ b/src/node/interfaces.cpp @@ -125,17 +125,17 @@ public: bool isSettingIgnored(const std::string& name) override { bool ignored = false; - args().LockSettings([&](util::Settings& settings) { - if (auto* options = util::FindKey(settings.command_line_options, name)) { + args().LockSettings([&](common::Settings& settings) { + if (auto* options = common::FindKey(settings.command_line_options, name)) { ignored = !options->empty(); } }); return ignored; } - util::SettingsValue getPersistentSetting(const std::string& name) override { return args().GetPersistentSetting(name); } - void updateRwSetting(const std::string& name, const util::SettingsValue& value) override + common::SettingsValue getPersistentSetting(const std::string& name) override { return args().GetPersistentSetting(name); } + void updateRwSetting(const std::string& name, const common::SettingsValue& value) override { - args().LockSettings([&](util::Settings& settings) { + args().LockSettings([&](common::Settings& settings) { if (value.isNull()) { settings.rw_settings.erase(name); } else { @@ -144,9 +144,9 @@ public: }); args().WriteSettingsFile(); } - void forceSetting(const std::string& name, const util::SettingsValue& value) override + void forceSetting(const std::string& name, const common::SettingsValue& value) override { - args().LockSettings([&](util::Settings& settings) { + args().LockSettings([&](common::Settings& settings) { if (value.isNull()) { settings.forced_settings.erase(name); } else { @@ -157,7 +157,7 @@ public: void resetSettings() override { args().WriteSettingsFile(/*errors=*/nullptr, /*backup=*/true); - args().LockSettings([&](util::Settings& settings) { + args().LockSettings([&](common::Settings& settings) { settings.rw_settings.clear(); }); args().WriteSettingsFile(); @@ -744,27 +744,27 @@ public: RPCRunLater(name, std::move(fn), seconds); } int rpcSerializationFlags() override { return RPCSerializationFlags(); } - util::SettingsValue getSetting(const std::string& name) override + common::SettingsValue getSetting(const std::string& name) override { return args().GetSetting(name); } - std::vector getSettingsList(const std::string& name) override + std::vector getSettingsList(const std::string& name) override { return args().GetSettingsList(name); } - util::SettingsValue getRwSetting(const std::string& name) override + common::SettingsValue getRwSetting(const std::string& name) override { - util::SettingsValue result; - args().LockSettings([&](const util::Settings& settings) { - if (const util::SettingsValue* value = util::FindKey(settings.rw_settings, name)) { + common::SettingsValue result; + args().LockSettings([&](const common::Settings& settings) { + if (const common::SettingsValue* value = common::FindKey(settings.rw_settings, name)) { result = *value; } }); return result; } - bool updateRwSetting(const std::string& name, const util::SettingsValue& value, bool write) override + bool updateRwSetting(const std::string& name, const common::SettingsValue& value, bool write) override { - args().LockSettings([&](util::Settings& settings) { + args().LockSettings([&](common::Settings& settings) { if (value.isNull()) { settings.rw_settings.erase(name); } else { diff --git a/src/qt/optionsmodel.cpp b/src/qt/optionsmodel.cpp index 87a7e703b8..c1563fe1e2 100644 --- a/src/qt/optionsmodel.cpp +++ b/src/qt/optionsmodel.cpp @@ -60,7 +60,7 @@ static const char* SettingName(OptionsModel::OptionID option) } /** Call node.updateRwSetting() with Bitcoin 22.x workaround. */ -static void UpdateRwSetting(interfaces::Node& node, OptionsModel::OptionID option, const std::string& suffix, const util::SettingsValue& value) +static void UpdateRwSetting(interfaces::Node& node, OptionsModel::OptionID option, const std::string& suffix, const common::SettingsValue& value) { if (value.isNum() && (option == OptionsModel::DatabaseCache || @@ -81,14 +81,14 @@ static void UpdateRwSetting(interfaces::Node& node, OptionsModel::OptionID optio } //! Convert enabled/size values to bitcoin -prune setting. -static util::SettingsValue PruneSetting(bool prune_enabled, int prune_size_gb) +static common::SettingsValue PruneSetting(bool prune_enabled, int prune_size_gb) { assert(!prune_enabled || prune_size_gb >= 1); // PruneSizeGB and ParsePruneSizeGB never return less return prune_enabled ? PruneGBtoMiB(prune_size_gb) : 0; } //! Get pruning enabled value to show in GUI from bitcoin -prune setting. -static bool PruneEnabled(const util::SettingsValue& prune_setting) +static bool PruneEnabled(const common::SettingsValue& prune_setting) { // -prune=1 setting is manual pruning mode, so disabled for purposes of the gui return SettingToInt(prune_setting, 0) > 1; @@ -96,7 +96,7 @@ static bool PruneEnabled(const util::SettingsValue& prune_setting) //! Get pruning size value to show in GUI from bitcoin -prune setting. If //! pruning is not enabled, just show default recommended pruning size (2GB). -static int PruneSizeGB(const util::SettingsValue& prune_setting) +static int PruneSizeGB(const common::SettingsValue& prune_setting) { int value = SettingToInt(prune_setting, 0); return value > 1 ? PruneMiBtoGB(value) : DEFAULT_PRUNE_TARGET_GB; @@ -311,8 +311,8 @@ static QString GetDefaultProxyAddress() void OptionsModel::SetPruneTargetGB(int prune_target_gb) { - const util::SettingsValue cur_value = node().getPersistentSetting("prune"); - const util::SettingsValue new_value = PruneSetting(prune_target_gb > 0, prune_target_gb); + const common::SettingsValue cur_value = node().getPersistentSetting("prune"); + const common::SettingsValue new_value = PruneSetting(prune_target_gb > 0, prune_target_gb); // Force setting to take effect. It is still safe to change the value at // this point because this function is only called after the intro screen is @@ -331,7 +331,7 @@ void OptionsModel::SetPruneTargetGB(int prune_target_gb) // Keep previous pruning size, if pruning was disabled. if (PruneEnabled(cur_value)) { - UpdateRwSetting(node(), Prune, "-prev", PruneEnabled(new_value) ? util::SettingsValue{} : cur_value); + UpdateRwSetting(node(), Prune, "-prev", PruneEnabled(new_value) ? common::SettingsValue{} : cur_value); } } @@ -457,7 +457,7 @@ QVariant OptionsModel::getOption(OptionID option, const std::string& suffix) con bool OptionsModel::setOption(OptionID option, const QVariant& value, const std::string& suffix) { auto changed = [&] { return value.isValid() && value != getOption(option, suffix); }; - auto update = [&](const util::SettingsValue& value) { return UpdateRwSetting(node(), option, suffix, value); }; + auto update = [&](const common::SettingsValue& value) { return UpdateRwSetting(node(), option, suffix, value); }; bool successful = true; /* set to false on parse error */ QSettings settings; diff --git a/src/qt/test/optiontests.cpp b/src/qt/test/optiontests.cpp index 0838e21678..e5a5179d87 100644 --- a/src/qt/test/optiontests.cpp +++ b/src/qt/test/optiontests.cpp @@ -18,13 +18,13 @@ OptionTests::OptionTests(interfaces::Node& node) : m_node(node) { - gArgs.LockSettings([&](util::Settings& s) { m_previous_settings = s; }); + gArgs.LockSettings([&](common::Settings& s) { m_previous_settings = s; }); } void OptionTests::init() { // reset args - gArgs.LockSettings([&](util::Settings& s) { s = m_previous_settings; }); + gArgs.LockSettings([&](common::Settings& s) { s = m_previous_settings; }); gArgs.ClearPathCache(); } @@ -76,14 +76,14 @@ void OptionTests::integerGetArgBug() // Test regression https://github.com/bitcoin/bitcoin/issues/24457. Ensure // that setting integer prune value doesn't cause an exception to be thrown // in the OptionsModel constructor - gArgs.LockSettings([&](util::Settings& settings) { + gArgs.LockSettings([&](common::Settings& settings) { settings.forced_settings.erase("prune"); settings.rw_settings["prune"] = 3814; }); gArgs.WriteSettingsFile(); bilingual_str error; QVERIFY(OptionsModel{m_node}.Init(error)); - gArgs.LockSettings([&](util::Settings& settings) { + gArgs.LockSettings([&](common::Settings& settings) { settings.rw_settings.erase("prune"); }); gArgs.WriteSettingsFile(); @@ -95,7 +95,7 @@ void OptionTests::parametersInteraction() // It was fixed via https://github.com/bitcoin-core/gui/pull/568. // With fListen=false in ~/.config/Bitcoin/Bitcoin-Qt.conf and all else left as default, // bitcoin-qt should set both -listen and -listenonion to false and start successfully. - gArgs.LockSettings([&](util::Settings& s) { + gArgs.LockSettings([&](common::Settings& s) { s.forced_settings.erase("listen"); s.forced_settings.erase("listenonion"); }); diff --git a/src/qt/test/optiontests.h b/src/qt/test/optiontests.h index f8c0f75c34..2d7b94933f 100644 --- a/src/qt/test/optiontests.h +++ b/src/qt/test/optiontests.h @@ -26,7 +26,7 @@ private Q_SLOTS: private: interfaces::Node& m_node; - util::Settings m_previous_settings; + common::Settings m_previous_settings; }; #endif // BITCOIN_QT_TEST_OPTIONTESTS_H diff --git a/src/test/argsman_tests.cpp b/src/test/argsman_tests.cpp index 48bffc4ac9..0b789e7f5c 100644 --- a/src/test/argsman_tests.cpp +++ b/src/test/argsman_tests.cpp @@ -85,7 +85,7 @@ class CheckValueTest : public TestChain100Setup { public: struct Expect { - util::SettingsValue setting; + common::SettingsValue setting; bool default_string = false; bool default_int = false; bool default_bool = false; @@ -95,7 +95,7 @@ public: std::optional> list_value; const char* error = nullptr; - explicit Expect(util::SettingsValue s) : setting(std::move(s)) {} + explicit Expect(common::SettingsValue s) : setting(std::move(s)) {} Expect& DefaultString() { default_string = true; return *this; } Expect& DefaultInt() { default_int = true; return *this; } Expect& DefaultBool() { default_bool = true; return *this; } @@ -1022,14 +1022,14 @@ BOOST_AUTO_TEST_CASE(util_ReadWriteSettings) // Test writing setting. TestArgsManager args1; args1.ForceSetArg("-datadir", fs::PathToString(m_path_root)); - args1.LockSettings([&](util::Settings& settings) { settings.rw_settings["name"] = "value"; }); + args1.LockSettings([&](common::Settings& settings) { settings.rw_settings["name"] = "value"; }); args1.WriteSettingsFile(); // Test reading setting. TestArgsManager args2; args2.ForceSetArg("-datadir", fs::PathToString(m_path_root)); args2.ReadSettingsFile(); - args2.LockSettings([&](util::Settings& settings) { BOOST_CHECK_EQUAL(settings.rw_settings["name"].get_str(), "value"); }); + args2.LockSettings([&](common::Settings& settings) { BOOST_CHECK_EQUAL(settings.rw_settings["name"].get_str(), "value"); }); // Test error logging, and remove previously written setting. { diff --git a/src/test/fuzz/string.cpp b/src/test/fuzz/string.cpp index 52cf546e10..76242c5738 100644 --- a/src/test/fuzz/string.cpp +++ b/src/test/fuzz/string.cpp @@ -63,7 +63,7 @@ FUZZ_TARGET(string) (void)IsDeprecatedRPCEnabled(random_string_1); (void)Join(random_string_vector, random_string_1); (void)JSONRPCError(fuzzed_data_provider.ConsumeIntegral(), random_string_1); - const util::Settings settings; + const common::Settings settings; (void)OnlyHasDefaultSectionSetting(settings, random_string_1, random_string_2); (void)ParseNetwork(random_string_1); try { diff --git a/src/test/getarg_tests.cpp b/src/test/getarg_tests.cpp index 775d12508a..c73b675388 100644 --- a/src/test/getarg_tests.cpp +++ b/src/test/getarg_tests.cpp @@ -57,8 +57,8 @@ BOOST_AUTO_TEST_CASE(setting_args) ArgsManager args; SetupArgs(args, {{"-foo", ArgsManager::ALLOW_ANY}}); - auto set_foo = [&](const util::SettingsValue& value) { - args.LockSettings([&](util::Settings& settings) { + auto set_foo = [&](const common::SettingsValue& value) { + args.LockSettings([&](common::Settings& settings) { settings.rw_settings["foo"] = value; }); }; diff --git a/src/test/settings_tests.cpp b/src/test/settings_tests.cpp index 2b5f103fc6..c24921bf9b 100644 --- a/src/test/settings_tests.cpp +++ b/src/test/settings_tests.cpp @@ -21,20 +21,20 @@ #include #include -inline bool operator==(const util::SettingsValue& a, const util::SettingsValue& b) +inline bool operator==(const common::SettingsValue& a, const common::SettingsValue& b) { return a.write() == b.write(); } -inline std::ostream& operator<<(std::ostream& os, const util::SettingsValue& value) +inline std::ostream& operator<<(std::ostream& os, const common::SettingsValue& value) { os << value.write(); return os; } -inline std::ostream& operator<<(std::ostream& os, const std::pair& kv) +inline std::ostream& operator<<(std::ostream& os, const std::pair& kv) { - util::SettingsValue out(util::SettingsValue::VOBJ); + common::SettingsValue out(common::SettingsValue::VOBJ); out.__pushKV(kv.first, kv.second); os << out.write(); return os; @@ -60,7 +60,7 @@ BOOST_AUTO_TEST_CASE(ReadWrite) "null": null })"); - std::map expected{ + std::map expected{ {"string", "string"}, {"num", 5}, {"bool", true}, @@ -68,15 +68,15 @@ BOOST_AUTO_TEST_CASE(ReadWrite) }; // Check file read. - std::map values; + std::map values; std::vector errors; - BOOST_CHECK(util::ReadSettings(path, values, errors)); + BOOST_CHECK(common::ReadSettings(path, values, errors)); BOOST_CHECK_EQUAL_COLLECTIONS(values.begin(), values.end(), expected.begin(), expected.end()); BOOST_CHECK(errors.empty()); // Check no errors if file doesn't exist. fs::remove(path); - BOOST_CHECK(util::ReadSettings(path, values, errors)); + BOOST_CHECK(common::ReadSettings(path, values, errors)); BOOST_CHECK(values.empty()); BOOST_CHECK(errors.empty()); @@ -85,29 +85,29 @@ BOOST_AUTO_TEST_CASE(ReadWrite) "dupe": "string", "dupe": "dupe" })"); - BOOST_CHECK(!util::ReadSettings(path, values, errors)); + BOOST_CHECK(!common::ReadSettings(path, values, errors)); std::vector dup_keys = {strprintf("Found duplicate key dupe in settings file %s", fs::PathToString(path))}; BOOST_CHECK_EQUAL_COLLECTIONS(errors.begin(), errors.end(), dup_keys.begin(), dup_keys.end()); BOOST_CHECK(values.empty()); // Check non-kv json files not allowed WriteText(path, R"("non-kv")"); - BOOST_CHECK(!util::ReadSettings(path, values, errors)); + BOOST_CHECK(!common::ReadSettings(path, values, errors)); std::vector non_kv = {strprintf("Found non-object value \"non-kv\" in settings file %s", fs::PathToString(path))}; BOOST_CHECK_EQUAL_COLLECTIONS(errors.begin(), errors.end(), non_kv.begin(), non_kv.end()); // Check invalid json not allowed WriteText(path, R"(invalid json)"); - BOOST_CHECK(!util::ReadSettings(path, values, errors)); + BOOST_CHECK(!common::ReadSettings(path, values, errors)); std::vector fail_parse = {strprintf("Unable to parse settings file %s", fs::PathToString(path))}; BOOST_CHECK_EQUAL_COLLECTIONS(errors.begin(), errors.end(), fail_parse.begin(), fail_parse.end()); } //! Check settings struct contents against expected json strings. -static void CheckValues(const util::Settings& settings, const std::string& single_val, const std::string& list_val) +static void CheckValues(const common::Settings& settings, const std::string& single_val, const std::string& list_val) { - util::SettingsValue single_value = GetSetting(settings, "section", "name", false, false, false); - util::SettingsValue list_value(util::SettingsValue::VARR); + common::SettingsValue single_value = GetSetting(settings, "section", "name", false, false, false); + common::SettingsValue list_value(common::SettingsValue::VARR); for (const auto& item : GetSettingsList(settings, "section", "name", false)) { list_value.push_back(item); } @@ -118,7 +118,7 @@ static void CheckValues(const util::Settings& settings, const std::string& singl // Simple settings merge test case. BOOST_AUTO_TEST_CASE(Simple) { - util::Settings settings; + common::Settings settings; settings.command_line_options["name"].push_back("val1"); settings.command_line_options["name"].push_back("val2"); settings.ro_config["section"]["name"].push_back(2); @@ -126,7 +126,7 @@ BOOST_AUTO_TEST_CASE(Simple) // The last given arg takes precedence when specified via commandline. CheckValues(settings, R"("val2")", R"(["val1","val2",2])"); - util::Settings settings2; + common::Settings settings2; settings2.ro_config["section"]["name"].push_back("val2"); settings2.ro_config["section"]["name"].push_back("val3"); @@ -140,7 +140,7 @@ BOOST_AUTO_TEST_CASE(Simple) // its default value. BOOST_AUTO_TEST_CASE(NullOverride) { - util::Settings settings; + common::Settings settings; settings.command_line_options["name"].push_back("value"); BOOST_CHECK_EQUAL(R"("value")", GetSetting(settings, "section", "name", false, false, false).write().c_str()); settings.forced_settings["name"] = {}; @@ -195,11 +195,11 @@ BOOST_FIXTURE_TEST_CASE(Merge, MergeTestingSetup) bool ignore_default_section_config) { std::string desc; int value_suffix = 0; - util::Settings settings; + common::Settings settings; const std::string& name = ignore_default_section_config ? "wallet" : "server"; auto push_values = [&](Action action, const char* value_prefix, const std::string& name_prefix, - std::vector& dest) { + std::vector& dest) { if (action == SET || action == SECTION_SET) { for (int i = 0; i < 2; ++i) { dest.push_back(value_prefix + ToString(++value_suffix)); diff --git a/src/wallet/load.cpp b/src/wallet/load.cpp index 2560dda87c..4cdfadbee2 100644 --- a/src/wallet/load.cpp +++ b/src/wallet/load.cpp @@ -62,7 +62,7 @@ bool VerifyWallets(WalletContext& context) options.require_existing = true; options.verify = false; if (MakeWalletDatabase("", options, status, error_string)) { - util::SettingsValue wallets(util::SettingsValue::VARR); + common::SettingsValue wallets(common::SettingsValue::VARR); wallets.push_back(""); // Default wallet name is "" // Pass write=false because no need to write file and probably // better not to. If unnamed wallet needs to be added next startup diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index 63ace5c47f..7517c1a9d2 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -56,9 +56,9 @@ namespace wallet { bool AddWalletSetting(interfaces::Chain& chain, const std::string& wallet_name) { - util::SettingsValue setting_value = chain.getRwSetting("wallet"); + common::SettingsValue setting_value = chain.getRwSetting("wallet"); if (!setting_value.isArray()) setting_value.setArray(); - for (const util::SettingsValue& value : setting_value.getValues()) { + for (const common::SettingsValue& value : setting_value.getValues()) { if (value.isStr() && value.get_str() == wallet_name) return true; } setting_value.push_back(wallet_name); @@ -67,10 +67,10 @@ bool AddWalletSetting(interfaces::Chain& chain, const std::string& wallet_name) bool RemoveWalletSetting(interfaces::Chain& chain, const std::string& wallet_name) { - util::SettingsValue setting_value = chain.getRwSetting("wallet"); + common::SettingsValue setting_value = chain.getRwSetting("wallet"); if (!setting_value.isArray()) return true; - util::SettingsValue new_value(util::SettingsValue::VARR); - for (const util::SettingsValue& value : setting_value.getValues()) { + common::SettingsValue new_value(common::SettingsValue::VARR); + for (const common::SettingsValue& value : setting_value.getValues()) { if (!value.isStr() || value.get_str() != wallet_name) new_value.push_back(value); } if (new_value.size() == setting_value.size()) return true; @@ -2832,7 +2832,7 @@ bool CWallet::SetAddressPreviouslySpent(WalletBatch& batch, const CTxDestination return false; if (!used) { - if (auto* data{util::FindKey(m_address_book, dest)}) data->previously_spent = false; + if (auto* data{common::FindKey(m_address_book, dest)}) data->previously_spent = false; return batch.WriteAddressPreviouslySpent(dest, false); } @@ -2852,7 +2852,7 @@ void CWallet::LoadAddressReceiveRequest(const CTxDestination& dest, const std::s bool CWallet::IsAddressPreviouslySpent(const CTxDestination& dest) const { - if (auto* data{util::FindKey(m_address_book, dest)}) return data->previously_spent; + if (auto* data{common::FindKey(m_address_book, dest)}) return data->previously_spent; return false; } -- cgit v1.2.3