timeoffsets_tests.cpp raw

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