Bitcoin ABC  0.22.12
P2P Digital Currency
timedata.h
Go to the documentation of this file.
1 // Copyright (c) 2014-2016 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> class CMedianFilter {
22 private:
23  std::vector<T> vValues;
24  std::vector<T> vSorted;
25  unsigned int nSize;
26 
27 public:
28  CMedianFilter(unsigned int _size, T initial_value) : nSize(_size) {
29  vValues.reserve(_size);
30  vValues.push_back(initial_value);
31  vSorted = vValues;
32  }
33 
34  void input(T value) {
35  if (vValues.size() == nSize) {
36  vValues.erase(vValues.begin());
37  }
38  vValues.push_back(value);
39 
40  vSorted.resize(vValues.size());
41  std::copy(vValues.begin(), vValues.end(), vSorted.begin());
42  std::sort(vSorted.begin(), vSorted.end());
43  }
44 
45  T median() const {
46  int vSortedSize = vSorted.size();
47  assert(vSortedSize > 0);
48  if (vSortedSize & 1) {
49  // Odd number of elements
50  return vSorted[vSortedSize / 2];
51  } else {
52  // Even number of elements
53  auto left = vSorted[vSortedSize / 2 - 1];
54  auto right = vSorted[vSortedSize / 2];
55  return left / 2 + right / 2 + (left & right & 1);
56  }
57  }
58 
59  int size() const { return vValues.size(); }
60 
61  std::vector<T> sorted() const { return vSorted; }
62 };
63 
65 int64_t GetTimeOffset();
66 int64_t GetAdjustedTime();
67 void AddTimeData(const CNetAddr &ip, int64_t nTime);
68 
69 #endif // BITCOIN_TIMEDATA_H
void AddTimeData(const CNetAddr &ip, int64_t nTime)
Definition: timedata.cpp:45
Median filter over a stream of values.
Definition: timedata.h:21
std::vector< T > vSorted
Definition: timedata.h:24
std::vector< T > sorted() const
Definition: timedata.h:61
std::vector< T > vValues
Definition: timedata.h:23
int64_t GetTimeOffset()
Functions to keep track of adjusted P2P time.
Definition: timedata.cpp:29
void input(T value)
Definition: timedata.h:34
int64_t GetAdjustedTime()
Definition: timedata.cpp:34
IP address (IPv6, or IPv4 using mapped IPv6 range (::FFFF:0:0/96))
Definition: netaddress.h:30
CMedianFilter(unsigned int _size, T initial_value)
Definition: timedata.h:28
unsigned int nSize
Definition: timedata.h:25
int size() const
Definition: timedata.h:59
static const int64_t DEFAULT_MAX_TIME_ADJUSTMENT
Definition: timedata.h:13
T median() const
Definition: timedata.h:45