Skip to content

Add time support for wasm environments #1865

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions lightning-background-processor/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ bitcoin = "0.29.0"
lightning = { version = "0.0.112", path = "../lightning", features = ["std"] }
lightning-rapid-gossip-sync = { version = "0.0.112", path = "../lightning-rapid-gossip-sync" }
futures-util = { version = "0.3", default-features = false, features = ["async-await-macro"], optional = true }
instant = { version = "0.1", features = ["wasm-bindgen"] }

[dev-dependencies]
lightning = { version = "0.0.112", path = "../lightning", features = ["_test_utils"] }
Expand Down
2 changes: 1 addition & 1 deletion lightning-background-processor/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
use std::thread::JoinHandle;
use std::time::{Duration, Instant};
use instant::{Duration, Instant};
use std::ops::Deref;

#[cfg(feature = "futures")]
Expand Down
1 change: 1 addition & 0 deletions lightning-invoice/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ num-traits = { version = "0.2.8", default-features = false }
bitcoin_hashes = { version = "0.11", default-features = false }
hashbrown = { version = "0.8", optional = true }
serde = { version = "1.0.118", optional = true }
instant = { version = "0.1", features = ["wasm-bindgen"] }

[dev-dependencies]
lightning = { version = "0.0.112", path = "../lightning", default-features = false, features = ["_test_utils"] }
Expand Down
6 changes: 3 additions & 3 deletions lightning-invoice/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ extern crate core;
extern crate serde;

#[cfg(feature = "std")]
use std::time::SystemTime;
use instant::SystemTime;

use bech32::u5;
use bitcoin_hashes::Hash;
Expand Down Expand Up @@ -1850,7 +1850,7 @@ mod test {
use lightning::routing::router::RouteHintHop;
use secp256k1::Secp256k1;
use secp256k1::{SecretKey, PublicKey};
use std::time::{UNIX_EPOCH, Duration};
use instant::{SystemTime, Duration};

let secp_ctx = Secp256k1::new();

Expand Down Expand Up @@ -1939,7 +1939,7 @@ mod test {
assert_eq!(invoice.currency(), Currency::BitcoinTestnet);
#[cfg(feature = "std")]
assert_eq!(
invoice.timestamp().duration_since(UNIX_EPOCH).unwrap().as_secs(),
invoice.timestamp().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs(),
1234567
);
assert_eq!(invoice.payee_pub_key(), Some(&public_key));
Expand Down
6 changes: 3 additions & 3 deletions lightning-invoice/src/payment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ use core::future::Future;
use core::ops::Deref;
use core::time::Duration;
#[cfg(feature = "std")]
use std::time::SystemTime;
use instant::SystemTime;

/// A utility for paying [`Invoice`]s and sending spontaneous payments.
///
Expand All @@ -171,7 +171,7 @@ use std::time::SystemTime;
pub type InvoicePayer<P, R, L, E> = InvoicePayerUsingTime::<P, R, L, E, ConfiguredTime>;

#[cfg(not(feature = "no-std"))]
type ConfiguredTime = std::time::Instant;
type ConfiguredTime = instant::Instant;
#[cfg(feature = "no-std")]
use crate::time_utils;
#[cfg(feature = "no-std")]
Expand Down Expand Up @@ -891,7 +891,7 @@ mod tests {
use std::cell::RefCell;
use std::collections::VecDeque;
use std::ops::DerefMut;
use std::time::{SystemTime, Duration};
use instant::{SystemTime, Duration};
use crate::time_utils::tests::SinceEpoch;
use crate::DEFAULT_EXPIRY_TIME;
use lightning::util::errors::APIError::{ChannelUnavailable, MonitorUpdateInProgress};
Expand Down
10 changes: 5 additions & 5 deletions lightning-invoice/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ where
K::Target: KeysInterface,
L::Target: Logger,
{
use std::time::{SystemTime, UNIX_EPOCH};
use instant::SystemTime;

if phantom_route_hints.len() == 0 {
return Err(SignOrCreationError::CreationError(
Expand All @@ -152,7 +152,7 @@ where
payment_hash,
invoice_expiry_delta_secs,
SystemTime::now()
.duration_since(UNIX_EPOCH)
.duration_since(SystemTime::UNIX_EPOCH)
.expect("Time must be > 1970")
.as_secs(),
)
Expand All @@ -165,7 +165,7 @@ where
invoice_expiry_delta_secs,
&keys_manager,
SystemTime::now()
.duration_since(UNIX_EPOCH)
.duration_since(SystemTime::UNIX_EPOCH)
.expect("Time must be > 1970")
.as_secs(),
)
Expand Down Expand Up @@ -246,7 +246,7 @@ where
F::Target: FeeEstimator,
L::Target: Logger,
{
use std::time::SystemTime;
use instant::SystemTime;
let duration = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)
.expect("for the foreseeable future this shouldn't happen");
create_invoice_from_channelmanager_and_duration_since_epoch(
Expand Down Expand Up @@ -277,7 +277,7 @@ where
F::Target: FeeEstimator,
L::Target: Logger,
{
use std::time::SystemTime;
use instant::SystemTime;

let duration = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
Expand Down
1 change: 1 addition & 0 deletions lightning/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ default = ["std", "grind_signatures"]

[dependencies]
bitcoin = { version = "0.29.0", default-features = false, features = ["secp-recovery"] }
instant = { version = "0.1", features = ["wasm-bindgen"] }

hashbrown = { version = "0.8", optional = true }
hex = { version = "0.4", optional = true }
Expand Down
4 changes: 2 additions & 2 deletions lightning/src/offers/offer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
//!
//! # use lightning::onion_message::BlindedPath;
//! # #[cfg(feature = "std")]
//! # use std::time::SystemTime;
//! # use instant::SystemTime;
//! #
//! # fn create_blinded_path() -> BlindedPath { unimplemented!() }
//! # fn create_another_blinded_path() -> BlindedPath { unimplemented!() }
Expand Down Expand Up @@ -84,7 +84,7 @@ use crate::util::string::PrintableString;
use crate::prelude::*;

#[cfg(feature = "std")]
use std::time::SystemTime;
use instant::SystemTime;

/// Builds an [`Offer`] for the "offer to be paid" flow.
///
Expand Down
30 changes: 15 additions & 15 deletions lightning/src/routing/gossip.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ use core::ops::{Bound, Deref};
use bitcoin::hashes::hex::ToHex;

#[cfg(feature = "std")]
use std::time::{SystemTime, UNIX_EPOCH};
use instant::SystemTime;

/// We remove stale channel directional info two weeks after the last update, per BOLT 7's
/// suggestion.
Expand Down Expand Up @@ -452,7 +452,7 @@ where C::Target: chain::Access, L::Target: Logger
let mut gossip_start_time = 0;
#[cfg(feature = "std")]
{
gossip_start_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
gossip_start_time = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).expect("Time must be > 1970").as_secs();
if self.should_request_full_sync(&their_node_id) {
gossip_start_time -= 60 * 60 * 24 * 7 * 2; // 2 weeks ago
} else {
Expand Down Expand Up @@ -1513,7 +1513,7 @@ impl<L: Deref> NetworkGraph<L> where L::Target: Logger {
let mut announcement_received_time = 0;
#[cfg(feature = "std")]
{
announcement_received_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
announcement_received_time = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).expect("Time must be > 1970").as_secs();
}

let chan_info = ChannelInfo {
Expand All @@ -1537,7 +1537,7 @@ impl<L: Deref> NetworkGraph<L> where L::Target: Logger {
/// If not permanent, makes channels unavailable for routing.
pub fn channel_failed(&self, short_channel_id: u64, is_permanent: bool) {
#[cfg(feature = "std")]
let current_time_unix = Some(SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs());
let current_time_unix = Some(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).expect("Time must be > 1970").as_secs());
#[cfg(not(feature = "std"))]
let current_time_unix = None;

Expand All @@ -1564,7 +1564,7 @@ impl<L: Deref> NetworkGraph<L> where L::Target: Logger {
/// from local storage.
pub fn node_failed_permanent(&self, node_id: &PublicKey) {
#[cfg(feature = "std")]
let current_time_unix = Some(SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs());
let current_time_unix = Some(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).expect("Time must be > 1970").as_secs());
#[cfg(not(feature = "std"))]
let current_time_unix = None;

Expand Down Expand Up @@ -1611,7 +1611,7 @@ impl<L: Deref> NetworkGraph<L> where L::Target: Logger {
/// This method is only available with the `std` feature. See
/// [`NetworkGraph::remove_stale_channels_and_tracking_with_time`] for `no-std` use.
pub fn remove_stale_channels_and_tracking(&self) {
let time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
let time = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).expect("Time must be > 1970").as_secs();
self.remove_stale_channels_and_tracking_with_time(time);
}

Expand Down Expand Up @@ -1715,7 +1715,7 @@ impl<L: Deref> NetworkGraph<L> where L::Target: Logger {
{
// Note that many tests rely on being able to set arbitrarily old timestamps, thus we
// disable this check during tests!
let time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
let time = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).expect("Time must be > 1970").as_secs();
if (msg.timestamp as u64) < time - STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS {
return Err(LightningError{err: "channel_update is older than two weeks old".to_owned(), action: ErrorAction::IgnoreAndLog(Level::Gossip)});
}
Expand Down Expand Up @@ -2198,9 +2198,9 @@ mod tests {

#[cfg(feature = "std")]
{
use std::time::{SystemTime, UNIX_EPOCH};
use instant::SystemTime;

let tracking_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
let tracking_time = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).expect("Time must be > 1970").as_secs();
// Mark a node as permanently failed so it's tracked as removed.
gossip_sync.network_graph().node_failed_permanent(&PublicKey::from_secret_key(&secp_ctx, node_1_privkey));

Expand Down Expand Up @@ -2501,8 +2501,8 @@ mod tests {
// We want to check that this will work even if *one* of the channel updates is recent,
// so we should add it with a recent timestamp.
assert!(network_graph.read_only().channels().get(&short_channel_id).unwrap().one_to_two.is_none());
use std::time::{SystemTime, UNIX_EPOCH};
let announcement_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
use instant::SystemTime;
let announcement_time = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).expect("Time must be > 1970").as_secs();
let valid_channel_update = get_signed_channel_update(|unsigned_channel_update| {
unsigned_channel_update.timestamp = (announcement_time + 1 + STALE_CHANNEL_UPDATE_AGE_LIMIT_SECS) as u32;
}, node_1_privkey, &secp_ctx);
Expand All @@ -2522,9 +2522,9 @@ mod tests {

#[cfg(feature = "std")]
{
use std::time::{SystemTime, UNIX_EPOCH};
use instant::SystemTime;

let tracking_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
let tracking_time = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).expect("Time must be > 1970").as_secs();

// Clear tracked nodes and channels for clean slate
network_graph.removed_channels.lock().unwrap().clear();
Expand Down Expand Up @@ -2773,7 +2773,7 @@ mod tests {
#[test]
#[cfg(feature = "std")]
fn calling_sync_routing_table() {
use std::time::{SystemTime, UNIX_EPOCH};
use instant::SystemTime;
use crate::ln::msgs::Init;

let network_graph = create_network_graph();
Expand Down Expand Up @@ -2803,7 +2803,7 @@ mod tests {
MessageSendEvent::SendGossipTimestampFilter{ node_id, msg } => {
assert_eq!(node_id, &node_id_1);
assert_eq!(msg.chain_hash, chain_hash);
let expected_timestamp = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
let expected_timestamp = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).expect("Time must be > 1970").as_secs();
assert!((msg.first_timestamp as u64) >= expected_timestamp - 60*60*24*7*2);
assert!((msg.first_timestamp as u64) < expected_timestamp - 60*60*24*7*2 + 10);
assert_eq!(msg.timestamp_range, u32::max_value());
Expand Down
2 changes: 1 addition & 1 deletion lightning/src/routing/scoring.rs
Original file line number Diff line number Diff line change
Expand Up @@ -317,7 +317,7 @@ impl ReadableArgs<u64> for FixedPenaltyScorer {
}

#[cfg(not(feature = "no-std"))]
type ConfiguredTime = std::time::Instant;
type ConfiguredTime = instant::Instant;
#[cfg(feature = "no-std")]
use crate::util::time::Eternity;
#[cfg(feature = "no-std")]
Expand Down
4 changes: 2 additions & 2 deletions lightning/src/util/test_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ use bitcoin::bech32::u5;
use crate::chain::keysinterface::{InMemorySigner, Recipient, KeyMaterial};

#[cfg(feature = "std")]
use std::time::{SystemTime, UNIX_EPOCH};
use instant::SystemTime;
use bitcoin::Sequence;

pub struct TestVecWriter(pub Vec<u8>);
Expand Down Expand Up @@ -476,7 +476,7 @@ impl msgs::RoutingMessageHandler for TestRoutingMessageHandler {
let mut gossip_start_time = 0;
#[cfg(feature = "std")]
{
gossip_start_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
gossip_start_time = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).expect("Time must be > 1970").as_secs();
if self.request_full_sync.load(Ordering::Acquire) {
gossip_start_time -= 60 * 60 * 24 * 7 * 2; // 2 weeks ago
} else {
Expand Down
8 changes: 4 additions & 4 deletions lightning/src/util/time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,9 @@ impl Sub<Duration> for Eternity {
}

#[cfg(not(feature = "no-std"))]
impl Time for std::time::Instant {
impl Time for instant::Instant {
fn now() -> Self {
std::time::Instant::now()
instant::Instant::now()
}

fn duration_since(&self, earlier: Self) -> Duration {
Expand All @@ -74,11 +74,11 @@ impl Time for std::time::Instant {
}

fn duration_since_epoch() -> Duration {
use std::time::SystemTime;
use instant::SystemTime;
SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap()
}
fn elapsed(&self) -> Duration {
std::time::Instant::elapsed(self)
instant::Instant::elapsed(self)
}
}

Expand Down
2 changes: 1 addition & 1 deletion lightning/src/util/wakers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use crate::sync::{Condvar, Mutex, MutexGuard};
use crate::prelude::*;

#[cfg(any(test, feature = "std"))]
use std::time::{Duration, Instant};
use instant::{Duration, Instant};

use core::future::Future as StdFuture;
use core::task::{Context, Poll};
Expand Down