Bitcoin Core Fuzz Coverage Report for wallet_tx_can_be_bumped

Coverage Report

Created: 2025-11-19 11:20

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/Users/brunogarcia/projects/bitcoin-core-dev/src/logging.cpp
Line
Count
Source
1
// Copyright (c) 2009-2010 Satoshi Nakamoto
2
// Copyright (c) 2009-present The Bitcoin Core developers
3
// Distributed under the MIT software license, see the accompanying
4
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6
#include <logging.h>
7
#include <memusage.h>
8
#include <util/check.h>
9
#include <util/fs.h>
10
#include <util/string.h>
11
#include <util/threadnames.h>
12
#include <util/time.h>
13
14
#include <array>
15
#include <cstring>
16
#include <map>
17
#include <optional>
18
#include <utility>
19
20
using util::Join;
21
using util::RemovePrefixView;
22
23
const char * const DEFAULT_DEBUGLOGFILE = "debug.log";
24
constexpr auto MAX_USER_SETABLE_SEVERITY_LEVEL{BCLog::Level::Info};
25
26
BCLog::Logger& LogInstance()
27
106k
{
28
/**
29
 * NOTE: the logger instances is leaked on exit. This is ugly, but will be
30
 * cleaned up by the OS/libc. Defining a logger as a global object doesn't work
31
 * since the order of destruction of static/global objects is undefined.
32
 * Consider if the logger gets destroyed, and then some later destructor calls
33
 * LogPrintf, maybe indirectly, and you get a core dump at shutdown trying to
34
 * access the logger. When the shutdown sequence is fully audited and tested,
35
 * explicit destruction of these objects can be implemented by changing this
36
 * from a raw pointer to a std::unique_ptr.
37
 * Since the ~Logger() destructor is never called, the Logger class and all
38
 * its subclasses must have implicitly-defined destructors.
39
 *
40
 * This method of initialization was originally introduced in
41
 * ee3374234c60aba2cc4c5cd5cac1c0aefc2d817c.
42
 */
43
106k
    static BCLog::Logger* g_logger{new BCLog::Logger()};
44
106k
    return *g_logger;
45
106k
}
46
47
bool fLogIPs = DEFAULT_LOGIPS;
48
49
static int FileWriteStr(std::string_view str, FILE *fp)
50
0
{
51
0
    return fwrite(str.data(), 1, str.size(), fp);
52
0
}
53
54
bool BCLog::Logger::StartLogging()
55
0
{
56
0
    StdLockGuard scoped_lock(m_cs);
57
58
0
    assert(m_buffering);
59
0
    assert(m_fileout == nullptr);
60
61
0
    if (m_print_to_file) {
62
0
        assert(!m_file_path.empty());
63
0
        m_fileout = fsbridge::fopen(m_file_path, "a");
64
0
        if (!m_fileout) {
65
0
            return false;
66
0
        }
67
68
0
        setbuf(m_fileout, nullptr); // unbuffered
69
70
        // Add newlines to the logfile to distinguish this execution from the
71
        // last one.
72
0
        FileWriteStr("\n\n\n\n\n", m_fileout);
73
0
    }
74
75
    // dump buffered messages from before we opened the log
76
0
    m_buffering = false;
77
0
    if (m_buffer_lines_discarded > 0) {
78
0
        LogPrintStr_(strprintf("Early logging buffer overflowed, %d log lines discarded.\n", m_buffer_lines_discarded), std::source_location::current(), BCLog::ALL, Level::Info, /*should_ratelimit=*/false);
Line
Count
Source
1172
0
#define strprintf tfm::format
79
0
    }
80
0
    while (!m_msgs_before_open.empty()) {
81
0
        const auto& buflog = m_msgs_before_open.front();
82
0
        std::string s{buflog.str};
83
0
        FormatLogStrInPlace(s, buflog.category, buflog.level, buflog.source_loc, buflog.threadname, buflog.now, buflog.mocktime);
84
0
        m_msgs_before_open.pop_front();
85
86
0
        if (m_print_to_file) FileWriteStr(s, m_fileout);
87
0
        if (m_print_to_console) fwrite(s.data(), 1, s.size(), stdout);
88
0
        for (const auto& cb : m_print_callbacks) {
89
0
            cb(s);
90
0
        }
91
0
    }
92
0
    m_cur_buffer_memusage = 0;
93
0
    if (m_print_to_console) fflush(stdout);
94
95
0
    return true;
96
0
}
97
98
void BCLog::Logger::DisconnectTestLogger()
99
1
{
100
1
    StdLockGuard scoped_lock(m_cs);
101
1
    m_buffering = true;
102
1
    if (m_fileout != nullptr) 
fclose(m_fileout)0
;
103
1
    m_fileout = nullptr;
104
1
    m_print_callbacks.clear();
105
1
    m_max_buffer_memusage = DEFAULT_MAX_LOG_BUFFER;
106
1
    m_cur_buffer_memusage = 0;
107
1
    m_buffer_lines_discarded = 0;
108
1
    m_msgs_before_open.clear();
109
1
}
110
111
void BCLog::Logger::DisableLogging()
112
0
{
113
0
    {
114
0
        StdLockGuard scoped_lock(m_cs);
115
0
        assert(m_buffering);
116
0
        assert(m_print_callbacks.empty());
117
0
    }
118
0
    m_print_to_file = false;
119
0
    m_print_to_console = false;
120
0
    StartLogging();
121
0
}
122
123
void BCLog::Logger::EnableCategory(BCLog::LogFlags flag)
124
0
{
125
0
    m_categories |= flag;
126
0
}
127
128
bool BCLog::Logger::EnableCategory(std::string_view str)
129
0
{
130
0
    BCLog::LogFlags flag;
131
0
    if (!GetLogCategory(flag, str)) return false;
132
0
    EnableCategory(flag);
133
0
    return true;
134
0
}
135
136
void BCLog::Logger::DisableCategory(BCLog::LogFlags flag)
137
0
{
138
0
    m_categories &= ~flag;
139
0
}
140
141
bool BCLog::Logger::DisableCategory(std::string_view str)
142
0
{
143
0
    BCLog::LogFlags flag;
144
0
    if (!GetLogCategory(flag, str)) return false;
145
0
    DisableCategory(flag);
146
0
    return true;
147
0
}
148
149
bool BCLog::Logger::WillLogCategory(BCLog::LogFlags category) const
150
0
{
151
0
    return (m_categories.load(std::memory_order_relaxed) & category) != 0;
152
0
}
153
154
bool BCLog::Logger::WillLogCategoryLevel(BCLog::LogFlags category, BCLog::Level level) const
155
0
{
156
    // Log messages at Info, Warning and Error level unconditionally, so that
157
    // important troubleshooting information doesn't get lost.
158
0
    if (level >= BCLog::Level::Info) return true;
159
160
0
    if (!WillLogCategory(category)) return false;
161
162
0
    StdLockGuard scoped_lock(m_cs);
163
0
    const auto it{m_category_log_levels.find(category)};
164
0
    return level >= (it == m_category_log_levels.end() ? LogLevel() : it->second);
165
0
}
166
167
bool BCLog::Logger::DefaultShrinkDebugFile() const
168
0
{
169
0
    return m_categories == BCLog::NONE;
170
0
}
171
172
static const std::map<std::string, BCLog::LogFlags, std::less<>> LOG_CATEGORIES_BY_STR{
173
    {"net", BCLog::NET},
174
    {"tor", BCLog::TOR},
175
    {"mempool", BCLog::MEMPOOL},
176
    {"http", BCLog::HTTP},
177
    {"bench", BCLog::BENCH},
178
    {"zmq", BCLog::ZMQ},
179
    {"walletdb", BCLog::WALLETDB},
180
    {"rpc", BCLog::RPC},
181
    {"estimatefee", BCLog::ESTIMATEFEE},
182
    {"addrman", BCLog::ADDRMAN},
183
    {"selectcoins", BCLog::SELECTCOINS},
184
    {"reindex", BCLog::REINDEX},
185
    {"cmpctblock", BCLog::CMPCTBLOCK},
186
    {"rand", BCLog::RAND},
187
    {"prune", BCLog::PRUNE},
188
    {"proxy", BCLog::PROXY},
189
    {"mempoolrej", BCLog::MEMPOOLREJ},
190
    {"libevent", BCLog::LIBEVENT},
191
    {"coindb", BCLog::COINDB},
192
    {"qt", BCLog::QT},
193
    {"leveldb", BCLog::LEVELDB},
194
    {"validation", BCLog::VALIDATION},
195
    {"i2p", BCLog::I2P},
196
    {"ipc", BCLog::IPC},
197
#ifdef DEBUG_LOCKCONTENTION
198
    {"lock", BCLog::LOCK},
199
#endif
200
    {"blockstorage", BCLog::BLOCKSTORAGE},
201
    {"txreconciliation", BCLog::TXRECONCILIATION},
202
    {"scan", BCLog::SCAN},
203
    {"txpackages", BCLog::TXPACKAGES},
204
    {"kernel", BCLog::KERNEL},
205
};
206
207
static const std::unordered_map<BCLog::LogFlags, std::string> LOG_CATEGORIES_BY_FLAG{
208
    // Swap keys and values from LOG_CATEGORIES_BY_STR.
209
0
    [](const auto& in) {
210
0
        std::unordered_map<BCLog::LogFlags, std::string> out;
211
0
        for (const auto& [k, v] : in) {
212
0
            const bool inserted{out.emplace(v, k).second};
213
0
            assert(inserted);
214
0
        }
215
0
        return out;
216
0
    }(LOG_CATEGORIES_BY_STR)
217
};
218
219
bool GetLogCategory(BCLog::LogFlags& flag, std::string_view str)
220
0
{
221
0
    if (str.empty() || str == "1" || str == "all") {
222
0
        flag = BCLog::ALL;
223
0
        return true;
224
0
    }
225
0
    auto it = LOG_CATEGORIES_BY_STR.find(str);
226
0
    if (it != LOG_CATEGORIES_BY_STR.end()) {
227
0
        flag = it->second;
228
0
        return true;
229
0
    }
230
0
    return false;
231
0
}
232
233
std::string BCLog::Logger::LogLevelToStr(BCLog::Level level)
234
0
{
235
0
    switch (level) {
236
0
    case BCLog::Level::Trace:
237
0
        return "trace";
238
0
    case BCLog::Level::Debug:
239
0
        return "debug";
240
0
    case BCLog::Level::Info:
241
0
        return "info";
242
0
    case BCLog::Level::Warning:
243
0
        return "warning";
244
0
    case BCLog::Level::Error:
245
0
        return "error";
246
0
    }
247
0
    assert(false);
248
0
}
249
250
static std::string LogCategoryToStr(BCLog::LogFlags category)
251
0
{
252
0
    if (category == BCLog::ALL) {
253
0
        return "all";
254
0
    }
255
0
    auto it = LOG_CATEGORIES_BY_FLAG.find(category);
256
0
    assert(it != LOG_CATEGORIES_BY_FLAG.end());
257
0
    return it->second;
258
0
}
259
260
static std::optional<BCLog::Level> GetLogLevel(std::string_view level_str)
261
0
{
262
0
    if (level_str == "trace") {
263
0
        return BCLog::Level::Trace;
264
0
    } else if (level_str == "debug") {
265
0
        return BCLog::Level::Debug;
266
0
    } else if (level_str == "info") {
267
0
        return BCLog::Level::Info;
268
0
    } else if (level_str == "warning") {
269
0
        return BCLog::Level::Warning;
270
0
    } else if (level_str == "error") {
271
0
        return BCLog::Level::Error;
272
0
    } else {
273
0
        return std::nullopt;
274
0
    }
275
0
}
276
277
std::vector<LogCategory> BCLog::Logger::LogCategoriesList() const
278
0
{
279
0
    std::vector<LogCategory> ret;
280
0
    ret.reserve(LOG_CATEGORIES_BY_STR.size());
281
0
    for (const auto& [category, flag] : LOG_CATEGORIES_BY_STR) {
282
0
        ret.push_back(LogCategory{.category = category, .active = WillLogCategory(flag)});
283
0
    }
284
0
    return ret;
285
0
}
286
287
/** Log severity levels that can be selected by the user. */
288
static constexpr std::array<BCLog::Level, 3> LogLevelsList()
289
0
{
290
0
    return {BCLog::Level::Info, BCLog::Level::Debug, BCLog::Level::Trace};
291
0
}
292
293
std::string BCLog::Logger::LogLevelsString() const
294
0
{
295
0
    const auto& levels = LogLevelsList();
296
0
    return Join(std::vector<BCLog::Level>{levels.begin(), levels.end()}, ", ", [](BCLog::Level level) { return LogLevelToStr(level); });
297
0
}
298
299
std::string BCLog::Logger::LogTimestampStr(SystemClock::time_point now, std::chrono::seconds mocktime) const
300
0
{
301
0
    std::string strStamped;
302
303
0
    if (!m_log_timestamps)
304
0
        return strStamped;
305
306
0
    const auto now_seconds{std::chrono::time_point_cast<std::chrono::seconds>(now)};
307
0
    strStamped = FormatISO8601DateTime(TicksSinceEpoch<std::chrono::seconds>(now_seconds));
308
0
    if (m_log_time_micros && !strStamped.empty()) {
309
0
        strStamped.pop_back();
310
0
        strStamped += strprintf(".%06dZ", Ticks<std::chrono::microseconds>(now - now_seconds));
Line
Count
Source
1172
0
#define strprintf tfm::format
311
0
    }
312
0
    if (mocktime > 0s) {
313
0
        strStamped += " (mocktime: " + FormatISO8601DateTime(count_seconds(mocktime)) + ")";
314
0
    }
315
0
    strStamped += ' ';
316
317
0
    return strStamped;
318
0
}
319
320
namespace BCLog {
321
    /** Belts and suspenders: make sure outgoing log messages don't contain
322
     * potentially suspicious characters, such as terminal control codes.
323
     *
324
     * This escapes control characters except newline ('\n') in C syntax.
325
     * It escapes instead of removes them to still allow for troubleshooting
326
     * issues where they accidentally end up in strings.
327
     */
328
0
    std::string LogEscapeMessage(std::string_view str) {
329
0
        std::string ret;
330
0
        for (char ch_in : str) {
331
0
            uint8_t ch = (uint8_t)ch_in;
332
0
            if ((ch >= 32 || ch == '\n') && ch != '\x7f') {
333
0
                ret += ch_in;
334
0
            } else {
335
0
                ret += strprintf("\\x%02x", ch);
Line
Count
Source
1172
0
#define strprintf tfm::format
336
0
            }
337
0
        }
338
0
        return ret;
339
0
    }
340
} // namespace BCLog
341
342
std::string BCLog::Logger::GetLogPrefix(BCLog::LogFlags category, BCLog::Level level) const
343
0
{
344
0
    if (category == LogFlags::NONE) category = LogFlags::ALL;
345
346
0
    const bool has_category{m_always_print_category_level || category != LogFlags::ALL};
347
348
    // If there is no category, Info is implied
349
0
    if (!has_category && level == Level::Info) return {};
350
351
0
    std::string s{"["};
352
0
    if (has_category) {
353
0
        s += LogCategoryToStr(category);
354
0
    }
355
356
0
    if (m_always_print_category_level || !has_category || level != Level::Debug) {
357
        // If there is a category, Debug is implied, so don't add the level
358
359
        // Only add separator if we have a category
360
0
        if (has_category) s += ":";
361
0
        s += Logger::LogLevelToStr(level);
362
0
    }
363
364
0
    s += "] ";
365
0
    return s;
366
0
}
367
368
static size_t MemUsage(const BCLog::Logger::BufferedLog& buflog)
369
0
{
370
0
    return memusage::DynamicUsage(buflog.str) +
371
0
           memusage::DynamicUsage(buflog.threadname) +
372
0
           memusage::MallocUsage(sizeof(memusage::list_node<BCLog::Logger::BufferedLog>));
373
0
}
374
375
BCLog::LogRateLimiter::LogRateLimiter(uint64_t max_bytes, std::chrono::seconds reset_window)
376
0
    : m_max_bytes{max_bytes}, m_reset_window{reset_window} {}
377
378
std::shared_ptr<BCLog::LogRateLimiter> BCLog::LogRateLimiter::Create(
379
    SchedulerFunction&& scheduler_func, uint64_t max_bytes, std::chrono::seconds reset_window)
380
0
{
381
0
    auto limiter{std::shared_ptr<LogRateLimiter>(new LogRateLimiter(max_bytes, reset_window))};
382
0
    std::weak_ptr<LogRateLimiter> weak_limiter{limiter};
383
0
    auto reset = [weak_limiter] {
384
0
        if (auto shared_limiter{weak_limiter.lock()}) shared_limiter->Reset();
385
0
    };
386
0
    scheduler_func(reset, limiter->m_reset_window);
387
0
    return limiter;
388
0
}
389
390
BCLog::LogRateLimiter::Status BCLog::LogRateLimiter::Consume(
391
    const std::source_location& source_loc,
392
    const std::string& str)
393
0
{
394
0
    StdLockGuard scoped_lock(m_mutex);
395
0
    auto& stats{m_source_locations.try_emplace(source_loc, m_max_bytes).first->second};
396
0
    Status status{stats.m_dropped_bytes > 0 ? Status::STILL_SUPPRESSED : Status::UNSUPPRESSED};
397
398
0
    if (!stats.Consume(str.size()) && status == Status::UNSUPPRESSED) {
399
0
        status = Status::NEWLY_SUPPRESSED;
400
0
        m_suppression_active = true;
401
0
    }
402
403
0
    return status;
404
0
}
405
406
void BCLog::Logger::FormatLogStrInPlace(std::string& str, BCLog::LogFlags category, BCLog::Level level, const std::source_location& source_loc, std::string_view threadname, SystemClock::time_point now, std::chrono::seconds mocktime) const
407
0
{
408
0
    if (!str.ends_with('\n')) str.push_back('\n');
409
410
0
    str.insert(0, GetLogPrefix(category, level));
411
412
0
    if (m_log_sourcelocations) {
413
0
        str.insert(0, strprintf("[%s:%d] [%s] ", RemovePrefixView(source_loc.file_name(), "./"), source_loc.line(), source_loc.function_name()));
Line
Count
Source
1172
0
#define strprintf tfm::format
414
0
    }
415
416
0
    if (m_log_threadnames) {
417
0
        str.insert(0, strprintf("[%s] ", (threadname.empty() ? "unknown" : threadname)));
Line
Count
Source
1172
0
#define strprintf tfm::format
418
0
    }
419
420
0
    str.insert(0, LogTimestampStr(now, mocktime));
421
0
}
422
423
void BCLog::Logger::LogPrintStr(std::string_view str, std::source_location&& source_loc, BCLog::LogFlags category, BCLog::Level level, bool should_ratelimit)
424
0
{
425
0
    StdLockGuard scoped_lock(m_cs);
426
0
    return LogPrintStr_(str, std::move(source_loc), category, level, should_ratelimit);
427
0
}
428
429
// NOLINTNEXTLINE(misc-no-recursion)
430
void BCLog::Logger::LogPrintStr_(std::string_view str, std::source_location&& source_loc, BCLog::LogFlags category, BCLog::Level level, bool should_ratelimit)
431
0
{
432
0
    std::string str_prefixed = LogEscapeMessage(str);
433
434
0
    if (m_buffering) {
435
0
        {
436
0
            BufferedLog buf{
437
0
                .now = SystemClock::now(),
438
0
                .mocktime = GetMockTime(),
439
0
                .str = str_prefixed,
440
0
                .threadname = util::ThreadGetInternalName(),
441
0
                .source_loc = std::move(source_loc),
442
0
                .category = category,
443
0
                .level = level,
444
0
            };
445
0
            m_cur_buffer_memusage += MemUsage(buf);
446
0
            m_msgs_before_open.push_back(std::move(buf));
447
0
        }
448
449
0
        while (m_cur_buffer_memusage > m_max_buffer_memusage) {
450
0
            if (m_msgs_before_open.empty()) {
451
0
                m_cur_buffer_memusage = 0;
452
0
                break;
453
0
            }
454
0
            m_cur_buffer_memusage -= MemUsage(m_msgs_before_open.front());
455
0
            m_msgs_before_open.pop_front();
456
0
            ++m_buffer_lines_discarded;
457
0
        }
458
459
0
        return;
460
0
    }
461
462
0
    FormatLogStrInPlace(str_prefixed, category, level, source_loc, util::ThreadGetInternalName(), SystemClock::now(), GetMockTime());
463
0
    bool ratelimit{false};
464
0
    if (should_ratelimit && m_limiter) {
465
0
        auto status{m_limiter->Consume(source_loc, str_prefixed)};
466
0
        if (status == LogRateLimiter::Status::NEWLY_SUPPRESSED) {
467
            // NOLINTNEXTLINE(misc-no-recursion)
468
0
            LogPrintStr_(strprintf(
Line
Count
Source
1172
0
#define strprintf tfm::format
469
0
                             "Excessive logging detected from %s:%d (%s): >%d bytes logged during "
470
0
                             "the last time window of %is. Suppressing logging to disk from this "
471
0
                             "source location until time window resets. Console logging "
472
0
                             "unaffected. Last log entry.",
473
0
                             source_loc.file_name(), source_loc.line(), source_loc.function_name(),
474
0
                             m_limiter->m_max_bytes,
475
0
                             Ticks<std::chrono::seconds>(m_limiter->m_reset_window)),
476
0
                         std::source_location::current(), LogFlags::ALL, Level::Warning, /*should_ratelimit=*/false); // with should_ratelimit=false, this cannot lead to infinite recursion
477
0
        } else if (status == LogRateLimiter::Status::STILL_SUPPRESSED) {
478
0
            ratelimit = true;
479
0
        }
480
0
    }
481
482
    // To avoid confusion caused by dropped log messages when debugging an issue,
483
    // we prefix log lines with "[*]" when there are any suppressed source locations.
484
0
    if (m_limiter && m_limiter->SuppressionsActive()) {
485
0
        str_prefixed.insert(0, "[*] ");
486
0
    }
487
488
0
    if (m_print_to_console) {
489
        // print to console
490
0
        fwrite(str_prefixed.data(), 1, str_prefixed.size(), stdout);
491
0
        fflush(stdout);
492
0
    }
493
0
    for (const auto& cb : m_print_callbacks) {
494
0
        cb(str_prefixed);
495
0
    }
496
0
    if (m_print_to_file && !ratelimit) {
497
0
        assert(m_fileout != nullptr);
498
499
        // reopen the log file, if requested
500
0
        if (m_reopen_file) {
501
0
            m_reopen_file = false;
502
0
            FILE* new_fileout = fsbridge::fopen(m_file_path, "a");
503
0
            if (new_fileout) {
504
0
                setbuf(new_fileout, nullptr); // unbuffered
505
0
                fclose(m_fileout);
506
0
                m_fileout = new_fileout;
507
0
            }
508
0
        }
509
0
        FileWriteStr(str_prefixed, m_fileout);
510
0
    }
511
0
}
512
513
void BCLog::Logger::ShrinkDebugFile()
514
0
{
515
    // Amount of debug.log to save at end when shrinking (must fit in memory)
516
0
    constexpr size_t RECENT_DEBUG_HISTORY_SIZE = 10 * 1000000;
517
518
0
    assert(!m_file_path.empty());
519
520
    // Scroll debug.log if it's getting too big
521
0
    FILE* file = fsbridge::fopen(m_file_path, "r");
522
523
    // Special files (e.g. device nodes) may not have a size.
524
0
    size_t log_size = 0;
525
0
    try {
526
0
        log_size = fs::file_size(m_file_path);
527
0
    } catch (const fs::filesystem_error&) {}
528
529
    // If debug.log file is more than 10% bigger the RECENT_DEBUG_HISTORY_SIZE
530
    // trim it down by saving only the last RECENT_DEBUG_HISTORY_SIZE bytes
531
0
    if (file && log_size > 11 * (RECENT_DEBUG_HISTORY_SIZE / 10))
532
0
    {
533
        // Restart the file with some of the end
534
0
        std::vector<char> vch(RECENT_DEBUG_HISTORY_SIZE, 0);
535
0
        if (fseek(file, -((long)vch.size()), SEEK_END)) {
536
0
            LogPrintf("Failed to shrink debug log file: fseek(...) failed\n");
Line
Count
Source
373
0
#define LogPrintf(...) LogInfo(__VA_ARGS__)
Line
Count
Source
368
0
#define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
362
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__)
537
0
            fclose(file);
538
0
            return;
539
0
        }
540
0
        int nBytes = fread(vch.data(), 1, vch.size(), file);
541
0
        fclose(file);
542
543
0
        file = fsbridge::fopen(m_file_path, "w");
544
0
        if (file)
545
0
        {
546
0
            fwrite(vch.data(), 1, nBytes, file);
547
0
            fclose(file);
548
0
        }
549
0
    }
550
0
    else if (file != nullptr)
551
0
        fclose(file);
552
0
}
553
554
void BCLog::LogRateLimiter::Reset()
555
0
{
556
0
    decltype(m_source_locations) source_locations;
557
0
    {
558
0
        StdLockGuard scoped_lock(m_mutex);
559
0
        source_locations.swap(m_source_locations);
560
0
        m_suppression_active = false;
561
0
    }
562
0
    for (const auto& [source_loc, stats] : source_locations) {
563
0
        if (stats.m_dropped_bytes == 0) continue;
564
0
        LogPrintLevel_(
Line
Count
Source
362
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__)
565
0
            LogFlags::ALL, Level::Warning, /*should_ratelimit=*/false,
566
0
            "Restarting logging from %s:%d (%s): %d bytes were dropped during the last %ss.",
567
0
            source_loc.file_name(), source_loc.line(), source_loc.function_name(),
568
0
            stats.m_dropped_bytes, Ticks<std::chrono::seconds>(m_reset_window));
569
0
    }
570
0
}
571
572
bool BCLog::LogRateLimiter::Stats::Consume(uint64_t bytes)
573
0
{
574
0
    if (bytes > m_available_bytes) {
575
0
        m_dropped_bytes += bytes;
576
0
        m_available_bytes = 0;
577
0
        return false;
578
0
    }
579
580
0
    m_available_bytes -= bytes;
581
0
    return true;
582
0
}
583
584
bool BCLog::Logger::SetLogLevel(std::string_view level_str)
585
0
{
586
0
    const auto level = GetLogLevel(level_str);
587
0
    if (!level.has_value() || level.value() > MAX_USER_SETABLE_SEVERITY_LEVEL) return false;
588
0
    m_log_level = level.value();
589
0
    return true;
590
0
}
591
592
bool BCLog::Logger::SetCategoryLogLevel(std::string_view category_str, std::string_view level_str)
593
0
{
594
0
    BCLog::LogFlags flag;
595
0
    if (!GetLogCategory(flag, category_str)) return false;
596
597
0
    const auto level = GetLogLevel(level_str);
598
0
    if (!level.has_value() || level.value() > MAX_USER_SETABLE_SEVERITY_LEVEL) return false;
599
600
0
    StdLockGuard scoped_lock(m_cs);
601
0
    m_category_log_levels[flag] = level.value();
602
0
    return true;
603
0
}