diff --git a/src/test/util/time.h b/src/test/util/time.h index bcb97eb4e14..8cd9a1dafcb 100644 --- a/src/test/util/time.h +++ b/src/test/util/time.h @@ -34,4 +34,32 @@ public: } }; +/// Helper to initialize the global NodeClock, let a duration elapse, +/// and reset it after use in a test. +class NodeClockContext +{ + NodeSeconds m_t{std::chrono::seconds::max()}; + +public: + /// Initialize with the given time. + explicit NodeClockContext(NodeSeconds init_time) { set(init_time); } + explicit NodeClockContext(std::chrono::seconds init_time) { set(init_time); } + /// Initialize with current time, using the next tick to avoid going back by rounding to seconds. + explicit NodeClockContext() { set(++Now().time_since_epoch()); } + + /// Unset mocktime. + ~NodeClockContext() { set(0s); } + + NodeClockContext(const NodeClockContext&) = delete; + NodeClockContext& operator=(const NodeClockContext&) = delete; + + /// Set mocktime. + void set(NodeSeconds t) { SetMockTime(m_t = t); } + void set(std::chrono::seconds t) { set(NodeSeconds{t}); } + + /// Change mocktime by the given duration delta. + void operator+=(std::chrono::seconds d) { set(m_t += d); } + void operator-=(std::chrono::seconds d) { set(m_t -= d); } +}; + #endif // BITCOIN_TEST_UTIL_TIME_H