Bitcoin Core  27.99.0
P2P Digital Currency
timeoffsets_tests.cpp
Go to the documentation of this file.
1 // Copyright (c) 2024-present 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 
6 #include <node/timeoffsets.h>
8 
9 #include <boost/test/unit_test.hpp>
10 
11 #include <chrono>
12 #include <vector>
13 
14 using namespace std::chrono_literals;
15 
16 static void AddMulti(TimeOffsets& offsets, const std::vector<std::chrono::seconds>& to_add)
17 {
18  for (auto offset : to_add) {
19  offsets.Add(offset);
20  }
21 }
22 
23 BOOST_FIXTURE_TEST_SUITE(timeoffsets_tests, BasicTestingSetup)
24 
26 {
28  BOOST_CHECK(offsets.Median() == 0s);
29 
30  AddMulti(offsets, {{0s, -1s, -2s, -3s}});
31  // median should be zero for < 5 offsets
32  BOOST_CHECK(offsets.Median() == 0s);
33 
34  offsets.Add(-4s);
35  // we now have 5 offsets: [-4, -3, -2, -1, 0]
36  BOOST_CHECK(offsets.Median() == -2s);
37 
38  AddMulti(offsets, {4, 5s});
39  // we now have 9 offsets: [-4, -3, -2, -1, 0, 5, 5, 5, 5]
40  BOOST_CHECK(offsets.Median() == 0s);
41 
42  AddMulti(offsets, {41, 10s});
43  // the TimeOffsets is now at capacity with 50 offsets, oldest offsets is discarded for any additional offset
44  BOOST_CHECK(offsets.Median() == 10s);
45 
46  AddMulti(offsets, {25, 15s});
47  // we now have 25 offsets of 10s followed by 25 offsets of 15s
48  BOOST_CHECK(offsets.Median() == 15s);
49 }
50 
51 static bool IsWarningRaised(const std::vector<std::chrono::seconds>& check_offsets)
52 {
54  AddMulti(offsets, check_offsets);
55  return offsets.WarnIfOutOfSync();
56 }
57 
58 
59 BOOST_AUTO_TEST_CASE(timeoffsets_warning)
60 {
61  BOOST_CHECK(IsWarningRaised({{-60min, -40min, -30min, 0min, 10min}}));
62  BOOST_CHECK(IsWarningRaised({5, 11min}));
63 
64  BOOST_CHECK(!IsWarningRaised({4, 60min}));
65  BOOST_CHECK(!IsWarningRaised({100, 3min}));
66 }
67 
68 
BOOST_AUTO_TEST_SUITE_END()
#define BOOST_CHECK(expr)
Definition: object.cpp:17
static const int64_t offsets[]
Basic testing setup.
Definition: setup_common.h:54
static bool IsWarningRaised(const std::vector< std::chrono::seconds > &check_offsets)
BOOST_AUTO_TEST_CASE(timeoffsets)
static void AddMulti(TimeOffsets &offsets, const std::vector< std::chrono::seconds > &to_add)