diff --git a/lightning/src/ln/bolt11_payment.rs b/lightning/src/ln/bolt11_payment.rs index b4863d4b1e1..d0655968a60 100644 --- a/lightning/src/ln/bolt11_payment.rs +++ b/lightning/src/ln/bolt11_payment.rs @@ -91,19 +91,9 @@ mod tests { use crate::routing::router::Payee; use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey}; - use core::time::Duration; use lightning_invoice::{Currency, InvoiceBuilder}; - #[cfg(feature = "std")] use std::time::SystemTime; - fn duration_since_epoch() -> Duration { - #[cfg(feature = "std")] - let duration_since_epoch = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap(); - #[cfg(not(feature = "std"))] - let duration_since_epoch = Duration::from_secs(1234567); - duration_since_epoch - } - #[test] fn invoice_test() { let payment_hash = Sha256::hash(&[0; 32]); @@ -111,11 +101,12 @@ mod tests { let secp_ctx = Secp256k1::new(); let public_key = PublicKey::from_secret_key(&secp_ctx, &private_key); + let timestamp = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap(); let invoice = InvoiceBuilder::new(Currency::Bitcoin) .description("test".into()) .payment_hash(payment_hash) .payment_secret(PaymentSecret([0; 32])) - .duration_since_epoch(duration_since_epoch()) + .duration_since_epoch(timestamp) .min_final_cltv_expiry_delta(144) .amount_milli_satoshis(128) .build_signed(|hash| secp_ctx.sign_ecdsa_recoverable(hash, &private_key)) @@ -142,11 +133,12 @@ mod tests { let secp_ctx = Secp256k1::new(); let public_key = PublicKey::from_secret_key(&secp_ctx, &private_key); + let timestamp = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap(); let invoice = InvoiceBuilder::new(Currency::Bitcoin) .description("test".into()) .payment_hash(payment_hash) .payment_secret(PaymentSecret([0; 32])) - .duration_since_epoch(duration_since_epoch()) + .duration_since_epoch(timestamp) .min_final_cltv_expiry_delta(144) .build_signed(|hash| secp_ctx.sign_ecdsa_recoverable(hash, &private_key)) .unwrap(); @@ -167,12 +159,12 @@ mod tests { } #[test] - #[cfg(feature = "std")] fn payment_metadata_end_to_end() { use crate::events::Event; use crate::ln::channelmanager::{PaymentId, Retry}; use crate::ln::functional_test_utils::*; use crate::ln::msgs::ChannelMessageHandler; + // Test that a payment metadata read from an invoice passed to `pay_invoice` makes it all // the way out through the `PaymentClaimable` event. let chanmon_cfgs = create_chanmon_cfgs(2); @@ -188,12 +180,12 @@ mod tests { let secp_ctx = Secp256k1::new(); let node_secret = nodes[1].keys_manager.backing.get_node_secret_key(); - let time = std::time::SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap(); + let timestamp = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap(); let invoice = InvoiceBuilder::new(Currency::Bitcoin) .description("test".into()) .payment_hash(Sha256::from_slice(&payment_hash.0).unwrap()) .payment_secret(payment_secret) - .duration_since_epoch(time) + .duration_since_epoch(timestamp) .min_final_cltv_expiry_delta(144) .amount_milli_satoshis(50_000) .payment_metadata(payment_metadata.clone()) diff --git a/lightning/src/ln/functional_test_utils.rs b/lightning/src/ln/functional_test_utils.rs index 05e0a9cfd5b..37a8f9b679f 100644 --- a/lightning/src/ln/functional_test_utils.rs +++ b/lightning/src/ln/functional_test_utils.rs @@ -34,7 +34,7 @@ use crate::util::test_channel_signer::TestChannelSigner; #[cfg(test)] use crate::util::test_channel_signer::SignerOp; use crate::util::test_utils; -use crate::util::test_utils::{panicking, TestChainMonitor, TestScorer, TestKeysInterface}; +use crate::util::test_utils::{TestChainMonitor, TestScorer, TestKeysInterface}; use crate::util::ser::{ReadableArgs, Writeable}; use bitcoin::amount::Amount; @@ -194,28 +194,23 @@ impl ConnectStyle { } fn random_style() -> ConnectStyle { - #[cfg(feature = "std")] { - use core::hash::{BuildHasher, Hasher}; - // Get a random value using the only std API to do so - the DefaultHasher - let rand_val = std::collections::hash_map::RandomState::new().build_hasher().finish(); - let res = match rand_val % 9 { - 0 => ConnectStyle::BestBlockFirst, - 1 => ConnectStyle::BestBlockFirstSkippingBlocks, - 2 => ConnectStyle::BestBlockFirstReorgsOnlyTip, - 3 => ConnectStyle::TransactionsFirst, - 4 => ConnectStyle::TransactionsFirstSkippingBlocks, - 5 => ConnectStyle::TransactionsDuplicativelyFirstSkippingBlocks, - 6 => ConnectStyle::HighlyRedundantTransactionsFirstSkippingBlocks, - 7 => ConnectStyle::TransactionsFirstReorgsOnlyTip, - 8 => ConnectStyle::FullBlockViaListen, - _ => unreachable!(), - }; - eprintln!("Using Block Connection Style: {:?}", res); - res - } - #[cfg(not(feature = "std"))] { - ConnectStyle::FullBlockViaListen - } + use core::hash::{BuildHasher, Hasher}; + // Get a random value using the only std API to do so - the DefaultHasher + let rand_val = std::collections::hash_map::RandomState::new().build_hasher().finish(); + let res = match rand_val % 9 { + 0 => ConnectStyle::BestBlockFirst, + 1 => ConnectStyle::BestBlockFirstSkippingBlocks, + 2 => ConnectStyle::BestBlockFirstReorgsOnlyTip, + 3 => ConnectStyle::TransactionsFirst, + 4 => ConnectStyle::TransactionsFirstSkippingBlocks, + 5 => ConnectStyle::TransactionsDuplicativelyFirstSkippingBlocks, + 6 => ConnectStyle::HighlyRedundantTransactionsFirstSkippingBlocks, + 7 => ConnectStyle::TransactionsFirstReorgsOnlyTip, + 8 => ConnectStyle::FullBlockViaListen, + _ => unreachable!(), + }; + eprintln!("Using Block Connection Style: {:?}", res); + res } } @@ -270,9 +265,7 @@ fn do_connect_block_with_consistency_checks<'a, 'b, 'c, 'd>(node: &'a Node<'b, ' fn do_connect_block_without_consistency_checks<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, block: Block, skip_intermediaries: bool) { let height = node.best_block_info().1 + 1; - #[cfg(feature = "std")] { - eprintln!("Connecting block using Block Connection Style: {:?}", *node.connect_style.borrow()); - } + eprintln!("Connecting block using Block Connection Style: {:?}", *node.connect_style.borrow()); // Update the block internally before handing it over to LDK, to ensure our assertions regarding // transaction broadcast are correct. node.blocks.lock().unwrap().push((block.clone(), height)); @@ -340,9 +333,7 @@ fn do_connect_block_without_consistency_checks<'a, 'b, 'c, 'd>(node: &'a Node<'b pub fn disconnect_blocks<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, count: u32) { call_claimable_balances(node); - #[cfg(feature = "std")] { - eprintln!("Disconnecting {} blocks using Block Connection Style: {:?}", count, *node.connect_style.borrow()); - } + eprintln!("Disconnecting {} blocks using Block Connection Style: {:?}", count, *node.connect_style.borrow()); for i in 0..count { let orig = node.blocks.lock().unwrap().pop().unwrap(); assert!(orig.1 > 0); // Cannot disconnect genesis @@ -471,9 +462,7 @@ impl<'a, 'b, 'c> Node<'a, 'b, 'c> { } } -#[cfg(feature = "std")] impl<'a, 'b, 'c> std::panic::UnwindSafe for Node<'a, 'b, 'c> {} -#[cfg(feature = "std")] impl<'a, 'b, 'c> std::panic::RefUnwindSafe for Node<'a, 'b, 'c> {} impl<'a, 'b, 'c> Node<'a, 'b, 'c> { pub fn best_block_hash(&self) -> BlockHash { @@ -620,7 +609,7 @@ impl<'a, 'b: 'a, 'c: 'b> NodeHolder for Node<'a, 'b, 'c> { impl<'a, 'b, 'c> Drop for Node<'a, 'b, 'c> { fn drop(&mut self) { - if !panicking() { + if !std::thread::panicking() { // Check that we processed all pending events let msg_events = self.node.get_and_clear_pending_msg_events(); if !msg_events.is_empty() { diff --git a/lightning/src/ln/invoice_utils.rs b/lightning/src/ln/invoice_utils.rs index 5a793052cc3..7f9a14d1fb5 100644 --- a/lightning/src/ln/invoice_utils.rs +++ b/lightning/src/ln/invoice_utils.rs @@ -824,7 +824,6 @@ mod test { use crate::sign::PhantomKeysManager; use crate::events::{MessageSendEvent, MessageSendEventsProvider}; use crate::ln::types::PaymentHash; - #[cfg(feature = "std")] use crate::ln::types::PaymentPreimage; use crate::ln::channelmanager::{PhantomRouteHints, MIN_FINAL_CLTV_EXPIRY_DELTA, PaymentId, RecipientOnionFields, Retry}; use crate::ln::functional_test_utils::*; @@ -1281,13 +1280,11 @@ mod test { } #[test] - #[cfg(feature = "std")] fn test_multi_node_receive() { do_test_multi_node_receive(true); do_test_multi_node_receive(false); } - #[cfg(feature = "std")] fn do_test_multi_node_receive(user_generated_pmt_hash: bool) { use crate::events::{Event, EventsProvider}; use core::cell::RefCell; @@ -1395,7 +1392,6 @@ mod test { } #[test] - #[cfg(feature = "std")] fn test_multi_node_hints_has_htlc_min_max_values() { let mut chanmon_cfgs = create_chanmon_cfgs(3); let seed_1 = [42u8; 32]; @@ -1432,7 +1428,6 @@ mod test { } #[test] - #[cfg(feature = "std")] fn test_create_phantom_invoice_with_description_hash() { let chanmon_cfgs = create_chanmon_cfgs(3); let node_cfgs = create_node_cfgs(3, &chanmon_cfgs); @@ -1462,7 +1457,6 @@ mod test { } #[test] - #[cfg(feature = "std")] fn create_phantom_invoice_with_custom_payment_hash_and_custom_min_final_cltv_delta() { let chanmon_cfgs = create_chanmon_cfgs(3); let node_cfgs = create_node_cfgs(3, &chanmon_cfgs); @@ -1489,7 +1483,6 @@ mod test { } #[test] - #[cfg(feature = "std")] fn test_multi_node_hints_includes_single_channels_to_participating_nodes() { let mut chanmon_cfgs = create_chanmon_cfgs(3); let seed_1 = [42u8; 32]; @@ -1518,7 +1511,6 @@ mod test { } #[test] - #[cfg(feature = "std")] fn test_multi_node_hints_includes_one_channel_of_each_counterparty_nodes_per_participating_node() { let mut chanmon_cfgs = create_chanmon_cfgs(4); let seed_1 = [42u8; 32]; @@ -1549,7 +1541,6 @@ mod test { } #[test] - #[cfg(feature = "std")] fn test_multi_node_forwarding_info_not_assigned_channel_excluded_from_hints() { let mut chanmon_cfgs = create_chanmon_cfgs(4); let seed_1 = [42u8; 32]; @@ -1607,7 +1598,6 @@ mod test { } #[test] - #[cfg(feature = "std")] fn test_multi_node_with_only_public_channels_hints_includes_only_phantom_route() { let mut chanmon_cfgs = create_chanmon_cfgs(3); let seed_1 = [42u8; 32]; @@ -1640,7 +1630,6 @@ mod test { } #[test] - #[cfg(feature = "std")] fn test_multi_node_with_mixed_public_and_private_channel_hints_includes_only_phantom_route() { let mut chanmon_cfgs = create_chanmon_cfgs(4); let seed_1 = [42u8; 32]; @@ -1674,7 +1663,6 @@ mod test { } #[test] - #[cfg(feature = "std")] fn test_multi_node_hints_has_only_lowest_inbound_channel_above_minimum() { let mut chanmon_cfgs = create_chanmon_cfgs(3); let seed_1 = [42u8; 32]; @@ -1705,7 +1693,6 @@ mod test { } #[test] - #[cfg(feature = "std")] fn test_multi_node_channels_inbound_capacity_lower_than_invoice_amt_filtering() { let mut chanmon_cfgs = create_chanmon_cfgs(4); let seed_1 = [42u8; 32]; diff --git a/lightning/src/ln/outbound_payment.rs b/lightning/src/ln/outbound_payment.rs index 1fda943373d..69e97aa3573 100644 --- a/lightning/src/ln/outbound_payment.rs +++ b/lightning/src/ln/outbound_payment.rs @@ -26,9 +26,8 @@ use crate::routing::router::{BlindedTail, InFlightHtlcs, Path, PaymentParameters use crate::sign::{EntropySource, NodeSigner, Recipient}; use crate::util::errors::APIError; use crate::util::logger::Logger; -use crate::util::time::Time; -#[cfg(all(feature = "std", test))] -use crate::util::time::tests::SinceEpoch; +#[cfg(feature = "std")] +use crate::util::time::Instant; use crate::util::ser::ReadableArgs; use core::fmt::{self, Display, Formatter}; @@ -319,12 +318,9 @@ impl Retry { (Retry::Attempts(max_retry_count), PaymentAttempts { count, .. }) => { max_retry_count > count }, - #[cfg(all(feature = "std", not(test)))] - (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. }) => - *max_duration >= crate::util::time::MonotonicTime::now().duration_since(*first_attempted_at), - #[cfg(all(feature = "std", test))] + #[cfg(feature = "std")] (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. }) => - *max_duration >= SinceEpoch::now().duration_since(*first_attempted_at), + *max_duration >= Instant::now().duration_since(*first_attempted_at), } } } @@ -339,42 +335,28 @@ pub(super) fn has_expired(route_params: &RouteParameters) -> bool { false } -pub(crate) type PaymentAttempts = PaymentAttemptsUsingTime; - /// Storing minimal payment attempts information required for determining if a outbound payment can /// be retried. -pub(crate) struct PaymentAttemptsUsingTime { +pub(crate) struct PaymentAttempts { /// This count will be incremented only after the result of the attempt is known. When it's 0, /// it means the result of the first attempt is not known yet. pub(crate) count: u32, /// This field is only used when retry is `Retry::Timeout` which is only build with feature std #[cfg(feature = "std")] - first_attempted_at: T, - #[cfg(not(feature = "std"))] - phantom: core::marker::PhantomData, - + first_attempted_at: Instant, } -#[cfg(not(feature = "std"))] -type ConfiguredTime = crate::util::time::Eternity; -#[cfg(all(feature = "std", not(test)))] -type ConfiguredTime = crate::util::time::MonotonicTime; -#[cfg(all(feature = "std", test))] -type ConfiguredTime = SinceEpoch; - -impl PaymentAttemptsUsingTime { +impl PaymentAttempts { pub(crate) fn new() -> Self { - PaymentAttemptsUsingTime { + PaymentAttempts { count: 0, #[cfg(feature = "std")] - first_attempted_at: T::now(), - #[cfg(not(feature = "std"))] - phantom: core::marker::PhantomData, + first_attempted_at: Instant::now(), } } } -impl Display for PaymentAttemptsUsingTime { +impl Display for PaymentAttempts { fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { #[cfg(not(feature = "std"))] return write!(f, "attempts: {}", self.count); @@ -383,7 +365,7 @@ impl Display for PaymentAttemptsUsingTime { f, "attempts: {}, duration: {}s", self.count, - T::now().duration_since(self.first_attempted_at).as_secs() + Instant::now().duration_since(self.first_attempted_at).as_secs() ); } } diff --git a/lightning/src/ln/payment_tests.rs b/lightning/src/ln/payment_tests.rs index 291befa2abf..60dd82b75b0 100644 --- a/lightning/src/ln/payment_tests.rs +++ b/lightning/src/ln/payment_tests.rs @@ -46,7 +46,7 @@ use crate::routing::gossip::NodeId; #[cfg(feature = "std")] use { - crate::util::time::tests::SinceEpoch, + crate::util::time::Instant as TestTime, std::time::{SystemTime, Instant, Duration}, }; @@ -2340,7 +2340,7 @@ fn do_automatic_retries(test: AutoRetry) { pass_failed_attempt_with_retry_along_path!(channel_id_2, true); // Advance the time so the second attempt fails due to timeout. - SinceEpoch::advance(Duration::from_secs(61)); + TestTime::advance(Duration::from_secs(61)); // Make sure we don't retry again. nodes[0].node.process_pending_htlc_forwards(); diff --git a/lightning/src/ln/peer_handler.rs b/lightning/src/ln/peer_handler.rs index 6b03b365457..367a372f241 100644 --- a/lightning/src/ln/peer_handler.rs +++ b/lightning/src/ln/peer_handler.rs @@ -47,8 +47,6 @@ use core::sync::atomic::{AtomicBool, AtomicU32, AtomicI32, Ordering}; use core::{cmp, hash, fmt, mem}; use core::ops::Deref; use core::convert::Infallible; -#[cfg(feature = "std")] -use std::error; #[cfg(not(c_bindings))] use { crate::ln::channelmanager::{SimpleArcChannelManager, SimpleRefChannelManager}, @@ -497,13 +495,6 @@ impl fmt::Display for PeerHandleError { } } -#[cfg(feature = "std")] -impl error::Error for PeerHandleError { - fn description(&self) -> &str { - "Peer Sent Invalid Data" - } -} - enum InitSyncTracker{ NoSyncRequested, ChannelsSyncing(u64), diff --git a/lightning/src/onion_message/functional_tests.rs b/lightning/src/onion_message/functional_tests.rs index 508e7982b40..a96caba2c20 100644 --- a/lightning/src/onion_message/functional_tests.rs +++ b/lightning/src/onion_message/functional_tests.rs @@ -64,10 +64,8 @@ struct MessengerNode { impl Drop for MessengerNode { fn drop(&mut self) { - #[cfg(feature = "std")] { - if std::thread::panicking() { - return; - } + if std::thread::panicking() { + return; } assert!(release_events(self).is_empty()); } @@ -163,10 +161,8 @@ impl TestCustomMessageHandler { impl Drop for TestCustomMessageHandler { fn drop(&mut self) { - #[cfg(feature = "std")] { - if std::thread::panicking() { - return; - } + if std::thread::panicking() { + return; } assert!(self.expectations.lock().unwrap().is_empty()); } diff --git a/lightning/src/routing/gossip.rs b/lightning/src/routing/gossip.rs index 668caf21da4..1acd2ebdc26 100644 --- a/lightning/src/routing/gossip.rs +++ b/lightning/src/routing/gossip.rs @@ -309,7 +309,6 @@ where U::Target: UtxoLookup, L::Target: Logger { network_graph: G, utxo_lookup: RwLock>, - #[cfg(feature = "std")] full_syncs_requested: AtomicUsize, pending_events: Mutex>, logger: L, @@ -325,7 +324,6 @@ where U::Target: UtxoLookup, L::Target: Logger pub fn new(network_graph: G, utxo_lookup: Option, logger: L) -> Self { P2PGossipSync { network_graph, - #[cfg(feature = "std")] full_syncs_requested: AtomicUsize::new(0), utxo_lookup: RwLock::new(utxo_lookup), pending_events: Mutex::new(vec![]), @@ -348,10 +346,8 @@ where U::Target: UtxoLookup, L::Target: Logger &self.network_graph } - #[cfg(feature = "std")] /// Returns true when a full routing table sync should be performed with a peer. - fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool { - //TODO: Determine whether to request a full sync based on the network map. + fn should_request_full_sync(&self) -> bool { const FULL_SYNCS_TO_REQUEST: usize = 5; if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST { self.full_syncs_requested.fetch_add(1, Ordering::AcqRel); @@ -619,10 +615,12 @@ where U::Target: UtxoLookup, L::Target: Logger // For no-std builds, we bury our head in the sand and do a full sync on each connection. #[allow(unused_mut, unused_assignments)] let mut gossip_start_time = 0; + #[allow(unused)] + let should_sync = self.should_request_full_sync(); #[cfg(feature = "std")] { gossip_start_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs(); - if self.should_request_full_sync(&their_node_id) { + if should_sync { gossip_start_time -= 60 * 60 * 24 * 7 * 2; // 2 weeks ago } else { gossip_start_time -= 60 * 60; // an hour ago @@ -2452,18 +2450,16 @@ pub(crate) mod tests { } #[test] - #[cfg(feature = "std")] fn request_full_sync_finite_times() { let network_graph = create_network_graph(); - let (secp_ctx, gossip_sync) = create_gossip_sync(&network_graph); - let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&>::from_hex("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap()); - - assert!(gossip_sync.should_request_full_sync(&node_id)); - assert!(gossip_sync.should_request_full_sync(&node_id)); - assert!(gossip_sync.should_request_full_sync(&node_id)); - assert!(gossip_sync.should_request_full_sync(&node_id)); - assert!(gossip_sync.should_request_full_sync(&node_id)); - assert!(!gossip_sync.should_request_full_sync(&node_id)); + let (_, gossip_sync) = create_gossip_sync(&network_graph); + + assert!(gossip_sync.should_request_full_sync()); + assert!(gossip_sync.should_request_full_sync()); + assert!(gossip_sync.should_request_full_sync()); + assert!(gossip_sync.should_request_full_sync()); + assert!(gossip_sync.should_request_full_sync()); + assert!(!gossip_sync.should_request_full_sync()); } pub(crate) fn get_signed_node_announcement(f: F, node_key: &SecretKey, secp_ctx: &Secp256k1) -> NodeAnnouncement { diff --git a/lightning/src/routing/router.rs b/lightning/src/routing/router.rs index fa2bbac1d14..95977df84e8 100644 --- a/lightning/src/routing/router.rs +++ b/lightning/src/routing/router.rs @@ -7419,7 +7419,6 @@ mod tests { (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13)); } - #[cfg(feature = "std")] pub(super) fn random_init_seed() -> u64 { // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG. use core::hash::{BuildHasher, Hasher}; @@ -7429,7 +7428,6 @@ mod tests { } #[test] - #[cfg(feature = "std")] fn generate_routes() { use crate::routing::scoring::ProbabilisticScoringFeeParameters; @@ -7449,7 +7447,6 @@ mod tests { } #[test] - #[cfg(feature = "std")] fn generate_routes_mpp() { use crate::routing::scoring::ProbabilisticScoringFeeParameters; @@ -7469,7 +7466,6 @@ mod tests { } #[test] - #[cfg(feature = "std")] fn generate_large_mpp_routes() { use crate::routing::scoring::ProbabilisticScoringFeeParameters; @@ -8696,7 +8692,7 @@ mod tests { } } -#[cfg(all(any(test, ldk_bench), feature = "std"))] +#[cfg(any(test, ldk_bench))] pub(crate) mod bench_utils { use super::*; use std::fs::File; diff --git a/lightning/src/routing/scoring.rs b/lightning/src/routing/scoring.rs index adf70257136..480cbc5b366 100644 --- a/lightning/src/routing/scoring.rs +++ b/lightning/src/routing/scoring.rs @@ -49,11 +49,6 @@ //! # } //! ``` //! -//! # Note -//! -//! Persisting when built with feature `no-std` and restoring without it, or vice versa, uses -//! different types and thus is undefined. -//! //! [`find_route`]: crate::routing::router::find_route use crate::ln::msgs::DecodeError; diff --git a/lightning/src/util/mod.rs b/lightning/src/util/mod.rs index f19a9b8d8aa..bb138dd69d1 100644 --- a/lightning/src/util/mod.rs +++ b/lightning/src/util/mod.rs @@ -31,9 +31,11 @@ pub(crate) mod atomic_counter; pub(crate) mod async_poll; pub(crate) mod byte_utils; pub(crate) mod transaction_utils; -pub(crate) mod time; pub mod hash_tables; +#[cfg(feature = "std")] +pub(crate) mod time; + pub mod indexed_map; /// Logging macro utilities. diff --git a/lightning/src/util/test_utils.rs b/lightning/src/util/test_utils.rs index 5a7537b08cf..e9b4af08a8f 100644 --- a/lightning/src/util/test_utils.rs +++ b/lightning/src/util/test_utils.rs @@ -75,8 +75,6 @@ use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use core::mem; use crate::sign::{InMemorySigner, RandomBytes, Recipient, EntropySource, NodeSigner, SignerProvider}; -#[cfg(feature = "std")] -use std::time::{SystemTime, UNIX_EPOCH}; use bitcoin::psbt::Psbt; use bitcoin::Sequence; @@ -286,10 +284,8 @@ impl<'a> MessageRouter for TestRouter<'a> { impl<'a> Drop for TestRouter<'a> { fn drop(&mut self) { - #[cfg(feature = "std")] { - if std::thread::panicking() { - return; - } + if std::thread::panicking() { + return; } assert!(self.next_routes.lock().unwrap().is_empty()); } @@ -797,12 +793,9 @@ impl TestChannelMessageHandler { impl Drop for TestChannelMessageHandler { fn drop(&mut self) { - #[cfg(feature = "std")] - { - let l = self.expected_recv_msgs.lock().unwrap(); - if !std::thread::panicking() { - assert!(l.is_none() || l.as_ref().unwrap().is_empty()); - } + let l = self.expected_recv_msgs.lock().unwrap(); + if !std::thread::panicking() { + assert!(l.is_none() || l.as_ref().unwrap().is_empty()); } } } @@ -1051,8 +1044,9 @@ impl msgs::RoutingMessageHandler for TestRoutingMessageHandler { #[allow(unused_mut, unused_assignments)] let mut gossip_start_time = 0; - #[cfg(feature = "std")] + #[cfg(not(feature = "no-std"))] { + use std::time::{SystemTime, UNIX_EPOCH}; gossip_start_time = SystemTime::now().duration_since(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 @@ -1179,10 +1173,8 @@ impl Logger for TestLogger { *self.lines.lock().unwrap().entry((record.module_path, format!("{}", record.args))).or_insert(0) += 1; *self.context.lock().unwrap().entry((record.module_path, record.peer_id, record.channel_id)).or_insert(0) += 1; if record.level >= self.level { - #[cfg(all(not(ldk_bench), feature = "std"))] { - let pfx = format!("{} {} [{}:{}]", self.id, record.level.to_string(), record.module_path, record.line); - println!("{:<55}{}", pfx, record.args); - } + let pfx = format!("{} {} [{}:{}]", self.id, record.level.to_string(), record.module_path, record.line); + println!("{:<55}{}", pfx, record.args); } } } @@ -1380,17 +1372,9 @@ impl TestKeysInterface { } } -pub(crate) fn panicking() -> bool { - #[cfg(feature = "std")] - let panicking = ::std::thread::panicking(); - #[cfg(not(feature = "std"))] - let panicking = false; - return panicking; -} - impl Drop for TestKeysInterface { fn drop(&mut self) { - if panicking() { + if std::thread::panicking() { return; } @@ -1463,7 +1447,7 @@ impl chain::Filter for TestChainSource { impl Drop for TestChainSource { fn drop(&mut self) { - if panicking() { + if std::thread::panicking() { return; } } @@ -1530,10 +1514,8 @@ impl crate::routing::scoring::Score for TestScorer {} impl Drop for TestScorer { fn drop(&mut self) { - #[cfg(feature = "std")] { - if std::thread::panicking() { - return; - } + if std::thread::panicking() { + return; } if let Some(scorer_expectations) = self.scorer_expectations.borrow().as_ref() { diff --git a/lightning/src/util/time.rs b/lightning/src/util/time.rs index bedeab1d489..106a4ce4e17 100644 --- a/lightning/src/util/time.rs +++ b/lightning/src/util/time.rs @@ -4,93 +4,25 @@ // You may not use this file except in accordance with one or both of these // licenses. -//! [`Time`] trait and different implementations. Currently, it's mainly used in tests so we can -//! manually advance time. -//! Other crates may symlink this file to use it while [`Time`] trait is sealed here. - -use core::ops::Sub; -use core::time::Duration; - -/// A measurement of time. -pub trait Time: Copy + Sub where Self: Sized { - /// Returns an instance corresponding to the current moment. - fn now() -> Self; - - /// Returns the amount of time passed between `earlier` and `self`. - fn duration_since(&self, earlier: Self) -> Duration; -} - -/// A state in which time has no meaning. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct Eternity; - -impl Time for Eternity { - fn now() -> Self { - Self - } - - fn duration_since(&self, _earlier: Self) -> Duration { - Duration::from_secs(0) - } -} - -impl Sub for Eternity { - type Output = Self; - - fn sub(self, _other: Duration) -> Self { - self - } -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -#[cfg(feature = "std")] -pub struct MonotonicTime(std::time::Instant); - -/// The amount of time to shift `Instant` forward to prevent overflow when subtracting a `Duration` -/// from `Instant::now` on some operating systems (e.g., iOS representing `Instance` as `u64`). -#[cfg(feature = "std")] -const SHIFT: Duration = Duration::from_secs(10 * 365 * 24 * 60 * 60); // 10 years. - -#[cfg(feature = "std")] -impl Time for MonotonicTime { - fn now() -> Self { - let instant = std::time::Instant::now().checked_add(SHIFT).expect("Overflow on MonotonicTime instantiation"); - Self(instant) - } - - fn duration_since(&self, earlier: Self) -> Duration { - // On rust prior to 1.60 `Instant::duration_since` will panic if time goes backwards. - // However, we support rust versions prior to 1.60 and some users appear to have "monotonic - // clocks" that go backwards in practice (likely relatively ancient kernels/etc). Thus, we - // manually check for time going backwards here and return a duration of zero in that case. - let now = Self::now(); - if now.0 > earlier.0 { now.0 - earlier.0 } else { Duration::from_secs(0) } - } -} - -#[cfg(feature = "std")] -impl Sub for MonotonicTime { - type Output = Self; - - fn sub(self, other: Duration) -> Self { - let instant = self.0.checked_sub(other).expect("MonotonicTime is not supposed to go backward futher than 10 years"); - Self(instant) - } -} +//! A simple module which either re-exports [`std::time::Instant`] or a mocked version of it for +//! tests. #[cfg(test)] -pub mod tests { - use super::{Time, Eternity}; +pub use test::Instant; +#[cfg(not(test))] +pub use std::time::Instant; +#[cfg(test)] +mod test { use core::time::Duration; use core::ops::Sub; use core::cell::Cell; /// Time that can be advanced manually in tests. #[derive(Clone, Copy, Debug, PartialEq, Eq)] - pub struct SinceEpoch(Duration); + pub struct Instant(Duration); - impl SinceEpoch { + impl Instant { thread_local! { static ELAPSED: Cell = core::cell::Cell::new(Duration::from_secs(0)); } @@ -98,19 +30,17 @@ pub mod tests { pub fn advance(duration: Duration) { Self::ELAPSED.with(|elapsed| elapsed.set(elapsed.get() + duration)) } - } - impl Time for SinceEpoch { - fn now() -> Self { + pub fn now() -> Self { Self(Self::ELAPSED.with(|elapsed| elapsed.get())) } - fn duration_since(&self, earlier: Self) -> Duration { + pub fn duration_since(&self, earlier: Self) -> Duration { self.0 - earlier.0 } } - impl Sub for SinceEpoch { + impl Sub for Instant { type Output = Self; fn sub(self, other: Duration) -> Self { @@ -120,21 +50,13 @@ pub mod tests { #[test] fn time_passes_when_advanced() { - let now = SinceEpoch::now(); + let now = Instant::now(); - SinceEpoch::advance(Duration::from_secs(1)); - SinceEpoch::advance(Duration::from_secs(1)); + Instant::advance(Duration::from_secs(1)); + Instant::advance(Duration::from_secs(1)); - let later = SinceEpoch::now(); + let later = Instant::now(); assert_eq!(now.0 + Duration::from_secs(2), later.0); } - - #[test] - fn time_never_passes_in_an_eternity() { - let now = Eternity::now(); - let later = Eternity::now(); - - assert_eq!(later, now); - } } diff --git a/lightning/src/util/wakers.rs b/lightning/src/util/wakers.rs index 5107d05297f..e846ef677b3 100644 --- a/lightning/src/util/wakers.rs +++ b/lightning/src/util/wakers.rs @@ -730,7 +730,6 @@ mod tests { } #[test] - #[cfg(feature = "std")] fn multi_poll_stores_single_waker() { // When a `Future` is `poll()`ed multiple times, only the last `Waker` should be called, // but previously we'd store all `Waker`s until they're all woken at once. This tests a few