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