Bitcoin Core  25.99.0
P2P Digital Currency
timedata.h
Go to the documentation of this file.
1 // Copyright (c) 2014-2022 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 #ifndef BITCOIN_TIMEDATA_H
6 #define BITCOIN_TIMEDATA_H
7 
8 #include <util/time.h>
9 
10 #include <algorithm>
11 #include <cassert>
12 #include <chrono>
13 #include <cstdint>
14 #include <vector>
15 
16 static const int64_t DEFAULT_MAX_TIME_ADJUSTMENT = 70 * 60;
17 
18 class CNetAddr;
19 
24 template <typename T>
26 {
27 private:
28  std::vector<T> vValues;
29  std::vector<T> vSorted;
30  unsigned int nSize;
31 
32 public:
33  CMedianFilter(unsigned int _size, T initial_value) : nSize(_size)
34  {
35  vValues.reserve(_size);
36  vValues.push_back(initial_value);
37  vSorted = vValues;
38  }
39 
40  void input(T value)
41  {
42  if (vValues.size() == nSize) {
43  vValues.erase(vValues.begin());
44  }
45  vValues.push_back(value);
46 
47  vSorted.resize(vValues.size());
48  std::copy(vValues.begin(), vValues.end(), vSorted.begin());
49  std::sort(vSorted.begin(), vSorted.end());
50  }
51 
52  T median() const
53  {
54  int vSortedSize = vSorted.size();
55  assert(vSortedSize > 0);
56  if (vSortedSize & 1) // Odd number of elements
57  {
58  return vSorted[vSortedSize / 2];
59  } else // Even number of elements
60  {
61  return (vSorted[vSortedSize / 2 - 1] + vSorted[vSortedSize / 2]) / 2;
62  }
63  }
64 
65  int size() const
66  {
67  return vValues.size();
68  }
69 
70  std::vector<T> sorted() const
71  {
72  return vSorted;
73  }
74 };
75 
77 int64_t GetTimeOffset();
79 void AddTimeData(const CNetAddr& ip, int64_t nTime);
80 
85 
86 #endif // BITCOIN_TIMEDATA_H
Median filter over a stream of values.
Definition: timedata.h:26
std::vector< T > sorted() const
Definition: timedata.h:70
int size() const
Definition: timedata.h:65
unsigned int nSize
Definition: timedata.h:30
std::vector< T > vSorted
Definition: timedata.h:29
CMedianFilter(unsigned int _size, T initial_value)
Definition: timedata.h:33
T median() const
Definition: timedata.h:52
void input(T value)
Definition: timedata.h:40
std::vector< T > vValues
Definition: timedata.h:28
Network address.
Definition: netaddress.h:120
static CService ip(uint32_t i)
std::chrono::time_point< NodeClock > time_point
Definition: time.h:19
static const int64_t DEFAULT_MAX_TIME_ADJUSTMENT
Definition: timedata.h:16
int64_t GetTimeOffset()
Functions to keep track of adjusted P2P time.
Definition: timedata.cpp:30
void TestOnlyResetTimeData()
Reset the internal state of GetTimeOffset(), GetAdjustedTime() and AddTimeData().
Definition: timedata.cpp:114
NodeClock::time_point GetAdjustedTime()
Definition: timedata.cpp:36
void AddTimeData(const CNetAddr &ip, int64_t nTime)
Definition: timedata.cpp:47
assert(!tx.IsCoinBase())