26

Bitcoin needs to know the current time in order to validate blocks. How does it decide that?

Note that I'm talking about the Satoshi client specifically.

Nick ODell
  • 29,184
  • 11
  • 69
  • 129

2 Answers2

31

It takes the median time of the other clients connected, but only
1. if there are at least 5, and
2. if the median time does not differ from system time by more than 70 minutes.

For specifics, we look at AddTimeData, in timedata.cpp.

Note: I have edited it down for length

void AddTimeData(const CNetAddr& ip, int64 nTime)
{
    int64 nOffsetSample = nTime - GetTime();
    // Add data
    vTimeOffsets.input(nOffsetSample);
    if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
    {
        int64 nMedian = vTimeOffsets.median();
        // Only let other nodes change our time by so much
        if (abs64(nMedian) < 70 * 60)
        {
            nTimeOffset = nMedian;
        }
        else
        {
            nTimeOffset = 0;
        }
    }
}
Nick ODell
  • 29,184
  • 11
  • 69
  • 129
  • Is there a possible attack on manipulating this time on a client? – abeikverdi Mar 08 '15 at 06:20
  • 1
    @abeikverdi A full answer to that question would be too large to be contained within a single comment. It's an interesting question, though, and I encourage you to [ask it](http://bitcoin.stackexchange.com/questions/ask) as a separate question. Related: [Was a timejacking attack ever performed?](http://bitcoin.stackexchange.com/questions/3516/was-a-timejacking-attack-ever-performed/35441#35441) – Nick ODell Mar 08 '15 at 06:28
  • Yea, that's a big question! Thanks for the link! I guess I need to read more about timejacking in Bitcoin's network – abeikverdi Mar 08 '15 at 06:37
11

As individual clients may have an arbitrary timeshift, the Satoshi client will use the median of its neighbors times alongs with its own time to find an offset to the local clock. This offset will then be used throughout the client wherever an accurate time is needed.

cdecker
  • 9,319
  • 1
  • 38
  • 61