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