LCOV - code coverage report
Current view: top level - src/util - time.h (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 84.6 % 13 11
Test Date: 2026-03-28 03:58:45 Functions: 85.0 % 20 17
Branches: 18.4 % 38 7

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2009-2010 Satoshi Nakamoto
       2                 :             : // Copyright (c) 2009-present 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                 :             : #ifndef BITCOIN_UTIL_TIME_H
       7                 :             : #define BITCOIN_UTIL_TIME_H
       8                 :             : 
       9                 :             : // The `util/time.h` header is designed to be a drop-in replacement for `chrono`.
      10                 :             : #include <chrono> // IWYU pragma: export
      11                 :             : #include <cstdint>
      12                 :             : #include <optional>
      13                 :             : #include <string>
      14                 :             : #include <string_view>
      15                 :             : 
      16                 :             : using namespace std::chrono_literals;
      17                 :             : 
      18                 :             : /// Version of the system clock that is mockable in the context of tests (via
      19                 :             : /// NodeClockContext or ::SetMockTime), otherwise the system clock.
      20                 :             : struct NodeClock : public std::chrono::system_clock {
      21                 :             :     using time_point = std::chrono::time_point<NodeClock>;
      22                 :             :     /** Return current system time or mocked time, if set */
      23                 :             :     static time_point now() noexcept;
      24                 :             :     static std::time_t to_time_t(const time_point&) = delete; // unused
      25                 :             :     static time_point from_time_t(std::time_t) = delete;      // unused
      26                 :             : };
      27                 :             : using NodeSeconds = std::chrono::time_point<NodeClock, std::chrono::seconds>;
      28                 :             : 
      29                 :             : using SteadyClock = std::chrono::steady_clock;
      30                 :             : using SteadySeconds = std::chrono::time_point<std::chrono::steady_clock, std::chrono::seconds>;
      31                 :             : using SteadyMilliseconds = std::chrono::time_point<std::chrono::steady_clock, std::chrono::milliseconds>;
      32                 :             : using SteadyMicroseconds = std::chrono::time_point<std::chrono::steady_clock, std::chrono::microseconds>;
      33                 :             : 
      34                 :             : using SystemClock = std::chrono::system_clock;
      35                 :             : 
      36                 :             : /// Version of SteadyClock that is mockable in the context of tests (via
      37                 :             : /// SteadyClockContext, or Self::SetMockTime), otherwise the system steady
      38                 :             : /// clock.
      39                 :             : struct MockableSteadyClock : public std::chrono::steady_clock {
      40                 :             :     using time_point = std::chrono::time_point<MockableSteadyClock>;
      41                 :             : 
      42                 :             :     using mock_time_point = std::chrono::time_point<MockableSteadyClock, std::chrono::milliseconds>;
      43                 :             :     static constexpr mock_time_point::duration INITIAL_MOCK_TIME{1};
      44                 :             : 
      45                 :             :     /** Return current system time or mocked time, if set */
      46                 :             :     static time_point now() noexcept;
      47                 :             :     static std::time_t to_time_t(const time_point&) = delete; // unused
      48                 :             :     static time_point from_time_t(std::time_t) = delete;      // unused
      49                 :             : 
      50                 :             :     /** Set mock time for testing.
      51                 :             :      * When mocking the steady clock, start at INITIAL_MOCK_TIME and add durations to elapse time as necessary
      52                 :             :      * for testing.
      53                 :             :      * To stop mocking, call ClearMockTime().
      54                 :             :      */
      55                 :             :     static void SetMockTime(mock_time_point::duration mock_time_in);
      56                 :             : 
      57                 :             :     /** Clear mock time, go back to system steady clock. */
      58                 :             :     static void ClearMockTime();
      59                 :             : };
      60                 :             : 
      61                 :             : void UninterruptibleSleep(const std::chrono::microseconds& n);
      62                 :             : 
      63                 :             : /**
      64                 :             :  * Helper to count the seconds of a duration/time_point.
      65                 :             :  *
      66                 :             :  * All durations/time_points should be using std::chrono and calling this should generally
      67                 :             :  * be avoided in code. Though, it is still preferred to an inline t.count() to
      68                 :             :  * protect against a reliance on the exact type of t.
      69                 :             :  *
      70                 :             :  * This helper is used to convert durations/time_points before passing them over an
      71                 :             :  * interface that doesn't support std::chrono (e.g. RPC, debug log, or the GUI)
      72                 :             :  */
      73                 :             : template <typename Dur1, typename Dur2>
      74   [ +  -  -  - ]:    19437516 : constexpr auto Ticks(Dur2 d)
                 [ #  # ]
      75                 :             : {
      76   [ +  -  -  - ]:    19437516 :     return std::chrono::duration_cast<Dur1>(d).count();
                 [ #  # ]
      77                 :             : }
      78                 :             : 
      79                 :             : template <typename Duration>
      80                 :           1 : constexpr int64_t TicksSeconds(Duration d)
      81                 :             : {
      82                 :           1 :     return int64_t{Ticks<std::chrono::seconds>(d)};
      83                 :             : }
      84                 :             : template <typename Duration, typename Timepoint>
      85                 :    15512088 : constexpr auto TicksSinceEpoch(Timepoint t)
      86                 :             : {
      87                 :    15512088 :     return Ticks<Duration>(t.time_since_epoch());
      88                 :             : }
      89 [ +  + ][ -  -  :     2296422 : constexpr int64_t count_seconds(std::chrono::seconds t) { return t.count(); }
             -  -  +  - ]
           [ +  -  +  -  
          -  -  -  -  -  
             -  -  -  -  
                      - ]
      90         [ #  # ]:           0 : constexpr int64_t count_milliseconds(std::chrono::milliseconds t) { return t.count(); }
      91         [ #  # ]:           0 : constexpr int64_t count_microseconds(std::chrono::microseconds t) { return t.count(); }
      92                 :             : 
      93                 :             : using HoursDouble = std::chrono::duration<double, std::chrono::hours::period>;
      94                 :             : using SecondsDouble = std::chrono::duration<double, std::chrono::seconds::period>;
      95                 :             : using MillisecondsDouble = std::chrono::duration<double, std::chrono::milliseconds::period>;
      96                 :             : 
      97                 :             : /**
      98                 :             :  * DEPRECATED
      99                 :             :  * Use either ClockType::now() or Now<TimePointType>() if a cast is needed.
     100                 :             :  * ClockType is
     101                 :             :  * - SteadyClock/std::chrono::steady_clock for steady time
     102                 :             :  * - SystemClock/std::chrono::system_clock for system time
     103                 :             :  * - NodeClock                             for mockable system time
     104                 :             :  */
     105                 :             : int64_t GetTime();
     106                 :             : 
     107                 :             : /**
     108                 :             :  * DEPRECATED
     109                 :             :  * Use SetMockTime with chrono type
     110                 :             :  *
     111                 :             :  * @param[in] nMockTimeIn Time in seconds.
     112                 :             :  */
     113                 :             : void SetMockTime(int64_t nMockTimeIn);
     114                 :             : 
     115                 :             : /** For testing. Set e.g. with the setmocktime rpc, or -mocktime argument */
     116                 :             : void SetMockTime(std::chrono::seconds mock_time_in);
     117                 :             : void SetMockTime(std::chrono::time_point<NodeClock, std::chrono::seconds> mock);
     118                 :             : 
     119                 :             : /** For testing */
     120                 :             : std::chrono::seconds GetMockTime();
     121                 :             : 
     122                 :             : /**
     123                 :             :  * Return the current time point cast to the given precision. Only use this
     124                 :             :  * when an exact precision is needed, otherwise use T::clock::now() directly.
     125                 :             :  */
     126                 :             : template <typename T>
     127                 :     9678961 : T Now()
     128                 :             : {
     129                 :     9678961 :     return std::chrono::time_point_cast<typename T::duration>(T::clock::now());
     130                 :             : }
     131                 :             : /** DEPRECATED, see GetTime */
     132                 :             : template <typename T>
     133                 :     3822804 : T GetTime()
     134                 :             : {
     135                 :     3822804 :     return Now<std::chrono::time_point<NodeClock, T>>().time_since_epoch();
     136                 :             : }
     137                 :             : 
     138                 :             : /**
     139                 :             :  * ISO 8601 formatting is preferred. Use the FormatISO8601{DateTime,Date}
     140                 :             :  * helper functions if possible.
     141                 :             :  */
     142                 :             : std::string FormatISO8601DateTime(int64_t nTime);
     143                 :             : std::string FormatISO8601Date(int64_t nTime);
     144                 :             : std::optional<int64_t> ParseISO8601DateTime(std::string_view str);
     145                 :             : 
     146                 :             : /**
     147                 :             :  * RFC1123 formatting https://www.rfc-editor.org/rfc/rfc1123#section-5.2.14
     148                 :             :  * Used in HTTP/1.1 responses
     149                 :             :  */
     150                 :             : std::string FormatRFC1123DateTime(int64_t nTime);
     151                 :             : 
     152                 :             : /**
     153                 :             :  * Convert milliseconds to a struct timeval for e.g. select.
     154                 :             :  */
     155                 :             : struct timeval MillisToTimeval(int64_t nTimeout);
     156                 :             : 
     157                 :             : /**
     158                 :             :  * Convert milliseconds to a struct timeval for e.g. select.
     159                 :             :  */
     160                 :             : struct timeval MillisToTimeval(std::chrono::milliseconds ms);
     161                 :             : 
     162                 :             : #endif // BITCOIN_UTIL_TIME_H
        

Generated by: LCOV version 2.0-1