How does Bitcoin figure out what time it is?

25

3

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

Posted 2013-02-01T07:47:04.037

Reputation: 26 536

Answers

29

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

Posted 2013-02-01T07:47:04.037

Reputation: 26 536

Is there a possible attack on manipulating this time on a client?abeikverdi 2015-03-08T06:20:01.390

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 as a separate question. Related: Was a timejacking attack ever performed?

Nick ODell 2015-03-08T06:28:23.013

Yea, that's a big question! Thanks for the link! I guess I need to read more about timejacking in Bitcoin's networkabeikverdi 2015-03-08T06:37:07.693

10

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

Posted 2013-02-01T07:47:04.037

Reputation: 7 878