Skip to content

Commit

Permalink
nostr: add tweak methods to Timestamp
Browse files Browse the repository at this point in the history
  • Loading branch information
yukibtc committed Oct 5, 2023
1 parent 1f8a712 commit 6787760
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions crates/nostr/src/types/time/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ use core::ops::{Add, Sub};
use core::str::FromStr;
use core::time::Duration;

#[cfg(feature = "std")]
use bitcoin::secp256k1::rand::rngs::OsRng;
use bitcoin::secp256k1::rand::Rng;

mod supplier;

pub use self::supplier::TimeSupplier;
Expand Down Expand Up @@ -42,6 +46,44 @@ impl Timestamp {
supplier.to_timestamp(duration)
}

/// Get tweaked UNIX timestamp
///
/// Remove a random number of seconds from now (max 65535 secs)
#[cfg(feature = "std")]
pub fn tweaked() -> Self {
let mut now: Timestamp = Self::now();
now.tweak();
now
}

/// Get tweaked UNIX timestamp
///
/// Remove a random number of seconds from now (max 65535 secs)
pub fn tweaked_with_supplier_and_rng<T, R>(supplier: &T, rng: &mut R) -> Self
where
T: TimeSupplier,
R: Rng,
{
let mut now: Timestamp = Self::now_with_supplier(supplier);
now.tweak_with_rng(rng);
now
}

/// Remove a random number of seconds from [`Timestamp`] (max 65535 secs)
#[cfg(feature = "std")]
pub fn tweak(&mut self) {
self.tweak_with_rng(&mut OsRng);
}

/// Remove a random number of seconds from [`Timestamp`] (max 65535 secs)
pub fn tweak_with_rng<R>(&mut self, rng: &mut R)
where
R: Rng,
{
let secs: u16 = rng.gen_range(0..=u16::MAX);
self.0 -= secs as i64;
}

/// Get timestamp as [`u64`]
pub fn as_u64(&self) -> u64 {
if self.0 >= 0 {
Expand Down

0 comments on commit 6787760

Please sign in to comment.