Bitcoin Core  24.1.0
P2P Digital Currency
time.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2021 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 #if defined(HAVE_CONFIG_H)
8 #endif
9 
10 #include <compat/compat.h>
11 #include <tinyformat.h>
12 #include <util/time.h>
13 #include <util/check.h>
14 
15 #include <boost/date_time/posix_time/posix_time.hpp>
16 
17 #include <atomic>
18 #include <chrono>
19 #include <ctime>
20 #include <locale>
21 #include <thread>
22 #include <sstream>
23 #include <string>
24 
25 void UninterruptibleSleep(const std::chrono::microseconds& n) { std::this_thread::sleep_for(n); }
26 
27 static std::atomic<int64_t> nMockTime(0);
28 
30 {
31  // std::chrono::system_clock.time_since_epoch and time_t(0) are not guaranteed
32  // to use the Unix epoch timestamp, prior to C++20, but in practice they almost
33  // certainly will. Any differing behavior will be assumed to be an error, unless
34  // certain platforms prove to consistently deviate, at which point we'll cope
35  // with it by adding offsets.
36 
37  // Create a new clock from time_t(0) and make sure that it represents 0
38  // seconds from the system_clock's time_since_epoch. Then convert that back
39  // to a time_t and verify that it's the same as before.
40  const time_t time_t_epoch{};
41  auto clock = std::chrono::system_clock::from_time_t(time_t_epoch);
42  if (std::chrono::duration_cast<std::chrono::seconds>(clock.time_since_epoch()).count() != 0) {
43  return false;
44  }
45 
46  time_t time_val = std::chrono::system_clock::to_time_t(clock);
47  if (time_val != time_t_epoch) {
48  return false;
49  }
50 
51  // Check that the above zero time is actually equal to the known unix timestamp.
52  struct tm epoch;
53 #ifdef HAVE_GMTIME_R
54  if (gmtime_r(&time_val, &epoch) == nullptr) {
55 #else
56  if (gmtime_s(&epoch, &time_val) != 0) {
57 #endif
58  return false;
59  }
60 
61  if ((epoch.tm_sec != 0) ||
62  (epoch.tm_min != 0) ||
63  (epoch.tm_hour != 0) ||
64  (epoch.tm_mday != 1) ||
65  (epoch.tm_mon != 0) ||
66  (epoch.tm_year != 70)) {
67  return false;
68  }
69  return true;
70 }
71 
73 {
74  const std::chrono::seconds mocktime{nMockTime.load(std::memory_order_relaxed)};
75  const auto ret{
76  mocktime.count() ?
77  mocktime :
78  std::chrono::system_clock::now().time_since_epoch()};
79  assert(ret > 0s);
80  return time_point{ret};
81 };
82 
83 template <typename T>
84 static T GetSystemTime()
85 {
86  const auto now = std::chrono::duration_cast<T>(std::chrono::system_clock::now().time_since_epoch());
87  assert(now.count() > 0);
88  return now;
89 }
90 
91 void SetMockTime(int64_t nMockTimeIn)
92 {
93  Assert(nMockTimeIn >= 0);
94  nMockTime.store(nMockTimeIn, std::memory_order_relaxed);
95 }
96 
97 void SetMockTime(std::chrono::seconds mock_time_in)
98 {
99  nMockTime.store(mock_time_in.count(), std::memory_order_relaxed);
100 }
101 
102 std::chrono::seconds GetMockTime()
103 {
104  return std::chrono::seconds(nMockTime.load(std::memory_order_relaxed));
105 }
106 
107 int64_t GetTimeMillis()
108 {
109  return int64_t{GetSystemTime<std::chrono::milliseconds>().count()};
110 }
111 
112 int64_t GetTimeMicros()
113 {
114  return int64_t{GetSystemTime<std::chrono::microseconds>().count()};
115 }
116 
117 int64_t GetTime() { return GetTime<std::chrono::seconds>().count(); }
118 
119 std::string FormatISO8601DateTime(int64_t nTime) {
120  struct tm ts;
121  time_t time_val = nTime;
122 #ifdef HAVE_GMTIME_R
123  if (gmtime_r(&time_val, &ts) == nullptr) {
124 #else
125  if (gmtime_s(&ts, &time_val) != 0) {
126 #endif
127  return {};
128  }
129  return strprintf("%04i-%02i-%02iT%02i:%02i:%02iZ", ts.tm_year + 1900, ts.tm_mon + 1, ts.tm_mday, ts.tm_hour, ts.tm_min, ts.tm_sec);
130 }
131 
132 std::string FormatISO8601Date(int64_t nTime) {
133  struct tm ts;
134  time_t time_val = nTime;
135 #ifdef HAVE_GMTIME_R
136  if (gmtime_r(&time_val, &ts) == nullptr) {
137 #else
138  if (gmtime_s(&ts, &time_val) != 0) {
139 #endif
140  return {};
141  }
142  return strprintf("%04i-%02i-%02i", ts.tm_year + 1900, ts.tm_mon + 1, ts.tm_mday);
143 }
144 
145 int64_t ParseISO8601DateTime(const std::string& str)
146 {
147  static const boost::posix_time::ptime epoch = boost::posix_time::from_time_t(0);
148  static const std::locale loc(std::locale::classic(),
149  new boost::posix_time::time_input_facet("%Y-%m-%dT%H:%M:%SZ"));
150  std::istringstream iss(str);
151  iss.imbue(loc);
152  boost::posix_time::ptime ptime(boost::date_time::not_a_date_time);
153  iss >> ptime;
154  if (ptime.is_not_a_date_time() || epoch > ptime)
155  return 0;
156  return (ptime - epoch).total_seconds();
157 }
158 
159 struct timeval MillisToTimeval(int64_t nTimeout)
160 {
161  struct timeval timeout;
162  timeout.tv_sec = nTimeout / 1000;
163  timeout.tv_usec = (nTimeout % 1000) * 1000;
164  return timeout;
165 }
166 
167 struct timeval MillisToTimeval(std::chrono::milliseconds ms)
168 {
170 }
static T GetSystemTime()
Definition: time.cpp:84
int ret
std::chrono::time_point< NodeClock > time_point
Definition: time.h:19
std::chrono::seconds GetMockTime()
For testing.
Definition: time.cpp:102
assert(!tx.IsCoinBase())
std::string FormatISO8601Date(int64_t nTime)
Definition: time.cpp:132
int64_t GetTimeMillis()
Returns the system time (not mockable)
Definition: time.cpp:107
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
bool ChronoSanityCheck()
Sanity check epoch match normal Unix epoch.
Definition: time.cpp:29
std::string FormatISO8601DateTime(int64_t nTime)
ISO 8601 formatting is preferred.
Definition: time.cpp:119
static std::atomic< int64_t > nMockTime(0)
For testing.
int64_t ParseISO8601DateTime(const std::string &str)
Definition: time.cpp:145
void SetMockTime(int64_t nMockTimeIn)
DEPRECATED Use SetMockTime with chrono type.
Definition: time.cpp:91
constexpr int64_t count_milliseconds(std::chrono::milliseconds t)
Definition: time.h:55
int64_t GetTimeMicros()
Returns the system time (not mockable)
Definition: time.cpp:112
static time_point now() noexcept
Return current system time or mocked time, if set.
Definition: time.cpp:72
void UninterruptibleSleep(const std::chrono::microseconds &n)
Definition: time.cpp:25
static int count
Definition: tests.c:33
struct timeval MillisToTimeval(int64_t nTimeout)
Convert milliseconds to a struct timeval for e.g.
Definition: time.cpp:159
int64_t GetTime()
DEPRECATED, see GetTime.
Definition: time.cpp:117
#define Assert(val)
Identity function.
Definition: check.h:74