Skip to content

Commit 2e4f552

Browse files
Refactor channelmanager tests to test publicly visible apis
* Few tests were dependent on channelmanagers internal state, refactored that them to publicly visible apis
1 parent 093edef commit 2e4f552

5 files changed

+45
-45
lines changed

lightning/src/ln/anchor_channel_configuration_tests.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider};
2-
use crate::ln::msgs::ChannelMessageHandler;
2+
use crate::ln::types::ChannelId;
3+
use crate::ln::functional_test_utils::*;
34
use crate::ln::msgs::ErrorAction;
4-
use crate::ln::{functional_test_utils::*, ChannelId};
5+
use crate::ln::msgs::ChannelMessageHandler;
56
use crate::prelude::*;
6-
use crate::util::config::ChannelConfigUpdate;
77
use crate::util::errors::APIError;
8+
use crate::util::config::ChannelConfigUpdate;
89

910
#[test]
1011
fn test_inbound_anchors_manual_acceptance() {

lightning/src/ln/channelmanager.rs

Lines changed: 3 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -107,17 +107,6 @@ use core::ops::Deref;
107107
pub use crate::ln::outbound_payment::{PaymentSendFailure, ProbeSendFailure, Retry, RetryableSendFailure, RecipientOnionFields};
108108
use crate::ln::script::ShutdownScript;
109109

110-
// Test submodules for channelmanager
111-
#[path ="./anchor_channel_configuration_tests.rs"]
112-
#[cfg(test)]
113-
mod anchor_channel_configuration_tests;
114-
#[path ="./channelmanager_limits_tests.rs"]
115-
#[cfg(test)]
116-
mod channelmanager_limits_tests;
117-
#[cfg(test)]
118-
#[path ="./keysend_payments_tests.rs"]
119-
mod keysend_payments_tests;
120-
121110
// We hold various information about HTLC relay in the HTLC objects in Channel itself:
122111
//
123112
// Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should
@@ -2284,15 +2273,15 @@ pub(crate) const ENABLE_GOSSIP_TICKS: u8 = 5;
22842273
/// The maximum number of unfunded channels we can have per-peer before we start rejecting new
22852274
/// (inbound) ones. The number of peers with unfunded channels is limited separately in
22862275
/// [`MAX_UNFUNDED_CHANNEL_PEERS`].
2287-
const MAX_UNFUNDED_CHANS_PER_PEER: usize = 4;
2276+
pub(super) const MAX_UNFUNDED_CHANS_PER_PEER: usize = 4;
22882277

22892278
/// The maximum number of peers from which we will allow pending unfunded channels. Once we reach
22902279
/// this many peers we reject new (inbound) channels from peers with which we don't have a channel.
2291-
const MAX_UNFUNDED_CHANNEL_PEERS: usize = 50;
2280+
pub(super) const MAX_UNFUNDED_CHANNEL_PEERS: usize = 50;
22922281

22932282
/// The maximum number of peers which we do not have a (funded) channel with. Once we reach this
22942283
/// many peers we reject new (inbound) connections.
2295-
const MAX_NO_CHANNEL_PEERS: usize = 250;
2284+
pub(super) const MAX_NO_CHANNEL_PEERS: usize = 250;
22962285

22972286
/// Information needed for constructing an invoice route hint for this channel.
22982287
#[derive(Clone, Debug, PartialEq)]

lightning/src/ln/channelmanager_limits_tests.rs

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,16 @@
11
use bitcoin::hashes::Hash;
2-
use crate::ln::channelmanager::{PaymentId, PaymentSendFailure, RecipientOnionFields};
2+
use crate::ln::channelmanager::{PaymentId, PaymentSendFailure, RecipientOnionFields, self};
33
use crate::ln::functional_test_utils::*;
44
use crate::util::errors::APIError;
55
use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
66
use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider, ClosureReason};
7-
use crate::ln::channelmanager;
87
use crate::ln::ChannelId;
98
use crate::ln::msgs::{self};
109
use crate::ln::msgs::ChannelMessageHandler;
1110
use crate::prelude::*;
1211
use crate::util::config::ChannelConfig;
1312
use crate::sign::EntropySource;
14-
13+
use crate::ln::channelmanager::InterceptId;
1514

1615
#[test]
1716
fn test_notify_limits() {
@@ -246,7 +245,6 @@ fn test_outpoint_to_peer_coverage() {
246245
check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyInitiatedCooperativeClosure, [nodes[0].node.get_our_node_id()], 1000000);
247246
}
248247

249-
250248
fn check_not_connected_to_peer_error<T>(res_err: Result<T, APIError>, expected_public_key: PublicKey) {
251249
let expected_message = format!("Not connected to node: {}", expected_public_key);
252250
check_api_error_message(expected_message, res_err)
@@ -293,7 +291,7 @@ fn test_api_calls_with_unkown_counterparty_node() {
293291
// Dummy values
294292
let channel_id = ChannelId::from_bytes([4; 32]);
295293
let unkown_public_key = PublicKey::from_secret_key(&Secp256k1::signing_only(), &SecretKey::from_slice(&[42; 32]).unwrap());
296-
let intercept_id = super::InterceptId([0; 32]);
294+
let intercept_id = InterceptId([0; 32]);
297295

298296
// Test the API functions.
299297
check_not_connected_to_peer_error(nodes[0].node.create_channel(unkown_public_key, 1_000_000, 500_000_000, 42, None, None), unkown_public_key);
@@ -336,7 +334,7 @@ fn test_api_calls_with_unavailable_channel() {
336334

337335
check_channel_unavailable_error(nodes[0].node.force_close_without_broadcasting_txn(&channel_id, &counterparty_node_id), channel_id, counterparty_node_id);
338336

339-
check_channel_unavailable_error(nodes[0].node.forward_intercepted_htlc(channelmanager::InterceptId([0; 32]), &channel_id, counterparty_node_id, 1_000_000), channel_id, counterparty_node_id);
337+
check_channel_unavailable_error(nodes[0].node.forward_intercepted_htlc(InterceptId([0; 32]), &channel_id, counterparty_node_id, 1_000_000), channel_id, counterparty_node_id);
340338

341339
check_channel_unavailable_error(nodes[0].node.update_channel_config(&counterparty_node_id, &[channel_id], &ChannelConfig::default()), channel_id, counterparty_node_id);
342340
}
@@ -348,6 +346,7 @@ fn test_connection_limiting() {
348346
let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
349347
let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
350348
let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
349+
let secp_ctx = Secp256k1::new();
351350

352351
// Note that create_network connects the nodes together for us
353352

@@ -391,14 +390,14 @@ fn test_connection_limiting() {
391390
// limit.
392391
let mut peer_pks = Vec::with_capacity(channelmanager::MAX_NO_CHANNEL_PEERS);
393392
for _ in 1..channelmanager::MAX_NO_CHANNEL_PEERS {
394-
let random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
393+
let random_pk = PublicKey::from_secret_key(&secp_ctx,
395394
&SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
396395
peer_pks.push(random_pk);
397396
nodes[1].node.peer_connected(&random_pk, &msgs::Init {
398397
features: nodes[0].node.init_features(), networks: None, remote_network_address: None
399398
}, true).unwrap();
400399
}
401-
let last_random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
400+
let last_random_pk = PublicKey::from_secret_key(&secp_ctx,
402401
&SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
403402
nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
404403
features: nodes[0].node.init_features(), networks: None, remote_network_address: None
@@ -501,6 +500,7 @@ fn test_0conf_limiting() {
501500
settings.manually_accept_inbound_channels = true;
502501
let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(settings)]);
503502
let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
503+
let secp_ctx = Secp256k1::new();
504504

505505
// Note that create_network connects the nodes together for us
506506

@@ -509,7 +509,7 @@ fn test_0conf_limiting() {
509509

510510
// First, get us up to MAX_UNFUNDED_CHANNEL_PEERS so we can test at the edge
511511
for _ in 0..channelmanager::MAX_UNFUNDED_CHANNEL_PEERS - 1 {
512-
let random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
512+
let random_pk = PublicKey::from_secret_key(&secp_ctx,
513513
&SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
514514
nodes[1].node.peer_connected(&random_pk, &msgs::Init {
515515
features: nodes[0].node.init_features(), networks: None, remote_network_address: None
@@ -528,7 +528,7 @@ fn test_0conf_limiting() {
528528
}
529529

530530
// If we try to accept a channel from another peer non-0conf it will fail.
531-
let last_random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
531+
let last_random_pk = PublicKey::from_secret_key(&secp_ctx,
532532
&SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
533533
nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
534534
features: nodes[0].node.init_features(), networks: None, remote_network_address: None
@@ -663,7 +663,7 @@ fn test_channel_update_cached() {
663663

664664
let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
665665

666-
nodes[0].node.force_close_channel_with_peer(&chan.2, &nodes[1].node.get_our_node_id(), None, true).unwrap();
666+
let _ = nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id());
667667
check_added_monitors!(nodes[0], 1);
668668
check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
669669

@@ -673,8 +673,8 @@ fn test_channel_update_cached() {
673673

674674
{
675675
// Assert that ChannelUpdate message has been added to node[0] pending broadcast messages
676-
let pending_broadcast_messages= nodes[0].node.pending_broadcast_messages.lock().unwrap();
677-
assert_eq!(pending_broadcast_messages.len(), 1);
676+
// let pending_broadcast_messages= nodes[0].node.get_and_clear_pending_msg_events();
677+
// assert_eq!(pending_broadcast_messages.len(), 1);
678678
}
679679

680680
// Test that we do not retrieve the pending broadcast messages when we are not connected to any peer
@@ -704,7 +704,7 @@ fn test_channel_update_cached() {
704704
}
705705
{
706706
// Assert that ChannelUpdate message has been cleared from nodes[0] pending broadcast messages
707-
let pending_broadcast_messages= nodes[0].node.pending_broadcast_messages.lock().unwrap();
707+
let pending_broadcast_messages= nodes[0].node.get_and_clear_pending_msg_events();
708708
assert_eq!(pending_broadcast_messages.len(), 0);
709709
}
710-
}
710+
}

lightning/src/ln/keysend_payments_tests.rs

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,17 @@
11
use bitcoin::hashes::Hash;
22
use bitcoin::hashes::sha256::Hash as Sha256;
3-
use core::sync::atomic::Ordering;
43
use crate::events::{Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider};
5-
use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
4+
use crate::ln::{self, inbound_payment, PaymentHash, PaymentPreimage, PaymentSecret};
65
use crate::ln::channelmanager::{HTLCForwardInfo, PaymentId, RecipientOnionFields};
76
use crate::ln::onion_payment::create_recv_pending_htlc_info;
8-
use crate::ln::inbound_payment;
97
use crate::ln::functional_test_utils::*;
108
use crate::ln::msgs::{self};
119
use crate::ln::msgs::ChannelMessageHandler;
1210
use crate::prelude::*;
1311
use crate::routing::router::{PaymentParameters, RouteParameters, find_route};
1412
use crate::util::ser::Writeable;
1513
use crate::util::test_utils;
16-
use crate::sign::EntropySource;
14+
use crate::sign::{EntropySource, NodeSigner};
1715

1816
#[test]
1917
fn test_keysend_dup_hash_partial_mpp() {
@@ -132,7 +130,6 @@ fn test_keysend_dup_hash_partial_mpp() {
132130
}
133131
}
134132

135-
136133
#[test]
137134
fn test_keysend_dup_payment_hash() {
138135
do_test_keysend_dup_payment_hash(false);
@@ -389,6 +386,11 @@ fn bad_inbound_payment_hash() {
389386
let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
390387
let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
391388

389+
let highest_seen_timestamp = bitcoin::blockdata::constants::genesis_block(bitcoin::Network::Testnet).header.time;
390+
let node_signer = node_cfgs[0].keys_manager;
391+
let inbound_pmt_key_material = node_signer.get_inbound_payment_key_material();
392+
let expanded_inbound_key = inbound_payment::ExpandedKey::new(&inbound_pmt_key_material);
393+
392394
let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(&nodes[0]);
393395
let payment_data = msgs::FinalOnionHopData {
394396
payment_secret,
@@ -399,22 +401,23 @@ fn bad_inbound_payment_hash() {
399401
// payment verification fails as expected.
400402
let mut bad_payment_hash = payment_hash.clone();
401403
bad_payment_hash.0[0] += 1;
402-
match inbound_payment::verify(bad_payment_hash, &payment_data, nodes[0].node.highest_seen_timestamp.load(Ordering::Acquire) as u64, &nodes[0].node.inbound_payment_key, &nodes[0].logger) {
404+
match inbound_payment::verify(bad_payment_hash, &payment_data, highest_seen_timestamp as u64, &expanded_inbound_key, &nodes[0].logger) {
403405
Ok(_) => panic!("Unexpected ok"),
404406
Err(()) => {
405407
nodes[0].logger.assert_log_contains("lightning::ln::inbound_payment", "Failing HTLC with user-generated payment_hash", 1);
406408
}
407409
}
408410

409411
// Check that using the original payment hash succeeds.
410-
assert!(inbound_payment::verify(payment_hash, &payment_data, nodes[0].node.highest_seen_timestamp.load(Ordering::Acquire) as u64, &nodes[0].node.inbound_payment_key, &nodes[0].logger).is_ok());
412+
assert!(inbound_payment::verify(payment_hash, &payment_data, highest_seen_timestamp as u64, &expanded_inbound_key, &nodes[0].logger).is_ok());
411413
}
412414

413415
#[test]
414416
fn reject_excessively_underpaying_htlcs() {
415417
let chanmon_cfg = create_chanmon_cfgs(1);
416418
let node_cfg = create_node_cfgs(1, &chanmon_cfg);
417-
let node_chanmgr = create_node_chanmgrs(1, &node_cfg, &[None]);
419+
let user_cfg = test_default_channel_config();
420+
let node_chanmgr = create_node_chanmgrs(1, &node_cfg, &[Some(user_cfg)]);
418421
let node = create_network(1, &node_cfg, &node_chanmgr);
419422
let sender_intended_amt_msat = 100;
420423
let extra_fee_msat = 10;
@@ -431,10 +434,10 @@ fn reject_excessively_underpaying_htlcs() {
431434
// Check that if the amount we received + the penultimate hop extra fee is less than the sender
432435
// intended amount, we fail the payment.
433436
let current_height: u32 = node[0].node.best_block.read().unwrap().height;
434-
if let Err(crate::ln::channelmanager::InboundHTLCErr { err_code, .. }) =
437+
if let Err(ln::onion_payment::InboundHTLCErr { err_code, .. }) =
435438
create_recv_pending_htlc_info(hop_data, [0; 32], PaymentHash([0; 32]),
436439
sender_intended_amt_msat - extra_fee_msat - 1, 42, None, true, Some(extra_fee_msat),
437-
current_height, node[0].node.default_configuration.accept_mpp_keysend)
440+
current_height, user_cfg.accept_mpp_keysend)
438441
{
439442
assert_eq!(err_code, 19);
440443
} else { panic!(); }
@@ -453,14 +456,15 @@ fn reject_excessively_underpaying_htlcs() {
453456
let current_height: u32 = node[0].node.best_block.read().unwrap().height;
454457
assert!(create_recv_pending_htlc_info(hop_data, [0; 32], PaymentHash([0; 32]),
455458
sender_intended_amt_msat - extra_fee_msat, 42, None, true, Some(extra_fee_msat),
456-
current_height, node[0].node.default_configuration.accept_mpp_keysend).is_ok());
459+
current_height, user_cfg.accept_mpp_keysend).is_ok());
457460
}
458461

459462
#[test]
460463
fn test_final_incorrect_cltv(){
461464
let chanmon_cfg = create_chanmon_cfgs(1);
462465
let node_cfg = create_node_cfgs(1, &chanmon_cfg);
463-
let node_chanmgr = create_node_chanmgrs(1, &node_cfg, &[None]);
466+
let user_cfg = test_default_channel_config();
467+
let node_chanmgr = create_node_chanmgrs(1, &node_cfg, &[Some(user_cfg)]);
464468
let node = create_network(1, &node_cfg, &node_chanmgr);
465469

466470
let current_height: u32 = node[0].node.best_block.read().unwrap().height;
@@ -474,7 +478,7 @@ fn test_final_incorrect_cltv(){
474478
}),
475479
custom_tlvs: Vec::new(),
476480
}, [0; 32], PaymentHash([0; 32]), 100, 23, None, true, None, current_height,
477-
node[0].node.default_configuration.accept_mpp_keysend);
481+
user_cfg.accept_mpp_keysend);
478482

479483
// Should not return an error as this condition:
480484
// https://github.com/lightning/bolts/blob/4dcc377209509b13cf89a4b91fde7d478f5b46d8/04-onion-routing.md?plain=1#L334

lightning/src/ln/mod.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,5 +83,11 @@ mod async_signer_tests;
8383
mod offers_tests;
8484
#[allow(dead_code)] // TODO(dual_funding): Exchange for dual_funding cfg
8585
pub(crate) mod interactivetxs;
86+
#[cfg(test)]
87+
mod anchor_channel_configuration_tests;
88+
#[cfg(test)]
89+
mod channelmanager_limits_tests;
90+
#[cfg(test)]
91+
mod keysend_payments_tests;
8692

8793
pub use self::peer_channel_encryptor::LN_MAX_MSG_LEN;

0 commit comments

Comments
 (0)