Skip to content

Commit

Permalink
feat: change SignedPacket::last_seen to be u64 instead of instant for…
Browse files Browse the repository at this point in the history
… easier serialization
  • Loading branch information
Nuhvi committed Apr 30, 2024
1 parent d7e55b8 commit c1c69c4
Show file tree
Hide file tree
Showing 7 changed files with 76 additions and 98 deletions.
19 changes: 4 additions & 15 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 1 addition & 2 deletions pkarr/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ use std::{
net::{SocketAddr, ToSocketAddrs},
num::NonZeroUsize,
thread,
time::Instant,
};
use tracing::{debug, info, instrument, trace};

Expand Down Expand Up @@ -438,7 +437,7 @@ fn run(
if (*seq as u64) == cached.timestamp() {
trace!("Remote node has the a packet with same timestamp, refreshing cached packet.");

cached.set_last_seen(&Instant::now());
cached.refresh();
cache.put(target, &cached);

// Send the found sequence as a timestamp to the caller to decide what to do
Expand Down
1 change: 0 additions & 1 deletion pkarr/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
#![doc = include_str!("../README.md")]

// TODO: add support for wasm using relays.
// TODO: allow custom Cache with traits.

// Rexports
pub use bytes;
Expand Down
51 changes: 30 additions & 21 deletions pkarr/src/signed_packet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use std::{
char,
fmt::{self, Display, Formatter},
net::{Ipv4Addr, Ipv6Addr},
time::{Duration, Instant, SystemTime},
time::SystemTime,
};

const DOT: char = '.';
Expand Down Expand Up @@ -61,7 +61,7 @@ impl Inner {
/// Signed DNS packet
pub struct SignedPacket {
inner: Inner,
last_seen: Instant,
last_seen: u64,
}

impl SignedPacket {
Expand Down Expand Up @@ -101,13 +101,13 @@ impl SignedPacket {

Ok(SignedPacket {
inner: Inner::try_from_bytes(bytes)?,
last_seen: Instant::now(),
last_seen: system_time(),
})
}

/// Useful for cloning a [SignedPacket], or cerating one from a previously checked bytes,
/// like ones stored on disk or in a database.
pub fn from_bytes_unchecked(bytes: &Bytes, last_seen: Instant) -> SignedPacket {
pub fn from_bytes_unchecked(bytes: &Bytes, last_seen: u64) -> SignedPacket {
SignedPacket {
inner: Inner::try_from_bytes(bytes).unwrap(),
last_seen,
Expand Down Expand Up @@ -171,7 +171,7 @@ impl SignedPacket {
return Err(Error::PacketTooLarge(encoded_packet.len()));
}

let timestamp = system_time().as_micros() as u64;
let timestamp = system_time();

let signature = keypair.sign(&signable(timestamp, &encoded_packet));

Expand All @@ -182,7 +182,7 @@ impl SignedPacket {
timestamp,
&encoded_packet,
)?,
last_seen: Instant::now(),
last_seen: system_time(),
})
}

Expand Down Expand Up @@ -234,19 +234,25 @@ impl SignedPacket {
self.inner.borrow_dependent()
}

pub fn last_seen(&self) -> &Instant {
/// Unix last_seen time in microseconds
pub fn last_seen(&self) -> &u64 {
&self.last_seen
}

// === Setters ===

/// Set the [Self::last_seen] property
pub fn set_last_seen(&mut self, last_seen: &Instant) {
pub fn set_last_seen(&mut self, last_seen: &u64) {
self.last_seen = *last_seen;
}

// === Public Methods ===

/// Set the [Self::last_seen] to the current system time
pub fn refresh(&mut self) {
self.last_seen = system_time();
}

/// Return whether this [SignedPacket] is more recent than the given one.
/// If the timestamps are erqual, the one with the largest value is considered more recent.
/// Usefel for determining which packet contains the latest information from the Dht.
Expand Down Expand Up @@ -285,12 +291,9 @@ impl SignedPacket {
let origin = self.public_key().to_z32();
let normalized_name = normalize_name(&origin, name.to_string());

let elapsed = self.last_seen().elapsed().as_secs() as u32;

self.packet()
.answers
.iter()
.filter(move |rr| rr.name == Name::new(&normalized_name).unwrap() && rr.ttl > elapsed)
self.packet().answers.iter().filter(move |rr| {
rr.name == Name::new(&normalized_name).unwrap() && rr.ttl > self.elapsed()
})
}

/// calculates the remaining seconds by comparing the [Self::ttl] (clamped by `min` and `max`)
Expand All @@ -300,10 +303,7 @@ impl SignedPacket {
///
/// Panics if `min` < `max`
pub fn expires_in(&self, min: u32, max: u32) -> u32 {
match self
.ttl(min, max)
.overflowing_sub(self.last_seen.elapsed().as_secs() as u32)
{
match self.ttl(min, max).overflowing_sub(self.elapsed()) {
(_, true) => 0,
(ttl, false) => ttl,
}
Expand All @@ -323,6 +323,13 @@ impl SignedPacket {
.min()
.map_or(min, |v| v.clamp(min, max))
}

// === Private Methods ===

/// Time since the [Self::last_seen] in seconds
fn elapsed(&self) -> u32 {
((system_time() - self.last_seen) / 1_000_000) as u32
}
}

fn signable(timestamp: u64, v: &Bytes) -> Bytes {
Expand All @@ -331,10 +338,12 @@ fn signable(timestamp: u64, v: &Bytes) -> Bytes {
signable.into()
}

fn system_time() -> Duration {
/// Return the number of microseconds since [SystemTime::UNIX_EPOCH]
pub fn system_time() -> u64 {
SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.expect("time drift")
.as_micros() as u64
}

#[cfg(feature = "dht")]
Expand Down Expand Up @@ -364,7 +373,7 @@ impl TryFrom<&MutableItem> for SignedPacket {

Ok(Self {
inner: Inner::try_from_parts(&public_key, &signature, seq, i.value())?,
last_seen: Instant::now(),
last_seen: system_time(),
})
}
}
Expand All @@ -389,7 +398,7 @@ impl Display for SignedPacket {
f,
"SignedPacket ({}):\n last_seen: {} seconds ago\n timestamp: {},\n signature: {}\n records:\n",
&self.public_key(),
&self.last_seen().elapsed().as_secs(),
&self.elapsed(),
&self.timestamp(),
&self.signature(),
)?;
Expand Down
3 changes: 2 additions & 1 deletion server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,5 @@ thiserror = "1.0.49"
bytes = "1.6.0"
tower_governor = "0.3.2"
governor = "0.6.3"
heed = "0.20.0"
heed = { version = "0.20.0", default-features = false }
byteorder = "1.5.0"
Loading

0 comments on commit c1c69c4

Please sign in to comment.