Page MenuHomePhabricator

D2016.diff
No OneTemporary

D2016.diff

diff --git a/src/addrman.h b/src/addrman.h
--- a/src/addrman.h
+++ b/src/addrman.h
@@ -536,7 +536,8 @@
LOCK(cs);
int err;
if ((err = Check_())) {
- LogPrintf("ADDRMAN CONSISTENCY CHECK FAILED!!! err=%i\n", err);
+ LogPrint(BCLog::ADDRMAN,
+ "ADDRMAN CONSISTENCY CHECK FAILED!!! err=%i\n", err);
}
}
#endif
diff --git a/src/dbwrapper.h b/src/dbwrapper.h
--- a/src/dbwrapper.h
+++ b/src/dbwrapper.h
@@ -231,7 +231,8 @@
leveldb::Status status = pdb->Get(readoptions, slKey, &strValue);
if (!status.ok()) {
if (status.IsNotFound()) return false;
- LogPrintf("LevelDB read failure: %s\n", status.ToString());
+ LogPrint(BCLog::LEVELDB, "LevelDB read failure: %s\n",
+ status.ToString());
dbwrapper_private::HandleError(status);
}
try {
@@ -263,7 +264,8 @@
leveldb::Status status = pdb->Get(readoptions, slKey, &strValue);
if (!status.ok()) {
if (status.IsNotFound()) return false;
- LogPrintf("LevelDB read failure: %s\n", status.ToString());
+ LogPrint(BCLog::LEVELDB, "LevelDB read failure: %s\n",
+ status.ToString());
dbwrapper_private::HandleError(status);
}
return true;
diff --git a/src/dbwrapper.cpp b/src/dbwrapper.cpp
--- a/src/dbwrapper.cpp
+++ b/src/dbwrapper.cpp
@@ -65,7 +65,7 @@
assert(p <= limit);
base[std::min(bufsize - 1, (int)(p - base))] = '\0';
- LogPrintf("leveldb: %s", base);
+ LogPrint(BCLog::LEVELDB, "leveldb: %s", base);
if (base != buffer) {
delete[] base;
}
@@ -106,21 +106,23 @@
options.env = penv;
} else {
if (fWipe) {
- LogPrintf("Wiping LevelDB in %s\n", path.string());
+ LogPrint(BCLog::LEVELDB, "Wiping LevelDB in %s\n", path.string());
leveldb::Status result = leveldb::DestroyDB(path.string(), options);
dbwrapper_private::HandleError(result);
}
TryCreateDirectories(path);
- LogPrintf("Opening LevelDB in %s\n", path.string());
+ LogPrint(BCLog::LEVELDB, "Opening LevelDB in %s\n", path.string());
}
leveldb::Status status = leveldb::DB::Open(options, path.string(), &pdb);
dbwrapper_private::HandleError(status);
- LogPrintf("Opened LevelDB successfully\n");
+ LogPrint(BCLog::LEVELDB, "Opened LevelDB successfully\n");
if (gArgs.GetBoolArg("-forcecompactdb", false)) {
- LogPrintf("Starting database compaction of %s\n", path.string());
+ LogPrint(BCLog::LEVELDB, "Starting database compaction of %s\n",
+ path.string());
pdb->CompactRange(nullptr, nullptr);
- LogPrintf("Finished database compaction of %s\n", path.string());
+ LogPrint(BCLog::LEVELDB, "Finished database compaction of %s\n",
+ path.string());
}
// The base-case obfuscation key, which is a noop.
@@ -137,12 +139,12 @@
Write(OBFUSCATE_KEY_KEY, new_key);
obfuscate_key = new_key;
- LogPrintf("Wrote new obfuscate key for %s: %s\n", path.string(),
- HexStr(obfuscate_key));
+ LogPrint(BCLog::LEVELDB, "Wrote new obfuscate key for %s: %s\n",
+ path.string(), HexStr(obfuscate_key));
}
- LogPrintf("Using obfuscation key for %s: %s\n", path.string(),
- HexStr(obfuscate_key));
+ LogPrint(BCLog::LEVELDB, "Using obfuscation key for %s: %s\n",
+ path.string(), HexStr(obfuscate_key));
}
CDBWrapper::~CDBWrapper() {
@@ -208,7 +210,7 @@
if (status.ok()) {
return;
}
- LogPrintf("%s\n", status.ToString());
+ LogPrint(BCLog::LEVELDB, "%s\n", status.ToString());
if (status.IsCorruption()) {
throw dbwrapper_error("Database corrupted");
}
diff --git a/src/httprpc.cpp b/src/httprpc.cpp
--- a/src/httprpc.cpp
+++ b/src/httprpc.cpp
@@ -296,8 +296,9 @@
JSONRPCRequest jreq;
if (!RPCAuthorized(config, authHeader.second, jreq.authUser)) {
- LogPrintf("ThreadRPCServer incorrect password attempt from %s\n",
- req->GetPeer().ToString());
+ LogPrint(BCLog::RPC,
+ "ThreadRPCServer incorrect password attempt from %s\n",
+ req->GetPeer().ToString());
/**
* Deter brute-forcing.
@@ -351,7 +352,8 @@
static bool InitRPCAuthentication(Config &config) {
if (gArgs.GetArg("-rpcpassword", "") == "") {
- LogPrintf("No rpcpassword set - using random cookie authentication\n");
+ LogPrint(BCLog::RPC,
+ "No rpcpassword set - using random cookie authentication\n");
std::string generatedUserAndPassword;
if (!GenerateAuthCookie(&generatedUserAndPassword)) {
// Same message as AbortNode.
@@ -363,10 +365,11 @@
}
config.SetRPCUserAndPassword(generatedUserAndPassword);
} else {
- LogPrintf("Config options rpcuser and rpcpassword will soon be "
- "deprecated. Locally-run instances may remove rpcuser to use "
- "cookie-based auth, or may be replaced with rpcauth. Please "
- "see share/rpcuser for rpcauth auth generation.\n");
+ LogPrint(BCLog::RPC,
+ "Config options rpcuser and rpcpassword will soon be "
+ "deprecated. Locally-run instances may remove rpcuser to use "
+ "cookie-based auth, or may be replaced with rpcauth. Please "
+ "see share/rpcuser for rpcauth auth generation.\n");
config.SetRPCUserAndPassword(gArgs.GetArg("-rpcuser", "") + ":" +
gArgs.GetArg("-rpcpassword", ""));
}
diff --git a/src/httpserver.cpp b/src/httpserver.cpp
--- a/src/httpserver.cpp
+++ b/src/httpserver.cpp
@@ -276,9 +276,10 @@
/* if true, queue took ownership */
item.release();
} else {
- LogPrintf("WARNING: request rejected because http work queue depth "
- "exceeded, it can be increased with the -rpcworkqueue= "
- "setting\n");
+ LogPrint(BCLog::HTTP,
+ "WARNING: request rejected because http work queue depth "
+ "exceeded, it can be increased with the -rpcworkqueue= "
+ "setting\n");
item->req->WriteReply(HTTP_INTERNAL, "Work queue depth exceeded");
}
} else {
@@ -313,9 +314,10 @@
endpoints.push_back(std::make_pair("::1", defaultPort));
endpoints.push_back(std::make_pair("127.0.0.1", defaultPort));
if (gArgs.IsArgSet("-rpcbind")) {
- LogPrintf("WARNING: option -rpcbind was ignored because "
- "-rpcallowip was not specified, refusing to allow "
- "everyone to connect\n");
+ LogPrint(BCLog::HTTP,
+ "WARNING: option -rpcbind was ignored because "
+ "-rpcallowip was not specified, refusing to allow "
+ "everyone to connect\n");
}
} else if (gArgs.IsArgSet("-rpcbind")) {
// Specific bind address.
@@ -342,8 +344,8 @@
if (bind_handle) {
boundSockets.push_back(bind_handle);
} else {
- LogPrintf("Binding RPC on address %s port %i failed.\n", i->first,
- i->second);
+ LogPrint(BCLog::HTTP, "Binding RPC on address %s port %i failed.\n",
+ i->first, i->second);
}
}
return !boundSockets.empty();
@@ -363,7 +365,7 @@
#endif
// Log warn messages and higher without debug category.
if (severity >= EVENT_LOG_WARN) {
- LogPrintf("libevent: %s\n", msg);
+ LogPrint(BCLog::HTTP, "libevent: %s\n", msg);
} else {
LogPrint(BCLog::LIBEVENT, "libevent: %s\n", msg);
}
@@ -402,14 +404,14 @@
// XXX RAII: Create a new event_base for Libevent use
base = event_base_new();
if (!base) {
- LogPrintf("Couldn't create an event_base: exiting\n");
+ LogPrint(BCLog::HTTP, "Couldn't create an event_base: exiting\n");
return false;
}
// XXX RAII: Create a new evhttp object to handle requests
http = evhttp_new(base);
if (!http) {
- LogPrintf("couldn't create evhttp. Exiting.\n");
+ LogPrint(BCLog::HTTP, "couldn't create evhttp. Exiting.\n");
event_base_free(base);
return false;
}
@@ -429,7 +431,7 @@
EVHTTP_REQ_DELETE | EVHTTP_REQ_OPTIONS);
if (!HTTPBindAddresses(http)) {
- LogPrintf("Unable to bind any endpoint for RPC server\n");
+ LogPrint(BCLog::HTTP, "Unable to bind any endpoint for RPC server\n");
evhttp_free(http);
event_base_free(base);
return false;
@@ -438,7 +440,8 @@
LogPrint(BCLog::HTTP, "Initialized HTTP server\n");
int workQueueDepth = std::max(
(long)gArgs.GetArg("-rpcworkqueue", DEFAULT_HTTP_WORKQUEUE), 1L);
- LogPrintf("HTTP: creating work queue of depth %d\n", workQueueDepth);
+ LogPrint(BCLog::HTTP, "HTTP: creating work queue of depth %d\n",
+ workQueueDepth);
workQueue = new WorkQueue<HTTPClosure>(workQueueDepth);
eventBase = base;
@@ -453,7 +456,7 @@
LogPrint(BCLog::HTTP, "Starting HTTP server\n");
int rpcThreads =
std::max((long)gArgs.GetArg("-rpcthreads", DEFAULT_HTTP_THREADS), 1L);
- LogPrintf("HTTP: starting %d worker threads\n", rpcThreads);
+ LogPrint(BCLog::HTTP, "HTTP: starting %d worker threads\n", rpcThreads);
std::packaged_task<bool(event_base *, evhttp *)> task(ThreadHTTP);
threadResult = task.get_future();
threadHTTP = std::thread(std::move(task), eventBase, eventHTTP);
@@ -497,8 +500,9 @@
if (threadResult.valid() &&
threadResult.wait_for(std::chrono::milliseconds(2000)) ==
std::future_status::timeout) {
- LogPrintf("HTTP event loop did not exit within allotted time, "
- "sending loopbreak\n");
+ LogPrint(BCLog::HTTP,
+ "HTTP event loop did not exit within allotted time, "
+ "sending loopbreak\n");
event_base_loopbreak(eventBase);
}
threadHTTP.join();
@@ -548,7 +552,7 @@
HTTPRequest::~HTTPRequest() {
if (!replySent) {
// Keep track of whether reply was sent to avoid request leaks
- LogPrintf("%s: Unhandled request\n", __func__);
+ LogPrint(BCLog::HTTP, "%s: Unhandled request\n", __func__);
WriteReply(HTTP_INTERNAL, "Unhandled request");
}
// evhttpd cleans up the request, as long as a reply was sent.
diff --git a/src/init.cpp b/src/init.cpp
--- a/src/init.cpp
+++ b/src/init.cpp
@@ -142,7 +142,8 @@
uiInterface.ThreadSafeMessageBox(
_("Error reading from database, shutting down."), "",
CClientUIInterface::MSG_ERROR);
- LogPrintf("Error reading from database: %s\n", e.what());
+ LogPrint(BCLog::LEVELDB, "Error reading from database: %s\n",
+ e.what());
// Starting the shutdown sequence and returning false to the caller
// would be interpreted as 'entry not found' (as opposed to unable
// to read data), and could lead to invalid interpretation. Just
@@ -172,7 +173,7 @@
}
void Shutdown() {
- LogPrintf("%s: In progress...\n", __func__);
+ LogPrint(BCLog::INIT, "%s: In progress...\n", __func__);
static CCriticalSection cs_Shutdown;
TRY_LOCK(cs_Shutdown, lockShutdown);
if (!lockShutdown) {
@@ -217,8 +218,9 @@
if (!est_fileout.IsNull()) {
mempool.WriteFeeEstimates(est_fileout);
} else {
- LogPrintf("%s: Failed to write fee estimates to %s\n", __func__,
- est_path.string());
+ LogPrint(BCLog::ESTIMATEFEE,
+ "%s: Failed to write fee estimates to %s\n", __func__,
+ est_path.string());
}
fFeeEstimatesInitialized = false;
}
@@ -267,7 +269,8 @@
try {
fs::remove(GetPidFile());
} catch (const fs::filesystem_error &e) {
- LogPrintf("%s: Unable to remove pidfile: %s\n", __func__, e.what());
+ LogPrint(BCLog::INIT, "%s: Unable to remove pidfile: %s\n", __func__,
+ e.what());
}
#endif
UnregisterAllValidationInterfaces();
@@ -280,7 +283,7 @@
#endif
globalVerifyHandle.reset();
ECC_Stop();
- LogPrintf("%s: done\n", __func__);
+ LogPrint(BCLog::INIT, "%s: done\n", __func__);
}
/**
@@ -984,8 +987,9 @@
// Glob all blk?????.dat and rev?????.dat files from the blocks directory.
// Remove the rev files immediately and insert the blk file paths into an
// ordered map keyed by block file index.
- LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for "
- "-reindex with -prune\n");
+ LogPrint(BCLog::INIT,
+ "Removing unusable blk?????.dat and rev?????.dat files for "
+ "-reindex with -prune\n");
fs::path blocksdir = GetDataDir() / "blocks";
for (fs::directory_iterator it(blocksdir); it != fs::directory_iterator();
it++) {
@@ -1035,14 +1039,15 @@
// This error is logged in OpenBlockFile
break;
}
- LogPrintf("Reindexing block file blk%05u.dat...\n",
- (unsigned int)nFile);
+ LogPrint(BCLog::REINDEX,
+ "Reindexing block file blk%05u.dat...\n",
+ (unsigned int)nFile);
LoadExternalBlockFile(config, file, &pos);
nFile++;
}
pblocktree->WriteReindexing(false);
fReindex = false;
- LogPrintf("Reindexing finished\n");
+ LogPrint(BCLog::REINDEX, "Reindexing finished\n");
// To avoid ending up in a situation without genesis block, re-try
// initializing (no-op if reindexing worked):
LoadGenesisBlock(config.GetChainParams());
@@ -1054,12 +1059,13 @@
FILE *file = fsbridge::fopen(pathBootstrap, "rb");
if (file) {
fs::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
- LogPrintf("Importing bootstrap.dat...\n");
+ LogPrint(BCLog::INIT, "Importing bootstrap.dat...\n");
LoadExternalBlockFile(config, file);
RenameOver(pathBootstrap, pathBootstrapOld);
} else {
- LogPrintf("Warning: Could not open bootstrap file %s\n",
- pathBootstrap.string());
+ LogPrint(BCLog::INIT,
+ "Warning: Could not open bootstrap file %s\n",
+ pathBootstrap.string());
}
}
@@ -1067,11 +1073,13 @@
for (const fs::path &path : vImportFiles) {
FILE *file = fsbridge::fopen(path, "rb");
if (file) {
- LogPrintf("Importing blocks file %s...\n", path.string());
+ LogPrint(BCLog::INIT, "Importing blocks file %s...\n",
+ path.string());
LoadExternalBlockFile(config, file);
} else {
- LogPrintf("Warning: Could not open blocks file %s\n",
- path.string());
+ LogPrint(BCLog::INIT,
+ "Warning: Could not open blocks file %s\n",
+ path.string());
}
}
@@ -1079,13 +1087,13 @@
// connected in the active best chain
CValidationState state;
if (!ActivateBestChain(config, state)) {
- LogPrintf("Failed to connect best block");
+ LogPrint(BCLog::INIT, "Failed to connect best block");
StartShutdown();
}
if (gArgs.GetBoolArg("-stopafterblockimport",
DEFAULT_STOPAFTERBLOCKIMPORT)) {
- LogPrintf("Stopping after block import\n");
+ LogPrint(BCLog::INIT, "Stopping after block import\n");
StartShutdown();
}
} // End scope of CImportingNow
@@ -1147,16 +1155,18 @@
// even when -connect or -proxy is specified.
if (gArgs.IsArgSet("-bind")) {
if (gArgs.SoftSetBoolArg("-listen", true)) {
- LogPrintf(
+ LogPrint(
+ BCLog::NET,
"%s: parameter interaction: -bind set -> setting -listen=1\n",
__func__);
}
}
if (gArgs.IsArgSet("-whitebind")) {
if (gArgs.SoftSetBoolArg("-listen", true)) {
- LogPrintf("%s: parameter interaction: -whitebind set -> setting "
- "-listen=1\n",
- __func__);
+ LogPrint(BCLog::NET,
+ "%s: parameter interaction: -whitebind set -> setting "
+ "-listen=1\n",
+ __func__);
}
}
@@ -1164,14 +1174,16 @@
// when only connecting to trusted nodes, do not seed via DNS, or listen
// by default.
if (gArgs.SoftSetBoolArg("-dnsseed", false)) {
- LogPrintf("%s: parameter interaction: -connect set -> setting "
- "-dnsseed=0\n",
- __func__);
+ LogPrint(BCLog::NET,
+ "%s: parameter interaction: -connect set -> setting "
+ "-dnsseed=0\n",
+ __func__);
}
if (gArgs.SoftSetBoolArg("-listen", false)) {
- LogPrintf("%s: parameter interaction: -connect set -> setting "
- "-listen=0\n",
- __func__);
+ LogPrint(BCLog::NET,
+ "%s: parameter interaction: -connect set -> setting "
+ "-listen=0\n",
+ __func__);
}
}
@@ -1179,7 +1191,8 @@
// to protect privacy, do not listen by default if a default proxy
// server is specified.
if (gArgs.SoftSetBoolArg("-listen", false)) {
- LogPrintf(
+ LogPrint(
+ BCLog::PROXY,
"%s: parameter interaction: -proxy set -> setting -listen=0\n",
__func__);
}
@@ -1187,15 +1200,17 @@
// still specify -listen=1 to listen locally, so don't rely on this
// happening through -listen below.
if (gArgs.SoftSetBoolArg("-upnp", false)) {
- LogPrintf(
+ LogPrint(
+ BCLog::PROXY,
"%s: parameter interaction: -proxy set -> setting -upnp=0\n",
__func__);
}
// to protect privacy, do not discover addresses by default
if (gArgs.SoftSetBoolArg("-discover", false)) {
- LogPrintf("%s: parameter interaction: -proxy set -> setting "
- "-discover=0\n",
- __func__);
+ LogPrint(BCLog::PROXY,
+ "%s: parameter interaction: -proxy set -> setting "
+ "-discover=0\n",
+ __func__);
}
}
@@ -1203,37 +1218,42 @@
// do not map ports or try to retrieve public IP when not listening
// (pointless)
if (gArgs.SoftSetBoolArg("-upnp", false)) {
- LogPrintf(
+ LogPrint(
+ BCLog::NET,
"%s: parameter interaction: -listen=0 -> setting -upnp=0\n",
__func__);
}
if (gArgs.SoftSetBoolArg("-discover", false)) {
- LogPrintf(
+ LogPrint(
+ BCLog::NET,
"%s: parameter interaction: -listen=0 -> setting -discover=0\n",
__func__);
}
if (gArgs.SoftSetBoolArg("-listenonion", false)) {
- LogPrintf("%s: parameter interaction: -listen=0 -> setting "
- "-listenonion=0\n",
- __func__);
+ LogPrint(BCLog::NET,
+ "%s: parameter interaction: -listen=0 -> setting "
+ "-listenonion=0\n",
+ __func__);
}
}
if (gArgs.IsArgSet("-externalip")) {
// if an explicit public IP is specified, do not try to find others
if (gArgs.SoftSetBoolArg("-discover", false)) {
- LogPrintf("%s: parameter interaction: -externalip set -> setting "
- "-discover=0\n",
- __func__);
+ LogPrint(BCLog::NET,
+ "%s: parameter interaction: -externalip set -> setting "
+ "-discover=0\n",
+ __func__);
}
}
// disable whitelistrelay in blocksonly mode
if (gArgs.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY)) {
if (gArgs.SoftSetBoolArg("-whitelistrelay", false)) {
- LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting "
- "-whitelistrelay=0\n",
- __func__);
+ LogPrint(BCLog::NET,
+ "%s: parameter interaction: -blocksonly=1 -> setting "
+ "-whitelistrelay=0\n",
+ __func__);
}
}
@@ -1241,9 +1261,10 @@
// them in the first place.
if (gArgs.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
if (gArgs.SoftSetBoolArg("-whitelistrelay", true)) {
- LogPrintf("%s: parameter interaction: -whitelistforcerelay=1 -> "
- "setting -whitelistrelay=1\n",
- __func__);
+ LogPrint(BCLog::NET,
+ "%s: parameter interaction: -whitelistforcerelay=1 -> "
+ "setting -whitelistrelay=1\n",
+ __func__);
}
}
}
@@ -1263,8 +1284,8 @@
fLogIPs = gArgs.GetBoolArg("-logips", DEFAULT_LOGIPS);
- LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
- LogPrintf("%s version %s\n", CLIENT_NAME, FormatFullVersion());
+ LogPrint(BCLog::INIT, "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
+ LogPrint(BCLog::INIT, "%s version %s\n", CLIENT_NAME, FormatFullVersion());
}
namespace { // Variables internal to initialization process only
@@ -1277,10 +1298,10 @@
[[noreturn]] static void new_handler_terminate() {
// Rather than throwing std::bad-alloc if allocation fails, terminate
- // immediately to (try to) avoid chain corruption. Since LogPrintf may
+ // immediately to (try to) avoid chain corruption. Since LogPrint may
// itself allocate memory, set the handler directly to terminate first.
std::set_new_handler(std::terminate);
- LogPrintf("Error: Out of memory. Terminating.\n");
+ LogPrint(BCLog::INIT, "Error: Out of memory. Terminating.\n");
// The log was successful, terminate now.
std::terminate();
@@ -1485,10 +1506,11 @@
gArgs.GetArg("-assumevalid",
chainparams.GetConsensus().defaultAssumeValid.GetHex()));
if (!hashAssumeValid.IsNull()) {
- LogPrintf("Assuming ancestors of block %s have valid signatures.\n",
- hashAssumeValid.GetHex());
+ LogPrint(BCLog::INIT,
+ "Assuming ancestors of block %s have valid signatures.\n",
+ hashAssumeValid.GetHex());
} else {
- LogPrintf("Validating signatures for all blocks.\n");
+ LogPrint(BCLog::INIT, "Validating signatures for all blocks.\n");
}
if (gArgs.IsArgSet("-minimumchainwork")) {
@@ -1504,11 +1526,13 @@
nMinimumChainWork =
UintToArith256(chainparams.GetConsensus().nMinimumChainWork);
}
- LogPrintf("Setting nMinimumChainWork=%s\n", nMinimumChainWork.GetHex());
+ LogPrint(BCLog::INIT, "Setting nMinimumChainWork=%s\n",
+ nMinimumChainWork.GetHex());
if (nMinimumChainWork <
UintToArith256(chainparams.GetConsensus().nMinimumChainWork)) {
- LogPrintf("Warning: nMinimumChainWork set below default value of %s\n",
- chainparams.GetConsensus().nMinimumChainWork.GetHex());
+ LogPrint(BCLog::INIT,
+ "Warning: nMinimumChainWork set below default value of %s\n",
+ chainparams.GetConsensus().nMinimumChainWork.GetHex());
}
// mempool limits
@@ -1560,9 +1584,10 @@
nPruneTarget = (uint64_t)nPruneArg * 1024 * 1024;
if (nPruneArg == 1) {
// manual pruning: -prune=1
- LogPrintf("Block pruning enabled. Use RPC call "
- "pruneblockchain(height) to manually prune block and undo "
- "files.\n");
+ LogPrint(BCLog::PRUNE,
+ "Block pruning enabled. Use RPC call "
+ "pruneblockchain(height) to manually prune block and undo "
+ "files.\n");
nPruneTarget = std::numeric_limits<uint64_t>::max();
fPruneMode = true;
} else if (nPruneTarget) {
@@ -1572,9 +1597,10 @@
"Please use a higher number."),
MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
}
- LogPrintf("Prune configured to target %uMiB on disk for block and undo "
- "files.\n",
- nPruneTarget / 1024 / 1024);
+ LogPrint(BCLog::PRUNE,
+ "Prune configured to target %uMiB on disk for block and undo "
+ "files.\n",
+ nPruneTarget / 1024 / 1024);
fPruneMode = true;
}
@@ -1716,7 +1742,8 @@
// Initialize elliptic curve code
std::string sha256_algo = SHA256AutoDetect();
- LogPrintf("Using the '%s' SHA256 implementation\n", sha256_algo);
+ LogPrint(BCLog::INIT, "Using the '%s' SHA256 implementation\n",
+ sha256_algo);
RandomInit();
ECC_Start();
globalVerifyHandle.reset(new ECCVerifyHandle());
@@ -1770,23 +1797,25 @@
}
if (!logger.m_log_timestamps) {
- LogPrintf("Startup time: %s\n",
- DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()));
- }
- LogPrintf("Default data directory %s\n", GetDefaultDataDir().string());
- LogPrintf("Using data directory %s\n", GetDataDir().string());
- LogPrintf(
- "Using config file %s\n",
+ LogPrint(BCLog::INIT, "Startup time: %s\n",
+ DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()));
+ }
+ LogPrint(BCLog::INIT, "Default data directory %s\n",
+ GetDefaultDataDir().string());
+ LogPrint(BCLog::INIT, "Using data directory %s\n", GetDataDir().string());
+ LogPrint(
+ BCLog::INIT, "Using config file %s\n",
GetConfigFile(gArgs.GetArg("-conf", BITCOIN_CONF_FILENAME)).string());
- LogPrintf("Using at most %i automatic connections (%i file descriptors "
- "available)\n",
- nMaxConnections, nFD);
+ LogPrint(BCLog::INIT,
+ "Using at most %i automatic connections (%i file descriptors "
+ "available)\n",
+ nMaxConnections, nFD);
InitSignatureCache();
InitScriptExecutionCache();
- LogPrintf("Using %u threads for script verification\n",
- nScriptCheckThreads);
+ LogPrint(BCLog::INIT, "Using %u threads for script verification\n",
+ nScriptCheckThreads);
if (nScriptCheckThreads) {
for (int i = 0; i < nScriptCheckThreads - 1; i++) {
threadGroup.create_thread(&ThreadScriptCheck);
@@ -1970,15 +1999,16 @@
nCoinCacheUsage = nTotalCache;
int64_t nMempoolSizeMax =
gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
- LogPrintf("Cache configuration:\n");
- LogPrintf("* Using %.1fMiB for block index database\n",
- nBlockTreeDBCache * (1.0 / 1024 / 1024));
- LogPrintf("* Using %.1fMiB for chain state database\n",
- nCoinDBCache * (1.0 / 1024 / 1024));
- LogPrintf("* Using %.1fMiB for in-memory UTXO set (plus up to %.1fMiB of "
- "unused mempool space)\n",
- nCoinCacheUsage * (1.0 / 1024 / 1024),
- nMempoolSizeMax * (1.0 / 1024 / 1024));
+ LogPrint(BCLog::MEMPOOL, "Cache configuration:\n");
+ LogPrint(BCLog::MEMPOOL, "* Using %.1fMiB for block index database\n",
+ nBlockTreeDBCache * (1.0 / 1024 / 1024));
+ LogPrint(BCLog::MEMPOOL, "* Using %.1fMiB for chain state database\n",
+ nCoinDBCache * (1.0 / 1024 / 1024));
+ LogPrint(BCLog::MEMPOOL,
+ "* Using %.1fMiB for in-memory UTXO set (plus up to %.1fMiB of "
+ "unused mempool space)\n",
+ nCoinCacheUsage * (1.0 / 1024 / 1024),
+ nMempoolSizeMax * (1.0 / 1024 / 1024));
int64_t nStart = 0;
bool fLoaded = false;
@@ -2113,10 +2143,11 @@
if (fHavePruned &&
gArgs.GetArg("-checkblocks", DEFAULT_CHECKBLOCKS) >
MIN_BLOCKS_TO_KEEP) {
- LogPrintf("Prune: pruned datadir may not have more "
- "than %d blocks; only checking available "
- "blocks",
- MIN_BLOCKS_TO_KEEP);
+ LogPrint(BCLog::PRUNE,
+ "Prune: pruned datadir may not have more "
+ "than %d blocks; only checking available "
+ "blocks",
+ MIN_BLOCKS_TO_KEEP);
}
{
@@ -2147,7 +2178,7 @@
}
}
} catch (const std::exception &e) {
- LogPrintf("%s\n", e.what());
+ LogPrint(BCLog::INIT, "%s\n", e.what());
strLoadError = _("Error opening block database");
break;
}
@@ -2170,7 +2201,8 @@
fReindex = true;
fRequestShutdown = false;
} else {
- LogPrintf("Aborted block database rebuild. Exiting.\n");
+ LogPrint(BCLog::INIT,
+ "Aborted block database rebuild. Exiting.\n");
return false;
}
} else {
@@ -2184,10 +2216,10 @@
// As the program has not fully started yet, Shutdown() is possibly
// overkill.
if (fRequestShutdown) {
- LogPrintf("Shutdown requested. Exiting.\n");
+ LogPrint(BCLog::INIT, "Shutdown requested. Exiting.\n");
return false;
}
- LogPrintf(" block index %15dms\n", GetTimeMillis() - nStart);
+ LogPrint(BCLog::INIT, " block index %15dms\n", GetTimeMillis() - nStart);
fs::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
CAutoFile est_filein(fsbridge::fopen(est_path, "rb"), SER_DISK,
@@ -2209,7 +2241,7 @@
return false;
}
#else
- LogPrintf("No wallet support compiled in!\n");
+ LogPrint(BCLog::WALLET, "No wallet support compiled in!\n");
#endif
// Step 9: data directory maintenance
@@ -2217,7 +2249,7 @@
// if pruning, unset the service bit and perform the initial blockstore
// prune after any wallet rescanning has taken place.
if (fPruneMode) {
- LogPrintf("Unsetting NODE_NETWORK on prune mode\n");
+ LogPrint(BCLog::PRUNE, "Unsetting NODE_NETWORK on prune mode\n");
nLocalServices = ServiceFlags(nLocalServices & ~NODE_NETWORK);
if (!fReindex) {
uiInterface.InitMessage(_("Pruning blockstore..."));
@@ -2266,8 +2298,8 @@
// Step 11: start node
//// debug print
- LogPrintf("mapBlockIndex.size() = %u\n", mapBlockIndex.size());
- LogPrintf("nBestHeight = %d\n", chainActive.Height());
+ LogPrint(BCLog::INIT, "mapBlockIndex.size() = %u\n", mapBlockIndex.size());
+ LogPrint(BCLog::INIT, "nBestHeight = %d\n", chainActive.Height());
if (gArgs.GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION)) {
StartTorControl();
}
diff --git a/src/logging.h b/src/logging.h
--- a/src/logging.h
+++ b/src/logging.h
@@ -47,6 +47,13 @@
COINDB = (1 << 18),
QT = (1 << 19),
LEVELDB = (1 << 20),
+ SCRIPT = (1 << 21),
+ TEST = (1 << 22),
+ WALLET = (1 << 23),
+ INIT = (1 << 24),
+ NOUI = (1 << 25),
+ SYNC = (1 << 26),
+ UTIL = (1 << 27),
ALL = ~uint32_t(0),
};
@@ -93,7 +100,7 @@
bool DisableCategory(const std::string &str);
/** Return true if log accepts specified category */
- bool WillLogCategory(LogFlags category) const;
+ bool WillLogCategory(LogFlags category);
/** Default for whether ShrinkDebugFile should be run */
bool DefaultShrinkDebugFile() const;
@@ -121,9 +128,4 @@
} \
} while (0)
-#define LogPrintf(...) \
- do { \
- GetLogger().LogPrintStr(tfm::format(__VA_ARGS__)); \
- } while (0)
-
#endif // BITCOIN_LOGGING_H
diff --git a/src/logging.cpp b/src/logging.cpp
--- a/src/logging.cpp
+++ b/src/logging.cpp
@@ -15,7 +15,7 @@
* cleaned up by the OS/libc. Defining a logger as a global object doesn't work
* since the order of destruction of static/global objects is undefined.
* Consider if the logger gets destroyed, and then some later destructor calls
- * LogPrintf, maybe indirectly, and you get a core dump at shutdown trying to
+ * LogPrint, maybe indirectly, and you get a core dump at shutdown trying to
* access the logger. When the shutdown sequence is fully audited and tested,
* explicit destruction of these objects can be implemented by changing this
* from a raw pointer to a std::unique_ptr.
@@ -78,6 +78,13 @@
{BCLog::COINDB, "coindb"},
{BCLog::QT, "qt"},
{BCLog::LEVELDB, "leveldb"},
+ {BCLog::SCRIPT, "script"},
+ {BCLog::TEST, "test"},
+ {BCLog::WALLET, "wallet"},
+ {BCLog::INIT, "init"},
+ {BCLog::NOUI, "noui"},
+ {BCLog::SYNC, "sync"},
+ {BCLog::UTIL, "util"},
{BCLog::ALL, "1"},
{BCLog::ALL, "all"},
};
@@ -221,12 +228,12 @@
return true;
}
-bool BCLog::Logger::WillLogCategory(LogFlags category) const {
+bool BCLog::Logger::WillLogCategory(LogFlags category) {
// ALL is not meant to be used as a logging category, but only as a mask
// representing all categories.
if (category == BCLog::NONE || category == BCLog::ALL) {
- LogPrintf("Error trying to log using a category mask instead of an "
- "explicit category.\n");
+ LogPrintStr("Error trying to log using a category mask instead of an "
+ "explicit category.\n");
return true;
}
diff --git a/src/miner.cpp b/src/miner.cpp
--- a/src/miner.cpp
+++ b/src/miner.cpp
@@ -214,8 +214,9 @@
uint64_t nSerializeSize =
GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION);
- LogPrintf("CreateNewBlock(): total size: %u txs: %u fees: %ld sigops %d\n",
- nSerializeSize, nBlockTx, nFees, nBlockSigOps);
+ LogPrint(BCLog::BENCH,
+ "CreateNewBlock(): total size: %u txs: %u fees: %ld sigops %d\n",
+ nSerializeSize, nBlockTx, nFees, nBlockSigOps);
// Fill in header.
pblock->hashPrevBlock = pindexPrev->GetBlockHash();
@@ -365,10 +366,9 @@
double dPriority = iter->GetPriority(nHeight);
Amount dummy;
mempool.ApplyDeltas(iter->GetTx().GetId(), dPriority, dummy);
- LogPrintf(
- "priority %.1f fee %s txid %s\n", dPriority,
- CFeeRate(iter->GetModifiedFee(), iter->GetTxSize()).ToString(),
- iter->GetTx().GetId().ToString());
+ LogPrint(BCLog::BENCH, "priority %.1f fee %s txid %s\n", dPriority,
+ CFeeRate(iter->GetModifiedFee(), iter->GetTxSize()).ToString(),
+ iter->GetTx().GetId().ToString());
}
}
diff --git a/src/net.cpp b/src/net.cpp
--- a/src/net.cpp
+++ b/src/net.cpp
@@ -213,7 +213,7 @@
return false;
}
- LogPrintf("AddLocal(%s,%i)\n", addr.ToString(), nScore);
+ LogPrint(BCLog::NET, "AddLocal(%s,%i)\n", addr.ToString(), nScore);
{
LOCK(cs_mapLocalHost);
@@ -234,7 +234,7 @@
void RemoveLocal(const CService &addr) {
LOCK(cs_mapLocalHost);
- LogPrintf("RemoveLocal(%s)\n", addr.ToString());
+ LogPrint(BCLog::NET, "RemoveLocal(%s)\n", addr.ToString());
mapLocalHost.erase(addr);
}
@@ -362,7 +362,8 @@
// Look for an existing connection
CNode *pnode = FindNode(static_cast<CService>(addrConnect));
if (pnode) {
- LogPrintf("Failed to open new connection, already connected\n");
+ LogPrint(BCLog::NET,
+ "Failed to open new connection, already connected\n");
return nullptr;
}
}
@@ -398,7 +399,8 @@
CNode *pnode = FindNode(static_cast<CService>(addrConnect));
if (pnode) {
pnode->MaybeSetAddrName(std::string(pszDest));
- LogPrintf("Failed to open new connection, already connected\n");
+ LogPrint(BCLog::NET,
+ "Failed to open new connection, already connected\n");
return nullptr;
}
}
@@ -938,7 +940,8 @@
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE &&
nErr != WSAEINTR && nErr != WSAEINPROGRESS) {
- LogPrintf("socket send error %s\n", NetworkErrorString(nErr));
+ LogPrint(BCLog::NET, "socket send error %s\n",
+ NetworkErrorString(nErr));
pnode->CloseSocketDisconnect();
}
@@ -1148,7 +1151,7 @@
if (hSocket != INVALID_SOCKET) {
if (!addr.SetSockAddr((const struct sockaddr *)&sockaddr)) {
- LogPrintf("Warning: Unknown socket family\n");
+ LogPrint(BCLog::NET, "Warning: Unknown socket family\n");
}
}
@@ -1165,22 +1168,24 @@
if (hSocket == INVALID_SOCKET) {
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK) {
- LogPrintf("socket error accept failed: %s\n",
- NetworkErrorString(nErr));
+ LogPrint(BCLog::NET, "socket error accept failed: %s\n",
+ NetworkErrorString(nErr));
}
return;
}
if (!fNetworkActive) {
- LogPrintf("connection from %s dropped: not accepting new connections\n",
- addr.ToString());
+ LogPrint(BCLog::NET,
+ "connection from %s dropped: not accepting new connections\n",
+ addr.ToString());
CloseSocket(hSocket);
return;
}
if (!IsSelectableSocket(hSocket)) {
- LogPrintf("connection from %s dropped: non-selectable socket\n",
- addr.ToString());
+ LogPrint(BCLog::NET,
+ "connection from %s dropped: non-selectable socket\n",
+ addr.ToString());
CloseSocket(hSocket);
return;
}
@@ -1376,7 +1381,8 @@
if (nSelect == SOCKET_ERROR) {
if (have_fds) {
int nErr = WSAGetLastError();
- LogPrintf("socket select error %s\n", NetworkErrorString(nErr));
+ LogPrint(BCLog::NET, "socket select error %s\n",
+ NetworkErrorString(nErr));
for (unsigned int i = 0; i <= hSocketMax; i++) {
FD_SET(i, &fdsetRecv);
}
@@ -1482,8 +1488,8 @@
if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE &&
nErr != WSAEINTR && nErr != WSAEINPROGRESS) {
if (!pnode->fDisconnect) {
- LogPrintf("socket recv error %s\n",
- NetworkErrorString(nErr));
+ LogPrint(BCLog::NET, "socket recv error %s\n",
+ NetworkErrorString(nErr));
}
pnode->CloseSocketDisconnect();
}
@@ -1513,21 +1519,21 @@
pnode->GetId());
pnode->fDisconnect = true;
} else if (nTime - pnode->nLastSend > TIMEOUT_INTERVAL) {
- LogPrintf("socket sending timeout: %is\n",
- nTime - pnode->nLastSend);
+ LogPrint(BCLog::NET, "socket sending timeout: %is\n",
+ nTime - pnode->nLastSend);
pnode->fDisconnect = true;
} else if (nTime - pnode->nLastRecv >
(pnode->nVersion > BIP0031_VERSION ? TIMEOUT_INTERVAL
: 90 * 60)) {
- LogPrintf("socket receive timeout: %is\n",
- nTime - pnode->nLastRecv);
+ LogPrint(BCLog::NET, "socket receive timeout: %is\n",
+ nTime - pnode->nLastRecv);
pnode->fDisconnect = true;
} else if (pnode->nPingNonceSent &&
pnode->nPingUsecStart + TIMEOUT_INTERVAL * 1000000 <
GetTimeMicros()) {
- LogPrintf("ping timeout: %fs\n",
- 0.000001 *
- (GetTimeMicros() - pnode->nPingUsecStart));
+ LogPrint(BCLog::NET, "ping timeout: %fs\n",
+ 0.000001 *
+ (GetTimeMicros() - pnode->nPingUsecStart));
pnode->fDisconnect = true;
} else if (!pnode->fSuccessfullyConnected) {
LogPrint(BCLog::NET, "version handshake timeout from %d\n",
@@ -1587,17 +1593,19 @@
r = UPNP_GetExternalIPAddress(
urls.controlURL, data.first.servicetype, externalIPAddress);
if (r != UPNPCOMMAND_SUCCESS) {
- LogPrintf("UPnP: GetExternalIPAddress() returned %d\n", r);
+ LogPrint(BCLog::NET,
+ "UPnP: GetExternalIPAddress() returned %d\n", r);
} else {
if (externalIPAddress[0]) {
CNetAddr resolved;
if (LookupHost(externalIPAddress, resolved, false)) {
- LogPrintf("UPnP: ExternalIPAddress = %s\n",
- resolved.ToString().c_str());
+ LogPrint(BCLog::NET, "UPnP: ExternalIPAddress = %s\n",
+ resolved.ToString().c_str());
AddLocal(resolved, LOCAL_UPNP);
}
} else {
- LogPrintf("UPnP: GetExternalIPAddress failed.\n");
+ LogPrint(BCLog::NET,
+ "UPnP: GetExternalIPAddress failed.\n");
}
}
}
@@ -1618,22 +1626,23 @@
#endif
if (r != UPNPCOMMAND_SUCCESS) {
- LogPrintf(
+ LogPrint(
+ BCLog::NET,
"AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
port, port, lanaddr, r, strupnperror(r));
} else {
- LogPrintf("UPnP Port Mapping successful.\n");
+ LogPrint(BCLog::NET, "UPnP Port Mapping successful.\n");
}
} while (g_upnp_interrupt.sleep_for(std::chrono::minutes(20)));
r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype,
port.c_str(), "TCP", 0);
- LogPrintf("UPNP_DeletePortMapping() returned: %d\n", r);
+ LogPrint(BCLog::NET, "UPNP_DeletePortMapping() returned: %d\n", r);
freeUPNPDevlist(devlist);
devlist = nullptr;
FreeUPNPUrls(&urls);
} else {
- LogPrintf("No valid UPnP IGDs found\n");
+ LogPrint(BCLog::NET, "No valid UPnP IGDs found\n");
freeUPNPDevlist(devlist);
devlist = nullptr;
if (r != 0) {
@@ -1694,7 +1703,7 @@
!pnode->fInbound;
}
if (nRelevant >= 2) {
- LogPrintf("P2P peers available. Skipped DNS seeding.\n");
+ LogPrint(BCLog::NET, "P2P peers available. Skipped DNS seeding.\n");
return;
}
}
@@ -1703,7 +1712,8 @@
config->GetChainParams().DNSSeeds();
int found = 0;
- LogPrintf("Loading addresses from DNS seeds (could take a while)\n");
+ LogPrint(BCLog::NET,
+ "Loading addresses from DNS seeds (could take a while)\n");
for (const std::string &seed : vSeeds) {
if (interruptNet) {
@@ -1745,7 +1755,7 @@
}
}
- LogPrintf("%d addresses found from DNS seeds\n", found);
+ LogPrint(BCLog::NET, "%d addresses found from DNS seeds\n", found);
}
void CConnman::DumpAddresses() {
@@ -1855,8 +1865,9 @@
if (addrman.size() == 0 && (GetTime() - nStart > 60)) {
static bool done = false;
if (!done) {
- LogPrintf("Adding fixed seed nodes as DNS doesn't seem to be "
- "available.\n");
+ LogPrint(BCLog::NET,
+ "Adding fixed seed nodes as DNS doesn't seem to be "
+ "available.\n");
CNetAddr local;
local.SetInternal("fixedseeds");
addrman.Add(convertSeed6(config->GetChainParams().FixedSeeds()),
@@ -2201,7 +2212,7 @@
if (!addrBind.GetSockAddr((struct sockaddr *)&sockaddr, &len)) {
strError = strprintf("Error: Bind address family for %s not supported",
addrBind.ToString());
- LogPrintf("%s\n", strError);
+ LogPrint(BCLog::NET, "%s\n", strError);
return false;
}
@@ -2210,7 +2221,7 @@
strError = strprintf("Error: Couldn't open socket for incoming "
"connections (socket returned error %s)",
NetworkErrorString(WSAGetLastError()));
- LogPrintf("%s\n", strError);
+ LogPrint(BCLog::NET, "%s\n", strError);
return false;
}
@@ -2246,18 +2257,18 @@
"(bind returned error %s)"),
addrBind.ToString(), NetworkErrorString(nErr));
}
- LogPrintf("%s\n", strError);
+ LogPrint(BCLog::NET, "%s\n", strError);
CloseSocket(hListenSocket);
return false;
}
- LogPrintf("Bound to %s\n", addrBind.ToString());
+ LogPrint(BCLog::NET, "Bound to %s\n", addrBind.ToString());
// Listen for incoming connections
if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR) {
strError = strprintf(_("Error: Listening for incoming connections "
"failed (listen returned error %s)"),
NetworkErrorString(WSAGetLastError()));
- LogPrintf("%s\n", strError);
+ LogPrint(BCLog::NET, "%s\n", strError);
CloseSocket(hListenSocket);
return false;
}
@@ -2284,8 +2295,8 @@
if (LookupHost(pszHostName, vaddr, 0, true)) {
for (const CNetAddr &addr : vaddr) {
if (AddLocal(addr, LOCAL_IF)) {
- LogPrintf("%s: %s - %s\n", __func__, pszHostName,
- addr.ToString());
+ LogPrint(BCLog::NET, "%s: %s - %s\n", __func__, pszHostName,
+ addr.ToString());
}
}
}
@@ -2305,16 +2316,16 @@
struct sockaddr_in *s4 = (struct sockaddr_in *)(ifa->ifa_addr);
CNetAddr addr(s4->sin_addr);
if (AddLocal(addr, LOCAL_IF)) {
- LogPrintf("%s: IPv4 %s: %s\n", __func__, ifa->ifa_name,
- addr.ToString());
+ LogPrint(BCLog::NET, "%s: IPv4 %s: %s\n", __func__,
+ ifa->ifa_name, addr.ToString());
}
} else if (ifa->ifa_addr->sa_family == AF_INET6) {
struct sockaddr_in6 *s6 =
(struct sockaddr_in6 *)(ifa->ifa_addr);
CNetAddr addr(s6->sin6_addr);
if (AddLocal(addr, LOCAL_IF)) {
- LogPrintf("%s: IPv6 %s: %s\n", __func__, ifa->ifa_name,
- addr.ToString());
+ LogPrint(BCLog::NET, "%s: IPv6 %s: %s\n", __func__,
+ ifa->ifa_name, addr.ToString());
}
}
}
@@ -2419,12 +2430,12 @@
{
CAddrDB adb(config->GetChainParams());
if (adb.Read(addrman)) {
- LogPrintf("Loaded %i addresses from peers.dat %dms\n",
- addrman.size(), GetTimeMillis() - nStart);
+ LogPrint(BCLog::NET, "Loaded %i addresses from peers.dat %dms\n",
+ addrman.size(), GetTimeMillis() - nStart);
} else {
// Addrman can be in an inconsistent state after failure, reset it
addrman.Clear();
- LogPrintf("Invalid or missing peers.dat; recreating\n");
+ LogPrint(BCLog::NET, "Invalid or missing peers.dat; recreating\n");
DumpAddresses();
}
}
@@ -2447,7 +2458,7 @@
"Loaded %d banned node ips/subnets from banlist.dat %dms\n",
banmap.size(), GetTimeMillis() - nStart);
} else {
- LogPrintf("Invalid or missing banlist.dat; recreating\n");
+ LogPrint(BCLog::NET, "Invalid or missing banlist.dat; recreating\n");
// force write
SetBannedSetDirty(true);
DumpBanlist();
@@ -2486,7 +2497,7 @@
std::function<void()>(std::bind(&CConnman::ThreadSocketHandler, this)));
if (!gArgs.GetBoolArg("-dnsseed", true)) {
- LogPrintf("DNS seeding disabled\n");
+ LogPrint(BCLog::NET, "DNS seeding disabled\n");
} else {
threadDNSAddressSeed =
std::thread(&TraceThread<std::function<void()>>, "dnsseed",
@@ -2600,8 +2611,9 @@
for (ListenSocket &hListenSocket : vhListenSocket) {
if (hListenSocket.socket != INVALID_SOCKET) {
if (!CloseSocket(hListenSocket.socket)) {
- LogPrintf("CloseSocket(hListenSocket) failed with error %s\n",
- NetworkErrorString(WSAGetLastError()));
+ LogPrint(BCLog::NET,
+ "CloseSocket(hListenSocket) failed with error %s\n",
+ NetworkErrorString(WSAGetLastError()));
}
}
}
@@ -3075,10 +3087,10 @@
// sanitize comments per BIP-0014, format user agent and check total size
for (const std::string &cmt : gArgs.GetArgs("-uacomment")) {
if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT)) {
- LogPrintf(
- "User Agent comment (%s) contains unsafe characters. "
- "We are going to use a sanitize version of the comment.\n",
- cmt);
+ LogPrint(BCLog::NET,
+ "User Agent comment (%s) contains unsafe characters. "
+ "We are going to use a sanitize version of the comment.\n",
+ cmt);
}
uacomments.push_back(cmt);
}
@@ -3086,13 +3098,15 @@
std::string subversion =
FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, uacomments);
if (subversion.size() > MAX_SUBVERSION_LENGTH) {
- LogPrintf("Total length of network version string (%i) exceeds maximum "
- "length (%i). Reduce the number or size of uacomments. "
- "String has been resized to the max length allowed.\n",
- subversion.size(), MAX_SUBVERSION_LENGTH);
+ LogPrint(BCLog::NET,
+ "Total length of network version string (%i) exceeds maximum "
+ "length (%i). Reduce the number or size of uacomments. "
+ "String has been resized to the max length allowed.\n",
+ subversion.size(), MAX_SUBVERSION_LENGTH);
subversion.resize(MAX_SUBVERSION_LENGTH - 2);
subversion.append(")/");
- LogPrintf("Current network string has been set to: %s\n", subversion);
+ LogPrint(BCLog::NET, "Current network string has been set to: %s\n",
+ subversion);
}
return subversion;
diff --git a/src/net_processing.cpp b/src/net_processing.cpp
--- a/src/net_processing.cpp
+++ b/src/net_processing.cpp
@@ -901,15 +901,16 @@
int banscore = gArgs.GetArg("-banscore", DEFAULT_BANSCORE_THRESHOLD);
if (state->nMisbehavior >= banscore &&
state->nMisbehavior - howmuch < banscore) {
- LogPrintf(
+ LogPrint(
+ BCLog::NET,
"%s: %s peer=%d (%d -> %d) reason: %s BAN THRESHOLD EXCEEDED\n",
__func__, state->name, pnode, state->nMisbehavior - howmuch,
state->nMisbehavior, reason.c_str());
state->fShouldBan = true;
} else {
- LogPrintf("%s: %s peer=%d (%d -> %d) reason: %s\n", __func__,
- state->name, pnode, state->nMisbehavior - howmuch,
- state->nMisbehavior, reason.c_str());
+ LogPrint(BCLog::NET, "%s: %s peer=%d (%d -> %d) reason: %s\n", __func__,
+ state->name, pnode, state->nMisbehavior - howmuch,
+ state->nMisbehavior, reason.c_str());
}
}
@@ -1269,10 +1270,11 @@
*pindexBestHeader,
consensusParams) < nOneMonth);
if (!send) {
- LogPrintf("%s: ignoring request from peer=%i for "
- "old block that isn't in the main "
- "chain\n",
- __func__, pfrom->GetId());
+ LogPrint(BCLog::NET,
+ "%s: ignoring request from peer=%i for "
+ "old block that isn't in the main "
+ "chain\n",
+ __func__, pfrom->GetId());
}
}
}
@@ -1447,7 +1449,8 @@
if (req.indices[i] >= block.vtx.size()) {
LOCK(cs_main);
Misbehaving(pfrom, 100, "out-of-bound-tx-index");
- LogPrintf(
+ LogPrint(
+ BCLog::NET,
"Peer %d sent us a getblocktxn with out-of-bounds tx indices",
pfrom->GetId());
return;
@@ -1700,9 +1703,10 @@
// nMinimumChainWork, even if a peer has a chain past our tip,
// as an anti-DoS measure.
if (IsOutboundDisconnectionCandidate(pfrom)) {
- LogPrintf("Disconnecting outbound peer %d -- headers "
- "chain has insufficient work\n",
- pfrom->GetId());
+ LogPrint(BCLog::NET,
+ "Disconnecting outbound peer %d -- headers "
+ "chain has insufficient work\n",
+ pfrom->GetId());
pfrom->fDisconnect = true;
}
}
@@ -1738,7 +1742,7 @@
SanitizeString(strCommand), vRecv.size(), pfrom->GetId());
if (gArgs.IsArgSet("-dropmessagestest") &&
GetRand(gArgs.GetArg("-dropmessagestest", 0)) == 0) {
- LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
+ LogPrint(BCLog::NET, "dropmessagestest DROPPING RECV MESSAGE\n");
return true;
}
@@ -1833,8 +1837,9 @@
if (nVersion < MIN_PEER_PROTO_VERSION) {
// disconnect from peers older than this proto version
- LogPrintf("peer=%d using obsolete version %i; disconnecting\n",
- pfrom->GetId(), nVersion);
+ LogPrint(BCLog::NET,
+ "peer=%d using obsolete version %i; disconnecting\n",
+ pfrom->GetId(), nVersion);
connman->PushMessage(
pfrom,
CNetMsgMaker(INIT_PROTO_VERSION)
@@ -1860,8 +1865,8 @@
}
// Disconnect if we connected to ourself
if (pfrom->fInbound && !connman->CheckIncomingNonce(nNonce)) {
- LogPrintf("connected to self at %s, disconnecting\n",
- pfrom->addr.ToString());
+ LogPrint(BCLog::NET, "connected to self at %s, disconnecting\n",
+ pfrom->addr.ToString());
pfrom->fDisconnect = true;
return true;
}
@@ -1939,11 +1944,12 @@
remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
}
- LogPrintf("receive version message: [%s] %s: version %d, blocks=%d, "
- "us=%s, peer=%d%s\n",
- pfrom->addr.ToString().c_str(), cleanSubVer, pfrom->nVersion,
- pfrom->nStartingHeight, addrMe.ToString(), pfrom->GetId(),
- remoteAddr);
+ LogPrint(BCLog::NET,
+ "receive version message: [%s] %s: version %d, blocks=%d, "
+ "us=%s, peer=%d%s\n",
+ pfrom->addr.ToString().c_str(), cleanSubVer, pfrom->nVersion,
+ pfrom->nStartingHeight, addrMe.ToString(), pfrom->GetId(),
+ remoteAddr);
int64_t nTimeOffset = nTime - GetTime();
pfrom->nTimeOffset = nTimeOffset;
@@ -2290,8 +2296,9 @@
BlockMap::iterator it = mapBlockIndex.find(req.blockhash);
if (it == mapBlockIndex.end() || !it->second->nStatus.hasData()) {
- LogPrintf("Peer %d sent us a getblocktxn for a block we don't have",
- pfrom->GetId());
+ LogPrint(BCLog::NET,
+ "Peer %d sent us a getblocktxn for a block we don't have",
+ pfrom->GetId());
return true;
}
@@ -2560,14 +2567,16 @@
// case.
int nDoS = 0;
if (!state.IsInvalid(nDoS) || nDoS == 0) {
- LogPrintf("Force relaying tx %s from whitelisted peer=%d\n",
- tx.GetId().ToString(), pfrom->GetId());
+ LogPrint(BCLog::NET,
+ "Force relaying tx %s from whitelisted peer=%d\n",
+ tx.GetId().ToString(), pfrom->GetId());
RelayTransaction(tx, connman);
} else {
- LogPrintf("Not relaying invalid transaction %s from "
- "whitelisted peer=%d (%s)\n",
- tx.GetId().ToString(), pfrom->GetId(),
- FormatStateMessage(state));
+ LogPrint(BCLog::NET,
+ "Not relaying invalid transaction %s from "
+ "whitelisted peer=%d (%s)\n",
+ tx.GetId().ToString(), pfrom->GetId(),
+ FormatStateMessage(state));
}
}
}
@@ -2635,8 +2644,9 @@
LOCK(cs_main);
Misbehaving(pfrom, nDoS, state.GetRejectReason());
}
- LogPrintf("Peer %d sent us invalid header via cmpctblock\n",
- pfrom->GetId());
+ LogPrint(BCLog::NET,
+ "Peer %d sent us invalid header via cmpctblock\n",
+ pfrom->GetId());
return true;
}
}
@@ -2742,8 +2752,9 @@
// Reset in-flight state in case of whitelist
MarkBlockAsReceived(pindex->GetBlockHash());
Misbehaving(pfrom, 100, "invalid-cmpctblk");
- LogPrintf("Peer %d sent us invalid compact block\n",
- pfrom->GetId());
+ LogPrint(BCLog::NET,
+ "Peer %d sent us invalid compact block\n",
+ pfrom->GetId());
return true;
} else if (status == READ_STATUS_FAILED) {
// Duplicate txindices, the block is now in-flight, so
@@ -2895,9 +2906,10 @@
// Reset in-flight state in case of whitelist.
MarkBlockAsReceived(resp.blockhash);
Misbehaving(pfrom, 100, "invalid-cmpctblk-txns");
- LogPrintf("Peer %d sent us invalid compact block/non-matching "
- "block transactions\n",
- pfrom->GetId());
+ LogPrint(BCLog::NET,
+ "Peer %d sent us invalid compact block/non-matching "
+ "block transactions\n",
+ pfrom->GetId());
return true;
} else if (status == READ_STATUS_FAILED) {
// Might have collided, fall back to getdata now :(
@@ -3238,16 +3250,18 @@
if (state.fShouldBan) {
state.fShouldBan = false;
if (pnode->fWhitelisted) {
- LogPrintf("Warning: not punishing whitelisted peer %s!\n",
- pnode->addr.ToString());
+ LogPrint(BCLog::NET,
+ "Warning: not punishing whitelisted peer %s!\n",
+ pnode->addr.ToString());
} else if (pnode->m_manual_connection) {
- LogPrintf("Warning: not punishing manually-connected peer %s!\n",
- pnode->addr.ToString());
+ LogPrint(BCLog::NET,
+ "Warning: not punishing manually-connected peer %s!\n",
+ pnode->addr.ToString());
} else {
pnode->fDisconnect = true;
if (pnode->addr.IsLocal()) {
- LogPrintf("Warning: not banning local peer %s!\n",
- pnode->addr.ToString());
+ LogPrint(BCLog::NET, "Warning: not banning local peer %s!\n",
+ pnode->addr.ToString());
} else {
connman->Ban(pnode->addr, BanReasonNodeMisbehaving);
}
@@ -3311,8 +3325,9 @@
if (memcmp(std::begin(msg.hdr.pchMessageStart),
std::begin(chainparams.NetMagic()),
CMessageHeader::MESSAGE_START_SIZE) != 0) {
- LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n",
- SanitizeString(msg.hdr.GetCommand()), pfrom->GetId());
+ LogPrint(BCLog::NET,
+ "PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n",
+ SanitizeString(msg.hdr.GetCommand()), pfrom->GetId());
// Make sure we ban where that come from for some time.
connman->Ban(pfrom->addr, BanReasonNodeMisbehaving);
@@ -3324,8 +3339,8 @@
// Read header
CMessageHeader &hdr = msg.hdr;
if (!hdr.IsValid(config)) {
- LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n",
- SanitizeString(hdr.GetCommand()), pfrom->GetId());
+ LogPrint(BCLog::NET, "PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n",
+ SanitizeString(hdr.GetCommand()), pfrom->GetId());
return fMoreWork;
}
std::string strCommand = hdr.GetCommand();
@@ -3338,9 +3353,9 @@
const uint256 &hash = msg.GetMessageHash();
if (memcmp(hash.begin(), hdr.pchChecksum, CMessageHeader::CHECKSUM_SIZE) !=
0) {
- LogPrintf(
- "%s(%s, %u bytes): CHECKSUM ERROR expected %s was %s\n", __func__,
- SanitizeString(strCommand), nMessageSize,
+ LogPrint(
+ BCLog::NET, "%s(%s, %u bytes): CHECKSUM ERROR expected %s was %s\n",
+ __func__, SanitizeString(strCommand), nMessageSize,
HexStr(hash.begin(), hash.begin() + CMessageHeader::CHECKSUM_SIZE),
HexStr(hdr.pchChecksum,
hdr.pchChecksum + CMessageHeader::CHECKSUM_SIZE));
@@ -3366,18 +3381,21 @@
std::string("error parsing message")));
if (strstr(e.what(), "end of data")) {
// Allow exceptions from under-length message on vRecv
- LogPrintf(
+ LogPrint(
+ BCLog::NET,
"%s(%s, %u bytes): Exception '%s' caught, normally caused by a "
"message being shorter than its stated length\n",
__func__, SanitizeString(strCommand), nMessageSize, e.what());
} else if (strstr(e.what(), "size too large")) {
// Allow exceptions from over-long size
- LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__,
- SanitizeString(strCommand), nMessageSize, e.what());
+ LogPrint(BCLog::NET, "%s(%s, %u bytes): Exception '%s' caught\n",
+ __func__, SanitizeString(strCommand), nMessageSize,
+ e.what());
} else if (strstr(e.what(), "non-canonical ReadCompactSize()")) {
// Allow exceptions from non-canonical encoding
- LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__,
- SanitizeString(strCommand), nMessageSize, e.what());
+ LogPrint(BCLog::NET, "%s(%s, %u bytes): Exception '%s' caught\n",
+ __func__, SanitizeString(strCommand), nMessageSize,
+ e.what());
} else {
PrintExceptionContinue(&e, "ProcessMessages()");
}
@@ -3388,8 +3406,8 @@
}
if (!fRet) {
- LogPrintf("%s(%s, %u bytes) FAILED peer=%d\n", __func__,
- SanitizeString(strCommand), nMessageSize, pfrom->GetId());
+ LogPrint(BCLog::NET, "%s(%s, %u bytes) FAILED peer=%d\n", __func__,
+ SanitizeString(strCommand), nMessageSize, pfrom->GetId());
}
LOCK(cs_main);
@@ -3441,7 +3459,8 @@
// update us.
if (state.m_chain_sync.m_sent_getheaders) {
// They've run out of time to catch up!
- LogPrintf(
+ LogPrint(
+ BCLog::NET,
"Disconnecting outbound peer %d for old chain, best known "
"block = %s\n",
pto->GetId(),
@@ -3577,9 +3596,10 @@
// Check whether our tip is stale, and if so, allow using an extra outbound
// peer.
if (TipMayBeStale(consensusParams)) {
- LogPrintf("Potential stale tip detected, will try using extra outbound "
- "peer (last tip update: %d seconds ago)\n",
- time_in_seconds - g_last_tip_update);
+ LogPrint(BCLog::NET,
+ "Potential stale tip detected, will try using extra outbound "
+ "peer (last tip update: %d seconds ago)\n",
+ time_in_seconds - g_last_tip_update);
connman->SetTryNewOutboundPeer(true);
} else if (connman->GetTryNewOutboundPeer()) {
connman->SetTryNewOutboundPeer(false);
@@ -4075,8 +4095,9 @@
// During normal steady state, the download window should be much larger
// than the to-be-downloaded set of blocks, so disconnection should only
// happen during initial block download.
- LogPrintf("Peer=%d is stalling block download, disconnecting\n",
- pto->GetId());
+ LogPrint(BCLog::NET,
+ "Peer=%d is stalling block download, disconnecting\n",
+ pto->GetId());
pto->fDisconnect = true;
return true;
}
@@ -4097,9 +4118,9 @@
(BLOCK_DOWNLOAD_TIMEOUT_BASE +
BLOCK_DOWNLOAD_TIMEOUT_PER_PEER *
nOtherPeersWithValidatedDownloads)) {
- LogPrintf("Timeout downloading block %s from peer=%d, "
- "disconnecting\n",
- queuedBlock.hash.ToString(), pto->GetId());
+ LogPrint(BCLog::NET, "Timeout downloading block %s from peer=%d, "
+ "disconnecting\n",
+ queuedBlock.hash.ToString(), pto->GetId());
pto->fDisconnect = true;
return true;
}
@@ -4119,15 +4140,17 @@
// our sync peer for stalling; we have bigger problems if we
// can't get any outbound peers.
if (!pto->fWhitelisted) {
- LogPrintf("Timeout downloading headers from peer=%d, "
- "disconnecting\n",
- pto->GetId());
+ LogPrint(BCLog::NET,
+ "Timeout downloading headers from peer=%d, "
+ "disconnecting\n",
+ pto->GetId());
pto->fDisconnect = true;
return true;
} else {
- LogPrintf("Timeout downloading headers from whitelisted "
- "peer=%d, not disconnecting\n",
- pto->GetId());
+ LogPrint(BCLog::NET,
+ "Timeout downloading headers from whitelisted "
+ "peer=%d, not disconnecting\n",
+ pto->GetId());
// Reset the headers sync state so that we have a chance to
// try downloading from a different peer.
// Note: this will also result in at least one more
diff --git a/src/netbase.cpp b/src/netbase.cpp
--- a/src/netbase.cpp
+++ b/src/netbase.cpp
@@ -336,9 +336,10 @@
uint8_t pchRet1[2];
if ((recvr = InterruptibleRecv(pchRet1, 2, SOCKS5_RECV_TIMEOUT, hSocket)) !=
IntrRecvError::OK) {
- LogPrintf("Socks5() connect to %s:%d failed: InterruptibleRecv() "
- "timeout or other failure\n",
- strDest, port);
+ LogPrint(BCLog::NET,
+ "Socks5() connect to %s:%d failed: InterruptibleRecv() "
+ "timeout or other failure\n",
+ strDest, port);
return false;
}
if (pchRet1[0] != SOCKSVersion::SOCKS5) {
@@ -414,8 +415,8 @@
}
if (pchRet2[1] != SOCKS5Reply::SUCCEEDED) {
// Failures to connect to a peer that are not proxy errors
- LogPrintf("Socks5() connect to %s:%d failed: %s\n", strDest, port,
- Socks5ErrorString(pchRet2[1]));
+ LogPrint(BCLog::NET, "Socks5() connect to %s:%d failed: %s\n", strDest,
+ port, Socks5ErrorString(pchRet2[1]));
return false;
}
// Reserved field must be 0
@@ -459,8 +460,9 @@
struct sockaddr_storage sockaddr;
socklen_t len = sizeof(sockaddr);
if (!addrConnect.GetSockAddr((struct sockaddr *)&sockaddr, &len)) {
- LogPrintf("Cannot create socket for %s: unsupported network\n",
- addrConnect.ToString());
+ LogPrint(BCLog::NET,
+ "Cannot create socket for %s: unsupported network\n",
+ addrConnect.ToString());
return INVALID_SOCKET;
}
@@ -472,8 +474,9 @@
if (!IsSelectableSocket(hSocket)) {
CloseSocket(hSocket);
- LogPrintf("Cannot create connection: non-selectable socket created (fd "
- ">= FD_SETSIZE ?)\n");
+ LogPrint(BCLog::NET,
+ "Cannot create connection: non-selectable socket created (fd "
+ ">= FD_SETSIZE ?)\n");
return INVALID_SOCKET;
}
@@ -490,9 +493,10 @@
// Set to non-blocking
if (!SetSocketNonBlocking(hSocket, true)) {
CloseSocket(hSocket);
- LogPrintf("ConnectSocketDirectly: Setting socket to non-blocking "
- "failed, error %s\n",
- NetworkErrorString(WSAGetLastError()));
+ LogPrint(BCLog::NET,
+ "ConnectSocketDirectly: Setting socket to non-blocking "
+ "failed, error %s\n",
+ NetworkErrorString(WSAGetLastError()));
}
return hSocket;
}
@@ -502,13 +506,13 @@
struct sockaddr_storage sockaddr;
socklen_t len = sizeof(sockaddr);
if (hSocket == INVALID_SOCKET) {
- LogPrintf("Cannot connect to %s: invalid socket\n",
- addrConnect.ToString());
+ LogPrint(BCLog::NET, "Cannot connect to %s: invalid socket\n",
+ addrConnect.ToString());
return false;
}
if (!addrConnect.GetSockAddr((struct sockaddr *)&sockaddr, &len)) {
- LogPrintf("Cannot connect to %s: unsupported network\n",
- addrConnect.ToString());
+ LogPrint(BCLog::NET, "Cannot connect to %s: unsupported network\n",
+ addrConnect.ToString());
return false;
}
if (connect(hSocket, (struct sockaddr *)&sockaddr, len) == SOCKET_ERROR) {
@@ -527,23 +531,24 @@
return false;
}
if (nRet == SOCKET_ERROR) {
- LogPrintf("select() for %s failed: %s\n",
- addrConnect.ToString(),
- NetworkErrorString(WSAGetLastError()));
+ LogPrint(BCLog::NET, "select() for %s failed: %s\n",
+ addrConnect.ToString(),
+ NetworkErrorString(WSAGetLastError()));
return false;
}
socklen_t nRetSize = sizeof(nRet);
if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR,
(sockopt_arg_type)&nRet,
&nRetSize) == SOCKET_ERROR) {
- LogPrintf("getsockopt() for %s failed: %s\n",
- addrConnect.ToString(),
- NetworkErrorString(WSAGetLastError()));
+ LogPrint(BCLog::NET, "getsockopt() for %s failed: %s\n",
+ addrConnect.ToString(),
+ NetworkErrorString(WSAGetLastError()));
return false;
}
if (nRet != 0) {
- LogPrintf("connect() to %s failed after select(): %s\n",
- addrConnect.ToString(), NetworkErrorString(nRet));
+ LogPrint(BCLog::NET,
+ "connect() to %s failed after select(): %s\n",
+ addrConnect.ToString(), NetworkErrorString(nRet));
return false;
}
}
@@ -553,8 +558,9 @@
else
#endif
{
- LogPrintf("connect() to %s failed: %s\n", addrConnect.ToString(),
- NetworkErrorString(WSAGetLastError()));
+ LogPrint(BCLog::NET, "connect() to %s failed: %s\n",
+ addrConnect.ToString(),
+ NetworkErrorString(WSAGetLastError()));
return false;
}
}
diff --git a/src/noui.cpp b/src/noui.cpp
--- a/src/noui.cpp
+++ b/src/noui.cpp
@@ -35,7 +35,7 @@
strCaption += caption;
}
- if (!fSecure) LogPrintf("%s: %s\n", strCaption, message);
+ if (!fSecure) LogPrint(BCLog::NOUI, "%s: %s\n", strCaption, message);
fprintf(stderr, "%s: %s\n", strCaption.c_str(), message.c_str());
return false;
}
@@ -48,7 +48,7 @@
}
static void noui_InitMessage(const std::string &message) {
- LogPrintf("init message: %s\n", message);
+ LogPrint(BCLog::NOUI, "init message: %s\n", message);
}
void noui_connect() {
diff --git a/src/protocol.cpp b/src/protocol.cpp
--- a/src/protocol.cpp
+++ b/src/protocol.cpp
@@ -131,8 +131,9 @@
// Message size
if (IsOversized(config)) {
- LogPrintf("CMessageHeader::IsValid(): (%s, %u bytes) is oversized\n",
- GetCommand(), nMessageSize);
+ LogPrint(BCLog::BENCH,
+ "CMessageHeader::IsValid(): (%s, %u bytes) is oversized\n",
+ GetCommand(), nMessageSize);
return false;
}
@@ -154,7 +155,8 @@
// Message size
if (nMessageSize > MAX_PROTOCOL_MESSAGE_LENGTH) {
- LogPrintf(
+ LogPrint(
+ BCLog::BENCH,
"CMessageHeader::IsValidForSeeder(): (%s, %u bytes) is oversized\n",
GetCommand(), nMessageSize);
return false;
diff --git a/src/qt/bitcoin.cpp b/src/qt/bitcoin.cpp
--- a/src/qt/bitcoin.cpp
+++ b/src/qt/bitcoin.cpp
@@ -77,7 +77,7 @@
Q_DECLARE_METATYPE(Config *)
static void InitMessage(const std::string &message) {
- LogPrintf("init message: %s\n", message);
+ LogPrint(BCLog::QT, "init message: %s\n", message);
}
/**
@@ -156,7 +156,7 @@
if (type == QtDebugMsg) {
LogPrint(BCLog::QT, "GUI: %s\n", msg.toStdString());
} else {
- LogPrintf("GUI: %s\n", msg.toStdString());
+ LogPrint(BCLog::QT, "GUI: %s\n", msg.toStdString());
}
}
diff --git a/src/qt/winshutdownmonitor.cpp b/src/qt/winshutdownmonitor.cpp
--- a/src/qt/winshutdownmonitor.cpp
+++ b/src/qt/winshutdownmonitor.cpp
@@ -27,9 +27,10 @@
// Warn only once as this is performance-critical
static bool warned = false;
if (!warned) {
- LogPrintf("%s: OpenSSL RAND_event() failed to seed OpenSSL PRNG "
- "with enough data.\n",
- __func__);
+ LogPrint(BCLog::QT,
+ "%s: OpenSSL RAND_event() failed to seed OpenSSL PRNG "
+ "with enough data.\n",
+ __func__);
warned = true;
}
}
diff --git a/src/random.cpp b/src/random.cpp
--- a/src/random.cpp
+++ b/src/random.cpp
@@ -49,7 +49,7 @@
#include <openssl/rand.h>
[[noreturn]] static void RandFailure() {
- LogPrintf("Failed to read randomness, aborting\n");
+ LogPrint(BCLog::RAND, "Failed to read randomness, aborting\n");
std::abort();
}
@@ -82,7 +82,7 @@
static void RDRandInit() {
uint32_t eax, ebx, ecx, edx;
if (__get_cpuid(1, &eax, &ebx, &ecx, &edx) && (ecx & CPUID_F1_ECX_RDRAND)) {
- LogPrintf("Using RdRand as an additional entropy source\n");
+ LogPrint(BCLog::RAND, "Using RdRand as an additional entropy source\n");
rdrand_supported = true;
}
hwrand_initialized.store(true);
@@ -178,9 +178,10 @@
// Warn only once
static bool warned = false;
if (!warned) {
- LogPrintf("%s: Warning: RegQueryValueExA(HKEY_PERFORMANCE_DATA) "
- "failed with code %i\n",
- __func__, ret);
+ LogPrint(BCLog::RAND,
+ "%s: Warning: RegQueryValueExA(HKEY_PERFORMANCE_DATA) "
+ "failed with code %i\n",
+ __func__, ret);
warned = true;
}
}
diff --git a/src/rpc/protocol.cpp b/src/rpc/protocol.cpp
--- a/src/rpc/protocol.cpp
+++ b/src/rpc/protocol.cpp
@@ -88,13 +88,15 @@
fs::path filepath = GetAuthCookieFile();
file.open(filepath.string().c_str());
if (!file.is_open()) {
- LogPrintf("Unable to open cookie authentication file %s for writing\n",
- filepath.string());
+ LogPrint(BCLog::RPC,
+ "Unable to open cookie authentication file %s for writing\n",
+ filepath.string());
return false;
}
file << cookie;
file.close();
- LogPrintf("Generated RPC authentication cookie %s\n", filepath.string());
+ LogPrint(BCLog::RPC, "Generated RPC authentication cookie %s\n",
+ filepath.string());
if (cookie_out) {
*cookie_out = cookie;
@@ -123,7 +125,8 @@
try {
fs::remove(GetAuthCookieFile());
} catch (const fs::filesystem_error &e) {
- LogPrintf("%s: Unable to remove random auth cookie file: %s\n",
- __func__, e.what());
+ LogPrint(BCLog::RPC,
+ "%s: Unable to remove random auth cookie file: %s\n", __func__,
+ e.what());
}
}
diff --git a/src/script/scriptcache.cpp b/src/script/scriptcache.cpp
--- a/src/script/scriptcache.cpp
+++ b/src/script/scriptcache.cpp
@@ -26,9 +26,10 @@
MAX_MAX_SCRIPT_CACHE_SIZE) *
(size_t(1) << 20);
size_t nElems = scriptExecutionCache.setup_bytes(nMaxCacheSize);
- LogPrintf("Using %zu MiB out of %zu requested for script execution cache, "
- "able to store %zu elements\n",
- (nElems * sizeof(uint256)) >> 20, nMaxCacheSize >> 20, nElems);
+ LogPrint(BCLog::SCRIPT,
+ "Using %zu MiB out of %zu requested for script execution cache, "
+ "able to store %zu elements\n",
+ (nElems * sizeof(uint256)) >> 20, nMaxCacheSize >> 20, nElems);
}
uint256 GetScriptCacheKey(const CTransaction &tx, uint32_t flags) {
diff --git a/src/script/sigcache.cpp b/src/script/sigcache.cpp
--- a/src/script/sigcache.cpp
+++ b/src/script/sigcache.cpp
@@ -76,9 +76,10 @@
MAX_MAX_SIG_CACHE_SIZE) *
(size_t(1) << 20);
size_t nElems = signatureCache.setup_bytes(nMaxCacheSize);
- LogPrintf("Using %zu MiB out of %zu requested for signature cache, able to "
- "store %zu elements\n",
- (nElems * sizeof(uint256)) >> 20, nMaxCacheSize >> 20, nElems);
+ LogPrint(BCLog::SCRIPT,
+ "Using %zu MiB out of %zu requested for signature cache, able to "
+ "store %zu elements\n",
+ (nElems * sizeof(uint256)) >> 20, nMaxCacheSize >> 20, nElems);
}
bool CachingTransactionSignatureChecker::VerifySignature(
diff --git a/src/sync.cpp b/src/sync.cpp
--- a/src/sync.cpp
+++ b/src/sync.cpp
@@ -16,8 +16,8 @@
#endif
void PrintLockContention(const char *pszName, const char *pszFile, int nLine) {
- LogPrintf("LOCKCONTENTION: %s\n", pszName);
- LogPrintf("Locker: %s:%d\n", pszFile, nLine);
+ LogPrint(BCLog::SYNC, "LOCKCONTENTION: %s\n", pszName);
+ LogPrint(BCLog::SYNC, "Locker: %s:%d\n", pszFile, nLine);
}
#endif /* DEBUG_LOCKCONTENTION */
@@ -78,26 +78,26 @@
static void
potential_deadlock_detected(const std::pair<void *, void *> &mismatch,
const LockStack &s1, const LockStack &s2) {
- LogPrintf("POTENTIAL DEADLOCK DETECTED\n");
- LogPrintf("Previous lock order was:\n");
+ LogPrint(BCLog::SYNC, "POTENTIAL DEADLOCK DETECTED\n");
+ LogPrint(BCLog::SYNC, "Previous lock order was:\n");
for (const std::pair<void *, CLockLocation> &i : s2) {
if (i.first == mismatch.first) {
- LogPrintf(" (1)");
+ LogPrint(BCLog::SYNC, " (1)");
}
if (i.first == mismatch.second) {
- LogPrintf(" (2)");
+ LogPrint(BCLog::SYNC, " (2)");
}
- LogPrintf(" %s\n", i.second.ToString());
+ LogPrint(BCLog::SYNC, " %s\n", i.second.ToString());
}
- LogPrintf("Current lock order is:\n");
+ LogPrint(BCLog::SYNC, "Current lock order is:\n");
for (const std::pair<void *, CLockLocation> &i : s1) {
if (i.first == mismatch.first) {
- LogPrintf(" (1)");
+ LogPrint(BCLog::SYNC, " (1)");
}
if (i.first == mismatch.second) {
- LogPrintf(" (2)");
+ LogPrint(BCLog::SYNC, " (2)");
}
- LogPrintf(" %s\n", i.second.ToString());
+ LogPrint(BCLog::SYNC, " %s\n", i.second.ToString());
}
if (g_debug_lockorder_abort) {
fprintf(stderr, "Assertion failed: detected inconsistent lock order at "
diff --git a/src/test/testutil.cpp b/src/test/testutil.cpp
--- a/src/test/testutil.cpp
+++ b/src/test/testutil.cpp
@@ -25,7 +25,7 @@
path = fs::path("/tmp");
#endif
if (path.empty() || !fs::is_directory(path)) {
- LogPrintf("GetTempPath(): failed to find temp path\n");
+ LogPrint(BCLog::TEST, "GetTempPath(): failed to find temp path\n");
return fs::path("");
}
return path;
diff --git a/src/torcontrol.cpp b/src/torcontrol.cpp
--- a/src/torcontrol.cpp
+++ b/src/torcontrol.cpp
@@ -179,7 +179,8 @@
// long lines. Do this after evbuffer_readln to make sure all full lines
// have been removed from the buffer. Everything left is an incomplete line.
if (evbuffer_get_length(input) > MAX_LINE_LENGTH) {
- LogPrintf("tor: Disconnecting because MAX_LINE_LENGTH exceeded\n");
+ LogPrint(BCLog::TOR,
+ "tor: Disconnecting because MAX_LINE_LENGTH exceeded\n");
self->Disconnect();
}
}
@@ -211,7 +212,7 @@
if (evutil_parse_sockaddr_port(target.c_str(),
(struct sockaddr *)&connect_to_addr,
&connect_to_addrlen) < 0) {
- LogPrintf("tor: Error parsing socket address %s\n", target);
+ LogPrint(BCLog::TOR, "tor: Error parsing socket address %s\n", target);
return false;
}
@@ -227,7 +228,7 @@
// Finally, connect to target
if (bufferevent_socket_connect(b_conn, (struct sockaddr *)&connect_to_addr,
connect_to_addrlen) < 0) {
- LogPrintf("tor: Error connecting to address %s\n", target);
+ LogPrint(BCLog::TOR, "tor: Error connecting to address %s\n", target);
return false;
}
return true;
@@ -300,7 +301,7 @@
// skip closing '"'
++ptr;
/* TODO: unescape value - according to the spec this depends on the
- * context, some strings use C-LogPrintf style escape codes, some
+ * context, some strings use C-printf style escape codes, some
* don't. So may be better handled at the call site.
*/
} else {
@@ -420,14 +421,16 @@
reconnect_ev(0), reconnect_timeout(RECONNECT_TIMEOUT_START) {
reconnect_ev = event_new(base, -1, 0, reconnect_cb, this);
if (!reconnect_ev)
- LogPrintf(
+ LogPrint(
+ BCLog::TOR,
"tor: Failed to create event for reconnection: out of memory?\n");
// Start connection attempts immediately
if (!conn.Connect(_target,
boost::bind(&TorController::connected_cb, this, _1),
boost::bind(&TorController::disconnected_cb, this, _1))) {
- LogPrintf("tor: Initiating connection to Tor control port %s failed\n",
- _target);
+ LogPrint(BCLog::TOR,
+ "tor: Initiating connection to Tor control port %s failed\n",
+ _target);
}
// Read service private key if cached
std::pair<bool, std::string> pkf = ReadBinaryFile(GetPrivateKeyFile());
@@ -460,22 +463,25 @@
}
service = LookupNumeric(std::string(service_id + ".onion").c_str(),
GetListenPort());
- LogPrintf("tor: Got service ID %s, advertising service %s\n",
- service_id, service.ToString());
+ LogPrint(BCLog::TOR, "tor: Got service ID %s, advertising service %s\n",
+ service_id, service.ToString());
if (WriteBinaryFile(GetPrivateKeyFile(), private_key)) {
LogPrint(BCLog::TOR, "tor: Cached service private key to %s\n",
GetPrivateKeyFile());
} else {
- LogPrintf("tor: Error writing service private key to %s\n",
- GetPrivateKeyFile());
+ LogPrint(BCLog::TOR,
+ "tor: Error writing service private key to %s\n",
+ GetPrivateKeyFile());
}
AddLocal(service, LOCAL_MANUAL);
// ... onion requested - keep connection open
} else if (reply.code == 510) { // 510 Unrecognized command
- LogPrintf("tor: Add onion failed with unrecognized command (You "
- "probably need to upgrade Tor)\n");
+ LogPrint(BCLog::TOR,
+ "tor: Add onion failed with unrecognized command (You "
+ "probably need to upgrade Tor)\n");
} else {
- LogPrintf("tor: Add onion failed; error code %d\n", reply.code);
+ LogPrint(BCLog::TOR, "tor: Add onion failed; error code %d\n",
+ reply.code);
}
}
@@ -507,7 +513,7 @@
private_key, GetListenPort(), GetListenPort()),
boost::bind(&TorController::add_onion_cb, this, _1, _2));
} else {
- LogPrintf("tor: Authentication failed\n");
+ LogPrint(BCLog::TOR, "tor: Authentication failed\n");
}
}
@@ -556,7 +562,8 @@
"tor: AUTHCHALLENGE ServerHash %s ServerNonce %s\n",
HexStr(serverHash), HexStr(serverNonce));
if (serverNonce.size() != 32) {
- LogPrintf(
+ LogPrint(
+ BCLog::TOR,
"tor: ServerNonce is not 32 bytes, as required by spec\n");
return;
}
@@ -564,9 +571,10 @@
std::vector<uint8_t> computedServerHash = ComputeResponse(
TOR_SAFE_SERVERKEY, cookie, clientNonce, serverNonce);
if (computedServerHash != serverHash) {
- LogPrintf("tor: ServerHash %s does not match expected "
- "ServerHash %s\n",
- HexStr(serverHash), HexStr(computedServerHash));
+ LogPrint(BCLog::TOR,
+ "tor: ServerHash %s does not match expected "
+ "ServerHash %s\n",
+ HexStr(serverHash), HexStr(computedServerHash));
return;
}
@@ -575,10 +583,11 @@
_conn.Command("AUTHENTICATE " + HexStr(computedClientHash),
boost::bind(&TorController::auth_cb, this, _1, _2));
} else {
- LogPrintf("tor: Invalid reply to AUTHCHALLENGE\n");
+ LogPrint(BCLog::TOR, "tor: Invalid reply to AUTHCHALLENGE\n");
}
} else {
- LogPrintf("tor: SAFECOOKIE authentication challenge failed\n");
+ LogPrint(BCLog::TOR,
+ "tor: SAFECOOKIE authentication challenge failed\n");
}
}
@@ -633,8 +642,9 @@
"AUTHENTICATE \"" + torpassword + "\"",
boost::bind(&TorController::auth_cb, this, _1, _2));
} else {
- LogPrintf("tor: Password provided with -torpassword, but "
- "HASHEDPASSWORD authentication is not available\n");
+ LogPrint(BCLog::TOR,
+ "tor: Password provided with -torpassword, but "
+ "HASHEDPASSWORD authentication is not available\n");
}
} else if (methods.count("NULL")) {
LogPrint(BCLog::TOR, "tor: Using NULL authentication\n");
@@ -660,24 +670,27 @@
this, _1, _2));
} else {
if (status_cookie.first) {
- LogPrintf("tor: Authentication cookie %s is not exactly %i "
- "bytes, as is required by the spec\n",
- cookiefile, TOR_COOKIE_SIZE);
+ LogPrint(BCLog::TOR,
+ "tor: Authentication cookie %s is not exactly %i "
+ "bytes, as is required by the spec\n",
+ cookiefile, TOR_COOKIE_SIZE);
} else {
- LogPrintf("tor: Authentication cookie %s could not be "
- "opened (check permissions)\n",
- cookiefile);
+ LogPrint(BCLog::TOR,
+ "tor: Authentication cookie %s could not be "
+ "opened (check permissions)\n",
+ cookiefile);
}
}
} else if (methods.count("HASHEDPASSWORD")) {
- LogPrintf("tor: The only supported authentication mechanism left "
- "is password, but no password provided with "
- "-torpassword\n");
+ LogPrint(BCLog::TOR,
+ "tor: The only supported authentication mechanism left "
+ "is password, but no password provided with "
+ "-torpassword\n");
} else {
- LogPrintf("tor: No supported authentication method\n");
+ LogPrint(BCLog::TOR, "tor: No supported authentication method\n");
}
} else {
- LogPrintf("tor: Requesting protocol info failed\n");
+ LogPrint(BCLog::TOR, "tor: Requesting protocol info failed\n");
}
}
@@ -688,7 +701,8 @@
if (!_conn.Command(
"PROTOCOLINFO 1",
boost::bind(&TorController::protocolinfo_cb, this, _1, _2)))
- LogPrintf("tor: Error sending initial protocolinfo command\n");
+ LogPrint(BCLog::TOR,
+ "tor: Error sending initial protocolinfo command\n");
}
void TorController::disconnected_cb(TorControlConnection &_conn) {
@@ -714,7 +728,8 @@
if (!conn.Connect(target,
boost::bind(&TorController::connected_cb, this, _1),
boost::bind(&TorController::disconnected_cb, this, _1))) {
- LogPrintf(
+ LogPrint(
+ BCLog::TOR,
"tor: Re-initiating connection to Tor control port %s failed\n",
target);
}
@@ -748,7 +763,7 @@
#endif
gBase = event_base_new();
if (!gBase) {
- LogPrintf("tor: Unable to create event_base\n");
+ LogPrint(BCLog::TOR, "tor: Unable to create event_base\n");
return;
}
@@ -758,7 +773,7 @@
void InterruptTorControl() {
if (gBase) {
- LogPrintf("tor: Thread interrupt\n");
+ LogPrint(BCLog::TOR, "tor: Thread interrupt\n");
event_base_loopbreak(gBase);
}
}
diff --git a/src/txdb.cpp b/src/txdb.cpp
--- a/src/txdb.cpp
+++ b/src/txdb.cpp
@@ -127,7 +127,7 @@
if (crash_simulate) {
static FastRandomContext rng;
if (rng.randrange(crash_simulate) == 0) {
- LogPrintf("Simulating a crash. Goodbye.\n");
+ LogPrint(BCLog::COINDB, "Simulating a crash. Goodbye.\n");
_Exit(0);
}
}
@@ -388,8 +388,8 @@
}
int64_t count = 0;
- LogPrintf("Upgrading utxo-set database...\n");
- LogPrintf("[0%%]...");
+ LogPrint(BCLog::COINDB, "Upgrading utxo-set database...\n");
+ LogPrint(BCLog::COINDB, "[0%%]...");
size_t batch_size = 1 << 24;
CDBBatch batch(db);
uiInterface.SetProgressBreakAction(StartShutdown);
@@ -416,7 +416,7 @@
percentageDone);
if (reportDone < percentageDone / 10) {
// report max. every 10% step
- LogPrintf("[%d%%]...", percentageDone);
+ LogPrint(BCLog::COINDB, "[%d%%]...", percentageDone);
reportDone = percentageDone / 10;
}
}
@@ -452,6 +452,7 @@
db.WriteBatch(batch);
db.CompactRange({DB_COINS, uint256()}, key);
uiInterface.SetProgressBreakAction(std::function<void(void)>());
- LogPrintf("[%s].\n", ShutdownRequested() ? "CANCELLED" : "DONE");
+ LogPrint(BCLog::COINDB, "[%s].\n",
+ ShutdownRequested() ? "CANCELLED" : "DONE");
return !ShutdownRequested();
}
diff --git a/src/txmempool.cpp b/src/txmempool.cpp
--- a/src/txmempool.cpp
+++ b/src/txmempool.cpp
@@ -982,8 +982,9 @@
fileout << CLIENT_VERSION;
minerPolicyEstimator->Write(fileout);
} catch (const std::exception &) {
- LogPrintf("CTxMemPool::WriteFeeEstimates(): unable to write policy "
- "estimator data (non-fatal)\n");
+ LogPrint(BCLog::MEMPOOL,
+ "CTxMemPool::WriteFeeEstimates(): unable to write policy "
+ "estimator data (non-fatal)\n");
return false;
}
return true;
@@ -1002,8 +1003,9 @@
LOCK(cs);
minerPolicyEstimator->Read(filein, nVersionThatWrote);
} catch (const std::exception &) {
- LogPrintf("CTxMemPool::ReadFeeEstimates(): unable to read policy "
- "estimator data (non-fatal)\n");
+ LogPrint(BCLog::MEMPOOL,
+ "CTxMemPool::ReadFeeEstimates(): unable to read policy "
+ "estimator data (non-fatal)\n");
return false;
}
return true;
@@ -1042,8 +1044,9 @@
}
}
}
- LogPrintf("PrioritiseTransaction: %s priority += %f, fee += %d\n", strHash,
- dPriorityDelta, FormatMoney(nFeeDelta));
+ LogPrint(BCLog::MEMPOOL,
+ "PrioritiseTransaction: %s priority += %f, fee += %d\n", strHash,
+ dPriorityDelta, FormatMoney(nFeeDelta));
}
void CTxMemPool::ApplyDeltas(const uint256 hash, double &dPriorityDelta,
diff --git a/src/util.h b/src/util.h
--- a/src/util.h
+++ b/src/util.h
@@ -61,7 +61,7 @@
bool SetupNetworking();
template <typename... Args> bool error(const char *fmt, const Args &... args) {
- LogPrintf("ERROR: " + tfm::format(fmt, args...) + "\n");
+ LogPrint(BCLog::UTIL, "ERROR: " + tfm::format(fmt, args...) + "\n");
return false;
}
@@ -236,11 +236,11 @@
std::string s = strprintf("bitcoin-%s", name);
RenameThread(s.c_str());
try {
- LogPrintf("%s thread start\n", name);
+ LogPrint(BCLog::UTIL, "%s thread start\n", name);
func();
- LogPrintf("%s thread exit\n", name);
+ LogPrint(BCLog::UTIL, "%s thread exit\n", name);
} catch (const boost::thread_interrupted &) {
- LogPrintf("%s thread interrupt\n", name);
+ LogPrint(BCLog::UTIL, "%s thread interrupt\n", name);
throw;
} catch (const std::exception &e) {
PrintExceptionContinue(&e, name);
diff --git a/src/util.cpp b/src/util.cpp
--- a/src/util.cpp
+++ b/src/util.cpp
@@ -182,7 +182,8 @@
bool bool_val = InterpretBool(val);
if (!bool_val) {
// Double negatives like -nofoo=0 are supported (but discouraged)
- LogPrintf(
+ LogPrint(
+ BCLog::INIT,
"Warning: parsed potentially confusing double-negative %s=%s\n",
key, val);
}
@@ -361,7 +362,7 @@
void PrintExceptionContinue(const std::exception *pex, const char *pszThread) {
std::string message = FormatException(pex, pszThread);
- LogPrintf("\n\n************************\n%s\n", message);
+ LogPrint(BCLog::UTIL, "\n\n************************\n%s\n", message);
fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
}
@@ -400,7 +401,7 @@
fs::path &path = fNetSpecific ? pathCachedNetSpecific : pathCached;
- // This can be called during exceptions by LogPrintf(), so we cache the
+ // This can be called during exceptions by LogPrint(), so we cache the
// value so we don't have to do memory allocations after that.
if (!path.empty()) {
return path;
@@ -647,7 +648,8 @@
return fs::path(pszPath);
}
- LogPrintf(
+ LogPrint(
+ BCLog::INIT,
"SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
return fs::path("");
}
@@ -659,8 +661,8 @@
}
int nErr = ::system(strCommand.c_str());
if (nErr) {
- LogPrintf("runCommand error: system(%s) returned %d\n", strCommand,
- nErr);
+ LogPrint(BCLog::UTIL, "runCommand error: system(%s) returned %d\n",
+ strCommand, nErr);
}
}
diff --git a/src/validation.cpp b/src/validation.cpp
--- a/src/validation.cpp
+++ b/src/validation.cpp
@@ -686,9 +686,10 @@
__func__, txid.ToString(), FormatStateMessage(state));
}
- LogPrintf("Warning: -promiscuousmempool flags set to not include "
- "currently enforced soft forks, this may break mining or "
- "otherwise cause instability!\n");
+ LogPrint(BCLog::MEMPOOL,
+ "Warning: -promiscuousmempool flags set to not include "
+ "currently enforced soft forks, this may break mining or "
+ "otherwise cause instability!\n");
}
// This transaction should only count for fee estimation if
@@ -929,7 +930,7 @@
if (chainActive.Tip()->GetBlockTime() < (GetTime() - nMaxTipAge)) {
return true;
}
- LogPrintf("Leaving InitialBlockDownload (latching to false)\n");
+ LogPrint(BCLog::INIT, "Leaving InitialBlockDownload (latching to false)\n");
latchToFalse.store(true, std::memory_order_relaxed);
return false;
}
@@ -987,19 +988,21 @@
}
if (pindexBestForkTip && pindexBestForkBase) {
- LogPrintf("%s: Warning: Large fork found\n forking the "
- "chain at height %d (%s)\n lasting to height %d "
- "(%s).\nChain state database corruption likely.\n",
- __func__, pindexBestForkBase->nHeight,
- pindexBestForkBase->phashBlock->ToString(),
- pindexBestForkTip->nHeight,
- pindexBestForkTip->phashBlock->ToString());
+ LogPrint(BCLog::BENCH,
+ "%s: Warning: Large fork found\n forking the "
+ "chain at height %d (%s)\n lasting to height %d "
+ "(%s).\nChain state database corruption likely.\n",
+ __func__, pindexBestForkBase->nHeight,
+ pindexBestForkBase->phashBlock->ToString(),
+ pindexBestForkTip->nHeight,
+ pindexBestForkTip->phashBlock->ToString());
SetfLargeWorkForkFound(true);
} else {
- LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks "
- "longer than our best chain.\nChain state database "
- "corruption likely.\n",
- __func__);
+ LogPrint(BCLog::BENCH,
+ "%s: Warning: Found invalid chain at least ~6 blocks "
+ "longer than our best chain.\nChain state database "
+ "corruption likely.\n",
+ __func__);
SetfLargeWorkInvalidChainFound(true);
}
} else {
@@ -1041,17 +1044,18 @@
pindexBestInvalid = pindexNew;
}
- LogPrintf(
- "%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
- pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
- log(pindexNew->nChainWork.getdouble()) / log(2.0),
- DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pindexNew->GetBlockTime()));
+ LogPrint(BCLog::BENCH,
+ "%s: invalid block=%s height=%d log2_work=%.8g date=%s\n",
+ __func__, pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
+ log(pindexNew->nChainWork.getdouble()) / log(2.0),
+ DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pindexNew->GetBlockTime()));
CBlockIndex *tip = chainActive.Tip();
assert(tip);
- LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n",
- __func__, tip->GetBlockHash().ToString(), chainActive.Height(),
- log(tip->nChainWork.getdouble()) / log(2.0),
- DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
+ LogPrint(BCLog::BENCH,
+ "%s: current best=%s height=%d log2_work=%.8g date=%s\n",
+ __func__, tip->GetBlockHash().ToString(), chainActive.Height(),
+ log(tip->nChainWork.getdouble()) / log(2.0),
+ DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
}
static void InvalidBlockFound(CBlockIndex *pindex,
@@ -1279,7 +1283,7 @@
bool AbortNode(const std::string &strMessage,
const std::string &userMessage = "") {
SetMiscWarning(strMessage);
- LogPrintf("*** %s\n", strMessage);
+ LogPrint(BCLog::BENCH, "*** %s\n", strMessage);
uiInterface.ThreadSafeMessageBox(
userMessage.empty() ? _("Error: A fatal internal error occurred, see "
"debug.log for details")
@@ -2095,23 +2099,24 @@
}
}
}
- LogPrintf("%s: new best=%s height=%d version=0x%08x log2_work=%.8g tx=%lu "
- "date='%s' progress=%f cache=%.1fMiB(%utxo)",
- __func__, chainActive.Tip()->GetBlockHash().ToString(),
- chainActive.Height(), chainActive.Tip()->nVersion,
- log(chainActive.Tip()->nChainWork.getdouble()) / log(2.0),
- (unsigned long)chainActive.Tip()->nChainTx,
- DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
- chainActive.Tip()->GetBlockTime()),
- GuessVerificationProgress(config.GetChainParams().TxData(),
- chainActive.Tip()),
- pcoinsTip->DynamicMemoryUsage() * (1.0 / (1 << 20)),
- pcoinsTip->GetCacheSize());
+ LogPrint(BCLog::BENCH,
+ "%s: new best=%s height=%d version=0x%08x log2_work=%.8g tx=%lu "
+ "date='%s' progress=%f cache=%.1fMiB(%utxo)",
+ __func__, chainActive.Tip()->GetBlockHash().ToString(),
+ chainActive.Height(), chainActive.Tip()->nVersion,
+ log(chainActive.Tip()->nChainWork.getdouble()) / log(2.0),
+ (unsigned long)chainActive.Tip()->nChainTx,
+ DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
+ chainActive.Tip()->GetBlockTime()),
+ GuessVerificationProgress(config.GetChainParams().TxData(),
+ chainActive.Tip()),
+ pcoinsTip->DynamicMemoryUsage() * (1.0 / (1 << 20)),
+ pcoinsTip->GetCacheSize());
if (!warningMessages.empty()) {
- LogPrintf(" warning='%s'",
- boost::algorithm::join(warningMessages, ", "));
+ LogPrint(BCLog::BENCH, " warning='%s'",
+ boost::algorithm::join(warningMessages, ", "));
}
- LogPrintf("\n");
+ LogPrint(BCLog::BENCH, "\n");
}
/**
@@ -2982,8 +2987,8 @@
if ((int)nFile != nLastBlockFile) {
if (!fKnown) {
- LogPrintf("Leaving block file %i: %s\n", nLastBlockFile,
- vinfoBlockFile[nLastBlockFile].ToString());
+ LogPrint(BCLog::BENCH, "Leaving block file %i: %s\n",
+ nLastBlockFile, vinfoBlockFile[nLastBlockFile].ToString());
}
FlushBlockFile(!fKnown);
nLastBlockFile = nFile;
@@ -3011,7 +3016,8 @@
if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
FILE *file = OpenBlockFile(pos);
if (file) {
- LogPrintf(
+ LogPrint(
+ BCLog::BENCH,
"Pre-allocating up to position 0x%x in blk%05u.dat\n",
nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
AllocateFileRange(file, pos.nPos,
@@ -3052,8 +3058,9 @@
if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
FILE *file = OpenUndoFile(pos);
if (file) {
- LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n",
- nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
+ LogPrint(BCLog::BENCH,
+ "Pre-allocating up to position 0x%x in rev%05u.dat\n",
+ nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
AllocateFileRange(file, pos.nPos,
nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
fclose(file);
@@ -3247,7 +3254,8 @@
// Check proof of work
if (block.nBits != GetNextWorkRequired(pindexPrev, &block, config)) {
- LogPrintf("bad bits after height: %d\n", pindexPrev->nHeight);
+ LogPrint(BCLog::BENCH, "bad bits after height: %d\n",
+ pindexPrev->nHeight);
return state.DoS(100, false, REJECT_INVALID, "bad-diffbits", false,
"incorrect proof of work");
}
@@ -3536,13 +3544,15 @@
bool isSameHeight = chainActive.Tip() &&
(pindex->nChainWork == chainActive.Tip()->nChainWork);
if (isSameHeight) {
- LogPrintf("Chain tip timestamp-to-received-time difference: hash=%s, "
- "diff=%d\n",
- chainActive.Tip()->GetBlockHash().ToString(),
- chainTipTimeDiff);
- LogPrintf("New block timestamp-to-received-time difference: hash=%s, "
- "diff=%d\n",
- pindex->GetBlockHash().ToString(), newBlockTimeDiff);
+ LogPrint(BCLog::BENCH,
+ "Chain tip timestamp-to-received-time difference: hash=%s, "
+ "diff=%d\n",
+ chainActive.Tip()->GetBlockHash().ToString(),
+ chainTipTimeDiff);
+ LogPrint(BCLog::BENCH,
+ "New block timestamp-to-received-time difference: hash=%s, "
+ "diff=%d\n",
+ pindex->GetBlockHash().ToString(), newBlockTimeDiff);
}
bool fHasMoreWork =
@@ -3797,7 +3807,8 @@
CDiskBlockPos pos(i, 0);
fs::remove(GetBlockPosFilename(pos, "blk"));
fs::remove(GetBlockPosFilename(pos, "rev"));
- LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, i);
+ LogPrint(BCLog::PRUNE, "Prune: %s deleted blk/rev (%05u)\n", __func__,
+ i);
}
}
@@ -3829,8 +3840,9 @@
setFilesToPrune.insert(fileNumber);
count++;
}
- LogPrintf("Prune (Manual): prune_height=%d removed %d blk/rev pairs\n",
- nLastBlockWeCanPrune, count);
+ LogPrint(BCLog::PRUNE,
+ "Prune (Manual): prune_height=%d removed %d blk/rev pairs\n",
+ nLastBlockWeCanPrune, count);
}
/* This function is called from the RPC code for pruneblockchain */
@@ -3941,14 +3953,14 @@
}
if (!file) {
- LogPrintf("Unable to open file %s\n", path.string());
+ LogPrint(BCLog::BENCH, "Unable to open file %s\n", path.string());
return nullptr;
}
if (pos.nPos) {
if (fseek(file, pos.nPos, SEEK_SET)) {
- LogPrintf("Unable to seek to position %u of %s\n", pos.nPos,
- path.string());
+ LogPrint(BCLog::BENCH, "Unable to seek to position %u of %s\n",
+ pos.nPos, path.string());
fclose(file);
return nullptr;
}
@@ -4064,13 +4076,14 @@
// Load block file info
pblocktree->ReadLastBlockFile(nLastBlockFile);
vinfoBlockFile.resize(nLastBlockFile + 1);
- LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
+ LogPrint(BCLog::BENCH, "%s: last block file = %i\n", __func__,
+ nLastBlockFile);
for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
}
- LogPrintf("%s: last block file info: %s\n", __func__,
- vinfoBlockFile[nLastBlockFile].ToString());
+ LogPrint(BCLog::BENCH, "%s: last block file info: %s\n", __func__,
+ vinfoBlockFile[nLastBlockFile].ToString());
for (int nFile = nLastBlockFile + 1; true; nFile++) {
CBlockFileInfo info;
@@ -4082,7 +4095,7 @@
}
// Check presence of blk files
- LogPrintf("Checking all blk files are present...\n");
+ LogPrint(BCLog::BENCH, "Checking all blk files are present...\n");
std::set<int> setBlkDataFiles;
for (const std::pair<uint256, CBlockIndex *> &item : mapBlockIndex) {
CBlockIndex *pindex = item.second;
@@ -4102,7 +4115,8 @@
// Check whether we have ever pruned block & undo files
pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
if (fHavePruned) {
- LogPrintf(
+ LogPrint(
+ BCLog::PRUNE,
"LoadBlockIndexDB(): Block files have previously been pruned\n");
}
@@ -4113,8 +4127,8 @@
// Check whether we have a transaction index
pblocktree->ReadFlag("txindex", fTxIndex);
- LogPrintf("%s: transaction index %s\n", __func__,
- fTxIndex ? "enabled" : "disabled");
+ LogPrint(BCLog::BENCH, "%s: transaction index %s\n", __func__,
+ fTxIndex ? "enabled" : "disabled");
return true;
}
@@ -4128,7 +4142,7 @@
if (pcoinsTip->GetBestBlock().IsNull() && mapBlockIndex.size() == 1) {
// In case we just added the genesis block, connect it now, so
// that we always have a chainActive.Tip() when we return.
- LogPrintf("%s: Connecting genesis block...\n", __func__);
+ LogPrint(BCLog::BENCH, "%s: Connecting genesis block...\n", __func__);
CValidationState state;
if (!ActivateBestChain(config, state)) {
return false;
@@ -4145,7 +4159,8 @@
PruneBlockIndexCandidates();
- LogPrintf(
+ LogPrint(
+ BCLog::BENCH,
"Loaded best chain: hashBestChain=%s height=%d date=%s progress=%f\n",
chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
@@ -4181,8 +4196,8 @@
}
nCheckLevel = std::max(0, std::min(4, nCheckLevel));
- LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth,
- nCheckLevel);
+ LogPrint(BCLog::BENCH, "Verifying last %i blocks at level %i\n",
+ nCheckDepth, nCheckLevel);
CCoinsViewCache coins(coinsview);
CBlockIndex *pindexState = chainActive.Tip();
@@ -4190,7 +4205,7 @@
int nGoodTransactions = 0;
CValidationState state;
int reportDone = 0;
- LogPrintf("[0%%]...");
+ LogPrint(BCLog::BENCH, "[0%%]...");
for (CBlockIndex *pindex = chainActive.Tip(); pindex && pindex->pprev;
pindex = pindex->pprev) {
boost::this_thread::interruption_point();
@@ -4202,7 +4217,7 @@
if (reportDone < percentageDone / 10) {
// report every 10% step
- LogPrintf("[%d%%]...", percentageDone);
+ LogPrint(BCLog::BENCH, "[%d%%]...", percentageDone);
reportDone = percentageDone / 10;
}
@@ -4213,9 +4228,10 @@
if (fPruneMode && !pindex->nStatus.hasData()) {
// If pruning, only go back as far as we have data.
- LogPrintf("VerifyDB(): block verification stopping at height %d "
- "(pruning, no data)\n",
- pindex->nHeight);
+ LogPrint(BCLog::PRUNE,
+ "VerifyDB(): block verification stopping at height %d "
+ "(pruning, no data)\n",
+ pindex->nHeight);
break;
}
@@ -4312,10 +4328,11 @@
}
}
- LogPrintf("[DONE].\n");
- LogPrintf("No coin database inconsistencies in last %i blocks (%i "
- "transactions)\n",
- chainActive.Height() - pindexState->nHeight, nGoodTransactions);
+ LogPrint(BCLog::BENCH, "[DONE].\n");
+ LogPrint(BCLog::BENCH,
+ "No coin database inconsistencies in last %i blocks (%i "
+ "transactions)\n",
+ chainActive.Height() - pindexState->nHeight, nGoodTransactions);
return true;
}
@@ -4367,7 +4384,7 @@
}
uiInterface.ShowProgress(_("Replaying blocks..."), 0);
- LogPrintf("Replaying blocks\n");
+ LogPrint(BCLog::BENCH, "Replaying blocks\n");
// Old tip during the interrupted flush.
const CBlockIndex *pindexOld = nullptr;
@@ -4407,8 +4424,8 @@
pindexOld->GetBlockHash().ToString());
}
- LogPrintf("Rolling back %s (%i)\n",
- pindexOld->GetBlockHash().ToString(), pindexOld->nHeight);
+ LogPrint(BCLog::BENCH, "Rolling back %s (%i)\n",
+ pindexOld->GetBlockHash().ToString(), pindexOld->nHeight);
DisconnectResult res = DisconnectBlock(block, pindexOld, cache);
if (res == DISCONNECT_FAILED) {
return error(
@@ -4432,8 +4449,8 @@
for (int nHeight = nForkHeight + 1; nHeight <= pindexNew->nHeight;
++nHeight) {
const CBlockIndex *pindex = pindexNew->GetAncestor(nHeight);
- LogPrintf("Rolling forward %s (%i)\n",
- pindex->GetBlockHash().ToString(), nHeight);
+ LogPrint(BCLog::BENCH, "Rolling forward %s (%i)\n",
+ pindex->GetBlockHash().ToString(), nHeight);
if (!RollforwardBlock(pindex, cache, config)) {
return false;
}
@@ -4551,7 +4568,7 @@
// instead only check it prior to LoadBlockIndexDB to set
// needs_init.
- LogPrintf("Initializing databases...\n");
+ LogPrint(BCLog::INIT, "Initializing databases...\n");
// Use the provided setting for -txindex in the new database
fTxIndex = gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX);
pblocktree->WriteFlag("txindex", fTxIndex);
@@ -4744,8 +4761,8 @@
}
}
} catch (const std::exception &e) {
- LogPrintf("%s: Deserialize or I/O error - %s\n", __func__,
- e.what());
+ LogPrint(BCLog::REINDEX, "%s: Deserialize or I/O error - %s\n",
+ __func__, e.what());
}
}
} catch (const std::runtime_error &e) {
@@ -4753,8 +4770,9 @@
}
if (nLoaded > 0) {
- LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded,
- GetTimeMillis() - nStart);
+ LogPrint(BCLog::REINDEX,
+ "Loaded %i blocks from external file in %dms\n", nLoaded,
+ GetTimeMillis() - nStart);
}
return nLoaded > 0;
@@ -5097,8 +5115,8 @@
FILE *filestr = fsbridge::fopen(GetDataDir() / "mempool.dat", "rb");
CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
if (file.IsNull()) {
- LogPrintf(
- "Failed to open mempool file from disk. Continuing anyway.\n");
+ LogPrint(BCLog::MEMPOOL,
+ "Failed to open mempool file from disk. Continuing anyway.\n");
return false;
}
@@ -5157,15 +5175,17 @@
prioritydummy, i.second);
}
} catch (const std::exception &e) {
- LogPrintf("Failed to deserialize mempool data on disk: %s. Continuing "
- "anyway.\n",
- e.what());
+ LogPrint(BCLog::MEMPOOL,
+ "Failed to deserialize mempool data on disk: %s. Continuing "
+ "anyway.\n",
+ e.what());
return false;
}
- LogPrintf("Imported mempool transactions from disk: %i successes, %i "
- "failed, %i expired\n",
- count, failed, skipped);
+ LogPrint(BCLog::MEMPOOL,
+ "Imported mempool transactions from disk: %i successes, %i "
+ "failed, %i expired\n",
+ count, failed, skipped);
return true;
}
@@ -5211,10 +5231,11 @@
RenameOver(GetDataDir() / "mempool.dat.new",
GetDataDir() / "mempool.dat");
int64_t last = GetTimeMicros();
- LogPrintf("Dumped mempool: %gs to copy, %gs to dump\n",
- (mid - start) * 0.000001, (last - mid) * 0.000001);
+ LogPrint(BCLog::MEMPOOL, "Dumped mempool: %gs to copy, %gs to dump\n",
+ (mid - start) * 0.000001, (last - mid) * 0.000001);
} catch (const std::exception &e) {
- LogPrintf("Failed to dump mempool: %s. Continuing anyway.\n", e.what());
+ LogPrint(BCLog::MEMPOOL,
+ "Failed to dump mempool: %s. Continuing anyway.\n", e.what());
}
}
diff --git a/src/wallet/crypter.cpp b/src/wallet/crypter.cpp
--- a/src/wallet/crypter.cpp
+++ b/src/wallet/crypter.cpp
@@ -183,8 +183,9 @@
if (fDecryptionThoroughlyChecked) break;
}
if (keyPass && keyFail) {
- LogPrintf("The wallet is probably corrupted: Some keys decrypt but "
- "not all.\n");
+ LogPrint(BCLog::WALLET,
+ "The wallet is probably corrupted: Some keys decrypt but "
+ "not all.\n");
assert(false);
}
if (keyFail || !keyPass) return false;
diff --git a/src/wallet/db.cpp b/src/wallet/db.cpp
--- a/src/wallet/db.cpp
+++ b/src/wallet/db.cpp
@@ -35,9 +35,10 @@
fDbEnvInit = false;
int ret = dbenv->close(0);
if (ret != 0) {
- LogPrintf("CDBEnv::EnvShutdown: Error %d shutting down database "
- "environment: %s\n",
- ret, DbEnv::strerror(ret));
+ LogPrint(BCLog::DB,
+ "CDBEnv::EnvShutdown: Error %d shutting down database "
+ "environment: %s\n",
+ ret, DbEnv::strerror(ret));
}
if (!fMockDb) {
@@ -77,8 +78,8 @@
fs::path pathLogDir = pathIn / "database";
TryCreateDirectories(pathLogDir);
fs::path pathErrorFile = pathIn / "db.log";
- LogPrintf("CDBEnv::Open: LogDir=%s ErrorFile=%s\n", pathLogDir.string(),
- pathErrorFile.string());
+ LogPrint(BCLog::DB, "CDBEnv::Open: LogDir=%s ErrorFile=%s\n",
+ pathLogDir.string(), pathErrorFile.string());
unsigned int nEnvFlags = 0;
if (gArgs.GetBoolArg("-privdb", DEFAULT_WALLET_PRIVDB)) {
@@ -178,19 +179,22 @@
int result = bitdb.dbenv->dbrename(nullptr, filename.c_str(), nullptr,
newFilename.c_str(), DB_AUTO_COMMIT);
if (result == 0) {
- LogPrintf("Renamed %s to %s\n", filename, newFilename);
+ LogPrint(BCLog::DB, "Renamed %s to %s\n", filename, newFilename);
} else {
- LogPrintf("Failed to rename %s to %s\n", filename, newFilename);
+ LogPrint(BCLog::DB, "Failed to rename %s to %s\n", filename,
+ newFilename);
return false;
}
std::vector<CDBEnv::KeyValPair> salvagedData;
bool fSuccess = bitdb.Salvage(newFilename, true, salvagedData);
if (salvagedData.empty()) {
- LogPrintf("Salvage(aggressive) found no records in %s.\n", newFilename);
+ LogPrint(BCLog::DB, "Salvage(aggressive) found no records in %s.\n",
+ newFilename);
return false;
}
- LogPrintf("Salvage(aggressive) found %u records\n", salvagedData.size());
+ LogPrint(BCLog::DB, "Salvage(aggressive) found %u records\n",
+ salvagedData.size());
std::unique_ptr<Db> pdbCopy(new Db(bitdb.dbenv, 0));
int ret = pdbCopy->open(nullptr, // Txn pointer
@@ -200,7 +204,7 @@
DB_CREATE, // Flags
0);
if (ret > 0) {
- LogPrintf("Cannot create database file %s\n", filename);
+ LogPrint(BCLog::DB, "Cannot create database file %s\n", filename);
return false;
}
@@ -229,8 +233,9 @@
bool CDB::VerifyEnvironment(const std::string &walletFile,
const fs::path &dataDir, std::string &errorStr) {
- LogPrintf("Using BerkeleyDB version %s\n", DbEnv::version(0, 0, 0));
- LogPrintf("Using wallet %s\n", walletFile);
+ LogPrint(BCLog::DB, "Using BerkeleyDB version %s\n",
+ DbEnv::version(0, 0, 0));
+ LogPrint(BCLog::DB, "Using wallet %s\n", walletFile);
// Wallet file must be a plain filename without a directory
if (walletFile != fs::basename(walletFile) + fs::extension(walletFile)) {
@@ -246,8 +251,8 @@
dataDir / strprintf("database.%d.bak", GetTime());
try {
fs::rename(pathDatabase, pathDatabaseBak);
- LogPrintf("Moved old %s to %s. Retrying.\n", pathDatabase.string(),
- pathDatabaseBak.string());
+ LogPrint(BCLog::DB, "Moved old %s to %s. Retrying.\n",
+ pathDatabase.string(), pathDatabaseBak.string());
} catch (const fs::filesystem_error &) {
// failure is ok (well, not really, but it's not worse than what we
// started with)
@@ -311,17 +316,20 @@
Db db(dbenv, 0);
int result = db.verify(strFile.c_str(), nullptr, &strDump, flags);
if (result == DB_VERIFY_BAD) {
- LogPrintf("CDBEnv::Salvage: Database salvage found errors, all data "
- "may not be recoverable.\n");
+ LogPrint(BCLog::DB,
+ "CDBEnv::Salvage: Database salvage found errors, all data "
+ "may not be recoverable.\n");
if (!fAggressive) {
- LogPrintf("CDBEnv::Salvage: Rerun with aggressive mode to ignore "
- "errors and continue.\n");
+ LogPrint(BCLog::DB,
+ "CDBEnv::Salvage: Rerun with aggressive mode to ignore "
+ "errors and continue.\n");
return false;
}
}
if (result != 0 && result != DB_VERIFY_BAD) {
- LogPrintf("CDBEnv::Salvage: Database salvage failed with result %d.\n",
- result);
+ LogPrint(BCLog::DB,
+ "CDBEnv::Salvage: Database salvage failed with result %d.\n",
+ result);
return false;
}
@@ -348,8 +356,9 @@
}
getline(strDump, valueHex);
if (valueHex == DATA_END) {
- LogPrintf("CDBEnv::Salvage: WARNING: Number of keys in data "
- "does not match number of values.\n");
+ LogPrint(BCLog::DB,
+ "CDBEnv::Salvage: WARNING: Number of keys in data "
+ "does not match number of values.\n");
break;
}
vResult.push_back(make_pair(ParseHex(keyHex), ParseHex(valueHex)));
@@ -357,8 +366,9 @@
}
if (keyHex != DATA_END) {
- LogPrintf("CDBEnv::Salvage: WARNING: Unexpected end of file while "
- "reading salvage output.\n");
+ LogPrint(BCLog::DB,
+ "CDBEnv::Salvage: WARNING: Unexpected end of file while "
+ "reading salvage output.\n");
return false;
}
@@ -512,7 +522,7 @@
env->mapFileUseCount.erase(strFile);
bool fSuccess = true;
- LogPrintf("CDB::Rewrite: Rewriting %s...\n", strFile);
+ LogPrint(BCLog::DB, "CDB::Rewrite: Rewriting %s...\n", strFile);
std::string strFileRes = strFile + ".rewrite";
{
// surround usage of db with extra {}
@@ -526,7 +536,8 @@
DB_CREATE, // Flags
0);
if (ret > 0) {
- LogPrintf(
+ LogPrint(
+ BCLog::DB,
"CDB::Rewrite: Can't create database file %s\n",
strFileRes);
fSuccess = false;
@@ -587,7 +598,8 @@
}
}
if (!fSuccess) {
- LogPrintf(
+ LogPrint(
+ BCLog::DB,
"CDB::Rewrite: Failed to rewrite database file %s\n",
strFileRes);
}
@@ -716,18 +728,20 @@
try {
if (fs::equivalent(pathSrc, pathDest)) {
- LogPrintf("cannot backup to wallet source file %s\n",
- pathDest.string());
+ LogPrint(BCLog::DB,
+ "cannot backup to wallet source file %s\n",
+ pathDest.string());
return false;
}
fs::copy_file(pathSrc, pathDest,
fs::copy_option::overwrite_if_exists);
- LogPrintf("copied %s to %s\n", strFile, pathDest.string());
+ LogPrint(BCLog::DB, "copied %s to %s\n", strFile,
+ pathDest.string());
return true;
} catch (const fs::filesystem_error &e) {
- LogPrintf("error copying %s to %s - %s\n", strFile,
- pathDest.string(), e.what());
+ LogPrint(BCLog::DB, "error copying %s to %s - %s\n",
+ strFile, pathDest.string(), e.what());
return false;
}
}
diff --git a/src/wallet/init.cpp b/src/wallet/init.cpp
--- a/src/wallet/init.cpp
+++ b/src/wallet/init.cpp
@@ -112,9 +112,10 @@
if (gArgs.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY) &&
gArgs.SoftSetBoolArg("-walletbroadcast", false)) {
- LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting "
- "-walletbroadcast=0\n",
- __func__);
+ LogPrint(BCLog::WALLET,
+ "%s: parameter interaction: -blocksonly=1 -> setting "
+ "-walletbroadcast=0\n",
+ __func__);
}
if (gArgs.GetBoolArg("-salvagewallet", false) &&
@@ -125,17 +126,19 @@
"-salvagewallet"));
}
// Rewrite just private keys: rescan to find transactions
- LogPrintf("%s: parameter interaction: -salvagewallet=1 -> setting "
- "-rescan=1\n",
- __func__);
+ LogPrint(BCLog::WALLET,
+ "%s: parameter interaction: -salvagewallet=1 -> setting "
+ "-rescan=1\n",
+ __func__);
}
int zapwallettxes = gArgs.GetArg("-zapwallettxes", 0);
// -zapwallettxes implies dropping the mempool on startup
if (zapwallettxes != 0 && gArgs.SoftSetBoolArg("-persistmempool", false)) {
- LogPrintf("%s: parameter interaction: -zapwallettxes=%s -> setting "
- "-persistmempool=0\n",
- __func__, zapwallettxes);
+ LogPrint(BCLog::WALLET,
+ "%s: parameter interaction: -zapwallettxes=%s -> setting "
+ "-persistmempool=0\n",
+ __func__, zapwallettxes);
}
// -zapwallettxes implies a rescan
@@ -146,13 +149,15 @@
"-zapwallettxes"));
}
if (gArgs.SoftSetBoolArg("-rescan", true)) {
- LogPrintf("%s: parameter interaction: -zapwallettxes=%s -> setting "
- "-rescan=1\n",
- __func__, zapwallettxes);
+ LogPrint(BCLog::WALLET,
+ "%s: parameter interaction: -zapwallettxes=%s -> setting "
+ "-rescan=1\n",
+ __func__, zapwallettxes);
}
- LogPrintf("%s: parameter interaction: -zapwallettxes=<mode> -> setting "
- "-rescan=1\n",
- __func__);
+ LogPrint(BCLog::WALLET,
+ "%s: parameter interaction: -zapwallettxes=<mode> -> setting "
+ "-rescan=1\n",
+ __func__);
}
if (is_multiwallet) {
@@ -322,7 +327,7 @@
bool InitLoadWallet(const CChainParams &chainParams) {
if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) {
- LogPrintf("Wallet disabled!\n");
+ LogPrint(BCLog::WALLET, "Wallet disabled!\n");
return true;
}
diff --git a/src/wallet/rpcdump.cpp b/src/wallet/rpcdump.cpp
--- a/src/wallet/rpcdump.cpp
+++ b/src/wallet/rpcdump.cpp
@@ -597,8 +597,9 @@
assert(key.VerifyPubKey(pubkey));
CKeyID keyid = pubkey.GetID();
if (pwallet->HaveKey(keyid)) {
- LogPrintf("Skipping import of %s (key already present)\n",
- EncodeDestination(keyid));
+ LogPrint(BCLog::WALLET,
+ "Skipping import of %s (key already present)\n",
+ EncodeDestination(keyid));
continue;
}
int64_t nTime = DecodeDumpTime(vstr[1]);
@@ -619,7 +620,7 @@
fLabel = true;
}
}
- LogPrintf("Importing %s...\n", EncodeDestination(keyid));
+ LogPrint(BCLog::WALLET, "Importing %s...\n", EncodeDestination(keyid));
if (!pwallet->AddKeyPubKey(key, pubkey)) {
fGood = false;
continue;
diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp
--- a/src/wallet/wallet.cpp
+++ b/src/wallet/wallet.cpp
@@ -337,11 +337,12 @@
*/
if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE) {
std::string strAddr = EncodeDestination(CScriptID(redeemScript));
- LogPrintf("%s: Warning: This wallet contains a redeemScript of size %i "
- "which exceeds maximum size %i thus can never be redeemed. "
- "Do not use address %s.\n",
- __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE,
- strAddr);
+ LogPrint(BCLog::WALLET,
+ "%s: Warning: This wallet contains a redeemScript of size %i "
+ "which exceeds maximum size %i thus can never be redeemed. "
+ "Do not use address %s.\n",
+ __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE,
+ strAddr);
return true;
}
@@ -454,7 +455,8 @@
pMasterKey.second.nDeriveIterations = 25000;
}
- LogPrintf(
+ LogPrint(
+ BCLog::WALLET,
"Wallet passphrase changed to an nDeriveIterations of %i\n",
pMasterKey.second.nDeriveIterations);
@@ -692,8 +694,9 @@
kMasterKey.nDeriveIterations = 25000;
}
- LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n",
- kMasterKey.nDeriveIterations);
+ LogPrint(BCLog::WALLET,
+ "Encrypting Wallet with an nDeriveIterations of %i\n",
+ kMasterKey.nDeriveIterations);
if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt,
kMasterKey.nDeriveIterations,
@@ -982,8 +985,8 @@
}
//// debug print
- LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetId().ToString(),
- (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
+ LogPrint(BCLog::WALLET, "AddToWallet %s %s%s\n", wtxIn.GetId().ToString(),
+ (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
// Write to disk
if ((fInsertedNew || fUpdated) && !walletdb.WriteTx(wtx)) {
@@ -1055,13 +1058,14 @@
range = mapTxSpends.equal_range(txin.prevout);
while (range.first != range.second) {
if (range.first->second != tx.GetId()) {
- LogPrintf("Transaction %s (in block %s) conflicts with "
- "wallet transaction %s (both spend %s:%i)\n",
- tx.GetId().ToString(),
- pIndex->GetBlockHash().ToString(),
- range.first->second.ToString(),
- range.first->first.GetTxId().ToString(),
- range.first->first.GetN());
+ LogPrint(BCLog::WALLET,
+ "Transaction %s (in block %s) conflicts with "
+ "wallet transaction %s (both spend %s:%i)\n",
+ tx.GetId().ToString(),
+ pIndex->GetBlockHash().ToString(),
+ range.first->second.ToString(),
+ range.first->first.GetTxId().ToString(),
+ range.first->first.GetN());
MarkConflicted(pIndex->GetBlockHash(), range.first->second);
}
range.first++;
@@ -1092,13 +1096,15 @@
std::map<CKeyID, int64_t>::const_iterator mi =
m_pool_key_to_index.find(keyid);
if (mi != m_pool_key_to_index.end()) {
- LogPrintf("%s: Detected a used keypool key, mark all "
- "keypool key up to this key as used\n",
- __func__);
+ LogPrint(BCLog::WALLET,
+ "%s: Detected a used keypool key, mark all "
+ "keypool key up to this key as used\n",
+ __func__);
MarkReserveKeysAsUsed(mi->second);
if (!TopUpKeyPool()) {
- LogPrintf(
+ LogPrint(
+ BCLog::WALLET,
"%s: Topping up keypool failed (locked wallet)\n",
__func__);
}
@@ -1600,9 +1606,10 @@
if (!ExtractDestination(txout.scriptPubKey, address) &&
!txout.scriptPubKey.IsUnspendable()) {
- LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, "
- "txid %s\n",
- this->GetId().ToString());
+ LogPrint(BCLog::WALLET,
+ "CWalletTx::GetAmounts: Unknown transaction type found, "
+ "txid %s\n",
+ this->GetId().ToString());
address = CNoDestination();
}
@@ -1638,8 +1645,8 @@
// to be scanned.
CBlockIndex *const startBlock =
chainActive.FindEarliestAtLeast(startTime - TIMESTAMP_WINDOW);
- LogPrintf("%s: Rescanning last %i blocks\n", __func__,
- startBlock ? chainActive.Height() - startBlock->nHeight + 1 : 0);
+ LogPrint(BCLog::WALLET, "%s: Rescanning last %i blocks\n", __func__,
+ startBlock ? chainActive.Height() - startBlock->nHeight + 1 : 0);
if (startBlock) {
const CBlockIndex *const failedBlock =
@@ -1715,15 +1722,17 @@
pindex = chainActive.Next(pindex);
if (GetTime() >= nNow + 60) {
nNow = GetTime();
- LogPrintf("Still rescanning. At block %d. Progress=%f\n",
- pindex->nHeight,
- GuessVerificationProgress(chainParams.TxData(), pindex));
+ LogPrint(BCLog::WALLET,
+ "Still rescanning. At block %d. Progress=%f\n",
+ pindex->nHeight,
+ GuessVerificationProgress(chainParams.TxData(), pindex));
}
}
if (pindex && fAbortRescan) {
- LogPrintf("Rescan aborted at block %d. Progress=%f\n", pindex->nHeight,
- GuessVerificationProgress(chainParams.TxData(), pindex));
+ LogPrint(BCLog::WALLET, "Rescan aborted at block %d. Progress=%f\n",
+ pindex->nHeight,
+ GuessVerificationProgress(chainParams.TxData(), pindex));
}
// Hide progress dialog in GUI.
@@ -1776,7 +1785,7 @@
CValidationState state;
// GetDepthInMainChain already catches known conflicts.
if (InMempool() || AcceptToMemoryPool(maxTxFee, state)) {
- LogPrintf("Relaying wtx %s\n", GetId().ToString());
+ LogPrint(BCLog::WALLET, "Relaying wtx %s\n", GetId().ToString());
if (connman) {
CInv inv(MSG_TX, GetId());
connman->ForEachNode(
@@ -2083,8 +2092,8 @@
std::vector<uint256> relayed =
ResendWalletTransactionsBefore(nBestBlockTime - 5 * 60, connman);
if (!relayed.empty()) {
- LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__,
- relayed.size());
+ LogPrint(BCLog::WALLET, "%s: rebroadcast %u unconfirmed transactions\n",
+ __func__, relayed.size());
}
}
@@ -3075,7 +3084,7 @@
bool CWallet::CommitTransaction(CWalletTx &wtxNew, CReserveKey &reservekey,
CConnman *connman, CValidationState &state) {
LOCK2(cs_main, cs_wallet);
- LogPrintf("CommitTransaction:\n%s", wtxNew.tx->ToString());
+ LogPrint(BCLog::WALLET, "CommitTransaction:\n%s", wtxNew.tx->ToString());
// Take key pair from key pool so it won't be used again.
reservekey.KeepKey();
@@ -3097,9 +3106,10 @@
if (fBroadcastTransactions) {
// Broadcast
if (!wtxNew.AcceptToMemoryPool(maxTxFee, state)) {
- LogPrintf("CommitTransaction(): Transaction cannot be "
- "broadcast immediately, %s\n",
- state.GetRejectReason());
+ LogPrint(BCLog::WALLET,
+ "CommitTransaction(): Transaction cannot be "
+ "broadcast immediately, %s\n",
+ state.GetRejectReason());
// TODO: if we expect the failure to be long term or permanent,
// instead delete wtx from the wallet and return failure.
} else {
@@ -3302,7 +3312,7 @@
return false;
}
- LogPrintf("CWallet::NewKeyPool rewrote keypool\n");
+ LogPrint(BCLog::WALLET, "CWallet::NewKeyPool rewrote keypool\n");
return true;
}
@@ -3384,11 +3394,11 @@
m_pool_key_to_index[pubkey.GetID()] = index;
}
if (missingInternal + missingExternal > 0) {
- LogPrintf(
- "keypool added %d keys (%d internal), size=%u (%u internal)\n",
- missingInternal + missingExternal, missingInternal,
- setInternalKeyPool.size() + setExternalKeyPool.size(),
- setInternalKeyPool.size());
+ LogPrint(BCLog::WALLET,
+ "keypool added %d keys (%d internal), size=%u (%u internal)\n",
+ missingInternal + missingExternal, missingInternal,
+ setInternalKeyPool.size() + setExternalKeyPool.size(),
+ setInternalKeyPool.size());
}
return true;
@@ -3435,14 +3445,14 @@
assert(keypool.vchPubKey.IsValid());
m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
- LogPrintf("keypool reserve %d\n", nIndex);
+ LogPrint(BCLog::WALLET, "keypool reserve %d\n", nIndex);
}
void CWallet::KeepKey(int64_t nIndex) {
// Remove from key pool.
CWalletDB walletdb(*dbw);
walletdb.ErasePool(nIndex);
- LogPrintf("keypool keep %d\n", nIndex);
+ LogPrint(BCLog::WALLET, "keypool keep %d\n", nIndex);
}
void CWallet::ReturnKey(int64_t nIndex, bool fInternal, const CPubKey &pubkey) {
@@ -3457,7 +3467,7 @@
m_pool_key_to_index[pubkey.GetID()] = nIndex;
}
- LogPrintf("keypool return %d\n", nIndex);
+ LogPrint(BCLog::WALLET, "keypool return %d\n", nIndex);
}
bool CWallet::GetKeyFromPool(CPubKey &result, bool internal) {
@@ -3919,8 +3929,9 @@
int64_t blocktime = mapBlockIndex[wtx.hashBlock]->GetBlockTime();
nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
} else {
- LogPrintf("%s: found %s in block %s not in index\n", __func__,
- wtx.GetId().ToString(), wtx.hashBlock.ToString());
+ LogPrint(BCLog::WALLET, "%s: found %s in block %s not in index\n",
+ __func__, wtx.GetId().ToString(),
+ wtx.hashBlock.ToString());
}
}
return nTimeSmart;
@@ -4033,12 +4044,14 @@
int nMaxVersion = gArgs.GetArg("-upgradewallet", 0);
// The -upgradewallet without argument case
if (nMaxVersion == 0) {
- LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
+ LogPrint(BCLog::WALLET, "Performing wallet upgrade to %i\n",
+ FEATURE_LATEST);
nMaxVersion = CLIENT_VERSION;
// permanently upgrade the wallet immediately
walletInstance->SetMinVersion(FEATURE_LATEST);
} else {
- LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
+ LogPrint(BCLog::WALLET, "Allowing wallet upgrade up to %i\n",
+ nMaxVersion);
}
if (nMaxVersion < walletInstance->GetVersion()) {
@@ -4090,7 +4103,7 @@
}
}
- LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart);
+ LogPrint(BCLog::WALLET, " wallet %15dms\n", GetTimeMillis() - nStart);
RegisterValidationInterface(walletInstance);
@@ -4127,9 +4140,10 @@
}
uiInterface.InitMessage(_("Rescanning..."));
- LogPrintf("Rescanning last %i blocks (from block %i)...\n",
- chainActive.Height() - pindexRescan->nHeight,
- pindexRescan->nHeight);
+ LogPrint(BCLog::WALLET,
+ "Rescanning last %i blocks (from block %i)...\n",
+ chainActive.Height() - pindexRescan->nHeight,
+ pindexRescan->nHeight);
// No need to read and scan block if block was created before our wallet
// birthday (as adjusted for block time variability)
@@ -4141,7 +4155,8 @@
nStart = GetTimeMillis();
walletInstance->ScanForWalletTransactions(pindexRescan, nullptr, true);
- LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart);
+ LogPrint(BCLog::WALLET, " rescan %15dms\n",
+ GetTimeMillis() - nStart);
walletInstance->SetBestChain(chainActive.GetLocator());
walletInstance->dbw->IncrementUpdateCounter();
@@ -4174,10 +4189,12 @@
gArgs.GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
LOCK(walletInstance->cs_wallet);
- LogPrintf("setKeyPool.size() = %u\n", walletInstance->GetKeyPoolSize());
- LogPrintf("mapWallet.size() = %u\n", walletInstance->mapWallet.size());
- LogPrintf("mapAddressBook.size() = %u\n",
- walletInstance->mapAddressBook.size());
+ LogPrint(BCLog::WALLET, "setKeyPool.size() = %u\n",
+ walletInstance->GetKeyPoolSize());
+ LogPrint(BCLog::WALLET, "mapWallet.size() = %u\n",
+ walletInstance->mapWallet.size());
+ LogPrint(BCLog::WALLET, "mapAddressBook.size() = %u\n",
+ walletInstance->mapAddressBook.size());
return walletInstance;
}
diff --git a/src/wallet/walletdb.cpp b/src/wallet/walletdb.cpp
--- a/src/wallet/walletdb.cpp
+++ b/src/wallet/walletdb.cpp
@@ -545,7 +545,7 @@
// Get cursor
Dbc *pcursor = batch.GetCursor();
if (!pcursor) {
- LogPrintf("Error getting wallet database cursor\n");
+ LogPrint(BCLog::DB, "Error getting wallet database cursor\n");
return DB_CORRUPT;
}
@@ -559,7 +559,8 @@
}
if (ret != 0) {
- LogPrintf("Error reading next record from wallet database\n");
+ LogPrint(BCLog::DB,
+ "Error reading next record from wallet database\n");
return DB_CORRUPT;
}
@@ -582,7 +583,7 @@
}
}
if (!strErr.empty()) {
- LogPrintf("%s\n", strErr);
+ LogPrint(BCLog::DB, "%s\n", strErr);
}
}
pcursor->close();
@@ -602,10 +603,11 @@
return result;
}
- LogPrintf("nFileVersion = %d\n", wss.nFileVersion);
+ LogPrint(BCLog::DB, "nFileVersion = %d\n", wss.nFileVersion);
- LogPrintf("Keys: %u plaintext, %u encrypted, %u w/ metadata, %u total\n",
- wss.nKeys, wss.nCKeys, wss.nKeyMeta, wss.nKeys + wss.nCKeys);
+ LogPrint(BCLog::DB,
+ "Keys: %u plaintext, %u encrypted, %u w/ metadata, %u total\n",
+ wss.nKeys, wss.nCKeys, wss.nKeyMeta, wss.nKeys + wss.nCKeys);
// nTimeFirstKey is only reliable if all keys have metadata
if ((wss.nKeys + wss.nCKeys + wss.nWatchKeys) != wss.nKeyMeta) {
@@ -657,7 +659,7 @@
// Get cursor
Dbc *pcursor = batch.GetCursor();
if (!pcursor) {
- LogPrintf("Error getting wallet database cursor\n");
+ LogPrint(BCLog::DB, "Error getting wallet database cursor\n");
return DB_CORRUPT;
}
@@ -671,7 +673,8 @@
}
if (ret != 0) {
- LogPrintf("Error reading next record from wallet database\n");
+ LogPrint(BCLog::DB,
+ "Error reading next record from wallet database\n");
return DB_CORRUPT;
}
@@ -826,8 +829,8 @@
return false;
}
if (!fReadOK) {
- LogPrintf("WARNING: CWalletDB::Recover skipping %s: %s\n", strType,
- strErr);
+ LogPrint(BCLog::DB, "WARNING: CWalletDB::Recover skipping %s: %s\n",
+ strType, strErr);
return false;
}

File Metadata

Mime Type
text/plain
Expires
Sat, Mar 1, 11:07 (14 h, 46 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
5187512
Default Alt Text
D2016.diff (146 KB)

Event Timeline