// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include #endif #include #include #include #include #include #include #include #include #include #include #include void UninterruptibleSleep(const std::chrono::microseconds& n) { std::this_thread::sleep_for(n); } static std::atomic nMockTime(0); //!< For testing NodeClock::time_point NodeClock::now() noexcept { const std::chrono::seconds mocktime{nMockTime.load(std::memory_order_relaxed)}; const auto ret{ mocktime.count() ? mocktime : std::chrono::system_clock::now().time_since_epoch()}; assert(ret > 0s); return time_point{ret}; }; void SetMockTime(int64_t nMockTimeIn) { Assert(nMockTimeIn >= 0); nMockTime.store(nMockTimeIn, std::memory_order_relaxed); } void SetMockTime(std::chrono::seconds mock_time_in) { nMockTime.store(mock_time_in.count(), std::memory_order_relaxed); } std::chrono::seconds GetMockTime() { return std::chrono::seconds(nMockTime.load(std::memory_order_relaxed)); } int64_t GetTime() { return GetTime().count(); } std::string FormatISO8601DateTime(int64_t nTime) { struct tm ts; time_t time_val = nTime; #ifdef HAVE_GMTIME_R if (gmtime_r(&time_val, &ts) == nullptr) { #else if (gmtime_s(&ts, &time_val) != 0) { #endif return {}; } 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); } std::string FormatISO8601Date(int64_t nTime) { struct tm ts; time_t time_val = nTime; #ifdef HAVE_GMTIME_R if (gmtime_r(&time_val, &ts) == nullptr) { #else if (gmtime_s(&ts, &time_val) != 0) { #endif return {}; } return strprintf("%04i-%02i-%02i", ts.tm_year + 1900, ts.tm_mon + 1, ts.tm_mday); } struct timeval MillisToTimeval(int64_t nTimeout) { struct timeval timeout; timeout.tv_sec = nTimeout / 1000; timeout.tv_usec = (nTimeout % 1000) * 1000; return timeout; } struct timeval MillisToTimeval(std::chrono::milliseconds ms) { return MillisToTimeval(count_milliseconds(ms)); }