clock.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. '''
  2. synchronized NTP clock
  3. '''
  4. import ntplib
  5. from time import ctime
  6. import math
  7. class SynchedNTPClock(object):
  8. def __init__(self, slot_length=1, ntp_server='europe.pool.ntp.org'):
  9. #TODO how long should be the slot length
  10. self.slot_length=slot_length
  11. self.ntp_server = ntp_server
  12. self.ntp_client = ntplib.NTPClient()
  13. #TODO validate the server
  14. # when was darkfi birthday? as seconds since the epoch
  15. self.darkfi_epoch=0
  16. def __repr__(self):
  17. return 'darkfi time: '+ ctime(self.darkfi_time) + ', current synched time: ' + ctime(self.synched_time)
  18. def __get_time_stat(self):
  19. response=None
  20. success=False
  21. while not success:
  22. try:
  23. response = self.ntp_client.request(self.ntp_server, version=3)
  24. success=True
  25. #except ntplib.NTPException as e:
  26. except:
  27. pass
  28. #print("connection failed: {}".format(e.what()))
  29. return response
  30. @property
  31. def synched_time(self):
  32. state = self.__get_time_stat()
  33. synched_time = state.tx_time
  34. return synched_time
  35. @property
  36. def darkfi_time(self):
  37. return self.synched_time - self.darkfi_epoch
  38. @property
  39. def slot(self):
  40. return math.floor(self.darkfi_time/self.slot_length)