Bitcoin ABC 0.30.5
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 <util/time.h>
9
10#include <algorithm>
11#include <cassert>
12#include <chrono>
13#include <cstdint>
14#include <vector>
15
16static const int64_t DEFAULT_MAX_TIME_ADJUSTMENT = 70 * 60;
17
18class CNetAddr;
19
24template <typename T> class CMedianFilter {
25private:
26 std::vector<T> vValues;
27 std::vector<T> vSorted;
28 unsigned int nSize;
29
30public:
31 CMedianFilter(unsigned int _size, T initial_value) : nSize(_size) {
32 vValues.reserve(_size);
33 vValues.push_back(initial_value);
35 }
36
37 void input(T value) {
38 if (vValues.size() == nSize) {
39 vValues.erase(vValues.begin());
40 }
41 vValues.push_back(value);
42
43 vSorted.resize(vValues.size());
44 std::copy(vValues.begin(), vValues.end(), vSorted.begin());
45 std::sort(vSorted.begin(), vSorted.end());
46 }
47
48 T median() const {
49 int vSortedSize = vSorted.size();
50 assert(vSortedSize > 0);
51 if (vSortedSize & 1) {
52 // Odd number of elements
53 return vSorted[vSortedSize / 2];
54 } else {
55 // Even number of elements
56 auto left = vSorted[vSortedSize / 2 - 1];
57 auto right = vSorted[vSortedSize / 2];
58 return left / 2 + right / 2 + (left & right & 1);
59 }
60 }
61
62 int size() const { return vValues.size(); }
63
64 std::vector<T> sorted() const { return vSorted; }
65};
66
68int64_t GetTimeOffset();
70void AddTimeData(const CNetAddr &ip, int64_t nTime);
71
77
78#endif // BITCOIN_TIMEDATA_H
Median filter over a stream of values.
Definition: timedata.h:24
std::vector< T > sorted() const
Definition: timedata.h:64
int size() const
Definition: timedata.h:62
unsigned int nSize
Definition: timedata.h:28
std::vector< T > vSorted
Definition: timedata.h:27
CMedianFilter(unsigned int _size, T initial_value)
Definition: timedata.h:31
T median() const
Definition: timedata.h:48
void input(T value)
Definition: timedata.h:37
std::vector< T > vValues
Definition: timedata.h:26
Network address.
Definition: netaddress.h:121
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:127
NodeClock::time_point GetAdjustedTime()
Definition: timedata.cpp:35
void AddTimeData(const CNetAddr &ip, int64_t nTime)
Definition: timedata.cpp:45
assert(!tx.IsCoinBase())