From 8b4e446342ab1af810732445592253cd467dc7b1 Mon Sep 17 00:00:00 2001 From: CryptoManiac Date: Sun, 20 Sep 2015 15:29:15 +0300 Subject: [PATCH] Add time samples from NTP while starting up. --- src/init.cpp | 18 ++++++++++++++++++ src/ntp.cpp | 18 ++++++++++++++++++ src/ntp.h | 7 ++++++- 3 files changed, 42 insertions(+), 1 deletions(-) diff --git a/src/init.cpp b/src/init.cpp index 1eb28a5..b93f2bd 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -8,6 +8,7 @@ #include "net.h" #include "init.h" #include "util.h" +#include "ntp.h" #include "ui_interface.h" #include "checkpoints.h" #include @@ -995,6 +996,23 @@ bool AppInit2() if (fServer) NewThread(ThreadRPCServer, NULL); + // ********************************************************* Step 12: add time data from four random NTP servers. + uiInterface.InitMessage(_("Synchronizing time through NTP...")); + printf("Synchronizing time through NTP...\n"); + int i = 0; + while(i < 4) { + CNetAddr ip; + int64_t nTime = NtpGetTime(ip); + + if (nTime > 0 && nTime != 2085978496) { // Skip the deliberately wrong timestamps + AddTimeData(ip, nTime); + printf("AddTimeData(%s, %" PRId64 ")\n", ip.ToString().c_str(), nTime); + } + + i++; + } + uiInterface.InitMessage(_("Done")); + printf("Done\n"); // ********************************************************* Step 12: finished uiInterface.InitMessage(_("Done loading")); diff --git a/src/ntp.cpp b/src/ntp.cpp index 58d224c..d7016d6 100644 --- a/src/ntp.cpp +++ b/src/ntp.cpp @@ -389,6 +389,24 @@ int64_t NtpGetTime() return nTime; } +int64_t NtpGetTime(CNetAddr& ip) +{ + struct sockaddr cliaddr; + + SOCKET sockfd; + socklen_t servlen; + + if (!InitWithRandom(sockfd, servlen, &cliaddr)) + return -1; + + ip = CNetAddr(((sockaddr_in *)&cliaddr)->sin_addr); + int64_t nTime = DoReq(sockfd, servlen, cliaddr); + + closesocket(sockfd); + + return nTime; +} + int64_t NtpGetTime(std::string &strHostName) { struct sockaddr cliaddr; diff --git a/src/ntp.h b/src/ntp.h index 4963124..d6c5863 100644 --- a/src/ntp.h +++ b/src/ntp.h @@ -1,3 +1,8 @@ +// Get time from random server. int64_t NtpGetTime(); -int64_t NtpGetTime(std::string &strHostName); +// Get time from random server and return server address. +int64_t NtpGetTime(CNetAddr& ip); + +// Get time from provided server. +int64_t NtpGetTime(std::string &strHostName); -- 1.7.1