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