Inside Bitcoin
Opening the selected file…
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
1// Copyright (c) 2024-present The Bitcoin Core developers2// Distributed under the MIT software license, see the accompanying3// file COPYING or http://www.opensource.org/licenses/mit-license.php.5#include <node/timeoffsets.h>6#include <node/warnings.h>7#include <sync.h>8#include <tinyformat.h>9#include <util/log.h>10#include <util/time.h>11#include <util/translation.h>13#include <algorithm>14#include <chrono>15#include <cstdint>16#include <deque>17#include <limits>18#include <optional>20using namespace std::chrono_literals;22void TimeOffsets::Add(std::chrono::seconds offset)23{24LOCK(m_mutex);26if (m_offsets.size() >= MAX_SIZE) {27m_offsets.pop_front();28}29m_offsets.push_back(offset);30LogDebug(BCLog::NET, "Added time offset %+ds, total samples %d\n",31Ticks<std::chrono::seconds>(offset), m_offsets.size());32}34std::chrono::seconds TimeOffsets::Median() const35{36LOCK(m_mutex);38// Only calculate the median if we have 5 or more offsets39if (m_offsets.size() < 5) return 0s;41auto sorted_copy = m_offsets;42std::sort(sorted_copy.begin(), sorted_copy.end());43return sorted_copy[sorted_copy.size() / 2]; // approximate median is good enough, keep it simple44}46bool TimeOffsets::WarnIfOutOfSync() const47{48// when median == std::numeric_limits<int64_t>::min(), calling std::chrono::abs is UB49auto median{std::max(Median(), std::chrono::seconds(std::numeric_limits<int64_t>::min() + 1))};50if (std::chrono::abs(median) <= WARN_THRESHOLD) {51m_warnings.Unset(node::Warning::CLOCK_OUT_OF_SYNC);52return false;53}55bilingual_str msg{strprintf(_(56"Your computer's date and time appear to be more than %d minutes out of sync with the network, "57"this may lead to consensus failure. After you've confirmed your computer's clock, this message "58"should no longer appear when you restart your node. Without a restart, it should stop showing "59"automatically after you've connected to a sufficient number of new outbound peers, which may "60"take some time. You can inspect the `timeoffset` field of the `getpeerinfo` and `getnetworkinfo` "61"RPC methods to get more info."62), Ticks<std::chrono::minutes>(WARN_THRESHOLD))};63LogWarning("%s\n", msg.original);64m_warnings.Set(node::Warning::CLOCK_OUT_OF_SYNC, msg);65return true;66}