8 #ifdef ENABLE_EXTERNAL_SIGNER
9 #include <boost/process.hpp>
10 #endif // ENABLE_EXTERNAL_SIGNER
22 #if (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__))
24 #include <pthread_np.h>
31 #ifdef _POSIX_C_SOURCE
32 #undef _POSIX_C_SOURCE
35 #define _POSIX_C_SOURCE 200112L
43 #include <sys/resource.h>
49 #pragma warning(disable:4786)
50 #pragma warning(disable:4804)
51 #pragma warning(disable:4805)
52 #pragma warning(disable:4717)
65 #ifdef HAVE_MALLOPT_ARENA_MAX
69 #include <boost/algorithm/string/replace.hpp>
77 #include <system_error>
101 fs::path pathLockFile = directory / lockfile_name;
110 if (file) fclose(file);
111 auto lock = std::make_unique<fsbridge::FileLock>(pathLockFile);
112 if (!lock->TryLock()) {
113 return error(
"Error while attempting to lock directory %s: %s",
fs::PathToString(directory), lock->GetReason());
139 if (!file)
return false;
149 constexpr uint64_t min_disk_space = 52428800;
151 uint64_t free_bytes_available = fs::space(dir).available;
152 return free_bytes_available >= min_disk_space + additional_bytes;
155 std::streampos
GetFileSize(
const char* path, std::streamsize max) {
156 std::ifstream file{path, std::ios::binary};
158 return file.gcount();
178 if (strValue.empty())
180 return (LocaleIndependentAtoi<int>(strValue) != 0);
185 return arg.size() > 0 && arg[0] ==
'-' ? arg.substr(1) : arg;
206 size_t option_index = key.find(
'.');
207 if (option_index != std::string::npos) {
208 result.
section = key.substr(0, option_index);
209 key.erase(0, option_index + 1);
211 if (key.substr(0, 2) ==
"no") {
236 error =
strprintf(
"Negating of -%s is meaningless and therefore forbidden", key.
name);
241 LogPrintf(
"Warning: parsed potentially confusing double-negative -%s=%s\n", key.
name, value);
257 std::set<std::string> unsuitables;
262 if (m_network.empty())
return std::set<std::string> {};
267 for (
const auto& arg : m_network_only_args) {
269 unsuitables.insert(arg);
278 static const std::set<std::string> available_sections{
286 std::list<SectionInfo> unrecognized = m_config_sections;
287 unrecognized.remove_if([](
const SectionInfo& appeared){
return available_sections.find(appeared.
m_name) != available_sections.end(); });
300 m_settings.command_line_options.clear();
302 for (
int i = 1; i < argc; i++) {
303 std::string key(argv[i]);
310 if (key.substr(0, 5) ==
"-psn_")
continue;
313 if (key ==
"-")
break;
315 size_t is_index = key.find(
'=');
316 if (is_index != std::string::npos) {
317 val = key.substr(is_index + 1);
327 if (!m_accept_any_command &&
m_command.empty()) {
344 if (key.length() > 1 && key[1] ==
'-')
361 if (!value)
return false;
363 m_settings.command_line_options[keyinfo.
name].push_back(*value);
367 if (
auto* includes =
util::FindKey(m_settings.command_line_options,
"includeconf")) {
371 error =
"-includeconf cannot be used from commandline; -includeconf=" +
values.begin()->write();
381 for (
const auto& arg_map : m_available_args) {
382 const auto search = arg_map.second.find(
name);
383 if (search != arg_map.second.end()) {
384 return search->second.m_flags;
394 return result.has_filename() ? result : result.parent_path();
400 fs::path& path = m_cached_blocks_path;
404 if (!path.empty())
return path;
408 if (!fs::is_directory(path)) {
425 fs::path& path = net_specific ? m_cached_network_datadir_path : m_cached_datadir_path;
429 if (!path.empty())
return path;
432 if (!datadir.empty()) {
434 if (!fs::is_directory(path)) {
446 if (net_specific && !
BaseParams().DataDir().empty()) {
461 m_cached_network_datadir_path =
fs::path();
474 if (!m_accept_any_command) {
480 ret.
args.push_back(*(it++));
487 std::vector<std::string> result;
489 result.push_back(value.isFalse() ?
"0" : value.isTrue() ?
"1" : value.get_str());
505 std::vector<std::string> errors;
529 static void SaveErrors(
const std::vector<std::string> errors, std::vector<std::string>* error_out)
531 for (
const auto&
error : errors) {
533 error_out->emplace_back(
error);
548 m_settings.rw_settings.clear();
549 std::vector<std::string> read_errors;
554 for (
const auto& setting : m_settings.rw_settings) {
557 LogPrintf(
"Ignoring unknown rw_settings value %s\n", setting.first);
567 throw std::logic_error(
"Attempt to write settings file when dynamic settings are disabled.");
571 std::vector<std::string> write_errors;
625 m_settings.forced_settings[
SettingName(strArg)] = strValue;
630 Assert(cmd.find(
'=') == std::string::npos);
634 m_accept_any_command =
false;
645 size_t eq_index =
name.find(
'=');
646 if (eq_index == std::string::npos) {
647 eq_index =
name.size();
649 std::string arg_name =
name.substr(0, eq_index);
652 std::map<std::string, Arg>& arg_map = m_available_args[cat];
653 auto ret = arg_map.emplace(arg_name,
Arg{
name.substr(eq_index,
name.size() - eq_index),
help,
flags});
657 m_network_only_args.emplace(arg_name);
663 for (
const std::string&
name : names) {
670 const bool show_debug =
GetBoolArg(
"-help-debug",
false);
672 std::string usage =
"";
674 for (
const auto& arg_map : m_available_args) {
675 switch(arg_map.first) {
701 if (show_debug) usage +=
HelpMessageGroup(
"Wallet debugging/testing options:");
722 for (
const auto& arg : arg_map.second) {
725 if (arg.second.m_help_param.empty()) {
728 name = arg.first + arg.second.m_help_param;
753 return std::string(message) + std::string(
"\n\n");
756 std::string
HelpMessageOpt(
const std::string &option,
const std::string &message) {
757 return std::string(
optIndent,
' ') + std::string(option) +
758 std::string(
"\n") + std::string(
msgIndent,
' ') +
767 GetModuleFileNameA(
nullptr, pszModule,
sizeof(pszModule));
769 const char* pszModule =
"bitcoin";
773 "EXCEPTION: %s \n%s \n%s in %s \n",
typeid(*pex).name(), pex->what(), pszModule, pszThread);
776 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
782 LogPrintf(
"\n\n************************\n%s\n", message);
783 tfm::format(std::cerr,
"\n\n************************\n%s\n", message);
793 return GetSpecialFolderPath(CSIDL_APPDATA) /
"Bitcoin";
796 char* pszHome = getenv(
"HOME");
797 if (pszHome ==
nullptr || strlen(pszHome) == 0)
803 return pathRet /
"Library/Application Support/Bitcoin";
806 return pathRet /
".bitcoin";
814 return datadir.empty() || fs::is_directory(
fs::absolute(datadir));
822 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)
825 std::string::size_type pos;
827 while (std::getline(stream, str)) {
828 bool used_hash =
false;
829 if ((pos = str.find(
'#')) != std::string::npos) {
830 str = str.substr(0, pos);
833 const static std::string pattern =
" \t\r\n";
836 if (*str.begin() ==
'[' && *str.rbegin() ==
']') {
837 const std::string section = str.substr(1, str.size() - 2);
838 sections.emplace_back(
SectionInfo{section, filepath, linenr});
840 }
else if (*str.begin() ==
'-') {
841 error =
strprintf(
"parse error on line %i: %s, options in configuration file must be specified without leading -", linenr, str);
843 }
else if ((pos = str.find(
'=')) != std::string::npos) {
845 std::string value =
TrimString(str.substr(pos + 1), pattern);
846 if (used_hash &&
name.find(
"rpcpassword") != std::string::npos) {
847 error =
strprintf(
"parse error on line %i, using # in rpcpassword can be ambiguous and should be avoided", linenr);
850 options.emplace_back(
name, value);
851 if ((pos =
name.rfind(
'.')) != std::string::npos &&
prefix.length() <= pos) {
852 sections.emplace_back(
SectionInfo{
name.substr(0, pos), filepath, linenr});
856 if (str.size() >= 2 && str.substr(0, 2) ==
"no") {
857 error +=
strprintf(
", if you intended to specify a negated option, use %s=1 instead", str);
870 std::vector<std::pair<std::string, std::string>> options;
874 for (
const std::pair<std::string, std::string>& option : options) {
882 m_settings.ro_config[key.
section][key.
name].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();
907 if (
IsArgSet(
"-conf") && !stream.good()) {
908 error =
strprintf(
"specified config file \"%s\" could not be opened.", confPath);
918 bool use_conf_file{
true};
921 if (
auto* includes =
util::FindKey(m_settings.command_line_options,
"includeconf")) {
924 use_conf_file =
false;
929 std::vector<std::string> conf_file_names;
931 auto add_includes = [&](
const std::string& network,
size_t skip = 0) {
932 size_t num_values = 0;
934 if (
auto* section =
util::FindKey(m_settings.ro_config, network)) {
937 conf_file_names.push_back((*
values)[i].get_str());
939 num_values =
values->size();
947 const size_t chain_includes = add_includes(chain_id);
948 const size_t default_includes = add_includes({});
950 for (
const std::string& conf_file_name : conf_file_names) {
951 std::ifstream conf_file_stream{
GetConfigFile(conf_file_name)};
952 if (conf_file_stream.good()) {
956 LogPrintf(
"Included configuration file %s\n", conf_file_name);
958 error =
"Failed to include configuration file " + conf_file_name;
964 conf_file_names.clear();
965 add_includes(chain_id, chain_includes);
966 add_includes({}, default_includes);
968 if (chain_id_final != chain_id) {
970 add_includes(chain_id_final);
972 for (
const std::string& conf_file_name : conf_file_names) {
973 tfm::format(std::cerr,
"warning: -includeconf cannot be used from included files; ignoring -includeconf=%s\n", conf_file_name);
989 auto get_net = [&](
const std::string& arg) {
997 const bool fRegTest = get_net(
"-regtest");
998 const bool fSigNet = get_net(
"-signet");
999 const bool fTestNet = get_net(
"-testnet");
1000 const bool is_chain_arg_set =
IsArgSet(
"-chain");
1002 if ((
int)is_chain_arg_set + (
int)fRegTest + (
int)fSigNet + (
int)fTestNet > 1) {
1003 throw std::runtime_error(
"Invalid combination of -regtest, -signet, -testnet and -chain. Can use at most one.");
1035 const std::string&
prefix,
1036 const std::string& section,
1037 const std::map<std::string, std::vector<util::SettingsValue>>&
args)
const
1039 std::string section_str = section.empty() ?
"" :
"[" + section +
"] ";
1040 for (
const auto& arg :
args) {
1041 for (
const auto& value : arg.second) {
1044 std::string value_str = (*
flags &
SENSITIVE) ?
"****" : value.write();
1054 for (
const auto& section : m_settings.ro_config) {
1055 logArgsPrefix(
"Config file arg:", section.first, section.second);
1057 for (
const auto& setting : m_settings.rw_settings) {
1058 LogPrintf(
"Setting file arg: %s = %s\n", setting.first, setting.second.write());
1060 logArgsPrefix(
"Command-line arg:",
"", m_settings.command_line_options);
1072 return MoveFileExW(src.wstring().c_str(), dest.wstring().c_str(),
1073 MOVEFILE_REPLACE_EXISTING) != 0;
1075 std::error_code
error;
1076 fs::rename(src, dest,
error);
1091 }
catch (
const fs::filesystem_error&) {
1102 if (fflush(file) != 0) {
1103 LogPrintf(
"%s: fflush failed: %d\n", __func__, errno);
1107 HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
1108 if (FlushFileBuffers(hFile) == 0) {
1109 LogPrintf(
"%s: FlushFileBuffers failed: %d\n", __func__, GetLastError());
1112 #elif defined(MAC_OSX) && defined(F_FULLFSYNC)
1113 if (fcntl(fileno(file), F_FULLFSYNC, 0) == -1) {
1114 LogPrintf(
"%s: fcntl F_FULLFSYNC failed: %d\n", __func__, errno);
1117 #elif HAVE_FDATASYNC
1118 if (fdatasync(fileno(file)) != 0 && errno != EINVAL) {
1119 LogPrintf(
"%s: fdatasync failed: %d\n", __func__, errno);
1123 if (fsync(fileno(file)) != 0 && errno != EINVAL) {
1124 LogPrintf(
"%s: fsync failed: %d\n", __func__, errno);
1136 fsync(fileno(file));
1144 return _chsize(_fileno(file), length) == 0;
1146 return ftruncate(fileno(file), length) == 0;
1158 struct rlimit limitFD;
1159 if (getrlimit(RLIMIT_NOFILE, &limitFD) != -1) {
1160 if (limitFD.rlim_cur < (rlim_t)nMinFD) {
1161 limitFD.rlim_cur = nMinFD;
1162 if (limitFD.rlim_cur > limitFD.rlim_max)
1163 limitFD.rlim_cur = limitFD.rlim_max;
1164 setrlimit(RLIMIT_NOFILE, &limitFD);
1165 getrlimit(RLIMIT_NOFILE, &limitFD);
1167 return limitFD.rlim_cur;
1180 HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
1181 LARGE_INTEGER nFileSize;
1182 int64_t nEndPos = (int64_t)offset + length;
1183 nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF;
1184 nFileSize.u.HighPart = nEndPos >> 32;
1185 SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN);
1186 SetEndOfFile(hFile);
1187 #elif defined(MAC_OSX)
1192 fst.fst_flags = F_ALLOCATECONTIG;
1193 fst.fst_posmode = F_PEOFPOSMODE;
1195 fst.fst_length = length;
1196 fst.fst_bytesalloc = 0;
1197 if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) {
1198 fst.fst_flags = F_ALLOCATEALL;
1199 fcntl(fileno(file), F_PREALLOCATE, &fst);
1201 ftruncate(fileno(file),
static_cast<off_t
>(offset) + length);
1203 #if defined(HAVE_POSIX_FALLOCATE)
1205 off_t nEndPos = (off_t)offset + length;
1206 if (0 == posix_fallocate(fileno(file), 0, nEndPos))
return;
1210 static const char buf[65536] = {};
1211 if (fseek(file, offset, SEEK_SET)) {
1214 while (length > 0) {
1215 unsigned int now = 65536;
1218 fwrite(buf, 1, now, file);
1225 fs::path GetSpecialFolderPath(
int nFolder,
bool fCreate)
1229 if(SHGetSpecialFolderPathW(
nullptr, pszPath, nFolder, fCreate))
1234 LogPrintf(
"SHGetSpecialFolderPathW() failed, could not obtain requested path.\n");
1242 std::string escaped = arg;
1243 boost::replace_all(escaped,
"'",
"'\"'\"'");
1244 return "'" + escaped +
"'";
1249 void runCommand(
const std::string& strCommand)
1251 if (strCommand.empty())
return;
1253 int nErr = ::system(strCommand.c_str());
1255 int nErr = ::_wsystem(std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>,
wchar_t>().from_bytes(strCommand).c_str());
1258 LogPrintf(
"runCommand error: system(%s) returned %d\n", strCommand, nErr);
1264 #ifdef ENABLE_EXTERNAL_SIGNER
1265 namespace bp = boost::process;
1268 bp::opstream stdin_stream;
1269 bp::ipstream stdout_stream;
1270 bp::ipstream stderr_stream;
1276 bp::std_out > stdout_stream,
1277 bp::std_err > stderr_stream,
1278 bp::std_in < stdin_stream
1280 if (!str_std_in.empty()) {
1281 stdin_stream << str_std_in << std::endl;
1283 stdin_stream.pipe().close();
1287 std::getline(stdout_stream, result);
1288 std::getline(stderr_stream,
error);
1291 const int n_error = c.exit_code();
1292 if (n_error)
throw std::runtime_error(
strprintf(
"RunCommandParseJSON error: process(%s) returned %d: %s\n", str_command, n_error,
error));
1293 if (!result_json.
read(result))
throw std::runtime_error(
"Unable to parse JSON: " + result);
1297 throw std::runtime_error(
"Compiled without external signing support (required for external signing).");
1298 #endif // ENABLE_EXTERNAL_SIGNER
1303 #ifdef HAVE_MALLOPT_ARENA_MAX
1309 if (
sizeof(
void*) == 4) {
1310 mallopt(M_ARENA_MAX, 1);
1315 #if !defined(WIN32) && !defined(MAC_OSX) && !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
1318 }
catch (
const std::runtime_error&) {
1319 setenv(
"LC_ALL",
"C.UTF-8", 1);
1321 #elif defined(WIN32)
1323 SetConsoleCP(CP_UTF8);
1324 SetConsoleOutputCP(CP_UTF8);
1333 int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
1334 if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2)
1342 return std::thread::hardware_concurrency();
1348 std::string strCopyrightHolders = strPrefix + copyright_devs;
1351 if (copyright_devs.find(
"Bitcoin Core") == std::string::npos) {
1352 strCopyrightHolders +=
"\n" + strPrefix +
"The Bitcoin Core developers";
1354 return strCopyrightHolders;
1365 if (path.is_absolute()) {
1374 const static sched_param param{};
1375 const int rc = pthread_setschedparam(pthread_self(), SCHED_BATCH, ¶m);
1377 LogPrintf(
"Failed to pthread_setschedparam: %s\n", strerror(rc));
1384 WinCmdLineArgs::WinCmdLineArgs()
1386 wchar_t** wargv = CommandLineToArgvW(GetCommandLineW(), &argc);
1387 std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>,
wchar_t> utf8_cvt;
1388 argv =
new char*[argc];
1390 for (
int i = 0; i < argc; i++) {
1391 args[i] = utf8_cvt.to_bytes(wargv[i]);
1392 argv[i] = &*
args[i].begin();
1397 WinCmdLineArgs::~WinCmdLineArgs()
1402 std::pair<int, char**> WinCmdLineArgs::get()
1404 return std::make_pair(argc, argv);