Bitcoin Core  26.1.0
P2P Digital Currency
timedata.cpp
Go to the documentation of this file.
1 // Copyright (c) 2014-2022 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 
5 #if defined(HAVE_CONFIG_H)
7 #endif
8 
9 #include <timedata.h>
10 
11 #include <common/args.h>
12 #include <logging.h>
13 #include <netaddress.h>
14 #include <node/interface_ui.h>
15 #include <sync.h>
16 #include <tinyformat.h>
17 #include <util/translation.h>
18 #include <warnings.h>
19 
21 static int64_t nTimeOffset GUARDED_BY(g_timeoffset_mutex) = 0;
22 
30 int64_t GetTimeOffset()
31 {
33  return nTimeOffset;
34 }
35 
37 {
38  return NodeClock::now() + std::chrono::seconds{GetTimeOffset()};
39 }
40 
41 #define BITCOIN_TIMEDATA_MAX_SAMPLES 200
42 
43 static std::set<CNetAddr> g_sources;
45 static bool g_warning_emitted;
46 
47 void AddTimeData(const CNetAddr& ip, int64_t nOffsetSample)
48 {
50  // Ignore duplicates
52  return;
53  if (!g_sources.insert(ip).second)
54  return;
55 
56  // Add data
57  g_time_offsets.input(nOffsetSample);
58  LogPrint(BCLog::NET, "added time data, samples %d, offset %+d (%+d minutes)\n", g_time_offsets.size(), nOffsetSample, nOffsetSample / 60);
59 
60  // There is a known issue here (see issue #4521):
61  //
62  // - The structure g_time_offsets contains up to 200 elements, after which
63  // any new element added to it will not increase its size, replacing the
64  // oldest element.
65  //
66  // - The condition to update nTimeOffset includes checking whether the
67  // number of elements in g_time_offsets is odd, which will never happen after
68  // there are 200 elements.
69  //
70  // But in this case the 'bug' is protective against some attacks, and may
71  // actually explain why we've never seen attacks which manipulate the
72  // clock offset.
73  //
74  // So we should hold off on fixing this and clean it up as part of
75  // a timing cleanup that strengthens it in a number of other ways.
76  //
77  if (g_time_offsets.size() >= 5 && g_time_offsets.size() % 2 == 1) {
78  int64_t nMedian = g_time_offsets.median();
79  std::vector<int64_t> vSorted = g_time_offsets.sorted();
80  // Only let other nodes change our time by so much
81  int64_t max_adjustment = std::max<int64_t>(0, gArgs.GetIntArg("-maxtimeadjustment", DEFAULT_MAX_TIME_ADJUSTMENT));
82  if (nMedian >= -max_adjustment && nMedian <= max_adjustment) {
83  nTimeOffset = nMedian;
84  } else {
85  nTimeOffset = 0;
86 
87  if (!g_warning_emitted) {
88  // If nobody has a time different than ours but within 5 minutes of ours, give a warning
89  bool fMatch = false;
90  for (const int64_t nOffset : vSorted) {
91  if (nOffset != 0 && nOffset > -5 * 60 && nOffset < 5 * 60) fMatch = true;
92  }
93 
94  if (!fMatch) {
95  g_warning_emitted = true;
96  bilingual_str strMessage = strprintf(_("Please check that your computer's date and time are correct! If your clock is wrong, %s will not work properly."), PACKAGE_NAME);
97  SetMiscWarning(strMessage);
98  uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_WARNING);
99  }
100  }
101  }
102 
104  std::string log_message{"time data samples: "};
105  for (const int64_t n : vSorted) {
106  log_message += strprintf("%+d ", n);
107  }
108  log_message += strprintf("| median offset = %+d (%+d minutes)", nTimeOffset, nTimeOffset / 60);
109  LogPrint(BCLog::NET, "%s\n", log_message);
110  }
111  }
112 }
113 
115 {
117  nTimeOffset = 0;
118  g_sources.clear();
120  g_warning_emitted = false;
121 }
std::chrono::time_point< NodeClock > time_point
Definition: time.h:17
static GlobalMutex g_timeoffset_mutex
Definition: timedata.cpp:20
CClientUIInterface uiInterface
#define LogPrint(category,...)
Definition: logging.h:246
Bilingual messages:
Definition: translation.h:18
#define BITCOIN_TIMEDATA_MAX_SAMPLES
Definition: timedata.cpp:41
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1162
void SetMiscWarning(const bilingual_str &warning)
Definition: warnings.cpp:19
void TestOnlyResetTimeData()
Reset the internal state of GetTimeOffset(), GetAdjustedTime() and AddTimeData(). ...
Definition: timedata.cpp:114
Median filter over a stream of values.
Definition: timedata.h:25
#define PACKAGE_NAME
int64_t GetTimeOffset()
"Never go to sea with two chronometers; take one or three." Our three time sources are: ...
Definition: timedata.cpp:30
NodeClock::time_point GetAdjustedTime()
Definition: timedata.cpp:36
static int64_t nTimeOffset GUARDED_BY(g_timeoffset_mutex)=0
#define LOCK(cs)
Definition: sync.h:258
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:74
static CService ip(uint32_t i)
ArgsManager gArgs
Definition: args.cpp:42
Network address.
Definition: netaddress.h:115
static std::set< CNetAddr > g_sources
Definition: timedata.cpp:43
static time_point now() noexcept
Return current system time or mocked time, if set.
Definition: time.cpp:70
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Definition: args.cpp:481
static bool LogAcceptCategory(BCLog::LogFlags category, BCLog::Level level)
Return true if log accepts specified category, at the specified level.
Definition: logging.h:207
Different type to mark Mutex at global scope.
Definition: sync.h:141
void AddTimeData(const CNetAddr &ip, int64_t nOffsetSample)
Definition: timedata.cpp:47
static const int64_t DEFAULT_MAX_TIME_ADJUSTMENT
Definition: timedata.h:16
static bool g_warning_emitted
Definition: timedata.cpp:45
static CMedianFilter< int64_t > g_time_offsets
Definition: timedata.cpp:44