clock_sync.rs 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 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 rand::prelude::SliceRandom;
  22. use serde_json::json;
  23. use url::Url;
  24. use super::{client::RpcClient, jsonrpc::JsonRequest};
  25. use crate::{util::time::Timestamp, Error, Result};
  26. /// Clock sync parameters
  27. const RETRIES: u8 = 10;
  28. /// TODO: Loop through set of ntps, get their average response concurrenyly.
  29. const NTP_ADDRESS: &str = "pool.ntp.org:123";
  30. const EPOCH: i64 = 2208988800; // 1900
  31. /// JSON-RPC request to a network peer (randomly selected), to
  32. /// retrieve their current system clock.
  33. async fn peer_request(peers: &[Url]) -> Result<Option<Timestamp>> {
  34. // Select peer, None if vector is empty.
  35. let peer = peers.choose(&mut rand::thread_rng());
  36. match peer {
  37. None => Ok(None),
  38. Some(p) => {
  39. // Create RPC client
  40. let rpc_client = RpcClient::new(p.clone()).await?;
  41. // Execute request
  42. let req = JsonRequest::new("clock", json!([]));
  43. let rep = rpc_client.oneshot_request(req).await?;
  44. // Parse response
  45. let timestamp: Timestamp = serde_json::from_value(rep)?;
  46. Ok(Some(timestamp))
  47. }
  48. }
  49. }
  50. /// Raw NTP request execution
  51. pub async fn ntp_request() -> Result<Timestamp> {
  52. // Create socket
  53. let sock = UdpSocket::bind("0.0.0.0:0")?;
  54. sock.set_read_timeout(Some(Duration::from_secs(5)))?;
  55. sock.set_write_timeout(Some(Duration::from_secs(5)))?;
  56. // Execute request
  57. let mut packet = [0u8; 48];
  58. packet[0] = (3 << 6) | (4 << 3) | 3;
  59. sock.send_to(&packet, NTP_ADDRESS)?;
  60. // Parse response
  61. sock.recv(&mut packet[..])?;
  62. let (bytes, _) = packet[40..44].split_at(core::mem::size_of::<u32>());
  63. let num = u32::from_be_bytes(bytes.try_into().unwrap());
  64. let timestamp = Timestamp(num as i64 - EPOCH);
  65. Ok(timestamp)
  66. }
  67. /// This is a very simple check to verify that the system time is correct.
  68. /// Retry loop is used in case discrepancies are found.
  69. /// If all retries fail, system clock is considered invalid.
  70. /// TODO: 1. Add proxy functionality in order not to leak connections
  71. pub async fn check_clock(peers: &[Url]) -> Result<()> {
  72. debug!(target: "rpc::clock_sync", "System clock check started...");
  73. let mut r = 0;
  74. while r < RETRIES {
  75. if let Err(e) = clock_check(peers).await {
  76. debug!(target: "rpc::clock_sync", "Error during clock check: {:#?}", e);
  77. r += 1;
  78. continue
  79. };
  80. break
  81. }
  82. debug!(target: "rpc::clock_sync", "System clock check finished. Retries: {}", r);
  83. if r == RETRIES {
  84. return Err(Error::InvalidClock)
  85. }
  86. Ok(())
  87. }
  88. async fn clock_check(peers: &[Url]) -> Result<()> {
  89. // Start elapsed time counter to cover for all requests and processing time
  90. let requests_start = Timestamp::current_time();
  91. // Poll one of the peers for their current UTC timestamp
  92. let peer_time = peer_request(peers).await?;
  93. // Start elapsed time counter to cover for NTP request and processing time
  94. let ntp_request_start = Timestamp::current_time();
  95. // Poll ntp.org for current timestamp
  96. let mut ntp_time = ntp_request().await?;
  97. // Stop elapsed time counters
  98. let ntp_elapsed_time = ntp_request_start.elapsed() as i64;
  99. let requests_elapsed_time = requests_start.elapsed() as i64;
  100. // Current system time
  101. let system_time = Timestamp::current_time();
  102. // Add elapsed time to response times
  103. ntp_time.add(ntp_elapsed_time);
  104. let peer_time = match peer_time {
  105. None => None,
  106. Some(p) => {
  107. let mut t = p;
  108. t.add(requests_elapsed_time);
  109. Some(t)
  110. }
  111. };
  112. debug!(target: "rpc::clock_sync", "peer_time: {:#?}", peer_time);
  113. debug!(target: "rpc::clock_sync", "ntp_time: {:#?}", ntp_time);
  114. debug!(target: "rpc::clock_sync", "system_time: {:#?}", system_time);
  115. // We verify that system time is equal to peer (if exists) and ntp times
  116. let check = match peer_time {
  117. Some(p) => (system_time == p) && (system_time == ntp_time),
  118. None => system_time == ntp_time,
  119. };
  120. match check {
  121. true => Ok(()),
  122. false => Err(Error::InvalidClock),
  123. }
  124. }