From: Matt Corallo Date: Sat, 17 Aug 2024 21:23:16 +0000 (+0000) Subject: Remove uneccessary `std` bounds on many tests X-Git-Tag: v0.0.124-rc1~18^2 X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=commitdiff_plain;h=refs%2Fheads%2F2024-08-feature-cleanup;p=rust-lightning Remove uneccessary `std` bounds on many tests We never actually build with `#![no_std]` in tests as Rust does not support it. Thus, many tests have spurious `std` feature gates when they run just fine without them. Here we remove those gates, though note that tests that depend on behavior elsewhere in the codebase which is `std`-gated obviously need to retain their feature gates. --- diff --git a/lightning/src/ln/bolt11_payment.rs b/lightning/src/ln/bolt11_payment.rs index b4863d4b1..d0655968a 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 05e0a9cfd..37a8f9b67 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 5a793052c..7f9a14d1f 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/onion_message/functional_tests.rs b/lightning/src/onion_message/functional_tests.rs index 508e7982b..a96caba2c 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/router.rs b/lightning/src/routing/router.rs index fa2bbac1d..95977df84 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/util/test_utils.rs b/lightning/src/util/test_utils.rs index 5a7537b08..e9b4af08a 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/wakers.rs b/lightning/src/util/wakers.rs index 5107d0529..e846ef677 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