Bitcoin Core 22.99.0
P2P Digital Currency
system.cpp
Go to the documentation of this file.
1// Copyright (c) 2009-2010 Satoshi Nakamoto
2// Copyright (c) 2009-2020 The Bitcoin Core developers
3// Distributed under the MIT software license, see the accompanying
4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6#include <util/system.h>
7
8#ifdef ENABLE_EXTERNAL_SIGNER
9#if defined(WIN32) && !defined(__kernel_entry)
10// A workaround for boost 1.71 incompatibility with mingw-w64 compiler.
11// For details see https://github.com/bitcoin/bitcoin/pull/22348.
12#define __kernel_entry
13#endif
14#include <boost/process.hpp>
15#endif // ENABLE_EXTERNAL_SIGNER
16
17#include <chainparamsbase.h>
18#include <sync.h>
19#include <util/check.h>
20#include <util/getuniquepath.h>
21#include <util/strencodings.h>
22#include <util/string.h>
23#include <util/translation.h>
24
25
26#if (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__))
27#include <pthread.h>
28#include <pthread_np.h>
29#endif
30
31#ifndef WIN32
32// for posix_fallocate, in configure.ac we check if it is present after this
33#ifdef __linux__
34
35#ifdef _POSIX_C_SOURCE
36#undef _POSIX_C_SOURCE
37#endif
38
39#define _POSIX_C_SOURCE 200112L
40
41#endif // __linux__
42
43#include <algorithm>
44#include <cassert>
45#include <fcntl.h>
46#include <sched.h>
47#include <sys/resource.h>
48#include <sys/stat.h>
49
50#else
51
52#ifdef _MSC_VER
53#pragma warning(disable:4786)
54#pragma warning(disable:4804)
55#pragma warning(disable:4805)
56#pragma warning(disable:4717)
57#endif
58
59#ifndef NOMINMAX
60#define NOMINMAX
61#endif
62#include <codecvt>
63
64#include <io.h> /* for _commit */
65#include <shellapi.h>
66#include <shlobj.h>
67#endif
68
69#ifdef HAVE_MALLOPT_ARENA_MAX
70#include <malloc.h>
71#endif
72
73#include <boost/algorithm/string/replace.hpp>
74#include <optional>
75#include <thread>
76#include <typeinfo>
77#include <univalue.h>
78
79// Application startup time (used for uptime calculation)
80const int64_t nStartupTime = GetTime();
81
82const char * const BITCOIN_CONF_FILENAME = "bitcoin.conf";
83const char * const BITCOIN_SETTINGS_FILENAME = "settings.json";
84
86
94static std::map<std::string, std::unique_ptr<fsbridge::FileLock>> dir_locks GUARDED_BY(cs_dir_locks);
95
96bool LockDirectory(const fs::path& directory, const std::string lockfile_name, bool probe_only)
97{
99 fs::path pathLockFile = directory / lockfile_name;
100
101 // If a lock for this directory already exists in the map, don't try to re-lock it
102 if (dir_locks.count(fs::PathToString(pathLockFile))) {
103 return true;
104 }
105
106 // Create empty lock file if it doesn't exist.
107 FILE* file = fsbridge::fopen(pathLockFile, "a");
108 if (file) fclose(file);
109 auto lock = std::make_unique<fsbridge::FileLock>(pathLockFile);
110 if (!lock->TryLock()) {
111 return error("Error while attempting to lock directory %s: %s", fs::PathToString(directory), lock->GetReason());
112 }
113 if (!probe_only) {
114 // Lock successful and we're not just probing, put it into the map
115 dir_locks.emplace(fs::PathToString(pathLockFile), std::move(lock));
116 }
117 return true;
118}
119
120void UnlockDirectory(const fs::path& directory, const std::string& lockfile_name)
121{
123 dir_locks.erase(fs::PathToString(directory / lockfile_name));
124}
125
127{
129 dir_locks.clear();
130}
131
132bool DirIsWritable(const fs::path& directory)
133{
134 fs::path tmpFile = GetUniquePath(directory);
135
136 FILE* file = fsbridge::fopen(tmpFile, "a");
137 if (!file) return false;
138
139 fclose(file);
140 remove(tmpFile);
141
142 return true;
143}
144
145bool CheckDiskSpace(const fs::path& dir, uint64_t additional_bytes)
146{
147 constexpr uint64_t min_disk_space = 52428800; // 50 MiB
148
149 uint64_t free_bytes_available = fs::space(dir).available;
150 return free_bytes_available >= min_disk_space + additional_bytes;
151}
152
153std::streampos GetFileSize(const char* path, std::streamsize max) {
154 std::ifstream file(path, std::ios::binary);
155 file.ignore(max);
156 return file.gcount();
157}
158
174static bool InterpretBool(const std::string& strValue)
175{
176 if (strValue.empty())
177 return true;
178 return (LocaleIndependentAtoi<int>(strValue) != 0);
179}
180
181static std::string SettingName(const std::string& arg)
182{
183 return arg.size() > 0 && arg[0] == '-' ? arg.substr(1) : arg;
184}
185
186struct KeyInfo {
187 std::string name;
188 std::string section;
189 bool negated{false};
190};
191
200KeyInfo InterpretKey(std::string key)
201{
202 KeyInfo result;
203 // Split section name from key name for keys like "testnet.foo" or "regtest.bar"
204 size_t option_index = key.find('.');
205 if (option_index != std::string::npos) {
206 result.section = key.substr(0, option_index);
207 key.erase(0, option_index + 1);
208 }
209 if (key.substr(0, 2) == "no") {
210 key.erase(0, 2);
211 result.negated = true;
212 }
213 result.name = key;
214 return result;
215}
216
228static std::optional<util::SettingsValue> InterpretValue(const KeyInfo& key, const std::string& value,
229 unsigned int flags, std::string& error)
230{
231 // Return negated settings as false values.
232 if (key.negated) {
234 error = strprintf("Negating of -%s is meaningless and therefore forbidden", key.name);
235 return std::nullopt;
236 }
237 // Double negatives like -nofoo=0 are supported (but discouraged)
238 if (!InterpretBool(value)) {
239 LogPrintf("Warning: parsed potentially confusing double-negative -%s=%s\n", key.name, value);
240 return true;
241 }
242 return false;
243 }
244 return value;
245}
246
247namespace {
248fs::path StripRedundantLastElementsOfPath(const fs::path& path)
249{
250 auto result = path;
251 while (fs::PathToString(result.filename()) == ".") {
252 result = result.parent_path();
253 }
254
255 assert(fs::equivalent(result, path));
256 return result;
257}
258} // namespace
259
260// Define default constructor and destructor that are not inline, so code instantiating this class doesn't need to
261// #include class definitions for all members.
262// For example, m_settings has an internal dependency on univalue.
265
266const std::set<std::string> ArgsManager::GetUnsuitableSectionOnlyArgs() const
267{
268 std::set<std::string> unsuitables;
269
270 LOCK(cs_args);
271
272 // if there's no section selected, don't worry
273 if (m_network.empty()) return std::set<std::string> {};
274
275 // if it's okay to use the default section for this network, don't worry
276 if (m_network == CBaseChainParams::MAIN) return std::set<std::string> {};
277
278 for (const auto& arg : m_network_only_args) {
279 if (OnlyHasDefaultSectionSetting(m_settings, m_network, SettingName(arg))) {
280 unsuitables.insert(arg);
281 }
282 }
283 return unsuitables;
284}
285
286const std::list<SectionInfo> ArgsManager::GetUnrecognizedSections() const
287{
288 // Section names to be recognized in the config file.
289 static const std::set<std::string> available_sections{
294 };
295
296 LOCK(cs_args);
297 std::list<SectionInfo> unrecognized = m_config_sections;
298 unrecognized.remove_if([](const SectionInfo& appeared){ return available_sections.find(appeared.m_name) != available_sections.end(); });
299 return unrecognized;
300}
301
302void ArgsManager::SelectConfigNetwork(const std::string& network)
303{
304 LOCK(cs_args);
305 m_network = network;
306}
307
308bool ArgsManager::ParseParameters(int argc, const char* const argv[], std::string& error)
309{
310 LOCK(cs_args);
311 m_settings.command_line_options.clear();
312
313 for (int i = 1; i < argc; i++) {
314 std::string key(argv[i]);
315
316#ifdef MAC_OSX
317 // At the first time when a user gets the "App downloaded from the
318 // internet" warning, and clicks the Open button, macOS passes
319 // a unique process serial number (PSN) as -psn_... command-line
320 // argument, which we filter out.
321 if (key.substr(0, 5) == "-psn_") continue;
322#endif
323
324 if (key == "-") break; //bitcoin-tx using stdin
325 std::string val;
326 size_t is_index = key.find('=');
327 if (is_index != std::string::npos) {
328 val = key.substr(is_index + 1);
329 key.erase(is_index);
330 }
331#ifdef WIN32
332 key = ToLower(key);
333 if (key[0] == '/')
334 key[0] = '-';
335#endif
336
337 if (key[0] != '-') {
338 if (!m_accept_any_command && m_command.empty()) {
339 // The first non-dash arg is a registered command
340 std::optional<unsigned int> flags = GetArgFlags(key);
341 if (!flags || !(*flags & ArgsManager::COMMAND)) {
342 error = strprintf("Invalid command '%s'", argv[i]);
343 return false;
344 }
345 }
346 m_command.push_back(key);
347 while (++i < argc) {
348 // The remaining args are command args
349 m_command.push_back(argv[i]);
350 }
351 break;
352 }
353
354 // Transform --foo to -foo
355 if (key.length() > 1 && key[1] == '-')
356 key.erase(0, 1);
357
358 // Transform -foo to foo
359 key.erase(0, 1);
360 KeyInfo keyinfo = InterpretKey(key);
361 std::optional<unsigned int> flags = GetArgFlags('-' + keyinfo.name);
362
363 // Unknown command line options and command line options with dot
364 // characters (which are returned from InterpretKey with nonempty
365 // section strings) are not valid.
366 if (!flags || !keyinfo.section.empty()) {
367 error = strprintf("Invalid parameter %s", argv[i]);
368 return false;
369 }
370
371 std::optional<util::SettingsValue> value = InterpretValue(keyinfo, val, *flags, error);
372 if (!value) return false;
373
374 m_settings.command_line_options[keyinfo.name].push_back(*value);
375 }
376
377 // we do not allow -includeconf from command line, only -noincludeconf
378 if (auto* includes = util::FindKey(m_settings.command_line_options, "includeconf")) {
379 const util::SettingsSpan values{*includes};
380 // Range may be empty if -noincludeconf was passed
381 if (!values.empty()) {
382 error = "-includeconf cannot be used from commandline; -includeconf=" + values.begin()->write();
383 return false; // pick first value as example
384 }
385 }
386 return true;
387}
388
389std::optional<unsigned int> ArgsManager::GetArgFlags(const std::string& name) const
390{
391 LOCK(cs_args);
392 for (const auto& arg_map : m_available_args) {
393 const auto search = arg_map.second.find(name);
394 if (search != arg_map.second.end()) {
395 return search->second.m_flags;
396 }
397 }
398 return std::nullopt;
399}
400
402{
403 LOCK(cs_args);
404 fs::path& path = m_cached_blocks_path;
405
406 // Cache the path to avoid calling fs::create_directories on every call of
407 // this function
408 if (!path.empty()) return path;
409
410 if (IsArgSet("-blocksdir")) {
411 path = fs::system_complete(fs::PathFromString(GetArg("-blocksdir", "")));
412 if (!fs::is_directory(path)) {
413 path = "";
414 return path;
415 }
416 } else {
417 path = GetDataDirBase();
418 }
419
420 path /= fs::PathFromString(BaseParams().DataDir());
421 path /= "blocks";
422 fs::create_directories(path);
423 path = StripRedundantLastElementsOfPath(path);
424 return path;
425}
426
427const fs::path& ArgsManager::GetDataDir(bool net_specific) const
428{
429 LOCK(cs_args);
430 fs::path& path = net_specific ? m_cached_network_datadir_path : m_cached_datadir_path;
431
432 // Cache the path to avoid calling fs::create_directories on every call of
433 // this function
434 if (!path.empty()) return path;
435
436 std::string datadir = GetArg("-datadir", "");
437 if (!datadir.empty()) {
439 if (!fs::is_directory(path)) {
440 path = "";
441 return path;
442 }
443 } else {
444 path = GetDefaultDataDir();
445 }
446 if (net_specific)
447 path /= fs::PathFromString(BaseParams().DataDir());
448
449 if (fs::create_directories(path)) {
450 // This is the first run, create wallets subdirectory too
451 fs::create_directories(path / "wallets");
452 }
453
454 path = StripRedundantLastElementsOfPath(path);
455 return path;
456}
457
459{
460 LOCK(cs_args);
461
462 m_cached_datadir_path = fs::path();
463 m_cached_network_datadir_path = fs::path();
464 m_cached_blocks_path = fs::path();
465}
466
467std::optional<const ArgsManager::Command> ArgsManager::GetCommand() const
468{
469 Command ret;
470 LOCK(cs_args);
471 auto it = m_command.begin();
472 if (it == m_command.end()) {
473 // No command was passed
474 return std::nullopt;
475 }
476 if (!m_accept_any_command) {
477 // The registered command
478 ret.command = *(it++);
479 }
480 while (it != m_command.end()) {
481 // The unregistered command and args (if any)
482 ret.args.push_back(*(it++));
483 }
484 return ret;
485}
486
487std::vector<std::string> ArgsManager::GetArgs(const std::string& strArg) const
488{
489 std::vector<std::string> result;
490 for (const util::SettingsValue& value : GetSettingsList(strArg)) {
491 result.push_back(value.isFalse() ? "0" : value.isTrue() ? "1" : value.get_str());
492 }
493 return result;
494}
495
496bool ArgsManager::IsArgSet(const std::string& strArg) const
497{
498 return !GetSetting(strArg).isNull();
499}
500
502{
503 if (!GetSettingsPath()) {
504 return true; // Do nothing if settings file disabled.
505 }
506
507 std::vector<std::string> errors;
508 if (!ReadSettingsFile(&errors)) {
509 error = strprintf("Failed loading settings file:\n%s\n", MakeUnorderedList(errors));
510 return false;
511 }
512 if (!WriteSettingsFile(&errors)) {
513 error = strprintf("Failed saving settings file:\n%s\n", MakeUnorderedList(errors));
514 return false;
515 }
516 return true;
517}
518
519bool ArgsManager::GetSettingsPath(fs::path* filepath, bool temp) const
520{
521 if (IsArgNegated("-settings")) {
522 return false;
523 }
524 if (filepath) {
525 std::string settings = GetArg("-settings", BITCOIN_SETTINGS_FILENAME);
526 *filepath = fsbridge::AbsPathJoin(GetDataDirNet(), fs::PathFromString(temp ? settings + ".tmp" : settings));
527 }
528 return true;
529}
530
531static void SaveErrors(const std::vector<std::string> errors, std::vector<std::string>* error_out)
532{
533 for (const auto& error : errors) {
534 if (error_out) {
535 error_out->emplace_back(error);
536 } else {
537 LogPrintf("%s\n", error);
538 }
539 }
540}
541
542bool ArgsManager::ReadSettingsFile(std::vector<std::string>* errors)
543{
544 fs::path path;
545 if (!GetSettingsPath(&path, /* temp= */ false)) {
546 return true; // Do nothing if settings file disabled.
547 }
548
549 LOCK(cs_args);
550 m_settings.rw_settings.clear();
551 std::vector<std::string> read_errors;
552 if (!util::ReadSettings(path, m_settings.rw_settings, read_errors)) {
553 SaveErrors(read_errors, errors);
554 return false;
555 }
556 for (const auto& setting : m_settings.rw_settings) {
557 KeyInfo key = InterpretKey(setting.first); // Split setting key into section and argname
558 if (!GetArgFlags('-' + key.name)) {
559 LogPrintf("Ignoring unknown rw_settings value %s\n", setting.first);
560 }
561 }
562 return true;
563}
564
565bool ArgsManager::WriteSettingsFile(std::vector<std::string>* errors) const
566{
567 fs::path path, path_tmp;
568 if (!GetSettingsPath(&path, /* temp= */ false) || !GetSettingsPath(&path_tmp, /* temp= */ true)) {
569 throw std::logic_error("Attempt to write settings file when dynamic settings are disabled.");
570 }
571
572 LOCK(cs_args);
573 std::vector<std::string> write_errors;
574 if (!util::WriteSettings(path_tmp, m_settings.rw_settings, write_errors)) {
575 SaveErrors(write_errors, errors);
576 return false;
577 }
578 if (!RenameOver(path_tmp, path)) {
579 SaveErrors({strprintf("Failed renaming settings file %s to %s\n", fs::PathToString(path_tmp), fs::PathToString(path))}, errors);
580 return false;
581 }
582 return true;
583}
584
585bool ArgsManager::IsArgNegated(const std::string& strArg) const
586{
587 return GetSetting(strArg).isFalse();
588}
589
590std::string ArgsManager::GetArg(const std::string& strArg, const std::string& strDefault) const
591{
592 const util::SettingsValue value = GetSetting(strArg);
593 return value.isNull() ? strDefault : value.isFalse() ? "0" : value.isTrue() ? "1" : value.get_str();
594}
595
596int64_t ArgsManager::GetIntArg(const std::string& strArg, int64_t nDefault) const
597{
598 const util::SettingsValue value = GetSetting(strArg);
599 return value.isNull() ? nDefault : value.isFalse() ? 0 : value.isTrue() ? 1 : value.isNum() ? value.get_int64() : LocaleIndependentAtoi<int64_t>(value.get_str());
600}
601
602bool ArgsManager::GetBoolArg(const std::string& strArg, bool fDefault) const
603{
604 const util::SettingsValue value = GetSetting(strArg);
605 return value.isNull() ? fDefault : value.isBool() ? value.get_bool() : InterpretBool(value.get_str());
606}
607
608bool ArgsManager::SoftSetArg(const std::string& strArg, const std::string& strValue)
609{
610 LOCK(cs_args);
611 if (IsArgSet(strArg)) return false;
612 ForceSetArg(strArg, strValue);
613 return true;
614}
615
616bool ArgsManager::SoftSetBoolArg(const std::string& strArg, bool fValue)
617{
618 if (fValue)
619 return SoftSetArg(strArg, std::string("1"));
620 else
621 return SoftSetArg(strArg, std::string("0"));
622}
623
624void ArgsManager::ForceSetArg(const std::string& strArg, const std::string& strValue)
625{
626 LOCK(cs_args);
627 m_settings.forced_settings[SettingName(strArg)] = strValue;
628}
629
630void ArgsManager::AddCommand(const std::string& cmd, const std::string& help)
631{
632 Assert(cmd.find('=') == std::string::npos);
633 Assert(cmd.at(0) != '-');
634
635 LOCK(cs_args);
636 m_accept_any_command = false; // latch to false
637 std::map<std::string, Arg>& arg_map = m_available_args[OptionsCategory::COMMANDS];
638 auto ret = arg_map.emplace(cmd, Arg{"", help, ArgsManager::COMMAND});
639 Assert(ret.second); // Fail on duplicate commands
640}
641
642void ArgsManager::AddArg(const std::string& name, const std::string& help, unsigned int flags, const OptionsCategory& cat)
643{
644 Assert((flags & ArgsManager::COMMAND) == 0); // use AddCommand
645
646 // Split arg name from its help param
647 size_t eq_index = name.find('=');
648 if (eq_index == std::string::npos) {
649 eq_index = name.size();
650 }
651 std::string arg_name = name.substr(0, eq_index);
652
653 LOCK(cs_args);
654 std::map<std::string, Arg>& arg_map = m_available_args[cat];
655 auto ret = arg_map.emplace(arg_name, Arg{name.substr(eq_index, name.size() - eq_index), help, flags});
656 assert(ret.second); // Make sure an insertion actually happened
657
659 m_network_only_args.emplace(arg_name);
660 }
661}
662
663void ArgsManager::AddHiddenArgs(const std::vector<std::string>& names)
664{
665 for (const std::string& name : names) {
667 }
668}
669
671{
672 const bool show_debug = GetBoolArg("-help-debug", false);
673
674 std::string usage = "";
675 LOCK(cs_args);
676 for (const auto& arg_map : m_available_args) {
677 switch(arg_map.first) {
679 usage += HelpMessageGroup("Options:");
680 break;
682 usage += HelpMessageGroup("Connection options:");
683 break;
685 usage += HelpMessageGroup("ZeroMQ notification options:");
686 break;
688 usage += HelpMessageGroup("Debugging/Testing options:");
689 break;
691 usage += HelpMessageGroup("Node relay options:");
692 break;
694 usage += HelpMessageGroup("Block creation options:");
695 break;
697 usage += HelpMessageGroup("RPC server options:");
698 break;
700 usage += HelpMessageGroup("Wallet options:");
701 break;
703 if (show_debug) usage += HelpMessageGroup("Wallet debugging/testing options:");
704 break;
706 usage += HelpMessageGroup("Chain selection options:");
707 break;
709 usage += HelpMessageGroup("UI Options:");
710 break;
712 usage += HelpMessageGroup("Commands:");
713 break;
715 usage += HelpMessageGroup("Register Commands:");
716 break;
717 default:
718 break;
719 }
720
721 // When we get to the hidden options, stop
722 if (arg_map.first == OptionsCategory::HIDDEN) break;
723
724 for (const auto& arg : arg_map.second) {
725 if (show_debug || !(arg.second.m_flags & ArgsManager::DEBUG_ONLY)) {
726 std::string name;
727 if (arg.second.m_help_param.empty()) {
728 name = arg.first;
729 } else {
730 name = arg.first + arg.second.m_help_param;
731 }
732 usage += HelpMessageOpt(name, arg.second.m_help_text);
733 }
734 }
735 }
736 return usage;
737}
738
739bool HelpRequested(const ArgsManager& args)
740{
741 return args.IsArgSet("-?") || args.IsArgSet("-h") || args.IsArgSet("-help") || args.IsArgSet("-help-debug");
742}
743
745{
746 args.AddArg("-?", "Print this help message and exit", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
747 args.AddHiddenArgs({"-h", "-help"});
748}
749
750static const int screenWidth = 79;
751static const int optIndent = 2;
752static const int msgIndent = 7;
753
754std::string HelpMessageGroup(const std::string &message) {
755 return std::string(message) + std::string("\n\n");
756}
757
758std::string HelpMessageOpt(const std::string &option, const std::string &message) {
759 return std::string(optIndent,' ') + std::string(option) +
760 std::string("\n") + std::string(msgIndent,' ') +
762 std::string("\n\n");
763}
764
765static std::string FormatException(const std::exception* pex, const char* pszThread)
766{
767#ifdef WIN32
768 char pszModule[MAX_PATH] = "";
769 GetModuleFileNameA(nullptr, pszModule, sizeof(pszModule));
770#else
771 const char* pszModule = "bitcoin";
772#endif
773 if (pex)
774 return strprintf(
775 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
776 else
777 return strprintf(
778 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
779}
780
781void PrintExceptionContinue(const std::exception* pex, const char* pszThread)
782{
783 std::string message = FormatException(pex, pszThread);
784 LogPrintf("\n\n************************\n%s\n", message);
785 tfm::format(std::cerr, "\n\n************************\n%s\n", message);
786}
787
789{
790 // Windows: C:\Users\Username\AppData\Roaming\Bitcoin
791 // macOS: ~/Library/Application Support/Bitcoin
792 // Unix-like: ~/.bitcoin
793#ifdef WIN32
794 // Windows
795 return GetSpecialFolderPath(CSIDL_APPDATA) / "Bitcoin";
796#else
797 fs::path pathRet;
798 char* pszHome = getenv("HOME");
799 if (pszHome == nullptr || strlen(pszHome) == 0)
800 pathRet = fs::path("/");
801 else
802 pathRet = fs::path(pszHome);
803#ifdef MAC_OSX
804 // macOS
805 return pathRet / "Library/Application Support/Bitcoin";
806#else
807 // Unix-like
808 return pathRet / ".bitcoin";
809#endif
810#endif
811}
812
814{
815 std::string datadir = gArgs.GetArg("-datadir", "");
816 return datadir.empty() || fs::is_directory(fs::system_complete(fs::PathFromString(datadir)));
817}
818
819fs::path GetConfigFile(const std::string& confPath)
820{
821 return AbsPathForConfigVal(fs::PathFromString(confPath), false);
822}
823
824static bool GetConfigOptions(std::istream& stream, const std::string& filepath, std::string& error, std::vector<std::pair<std::string, std::string>>& options, std::list<SectionInfo>& sections)
825{
826 std::string str, prefix;
827 std::string::size_type pos;
828 int linenr = 1;
829 while (std::getline(stream, str)) {
830 bool used_hash = false;
831 if ((pos = str.find('#')) != std::string::npos) {
832 str = str.substr(0, pos);
833 used_hash = true;
834 }
835 const static std::string pattern = " \t\r\n";
836 str = TrimString(str, pattern);
837 if (!str.empty()) {
838 if (*str.begin() == '[' && *str.rbegin() == ']') {
839 const std::string section = str.substr(1, str.size() - 2);
840 sections.emplace_back(SectionInfo{section, filepath, linenr});
841 prefix = section + '.';
842 } else if (*str.begin() == '-') {
843 error = strprintf("parse error on line %i: %s, options in configuration file must be specified without leading -", linenr, str);
844 return false;
845 } else if ((pos = str.find('=')) != std::string::npos) {
846 std::string name = prefix + TrimString(str.substr(0, pos), pattern);
847 std::string value = TrimString(str.substr(pos + 1), pattern);
848 if (used_hash && name.find("rpcpassword") != std::string::npos) {
849 error = strprintf("parse error on line %i, using # in rpcpassword can be ambiguous and should be avoided", linenr);
850 return false;
851 }
852 options.emplace_back(name, value);
853 if ((pos = name.rfind('.')) != std::string::npos && prefix.length() <= pos) {
854 sections.emplace_back(SectionInfo{name.substr(0, pos), filepath, linenr});
855 }
856 } else {
857 error = strprintf("parse error on line %i: %s", linenr, str);
858 if (str.size() >= 2 && str.substr(0, 2) == "no") {
859 error += strprintf(", if you intended to specify a negated option, use %s=1 instead", str);
860 }
861 return false;
862 }
863 }
864 ++linenr;
865 }
866 return true;
867}
868
869bool ArgsManager::ReadConfigStream(std::istream& stream, const std::string& filepath, std::string& error, bool ignore_invalid_keys)
870{
871 LOCK(cs_args);
872 std::vector<std::pair<std::string, std::string>> options;
873 if (!GetConfigOptions(stream, filepath, error, options, m_config_sections)) {
874 return false;
875 }
876 for (const std::pair<std::string, std::string>& option : options) {
877 KeyInfo key = InterpretKey(option.first);
878 std::optional<unsigned int> flags = GetArgFlags('-' + key.name);
879 if (flags) {
880 std::optional<util::SettingsValue> value = InterpretValue(key, option.second, *flags, error);
881 if (!value) {
882 return false;
883 }
884 m_settings.ro_config[key.section][key.name].push_back(*value);
885 } else {
886 if (ignore_invalid_keys) {
887 LogPrintf("Ignoring unknown configuration value %s\n", option.first);
888 } else {
889 error = strprintf("Invalid configuration value %s", option.first);
890 return false;
891 }
892 }
893 }
894 return true;
895}
896
897bool ArgsManager::ReadConfigFiles(std::string& error, bool ignore_invalid_keys)
898{
899 {
900 LOCK(cs_args);
901 m_settings.ro_config.clear();
902 m_config_sections.clear();
903 }
904
905 const std::string confPath = GetArg("-conf", BITCOIN_CONF_FILENAME);
906 fsbridge::ifstream stream(GetConfigFile(confPath));
907
908 // not ok to have a config file specified that cannot be opened
909 if (IsArgSet("-conf") && !stream.good()) {
910 error = strprintf("specified config file \"%s\" could not be opened.", confPath);
911 return false;
912 }
913 // ok to not have a config file
914 if (stream.good()) {
915 if (!ReadConfigStream(stream, confPath, error, ignore_invalid_keys)) {
916 return false;
917 }
918 // `-includeconf` cannot be included in the command line arguments except
919 // as `-noincludeconf` (which indicates that no included conf file should be used).
920 bool use_conf_file{true};
921 {
922 LOCK(cs_args);
923 if (auto* includes = util::FindKey(m_settings.command_line_options, "includeconf")) {
924 // ParseParameters() fails if a non-negated -includeconf is passed on the command-line
926 use_conf_file = false;
927 }
928 }
929 if (use_conf_file) {
930 std::string chain_id = GetChainName();
931 std::vector<std::string> conf_file_names;
932
933 auto add_includes = [&](const std::string& network, size_t skip = 0) {
934 size_t num_values = 0;
935 LOCK(cs_args);
936 if (auto* section = util::FindKey(m_settings.ro_config, network)) {
937 if (auto* values = util::FindKey(*section, "includeconf")) {
938 for (size_t i = std::max(skip, util::SettingsSpan(*values).negated()); i < values->size(); ++i) {
939 conf_file_names.push_back((*values)[i].get_str());
940 }
941 num_values = values->size();
942 }
943 }
944 return num_values;
945 };
946
947 // We haven't set m_network yet (that happens in SelectParams()), so manually check
948 // for network.includeconf args.
949 const size_t chain_includes = add_includes(chain_id);
950 const size_t default_includes = add_includes({});
951
952 for (const std::string& conf_file_name : conf_file_names) {
953 fsbridge::ifstream conf_file_stream(GetConfigFile(conf_file_name));
954 if (conf_file_stream.good()) {
955 if (!ReadConfigStream(conf_file_stream, conf_file_name, error, ignore_invalid_keys)) {
956 return false;
957 }
958 LogPrintf("Included configuration file %s\n", conf_file_name);
959 } else {
960 error = "Failed to include configuration file " + conf_file_name;
961 return false;
962 }
963 }
964
965 // Warn about recursive -includeconf
966 conf_file_names.clear();
967 add_includes(chain_id, /* skip= */ chain_includes);
968 add_includes({}, /* skip= */ default_includes);
969 std::string chain_id_final = GetChainName();
970 if (chain_id_final != chain_id) {
971 // Also warn about recursive includeconf for the chain that was specified in one of the includeconfs
972 add_includes(chain_id_final);
973 }
974 for (const std::string& conf_file_name : conf_file_names) {
975 tfm::format(std::cerr, "warning: -includeconf cannot be used from included files; ignoring -includeconf=%s\n", conf_file_name);
976 }
977 }
978 }
979
980 // If datadir is changed in .conf file:
982 if (!CheckDataDirOption()) {
983 error = strprintf("specified data directory \"%s\" does not exist.", GetArg("-datadir", ""));
984 return false;
985 }
986 return true;
987}
988
989std::string ArgsManager::GetChainName() const
990{
991 auto get_net = [&](const std::string& arg) {
992 LOCK(cs_args);
993 util::SettingsValue value = util::GetSetting(m_settings, /* section= */ "", SettingName(arg),
994 /* ignore_default_section_config= */ false,
995 /* get_chain_name= */ true);
996 return value.isNull() ? false : value.isBool() ? value.get_bool() : InterpretBool(value.get_str());
997 };
998
999 const bool fRegTest = get_net("-regtest");
1000 const bool fSigNet = get_net("-signet");
1001 const bool fTestNet = get_net("-testnet");
1002 const bool is_chain_arg_set = IsArgSet("-chain");
1003
1004 if ((int)is_chain_arg_set + (int)fRegTest + (int)fSigNet + (int)fTestNet > 1) {
1005 throw std::runtime_error("Invalid combination of -regtest, -signet, -testnet and -chain. Can use at most one.");
1006 }
1007 if (fRegTest)
1009 if (fSigNet) {
1011 }
1012 if (fTestNet)
1014
1015 return GetArg("-chain", CBaseChainParams::MAIN);
1016}
1017
1018bool ArgsManager::UseDefaultSection(const std::string& arg) const
1019{
1020 return m_network == CBaseChainParams::MAIN || m_network_only_args.count(arg) == 0;
1021}
1022
1024{
1025 LOCK(cs_args);
1026 return util::GetSetting(
1027 m_settings, m_network, SettingName(arg), !UseDefaultSection(arg), /* get_chain_name= */ false);
1028}
1029
1030std::vector<util::SettingsValue> ArgsManager::GetSettingsList(const std::string& arg) const
1031{
1032 LOCK(cs_args);
1033 return util::GetSettingsList(m_settings, m_network, SettingName(arg), !UseDefaultSection(arg));
1034}
1035
1037 const std::string& prefix,
1038 const std::string& section,
1039 const std::map<std::string, std::vector<util::SettingsValue>>& args) const
1040{
1041 std::string section_str = section.empty() ? "" : "[" + section + "] ";
1042 for (const auto& arg : args) {
1043 for (const auto& value : arg.second) {
1044 std::optional<unsigned int> flags = GetArgFlags('-' + arg.first);
1045 if (flags) {
1046 std::string value_str = (*flags & SENSITIVE) ? "****" : value.write();
1047 LogPrintf("%s %s%s=%s\n", prefix, section_str, arg.first, value_str);
1048 }
1049 }
1050 }
1051}
1052
1054{
1055 LOCK(cs_args);
1056 for (const auto& section : m_settings.ro_config) {
1057 logArgsPrefix("Config file arg:", section.first, section.second);
1058 }
1059 for (const auto& setting : m_settings.rw_settings) {
1060 LogPrintf("Setting file arg: %s = %s\n", setting.first, setting.second.write());
1061 }
1062 logArgsPrefix("Command-line arg:", "", m_settings.command_line_options);
1063}
1064
1066{
1067#ifdef WIN32
1068 return MoveFileExW(src.wstring().c_str(), dest.wstring().c_str(),
1069 MOVEFILE_REPLACE_EXISTING) != 0;
1070#else
1071 int rc = std::rename(src.c_str(), dest.c_str());
1072 return (rc == 0);
1073#endif /* WIN32 */
1074}
1075
1082{
1083 try
1084 {
1085 return fs::create_directories(p);
1086 } catch (const fs::filesystem_error&) {
1087 if (!fs::exists(p) || !fs::is_directory(p))
1088 throw;
1089 }
1090
1091 // create_directories didn't create the directory, it had to have existed already
1092 return false;
1093}
1094
1095bool FileCommit(FILE *file)
1096{
1097 if (fflush(file) != 0) { // harmless if redundantly called
1098 LogPrintf("%s: fflush failed: %d\n", __func__, errno);
1099 return false;
1100 }
1101#ifdef WIN32
1102 HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
1103 if (FlushFileBuffers(hFile) == 0) {
1104 LogPrintf("%s: FlushFileBuffers failed: %d\n", __func__, GetLastError());
1105 return false;
1106 }
1107#elif defined(MAC_OSX) && defined(F_FULLFSYNC)
1108 if (fcntl(fileno(file), F_FULLFSYNC, 0) == -1) { // Manpage says "value other than -1" is returned on success
1109 LogPrintf("%s: fcntl F_FULLFSYNC failed: %d\n", __func__, errno);
1110 return false;
1111 }
1112#elif HAVE_FDATASYNC
1113 if (fdatasync(fileno(file)) != 0 && errno != EINVAL) { // Ignore EINVAL for filesystems that don't support sync
1114 LogPrintf("%s: fdatasync failed: %d\n", __func__, errno);
1115 return false;
1116 }
1117#else
1118 if (fsync(fileno(file)) != 0 && errno != EINVAL) {
1119 LogPrintf("%s: fsync failed: %d\n", __func__, errno);
1120 return false;
1121 }
1122#endif
1123 return true;
1124}
1125
1126void DirectoryCommit(const fs::path &dirname)
1127{
1128#ifndef WIN32
1129 FILE* file = fsbridge::fopen(dirname, "r");
1130 if (file) {
1131 fsync(fileno(file));
1132 fclose(file);
1133 }
1134#endif
1135}
1136
1137bool TruncateFile(FILE *file, unsigned int length) {
1138#if defined(WIN32)
1139 return _chsize(_fileno(file), length) == 0;
1140#else
1141 return ftruncate(fileno(file), length) == 0;
1142#endif
1143}
1144
1150#if defined(WIN32)
1151 return 2048;
1152#else
1153 struct rlimit limitFD;
1154 if (getrlimit(RLIMIT_NOFILE, &limitFD) != -1) {
1155 if (limitFD.rlim_cur < (rlim_t)nMinFD) {
1156 limitFD.rlim_cur = nMinFD;
1157 if (limitFD.rlim_cur > limitFD.rlim_max)
1158 limitFD.rlim_cur = limitFD.rlim_max;
1159 setrlimit(RLIMIT_NOFILE, &limitFD);
1160 getrlimit(RLIMIT_NOFILE, &limitFD);
1161 }
1162 return limitFD.rlim_cur;
1163 }
1164 return nMinFD; // getrlimit failed, assume it's fine
1165#endif
1166}
1167
1172void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length) {
1173#if defined(WIN32)
1174 // Windows-specific version
1175 HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
1176 LARGE_INTEGER nFileSize;
1177 int64_t nEndPos = (int64_t)offset + length;
1178 nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF;
1179 nFileSize.u.HighPart = nEndPos >> 32;
1180 SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN);
1181 SetEndOfFile(hFile);
1182#elif defined(MAC_OSX)
1183 // OSX specific version
1184 // NOTE: Contrary to other OS versions, the OSX version assumes that
1185 // NOTE: offset is the size of the file.
1186 fstore_t fst;
1187 fst.fst_flags = F_ALLOCATECONTIG;
1188 fst.fst_posmode = F_PEOFPOSMODE;
1189 fst.fst_offset = 0;
1190 fst.fst_length = length; // mac os fst_length takes the # of free bytes to allocate, not desired file size
1191 fst.fst_bytesalloc = 0;
1192 if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) {
1193 fst.fst_flags = F_ALLOCATEALL;
1194 fcntl(fileno(file), F_PREALLOCATE, &fst);
1195 }
1196 ftruncate(fileno(file), static_cast<off_t>(offset) + length);
1197#else
1198 #if defined(HAVE_POSIX_FALLOCATE)
1199 // Version using posix_fallocate
1200 off_t nEndPos = (off_t)offset + length;
1201 if (0 == posix_fallocate(fileno(file), 0, nEndPos)) return;
1202 #endif
1203 // Fallback version
1204 // TODO: just write one byte per block
1205 static const char buf[65536] = {};
1206 if (fseek(file, offset, SEEK_SET)) {
1207 return;
1208 }
1209 while (length > 0) {
1210 unsigned int now = 65536;
1211 if (length < now)
1212 now = length;
1213 fwrite(buf, 1, now, file); // allowed to fail; this function is advisory anyway
1214 length -= now;
1215 }
1216#endif
1217}
1218
1219#ifdef WIN32
1220fs::path GetSpecialFolderPath(int nFolder, bool fCreate)
1221{
1222 WCHAR pszPath[MAX_PATH] = L"";
1223
1224 if(SHGetSpecialFolderPathW(nullptr, pszPath, nFolder, fCreate))
1225 {
1226 return fs::path(pszPath);
1227 }
1228
1229 LogPrintf("SHGetSpecialFolderPathW() failed, could not obtain requested path.\n");
1230 return fs::path("");
1231}
1232#endif
1233
1234#ifndef WIN32
1235std::string ShellEscape(const std::string& arg)
1236{
1237 std::string escaped = arg;
1238 boost::replace_all(escaped, "'", "'\"'\"'");
1239 return "'" + escaped + "'";
1240}
1241#endif
1242
1243#if HAVE_SYSTEM
1244void runCommand(const std::string& strCommand)
1245{
1246 if (strCommand.empty()) return;
1247#ifndef WIN32
1248 int nErr = ::system(strCommand.c_str());
1249#else
1250 int nErr = ::_wsystem(std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>,wchar_t>().from_bytes(strCommand).c_str());
1251#endif
1252 if (nErr)
1253 LogPrintf("runCommand error: system(%s) returned %d\n", strCommand, nErr);
1254}
1255#endif
1256
1257UniValue RunCommandParseJSON(const std::string& str_command, const std::string& str_std_in)
1258{
1259#ifdef ENABLE_EXTERNAL_SIGNER
1260 namespace bp = boost::process;
1261
1262 UniValue result_json;
1263 bp::opstream stdin_stream;
1264 bp::ipstream stdout_stream;
1265 bp::ipstream stderr_stream;
1266
1267 if (str_command.empty()) return UniValue::VNULL;
1268
1269 bp::child c(
1270 str_command,
1271 bp::std_out > stdout_stream,
1272 bp::std_err > stderr_stream,
1273 bp::std_in < stdin_stream
1274 );
1275 if (!str_std_in.empty()) {
1276 stdin_stream << str_std_in << std::endl;
1277 }
1278 stdin_stream.pipe().close();
1279
1280 std::string result;
1281 std::string error;
1282 std::getline(stdout_stream, result);
1283 std::getline(stderr_stream, error);
1284
1285 c.wait();
1286 const int n_error = c.exit_code();
1287 if (n_error) throw std::runtime_error(strprintf("RunCommandParseJSON error: process(%s) returned %d: %s\n", str_command, n_error, error));
1288 if (!result_json.read(result)) throw std::runtime_error("Unable to parse JSON: " + result);
1289
1290 return result_json;
1291#else
1292 throw std::runtime_error("Compiled without external signing support (required for external signing).");
1293#endif // ENABLE_EXTERNAL_SIGNER
1294}
1295
1297{
1298#ifdef HAVE_MALLOPT_ARENA_MAX
1299 // glibc-specific: On 32-bit systems set the number of arenas to 1.
1300 // By default, since glibc 2.10, the C library will create up to two heap
1301 // arenas per core. This is known to cause excessive virtual address space
1302 // usage in our usage. Work around it by setting the maximum number of
1303 // arenas to 1.
1304 if (sizeof(void*) == 4) {
1305 mallopt(M_ARENA_MAX, 1);
1306 }
1307#endif
1308 // On most POSIX systems (e.g. Linux, but not BSD) the environment's locale
1309 // may be invalid, in which case the "C.UTF-8" locale is used as fallback.
1310#if !defined(WIN32) && !defined(MAC_OSX) && !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
1311 try {
1312 std::locale(""); // Raises a runtime error if current locale is invalid
1313 } catch (const std::runtime_error&) {
1314 setenv("LC_ALL", "C.UTF-8", 1);
1315 }
1316#elif defined(WIN32)
1317 // Set the default input/output charset is utf-8
1318 SetConsoleCP(CP_UTF8);
1319 SetConsoleOutputCP(CP_UTF8);
1320#endif
1321 // The path locale is lazy initialized and to avoid deinitialization errors
1322 // in multithreading environments, it is set explicitly by the main thread.
1323 // A dummy locale is used to extract the internal default locale, used by
1324 // fs::path, which is then used to explicitly imbue the path.
1325 std::locale loc = fs::path::imbue(std::locale::classic());
1326#ifndef WIN32
1327 fs::path::imbue(loc);
1328#else
1329 fs::path::imbue(std::locale(loc, new std::codecvt_utf8_utf16<wchar_t>()));
1330#endif
1331}
1332
1334{
1335#ifdef WIN32
1336 // Initialize Windows Sockets
1337 WSADATA wsadata;
1338 int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
1339 if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2)
1340 return false;
1341#endif
1342 return true;
1343}
1344
1346{
1347 return std::thread::hardware_concurrency();
1348}
1349
1350std::string CopyrightHolders(const std::string& strPrefix)
1351{
1352 const auto copyright_devs = strprintf(_(COPYRIGHT_HOLDERS).translated, COPYRIGHT_HOLDERS_SUBSTITUTION);
1353 std::string strCopyrightHolders = strPrefix + copyright_devs;
1354
1355 // Make sure Bitcoin Core copyright is not removed by accident
1356 if (copyright_devs.find("Bitcoin Core") == std::string::npos) {
1357 strCopyrightHolders += "\n" + strPrefix + "The Bitcoin Core developers";
1358 }
1359 return strCopyrightHolders;
1360}
1361
1362// Obtain the application startup time (used for uptime calculation)
1364{
1365 return nStartupTime;
1366}
1367
1368fs::path AbsPathForConfigVal(const fs::path& path, bool net_specific)
1369{
1370 if (path.is_absolute()) {
1371 return path;
1372 }
1373 return fsbridge::AbsPathJoin(net_specific ? gArgs.GetDataDirNet() : gArgs.GetDataDirBase(), path);
1374}
1375
1377{
1378#ifdef SCHED_BATCH
1379 const static sched_param param{};
1380 const int rc = pthread_setschedparam(pthread_self(), SCHED_BATCH, &param);
1381 if (rc != 0) {
1382 LogPrintf("Failed to pthread_setschedparam: %s\n", strerror(rc));
1383 }
1384#endif
1385}
1386
1387namespace util {
1388#ifdef WIN32
1389WinCmdLineArgs::WinCmdLineArgs()
1390{
1391 wchar_t** wargv = CommandLineToArgvW(GetCommandLineW(), &argc);
1392 std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t> utf8_cvt;
1393 argv = new char*[argc];
1394 args.resize(argc);
1395 for (int i = 0; i < argc; i++) {
1396 args[i] = utf8_cvt.to_bytes(wargv[i]);
1397 argv[i] = &*args[i].begin();
1398 }
1399 LocalFree(wargv);
1400}
1401
1402WinCmdLineArgs::~WinCmdLineArgs()
1403{
1404 delete[] argv;
1405}
1406
1407std::pair<int, char**> WinCmdLineArgs::get()
1408{
1409 return std::make_pair(argc, argv);
1410}
1411#endif
1412} // namespace util
void help(char **argv)
Definition: bench_ecmult.c:21
#define COPYRIGHT_HOLDERS_SUBSTITUTION
#define COPYRIGHT_HOLDERS
int flags
Definition: bitcoin-tx.cpp:525
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
#define Assert(val)
Identity function.
Definition: check.h:57
const fs::path & GetDataDirBase() const
Get data directory path.
Definition: system.h:280
const std::set< std::string > GetUnsuitableSectionOnlyArgs() const
Log warnings for options in m_section_only_args when they are specified in the default section but no...
Definition: system.cpp:266
std::optional< const Command > GetCommand() const
Get the command and command args (returns std::nullopt if no command provided)
Definition: system.cpp:467
const fs::path & GetBlocksDirPath() const
Get blocks directory path.
Definition: system.cpp:401
bool IsArgNegated(const std::string &strArg) const
Return true if the argument was originally passed as a negated option, i.e.
Definition: system.cpp:585
@ NETWORK_ONLY
Definition: system.h:179
@ ALLOW_ANY
disable validation
Definition: system.h:166
@ DISALLOW_NEGATION
disallow -nofoo syntax
Definition: system.h:171
@ DEBUG_ONLY
Definition: system.h:173
@ SENSITIVE
Definition: system.h:181
bool ReadSettingsFile(std::vector< std::string > *errors=nullptr)
Read settings file.
Definition: system.cpp:542
void ForceSetArg(const std::string &strArg, const std::string &strValue)
Definition: system.cpp:624
bool InitSettings(std::string &error)
Read and update settings file with saved settings.
Definition: system.cpp:501
bool WriteSettingsFile(std::vector< std::string > *errors=nullptr) const
Write settings file.
Definition: system.cpp:565
bool ParseParameters(int argc, const char *const argv[], std::string &error)
Definition: system.cpp:308
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
Definition: system.cpp:487
std::optional< unsigned int > GetArgFlags(const std::string &name) const
Return Flags for known arg.
Definition: system.cpp:389
~ArgsManager()
Definition: system.cpp:264
bool SoftSetArg(const std::string &strArg, const std::string &strValue)
Set an argument if it doesn't already have a value.
Definition: system.cpp:608
void SelectConfigNetwork(const std::string &network)
Select the network in use.
Definition: system.cpp:302
std::string GetHelpMessage() const
Get the help string.
Definition: system.cpp:670
void ClearPathCache()
Clear cached directory paths.
Definition: system.cpp:458
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: system.cpp:496
const fs::path & GetDataDirNet() const
Get data directory path with appended network identifier.
Definition: system.h:288
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Definition: system.cpp:596
const fs::path & GetDataDir(bool net_specific) const
Get data directory path.
Definition: system.cpp:427
void logArgsPrefix(const std::string &prefix, const std::string &section, const std::map< std::string, std::vector< util::SettingsValue > > &args) const
Definition: system.cpp:1036
void AddCommand(const std::string &cmd, const std::string &help)
Add subcommand.
Definition: system.cpp:630
std::vector< util::SettingsValue > GetSettingsList(const std::string &arg) const
Get list of setting values.
Definition: system.cpp:1030
bool GetSettingsPath(fs::path *filepath=nullptr, bool temp=false) const
Get settings file path, or return false if read-write settings were disabled with -nosettings.
Definition: system.cpp:519
void LogArgs() const
Log the config file options and the command line arguments, useful for troubleshooting.
Definition: system.cpp:1053
RecursiveMutex cs_args
Definition: system.h:193
bool UseDefaultSection(const std::string &arg) const EXCLUSIVE_LOCKS_REQUIRED(cs_args)
Returns true if settings values from the default section should be used, depending on the current net...
Definition: system.cpp:1018
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:590
util::SettingsValue GetSetting(const std::string &arg) const
Get setting value.
Definition: system.cpp:1023
bool ReadConfigStream(std::istream &stream, const std::string &filepath, std::string &error, bool ignore_invalid_keys=false)
Definition: system.cpp:869
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn't already have a value.
Definition: system.cpp:616
bool ReadConfigFiles(std::string &error, bool ignore_invalid_keys=false)
Definition: system.cpp:897
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:602
void AddHiddenArgs(const std::vector< std::string > &args)
Add many hidden arguments.
Definition: system.cpp:663
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
Definition: system.cpp:642
const std::list< SectionInfo > GetUnrecognizedSections() const
Log warnings for unrecognized section names in the config file.
Definition: system.cpp:286
std::string GetChainName() const
Returns the appropriate chain name from the program arguments.
Definition: system.cpp:989
static const std::string REGTEST
static const std::string TESTNET
static const std::string SIGNET
static const std::string MAIN
Chain name strings.
const std::string & get_str() const
bool isTrue() const
Definition: univalue.h:76
@ VNULL
Definition: univalue.h:19
int64_t get_int64() const
bool isNull() const
Definition: univalue.h:75
bool isBool() const
Definition: univalue.h:78
bool isNum() const
Definition: univalue.h:80
bool isFalse() const
Definition: univalue.h:77
bool get_bool() const
bool read(const char *raw, size_t len)
Path class wrapper to prepare application code for transition from boost::filesystem library to std::...
Definition: fs.h:34
#define MAX_PATH
Definition: compat.h:71
fs::path GetUniquePath(const fs::path &base)
Helper function for getting a unique path.
#define LogPrintf(...)
Definition: logging.h:187
static path system_complete(const path &p)
Definition: fs.h:70
static bool exists(const path &p)
Definition: fs.h:77
static std::string PathToString(const path &path)
Convert path object to byte string.
Definition: fs.h:120
static path PathFromString(const std::string &string)
Convert byte string to path object.
Definition: fs.h:133
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:25
fs::path AbsPathJoin(const fs::path &base, const fs::path &path)
Helper function for joining two paths.
Definition: fs.cpp:35
fs::ifstream ifstream
Definition: fs.h:224
void format(std::ostream &out, const char *fmt, const Args &... args)
Format list of arguments to the stream according to given format string.
Definition: tinyformat.h:1062
std::vector< SettingsValue > GetSettingsList(const Settings &settings, const std::string &section, const std::string &name, bool ignore_default_section_config)
Get combined setting value similar to GetSetting(), except if setting was specified multiple times,...
Definition: settings.cpp:173
bool ReadSettings(const fs::path &path, std::map< std::string, SettingsValue > &values, std::vector< std::string > &errors)
Read settings file.
Definition: settings.cpp:58
bool OnlyHasDefaultSectionSetting(const Settings &settings, const std::string &section, const std::string &name)
Return true if a setting is set in the default config file section, and not overridden by a higher pr...
Definition: settings.cpp:218
bool WriteSettings(const fs::path &path, const std::map< std::string, SettingsValue > &values, std::vector< std::string > &errors)
Write settings file.
Definition: settings.cpp:101
auto FindKey(Map &&map, Key &&key) -> decltype(&map.at(key))
Map lookup helper.
Definition: settings.h:100
SettingsValue GetSetting(const Settings &settings, const std::string &section, const std::string &name, bool ignore_default_section_config, bool get_chain_name)
Get settings value from combined sources: forced settings, command line arguments,...
Definition: settings.cpp:120
CRPCCommand m_command
Definition: interfaces.cpp:425
const char * prefix
Definition: rest.cpp:714
const char * name
Definition: rest.cpp:43
static const int64_t values[]
A selection of numbers that do not trigger int64_t overflow when added/subtracted.
std::string FormatParagraph(const std::string &in, size_t width, size_t indent)
Format a paragraph of text to a fixed width, adding spaces for indentation to any added line.
std::string ToLower(const std::string &str)
Returns the lowercase equivalent of the given string.
std::string MakeUnorderedList(const std::vector< std::string > &items)
Create an unordered multi-line list of items.
Definition: string.h:70
std::string TrimString(const std::string &str, const std::string &pattern=" \f\n\r\t\v")
Definition: string.h:18
std::vector< std::string > args
If command is non-empty: Any args that followed it If command is empty: The unregistered command and ...
Definition: system.h:260
std::string command
The command (if one has been registered with AddCommand), or empty.
Definition: system.h:255
std::string name
Definition: system.cpp:187
bool negated
Definition: system.cpp:189
std::string section
Definition: system.cpp:188
std::string m_name
Definition: system.h:153
Accessor for list of settings that skips negated values when iterated over.
Definition: settings.h:83
size_t negated() const
Number of negated values.
Definition: settings.cpp:238
bool last_negated() const
True if the last value is negated.
Definition: settings.cpp:237
#define LOCK(cs)
Definition: sync.h:226
OptionsCategory
Definition: system.h:133
bool error(const char *fmt, const Args &... args)
Definition: system.h:49
int64_t GetTime()
DEPRECATED Use either GetTimeSeconds (not mockable) or GetTime<T> (mockable)
Definition: time.cpp:26
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:63
static Mutex cs_dir_locks
Mutex to protect dir_locks.
Definition: system.cpp:88
bool HelpRequested(const ArgsManager &args)
Definition: system.cpp:739
static bool GetConfigOptions(std::istream &stream, const std::string &filepath, std::string &error, std::vector< std::pair< std::string, std::string > > &options, std::list< SectionInfo > &sections)
Definition: system.cpp:824
void SetupHelpOptions(ArgsManager &args)
Add help options to the args manager.
Definition: system.cpp:744
fs::path GetDefaultDataDir()
Definition: system.cpp:788
fs::path AbsPathForConfigVal(const fs::path &path, bool net_specific)
Most paths passed as configuration arguments are treated as relative to the datadir if they are not a...
Definition: system.cpp:1368
static const int msgIndent
Definition: system.cpp:752
static void SaveErrors(const std::vector< std::string > errors, std::vector< std::string > *error_out)
Definition: system.cpp:531
int64_t GetStartupTime()
Definition: system.cpp:1363
const char *const BITCOIN_SETTINGS_FILENAME
Definition: system.cpp:83
std::string CopyrightHolders(const std::string &strPrefix)
Definition: system.cpp:1350
bool LockDirectory(const fs::path &directory, const std::string lockfile_name, bool probe_only)
Definition: system.cpp:96
void UnlockDirectory(const fs::path &directory, const std::string &lockfile_name)
Definition: system.cpp:120
bool CheckDataDirOption()
Definition: system.cpp:813
static std::string FormatException(const std::exception *pex, const char *pszThread)
Definition: system.cpp:765
bool DirIsWritable(const fs::path &directory)
Definition: system.cpp:132
bool RenameOver(fs::path src, fs::path dest)
Definition: system.cpp:1065
std::streampos GetFileSize(const char *path, std::streamsize max)
Get the size of a file by scanning it.
Definition: system.cpp:153
bool SetupNetworking()
Definition: system.cpp:1333
UniValue RunCommandParseJSON(const std::string &str_command, const std::string &str_std_in)
Execute a command which returns JSON, and parse the result.
Definition: system.cpp:1257
void ScheduleBatchPriority()
On platforms that support it, tell the kernel the calling thread is CPU-intensive and non-interactive...
Definition: system.cpp:1376
static const int screenWidth
Definition: system.cpp:750
int RaiseFileDescriptorLimit(int nMinFD)
this function tries to raise the file descriptor limit to the requested number.
Definition: system.cpp:1149
void DirectoryCommit(const fs::path &dirname)
Sync directory contents.
Definition: system.cpp:1126
static std::optional< util::SettingsValue > InterpretValue(const KeyInfo &key, const std::string &value, unsigned int flags, std::string &error)
Interpret settings value based on registered flags.
Definition: system.cpp:228
void ReleaseDirectoryLocks()
Release all directory locks.
Definition: system.cpp:126
bool TryCreateDirectories(const fs::path &p)
Ignores exceptions thrown by Boost's create_directories if the requested directory exists.
Definition: system.cpp:1081
void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length)
this function tries to make a particular range of a file allocated (corresponding to disk space) it i...
Definition: system.cpp:1172
ArgsManager gArgs
Definition: system.cpp:85
void SetupEnvironment()
Definition: system.cpp:1296
fs::path GetConfigFile(const std::string &confPath)
Definition: system.cpp:819
void PrintExceptionContinue(const std::exception *pex, const char *pszThread)
Definition: system.cpp:781
static std::string SettingName(const std::string &arg)
Definition: system.cpp:181
std::string HelpMessageGroup(const std::string &message)
Format a string to be used as group of options in help messages.
Definition: system.cpp:754
bool CheckDiskSpace(const fs::path &dir, uint64_t additional_bytes)
Definition: system.cpp:145
KeyInfo InterpretKey(std::string key)
Parse "name", "section.name", "noname", "section.noname" settings keys.
Definition: system.cpp:200
const int64_t nStartupTime
Definition: system.cpp:80
const char *const BITCOIN_CONF_FILENAME
Definition: system.cpp:82
bool TruncateFile(FILE *file, unsigned int length)
Definition: system.cpp:1137
static std::map< std::string, std::unique_ptr< fsbridge::FileLock > > dir_locks GUARDED_BY(cs_dir_locks)
A map that contains all the currently held directory locks.
static bool InterpretBool(const std::string &strValue)
Interpret a string argument as a boolean.
Definition: system.cpp:174
static const int optIndent
Definition: system.cpp:751
int GetNumCores()
Return the number of cores available on the current system.
Definition: system.cpp:1345
std::string HelpMessageOpt(const std::string &option, const std::string &message)
Format a string to be used as option description in help messages.
Definition: system.cpp:758
bool FileCommit(FILE *file)
Ensure file contents are fully committed to disk, using a platform-specific feature analogous to fsyn...
Definition: system.cpp:1095
std::string ShellEscape(const std::string &arg)
Definition: system.cpp:1235
assert(!tx.IsCoinBase())