Line data Source code
1 : // Copyright (c) 2014 The Bitcoin developers 2 : // Copyright (c) 2019-2020 The PIVX Core developers 3 : // Distributed under the MIT software license, see the accompanying 4 : // file COPYING or http://www.opensource.org/licenses/mit-license.php. 5 : 6 : #ifndef PIVX_TIMEDATA_H 7 : #define PIVX_TIMEDATA_H 8 : 9 : #include <algorithm> 10 : #include <assert.h> 11 : #include <stdint.h> 12 : #include <vector> 13 : 14 : class CNetAddr; 15 : 16 : /** 17 : * Median filter over a stream of values. 18 : * Returns the median of the last N numbers 19 : */ 20 : template <typename T> 21 : class CMedianFilter 22 : { 23 : private: 24 : std::vector<T> vValues; 25 : std::vector<T> vSorted; 26 : unsigned int nSize; 27 : 28 : public: 29 248 : CMedianFilter(unsigned int size, T initial_value) : nSize(size) 30 : { 31 248 : vValues.reserve(size); 32 248 : vValues.push_back(initial_value); 33 248 : vSorted = vValues; 34 248 : } 35 : 36 1366 : void input(T value) 37 : { 38 1366 : if (vValues.size() == nSize) { 39 2 : vValues.erase(vValues.begin()); 40 : } 41 1366 : vValues.push_back(value); 42 : 43 1366 : vSorted.resize(vValues.size()); 44 1366 : std::copy(vValues.begin(), vValues.end(), vSorted.begin()); 45 1366 : std::sort(vSorted.begin(), vSorted.end()); 46 1366 : } 47 : 48 467 : T median() const 49 : { 50 467 : int size = vSorted.size(); 51 467 : assert(size > 0); 52 467 : if (size & 1) // Odd number of elements 53 : { 54 465 : return vSorted[size / 2]; 55 : } else // Even number of elements 56 : { 57 2 : return (vSorted[size / 2 - 1] + vSorted[size / 2]) / 2; 58 : } 59 : } 60 : 61 3570 : int size() const 62 : { 63 1360 : return vValues.size(); 64 : } 65 : 66 460 : std::vector<T> sorted() const 67 : { 68 460 : return vSorted; 69 : } 70 : }; 71 : 72 : /** Functions to keep track of adjusted P2P time */ 73 1822 : inline int64_t abs64(int64_t n) { return (n >= 0 ? n : -n); } 74 : int64_t GetTimeOffset(); 75 : int64_t GetAdjustedTime(); 76 : void AddTimeData(const CNetAddr& ip, int64_t nTime, int nOffsetLimit); 77 : 78 : // Time Protocol V2 79 : int64_t GetTimeSlot(const int64_t nTime); 80 : int64_t GetCurrentTimeSlot(); 81 : 82 : #endif // PIVX_TIMEDATA_H