clock_sync.rs 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. //! Clock sync module
  19. use std::{net::UdpSocket, time::Duration};
  20. use log::debug;
  21. use url::Url;
  22. use crate::{util::time::Timestamp, Error, Result};
  23. /// Clock sync parameters
  24. const RETRIES: u8 = 10;
  25. /// TODO: Loop through set of ntps, get their average response concurrenyly.
  26. const NTP_ADDRESS: &str = "pool.ntp.org:123";
  27. const EPOCH: u32 = 2208988800; // 1900
  28. /// Raw NTP request execution
  29. pub async fn ntp_request() -> Result<Timestamp> {
  30. // Create socket
  31. let sock = UdpSocket::bind("0.0.0.0:0")?;
  32. sock.set_read_timeout(Some(Duration::from_secs(5)))?;
  33. sock.set_write_timeout(Some(Duration::from_secs(5)))?;
  34. // Execute request
  35. let mut packet = [0u8; 48];
  36. packet[0] = (3 << 6) | (4 << 3) | 3;
  37. sock.send_to(&packet, NTP_ADDRESS)?;
  38. // Parse response
  39. sock.recv(&mut packet[..])?;
  40. let (bytes, _) = packet[40..44].split_at(core::mem::size_of::<u32>());
  41. let num = u32::from_be_bytes(bytes.try_into().unwrap());
  42. let timestamp = Timestamp::from_u64((num - EPOCH) as u64);
  43. Ok(timestamp)
  44. }
  45. /// This is a very simple check to verify that the system time is correct.
  46. /// Retry loop is used in case discrepancies are found.
  47. /// If all retries fail, system clock is considered invalid.
  48. /// TODO: 1. Add proxy functionality in order not to leak connections
  49. pub async fn check_clock(peers: &[Url]) -> Result<()> {
  50. debug!(target: "rpc::clock_sync", "System clock check started...");
  51. let mut r = 0;
  52. while r < RETRIES {
  53. if let Err(e) = clock_check(peers).await {
  54. debug!(target: "rpc::clock_sync", "Error during clock check: {:#?}", e);
  55. r += 1;
  56. continue
  57. };
  58. break
  59. }
  60. debug!(target: "rpc::clock_sync", "System clock check finished. Retries: {}", r);
  61. if r == RETRIES {
  62. return Err(Error::InvalidClock)
  63. }
  64. Ok(())
  65. }
  66. async fn clock_check(_peers: &[Url]) -> Result<()> {
  67. // Start elapsed time counter to cover for all requests and processing time
  68. let requests_start = Timestamp::current_time();
  69. // Poll one of the peers for their current UTC timestamp
  70. //let peer_time = peer_request(peers).await?;
  71. let peer_time = Some(Timestamp::current_time());
  72. // Start elapsed time counter to cover for NTP request and processing time
  73. let ntp_request_start = Timestamp::current_time();
  74. // Poll ntp.org for current timestamp
  75. let ntp_time = ntp_request().await?;
  76. // Stop elapsed time counters
  77. let ntp_elapsed_time = ntp_request_start.elapsed()?;
  78. let requests_elapsed_time = requests_start.elapsed()?;
  79. // Current system time
  80. let system_time = Timestamp::current_time();
  81. // Add elapsed time to response times
  82. let ntp_time = ntp_time.checked_add(ntp_elapsed_time)?;
  83. let peer_time = match peer_time {
  84. None => None,
  85. Some(p) => Some(p.checked_add(requests_elapsed_time)?),
  86. };
  87. debug!(target: "rpc::clock_sync", "peer_time: {:#?}", peer_time);
  88. debug!(target: "rpc::clock_sync", "ntp_time: {:#?}", ntp_time);
  89. debug!(target: "rpc::clock_sync", "system_time: {:#?}", system_time);
  90. // We verify that system time is equal to peer (if exists) and ntp times
  91. let check = match peer_time {
  92. Some(p) => (system_time == p) && (system_time == ntp_time),
  93. None => system_time == ntp_time,
  94. };
  95. match check {
  96. true => Ok(()),
  97. false => Err(Error::InvalidClock),
  98. }
  99. }