| 45 | #define BITCOIN_TIMEDATA_MAX_SAMPLES 200 |
| 46 | |
| 47 | void AddTimeData(const CNetAddr& ip, int64_t nOffsetSample) |
| 48 | { |
| 49 | LOCK(cs_nTimeOffset); |
| 50 | // Ignore duplicates |
| 51 | static std::set<CNetAddr> setKnown; |
| 52 | if (setKnown.size() == BITCOIN_TIMEDATA_MAX_SAMPLES) |
| 53 | return; |
| 54 | if (!setKnown.insert(ip).second) |
| 55 | return; |
| 56 | |
| 57 | // Add data |
| 58 | static CMedianFilter<int64_t> vTimeOffsets(BITCOIN_TIMEDATA_MAX_SAMPLES, 0); |
| 59 | vTimeOffsets.input(nOffsetSample); |
| 60 | LogPrint(BCLog::NET,"added time data, samples %d, offset %+d (%+d minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60); |
| 61 | |
| 62 | // There is a known issue here (see issue #4521): |
| 63 | // |
| 64 | // - The structure vTimeOffsets contains up to 200 elements, after which |
| 65 | // any new element added to it will not increase its size, replacing the |
| 66 | // oldest element. |
| 67 | // |
| 68 | // - The condition to update nTimeOffset includes checking whether the |
| 69 | // number of elements in vTimeOffsets is odd, which will never happen after |
| 70 | // there are 200 elements. |
| 71 | // |
| 72 | // But in this case the 'bug' is protective against some attacks, and may |
| 73 | // actually explain why we've never seen attacks which manipulate the |
| 74 | // clock offset. |
| 75 | // |
| 76 | // So we should hold off on fixing this and clean it up as part of |
| 77 | // a timing cleanup that strengthens it in a number of other ways. |
| 78 | // |
| 79 | if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1) |
| 80 | { |
| 81 | int64_t nMedian = vTimeOffsets.median(); |
| 82 | std::vector<int64_t> vSorted = vTimeOffsets.sorted(); |
| 83 | // Only let other nodes change our time by so much |
| 84 | if (abs64(nMedian) <= std::max<int64_t>(0, gArgs.GetArg("-maxtimeadjustment", DEFAULT_MAX_TIME_ADJUSTMENT))) |
| 85 | { |
| 86 | nTimeOffset = nMedian; |
| 87 | } |
| 88 | else |
| 89 | { |
| 90 | nTimeOffset = 0; |
| 91 | |
| 92 | static bool fDone; |
| 93 | if (!fDone) |
| 94 | { |
| 95 | // If nobody has a time different than ours but within 5 minutes of ours, give a warning |
| 96 | bool fMatch = false; |
| 97 | for (int64_t nOffset : vSorted) |
| 98 | if (nOffset != 0 && abs64(nOffset) < 5 * 60) |
| 99 | fMatch = true; |
| 100 | |
| 101 | if (!fMatch) |
| 102 | { |
| 103 | fDone = true; |
| 104 | std::string strMessage = strprintf(_("Please check that your computer's date and time are correct! If your clock is wrong, %s will not work properly."), _(PACKAGE_NAME)); |
no test coverage detected