clock_sync.rs 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 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 tracing::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. ///
  47. /// Retry loop is used in case discrepancies are found.
  48. /// If all retries fail, system clock is considered invalid.
  49. /// TODO: 1. Add proxy functionality in order not to leak connections
  50. pub async fn check_clock(peers: &[Url]) -> Result<()> {
  51. debug!(target: "rpc::clock_sync", "System clock check started...");
  52. let mut r = 0;
  53. while r < RETRIES {
  54. if let Err(e) = clock_check(peers).await {
  55. debug!(target: "rpc::clock_sync", "Error during clock check: {e:#?}");
  56. r += 1;
  57. continue
  58. };
  59. break
  60. }
  61. debug!(target: "rpc::clock_sync", "System clock check finished. Retries: {r}");
  62. if r == RETRIES {
  63. return Err(Error::InvalidClock)
  64. }
  65. Ok(())
  66. }
  67. async fn clock_check(_peers: &[Url]) -> Result<()> {
  68. // Start elapsed time counter to cover for all requests and processing time
  69. let requests_start = Timestamp::current_time();
  70. // Poll one of the peers for their current UTC timestamp
  71. //let peer_time = peer_request(peers).await?;
  72. let peer_time = Some(Timestamp::current_time());
  73. // Start elapsed time counter to cover for NTP request and processing time
  74. let ntp_request_start = Timestamp::current_time();
  75. // Poll ntp.org for current timestamp
  76. let ntp_time = ntp_request().await?;
  77. // Stop elapsed time counters
  78. let ntp_elapsed_time = ntp_request_start.elapsed()?;
  79. let requests_elapsed_time = requests_start.elapsed()?;
  80. // Current system time
  81. let system_time = Timestamp::current_time();
  82. // Add elapsed time to response times
  83. let ntp_time = ntp_time.checked_add(ntp_elapsed_time)?;
  84. let peer_time = match peer_time {
  85. None => None,
  86. Some(p) => Some(p.checked_add(requests_elapsed_time)?),
  87. };
  88. debug!(target: "rpc::clock_sync", "peer_time: {peer_time:#?}");
  89. debug!(target: "rpc::clock_sync", "ntp_time: {ntp_time:#?}");
  90. debug!(target: "rpc::clock_sync", "system_time: {system_time:#?}");
  91. // We verify that system time is equal to peer (if exists) and ntp times
  92. let check = match peer_time {
  93. Some(p) => (system_time == p) && (system_time == ntp_time),
  94. None => system_time == ntp_time,
  95. };
  96. match check {
  97. true => Ok(()),
  98. false => Err(Error::InvalidClock),
  99. }
  100. }