8 #ifdef ENABLE_EXTERNAL_SIGNER
9 #include <boost/process.hpp>
10 #endif // ENABLE_EXTERNAL_SIGNER
21 #if (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__))
23 #include <pthread_np.h>
30 #ifdef _POSIX_C_SOURCE
31 #undef _POSIX_C_SOURCE
34 #define _POSIX_C_SOURCE 200112L
42 #include <sys/resource.h>
48 #pragma warning(disable:4786)
49 #pragma warning(disable:4804)
50 #pragma warning(disable:4805)
51 #pragma warning(disable:4717)
64 #ifdef HAVE_MALLOPT_ARENA_MAX
68 #include <boost/algorithm/string/replace.hpp>
90 bool LockDirectory(
const fs::path& directory,
const std::string lockfile_name,
bool probe_only)
93 fs::path pathLockFile = directory / lockfile_name;
96 if (dir_locks.count(pathLockFile.string())) {
102 if (file) fclose(file);
103 auto lock = std::make_unique<fsbridge::FileLock>(pathLockFile);
104 if (!lock->TryLock()) {
105 return error(
"Error while attempting to lock directory %s: %s", directory.string(), lock->GetReason());
109 dir_locks.emplace(pathLockFile.string(), std::move(lock));
117 dir_locks.erase((directory / lockfile_name).
string());
131 if (!file)
return false;
141 constexpr uint64_t min_disk_space = 52428800;
143 uint64_t free_bytes_available = fs::space(dir).available;
144 return free_bytes_available >= min_disk_space + additional_bytes;
147 std::streampos
GetFileSize(
const char* path, std::streamsize max) {
150 return file.gcount();
172 if (strValue.empty())
174 return (
atoi(strValue) != 0);
179 return arg.size() > 0 && arg[0] ==
'-' ? arg.substr(1) : arg;
205 size_t option_index = key.find(
'.');
206 if (option_index != std::string::npos) {
207 section = key.substr(0, option_index);
208 key.erase(0, option_index + 1);
210 if (key.substr(0, 2) ==
"no") {
214 LogPrintf(
"Warning: parsed potentially confusing double-negative -%s=%s\n", key, value);
232 error =
strprintf(
"Negating of -%s is meaningless and therefore forbidden", key);
246 std::set<std::string> unsuitables;
251 if (m_network.empty())
return std::set<std::string> {};
256 for (
const auto& arg : m_network_only_args) {
258 unsuitables.insert(arg);
267 static const std::set<std::string> available_sections{
275 std::list<SectionInfo> unrecognized = m_config_sections;
276 unrecognized.remove_if([](
const SectionInfo& appeared){
return available_sections.find(appeared.
m_name) != available_sections.end(); });
289 m_settings.command_line_options.clear();
291 for (
int i = 1; i < argc; i++) {
292 std::string key(argv[i]);
299 if (key.substr(0, 5) ==
"-psn_")
continue;
302 if (key ==
"-")
break;
304 size_t is_index = key.find(
'=');
305 if (is_index != std::string::npos) {
306 val = key.substr(is_index + 1);
316 if (!m_accept_any_command &&
m_command.empty()) {
333 if (key.length() > 1 && key[1] ==
'-')
345 if (!
flags || !section.empty()) {
352 m_settings.command_line_options[key].push_back(value);
357 if (
auto* includes =
util::FindKey(m_settings.command_line_options,
"includeconf")) {
359 error +=
"-includeconf cannot be used from commandline; -includeconf=" + include.get_str() +
"\n";
369 for (
const auto& arg_map : m_available_args) {
370 const auto search = arg_map.second.find(
name);
371 if (search != arg_map.second.end()) {
372 return search->second.m_flags;
387 if (!m_accept_any_command) {
393 ret.
args.push_back(*(
it++));
400 std::vector<std::string> result;
402 result.push_back(value.isFalse() ?
"0" : value.isTrue() ?
"1" : value.get_str());
418 std::vector<std::string> errors;
442 static void SaveErrors(
const std::vector<std::string> errors, std::vector<std::string>* error_out)
444 for (
const auto&
error : errors) {
446 error_out->emplace_back(
error);
461 m_settings.rw_settings.clear();
462 std::vector<std::string> read_errors;
467 for (
const auto& setting : m_settings.rw_settings) {
469 std::string key = setting.first;
472 LogPrintf(
"Ignoring unknown rw_settings value %s\n", setting.first);
480 fs::path path, path_tmp;
482 throw std::logic_error(
"Attempt to write settings file when dynamic settings are disabled.");
486 std::vector<std::string> write_errors;
492 SaveErrors({
strprintf(
"Failed renaming settings file %s to %s\n", path_tmp.string(), path.string())}, errors);
540 m_settings.forced_settings[
SettingName(strArg)] = strValue;
545 Assert(cmd.find(
'=') == std::string::npos);
549 m_accept_any_command =
false;
550 std::map<std::string, Arg>& arg_map = m_available_args[cat];
560 size_t eq_index =
name.find(
'=');
561 if (eq_index == std::string::npos) {
562 eq_index =
name.size();
564 std::string arg_name =
name.substr(0, eq_index);
567 std::map<std::string, Arg>& arg_map = m_available_args[cat];
568 auto ret = arg_map.emplace(arg_name,
Arg{
name.substr(eq_index,
name.size() - eq_index),
help,
flags});
572 m_network_only_args.emplace(arg_name);
578 for (
const std::string&
name : names) {
585 const bool show_debug =
GetBoolArg(
"-help-debug",
false);
587 std::string usage =
"";
589 for (
const auto& arg_map : m_available_args) {
590 switch(arg_map.first) {
616 if (show_debug) usage +=
HelpMessageGroup(
"Wallet debugging/testing options:");
637 for (
const auto& arg : arg_map.second) {
640 if (arg.second.m_help_param.empty()) {
643 name = arg.first + arg.second.m_help_param;
668 return std::string(message) + std::string(
"\n\n");
671 std::string
HelpMessageOpt(
const std::string &option,
const std::string &message) {
672 return std::string(
optIndent,
' ') + std::string(option) +
673 std::string(
"\n") + std::string(
msgIndent,
' ') +
682 GetModuleFileNameA(
nullptr, pszModule,
sizeof(pszModule));
684 const char* pszModule =
"bitcoin";
688 "EXCEPTION: %s \n%s \n%s in %s \n",
typeid(*pex).name(), pex->what(), pszModule, pszThread);
691 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
697 LogPrintf(
"\n\n************************\n%s\n", message);
698 tfm::format(std::cerr,
"\n\n************************\n%s\n", message);
708 return GetSpecialFolderPath(CSIDL_APPDATA) /
"Bitcoin";
711 char* pszHome = getenv(
"HOME");
712 if (pszHome ==
nullptr || strlen(pszHome) == 0)
713 pathRet = fs::path(
"/");
715 pathRet = fs::path(pszHome);
718 return pathRet /
"Library/Application Support/Bitcoin";
721 return pathRet /
".bitcoin";
727 fs::path StripRedundantLastElementsOfPath(
const fs::path& path)
730 while (result.filename().string() ==
".") {
731 result = result.parent_path();
734 assert(fs::equivalent(result, path));
751 if (!path.empty())
return path;
754 path = fs::system_complete(
gArgs.
GetArg(
"-blocksdir",
""));
755 if (!fs::is_directory(path)) {
765 fs::create_directories(path);
766 path = StripRedundantLastElementsOfPath(path);
777 if (!path.empty())
return path;
779 std::string datadir =
gArgs.
GetArg(
"-datadir",
"");
780 if (!datadir.empty()) {
781 path = fs::system_complete(datadir);
782 if (!fs::is_directory(path)) {
792 if (fs::create_directories(path)) {
794 fs::create_directories(path /
"wallets");
797 path = StripRedundantLastElementsOfPath(path);
803 std::string datadir =
gArgs.
GetArg(
"-datadir",
"");
804 return datadir.empty() || fs::is_directory(fs::system_complete(datadir));
821 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)
824 std::string::size_type pos;
826 while (std::getline(stream, str)) {
827 bool used_hash =
false;
828 if ((pos = str.find(
'#')) != std::string::npos) {
829 str = str.substr(0, pos);
832 const static std::string pattern =
" \t\r\n";
835 if (*str.begin() ==
'[' && *str.rbegin() ==
']') {
836 const std::string section = str.substr(1, str.size() - 2);
837 sections.emplace_back(
SectionInfo{section, filepath, linenr});
839 }
else if (*str.begin() ==
'-') {
840 error =
strprintf(
"parse error on line %i: %s, options in configuration file must be specified without leading -", linenr, str);
842 }
else if ((pos = str.find(
'=')) != std::string::npos) {
844 std::string value =
TrimString(str.substr(pos + 1), pattern);
845 if (used_hash &&
name.find(
"rpcpassword") != std::string::npos) {
846 error =
strprintf(
"parse error on line %i, using # in rpcpassword can be ambiguous and should be avoided", linenr);
849 options.emplace_back(
name, value);
850 if ((pos =
name.rfind(
'.')) != std::string::npos &&
prefix.length() <= pos) {
851 sections.emplace_back(
SectionInfo{
name.substr(0, pos), filepath, linenr});
855 if (str.size() >= 2 && str.substr(0, 2) ==
"no") {
856 error +=
strprintf(
", if you intended to specify a negated option, use %s=1 instead", str);
869 std::vector<std::pair<std::string, std::string>> options;
873 for (
const std::pair<std::string, std::string>& option : options) {
875 std::string key = option.first;
882 m_settings.ro_config[section][key].push_back(value);
884 if (ignore_invalid_keys) {
885 LogPrintf(
"Ignoring unknown configuration value %s\n", option.first);
887 error =
strprintf(
"Invalid configuration value %s", option.first);
899 m_settings.ro_config.clear();
900 m_config_sections.clear();
913 bool use_conf_file{
true};
916 if (
auto* includes =
util::FindKey(m_settings.command_line_options,
"includeconf")) {
919 use_conf_file =
false;
924 std::vector<std::string> conf_file_names;
926 auto add_includes = [&](
const std::string& network,
size_t skip = 0) {
927 size_t num_values = 0;
929 if (
auto* section =
util::FindKey(m_settings.ro_config, network)) {
932 conf_file_names.push_back((*values)[i].get_str());
934 num_values = values->size();
942 const size_t chain_includes = add_includes(chain_id);
943 const size_t default_includes = add_includes({});
945 for (
const std::string& conf_file_name : conf_file_names) {
947 if (conf_file_stream.good()) {
951 LogPrintf(
"Included configuration file %s\n", conf_file_name);
953 error =
"Failed to include configuration file " + conf_file_name;
959 conf_file_names.clear();
960 add_includes(chain_id, chain_includes);
961 add_includes({}, default_includes);
963 if (chain_id_final != chain_id) {
965 add_includes(chain_id_final);
967 for (
const std::string& conf_file_name : conf_file_names) {
968 tfm::format(std::cerr,
"warning: -includeconf cannot be used from included files; ignoring -includeconf=%s\n", conf_file_name);
984 auto get_net = [&](
const std::string& arg) {
992 const bool fRegTest = get_net(
"-regtest");
993 const bool fSigNet = get_net(
"-signet");
994 const bool fTestNet = get_net(
"-testnet");
995 const bool is_chain_arg_set =
IsArgSet(
"-chain");
997 if ((
int)is_chain_arg_set + (
int)fRegTest + (
int)fSigNet + (
int)fTestNet > 1) {
998 throw std::runtime_error(
"Invalid combination of -regtest, -signet, -testnet and -chain. Can use at most one.");
1030 const std::string&
prefix,
1031 const std::string& section,
1032 const std::map<std::string, std::vector<util::SettingsValue>>& args)
const
1034 std::string section_str = section.empty() ?
"" :
"[" + section +
"] ";
1035 for (
const auto& arg : args) {
1036 for (
const auto& value : arg.second) {
1039 std::string value_str = (*
flags &
SENSITIVE) ?
"****" : value.write();
1049 for (
const auto& section : m_settings.ro_config) {
1050 logArgsPrefix(
"Config file arg:", section.first, section.second);
1052 for (
const auto& setting : m_settings.rw_settings) {
1053 LogPrintf(
"Setting file arg: %s = %s\n", setting.first, setting.second.write());
1055 logArgsPrefix(
"Command-line arg:",
"", m_settings.command_line_options);
1061 return MoveFileExW(src.wstring().c_str(), dest.wstring().c_str(),
1062 MOVEFILE_REPLACE_EXISTING) != 0;
1064 int rc = std::rename(src.string().c_str(), dest.string().c_str());
1078 return fs::create_directories(p);
1079 }
catch (
const fs::filesystem_error&) {
1080 if (!fs::exists(p) || !fs::is_directory(p))
1090 if (fflush(file) != 0) {
1091 LogPrintf(
"%s: fflush failed: %d\n", __func__, errno);
1095 HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
1096 if (FlushFileBuffers(hFile) == 0) {
1097 LogPrintf(
"%s: FlushFileBuffers failed: %d\n", __func__, GetLastError());
1100 #elif defined(MAC_OSX) && defined(F_FULLFSYNC)
1101 if (fcntl(fileno(file), F_FULLFSYNC, 0) == -1) {
1102 LogPrintf(
"%s: fcntl F_FULLFSYNC failed: %d\n", __func__, errno);
1105 #elif HAVE_FDATASYNC
1106 if (fdatasync(fileno(file)) != 0 && errno != EINVAL) {
1107 LogPrintf(
"%s: fdatasync failed: %d\n", __func__, errno);
1111 if (fsync(fileno(file)) != 0 && errno != EINVAL) {
1112 LogPrintf(
"%s: fsync failed: %d\n", __func__, errno);
1124 fsync(fileno(file));
1132 return _chsize(_fileno(file), length) == 0;
1134 return ftruncate(fileno(file), length) == 0;
1146 struct rlimit limitFD;
1147 if (getrlimit(RLIMIT_NOFILE, &limitFD) != -1) {
1148 if (limitFD.rlim_cur < (rlim_t)nMinFD) {
1149 limitFD.rlim_cur = nMinFD;
1150 if (limitFD.rlim_cur > limitFD.rlim_max)
1151 limitFD.rlim_cur = limitFD.rlim_max;
1152 setrlimit(RLIMIT_NOFILE, &limitFD);
1153 getrlimit(RLIMIT_NOFILE, &limitFD);
1155 return limitFD.rlim_cur;
1168 HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
1169 LARGE_INTEGER nFileSize;
1170 int64_t nEndPos = (int64_t)offset + length;
1171 nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF;
1172 nFileSize.u.HighPart = nEndPos >> 32;
1173 SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN);
1174 SetEndOfFile(hFile);
1175 #elif defined(MAC_OSX)
1180 fst.fst_flags = F_ALLOCATECONTIG;
1181 fst.fst_posmode = F_PEOFPOSMODE;
1183 fst.fst_length = length;
1184 fst.fst_bytesalloc = 0;
1185 if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) {
1186 fst.fst_flags = F_ALLOCATEALL;
1187 fcntl(fileno(file), F_PREALLOCATE, &fst);
1189 ftruncate(fileno(file),
static_cast<off_t
>(offset) + length);
1191 #if defined(HAVE_POSIX_FALLOCATE)
1193 off_t nEndPos = (off_t)offset + length;
1194 if (0 == posix_fallocate(fileno(file), 0, nEndPos))
return;
1198 static const char buf[65536] = {};
1199 if (fseek(file, offset, SEEK_SET)) {
1202 while (length > 0) {
1203 unsigned int now = 65536;
1206 fwrite(buf, 1, now, file);
1213 fs::path GetSpecialFolderPath(
int nFolder,
bool fCreate)
1217 if(SHGetSpecialFolderPathW(
nullptr, pszPath, nFolder, fCreate))
1219 return fs::path(pszPath);
1222 LogPrintf(
"SHGetSpecialFolderPathW() failed, could not obtain requested path.\n");
1223 return fs::path(
"");
1230 std::string escaped = arg;
1231 boost::replace_all(escaped,
"'",
"'\"'\"'");
1232 return "'" + escaped +
"'";
1237 void runCommand(
const std::string& strCommand)
1239 if (strCommand.empty())
return;
1241 int nErr = ::system(strCommand.c_str());
1243 int nErr = ::_wsystem(std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>,
wchar_t>().from_bytes(strCommand).c_str());
1246 LogPrintf(
"runCommand error: system(%s) returned %d\n", strCommand, nErr);
1250 #ifdef ENABLE_EXTERNAL_SIGNER
1253 namespace bp = boost::process;
1256 bp::opstream stdin_stream;
1257 bp::ipstream stdout_stream;
1258 bp::ipstream stderr_stream;
1264 bp::std_out > stdout_stream,
1265 bp::std_err > stderr_stream,
1266 bp::std_in < stdin_stream
1268 if (!str_std_in.empty()) {
1269 stdin_stream << str_std_in << std::endl;
1271 stdin_stream.pipe().close();
1275 std::getline(stdout_stream, result);
1276 std::getline(stderr_stream,
error);
1279 const int n_error = c.exit_code();
1280 if (n_error)
throw std::runtime_error(
strprintf(
"RunCommandParseJSON error: process(%s) returned %d: %s\n", str_command, n_error,
error));
1281 if (!result_json.
read(result))
throw std::runtime_error(
"Unable to parse JSON: " + result);
1285 #endif // ENABLE_EXTERNAL_SIGNER
1289 #ifdef HAVE_MALLOPT_ARENA_MAX
1295 if (
sizeof(
void*) == 4) {
1296 mallopt(M_ARENA_MAX, 1);
1301 #if !defined(WIN32) && !defined(MAC_OSX) && !defined(__FreeBSD__) && !defined(__OpenBSD__)
1304 }
catch (
const std::runtime_error&) {
1305 setenv(
"LC_ALL",
"C.UTF-8", 1);
1307 #elif defined(WIN32)
1309 SetConsoleCP(CP_UTF8);
1310 SetConsoleOutputCP(CP_UTF8);
1316 std::locale loc = fs::path::imbue(std::locale::classic());
1318 fs::path::imbue(loc);
1320 fs::path::imbue(std::locale(loc,
new std::codecvt_utf8_utf16<wchar_t>()));
1329 int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
1330 if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2)
1338 return std::thread::hardware_concurrency();
1344 std::string strCopyrightHolders = strPrefix + copyright_devs;
1347 if (copyright_devs.find(
"Bitcoin Core") == std::string::npos) {
1348 strCopyrightHolders +=
"\n" + strPrefix +
"The Bitcoin Core developers";
1350 return strCopyrightHolders;
1361 if (path.is_absolute()) {
1370 const static sched_param param{};
1371 const int rc = pthread_setschedparam(pthread_self(), SCHED_BATCH, ¶m);
1373 LogPrintf(
"Failed to pthread_setschedparam: %s\n", strerror(rc));
1380 WinCmdLineArgs::WinCmdLineArgs()
1382 wchar_t** wargv = CommandLineToArgvW(GetCommandLineW(), &argc);
1383 std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>,
wchar_t> utf8_cvt;
1384 argv =
new char*[argc];
1386 for (
int i = 0; i < argc; i++) {
1387 args[i] = utf8_cvt.to_bytes(wargv[i]);
1388 argv[i] = &*args[i].begin();
1393 WinCmdLineArgs::~WinCmdLineArgs()
1398 std::pair<int, char**> WinCmdLineArgs::get()
1400 return std::make_pair(argc, argv);