clock.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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=180, 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=True
  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. print("connection failed: {}".format(e.what()))
  27. return response
  28. @property
  29. def synched_time(self):
  30. state = self.__get_time_stat()
  31. synched_time = state.tx_time
  32. return synched_time
  33. @property
  34. def darkfi_time(self):
  35. return self.synched_time - self.darkfi_epoch
  36. @property
  37. def slot(self):
  38. return math.floor(self.darkfi_time/self.slot_length)