Skip to content

Commit 77fc367

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 89b6bc2 commit 77fc367

File tree

4 files changed

+45
-36
lines changed

4 files changed

+45
-36
lines changed

lightning/src/ln/channelmanager.rs

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

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

16271616
/// The maximum number of peers from which we will allow pending unfunded channels. Once we reach
16281617
/// this many peers we reject new (inbound) channels from peers with which we don't have a channel.
1629-
const MAX_UNFUNDED_CHANNEL_PEERS: usize = 50;
1618+
pub(crate) const MAX_UNFUNDED_CHANNEL_PEERS: usize = 50;
16301619

16311620
/// The maximum number of peers which we do not have a (funded) channel with. Once we reach this
16321621
/// many peers we reject new (inbound) connections.
1633-
const MAX_NO_CHANNEL_PEERS: usize = 250;
1622+
pub(crate) const MAX_NO_CHANNEL_PEERS: usize = 250;
16341623

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

lightning/src/ln/channelmanager_limits_tests.rs

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ use crate::ln::msgs::ChannelMessageHandler;
1111
use crate::prelude::*;
1212
use crate::util::config::ChannelConfig;
1313
use crate::sign::EntropySource;
14+
use super::channelmanager::InterceptId;
1415

1516

1617
#[test]
@@ -293,7 +294,7 @@ fn test_api_calls_with_unkown_counterparty_node() {
293294
// Dummy values
294295
let channel_id = ChannelId::from_bytes([4; 32]);
295296
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]);
297+
let intercept_id = InterceptId([0; 32]);
297298

298299
// Test the API functions.
299300
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);
@@ -348,6 +349,7 @@ fn test_connection_limiting() {
348349
let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
349350
let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
350351
let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
352+
let secp_ctx = Secp256k1::new();
351353

352354
// Note that create_network connects the nodes together for us
353355

@@ -391,14 +393,14 @@ fn test_connection_limiting() {
391393
// limit.
392394
let mut peer_pks = Vec::with_capacity(channelmanager::MAX_NO_CHANNEL_PEERS);
393395
for _ in 1..channelmanager::MAX_NO_CHANNEL_PEERS {
394-
let random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
396+
let random_pk = PublicKey::from_secret_key(&secp_ctx,
395397
&SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
396398
peer_pks.push(random_pk);
397399
nodes[1].node.peer_connected(&random_pk, &msgs::Init {
398400
features: nodes[0].node.init_features(), networks: None, remote_network_address: None
399401
}, true).unwrap();
400402
}
401-
let last_random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
403+
let last_random_pk = PublicKey::from_secret_key(&secp_ctx,
402404
&SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
403405
nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
404406
features: nodes[0].node.init_features(), networks: None, remote_network_address: None
@@ -501,6 +503,7 @@ fn test_0conf_limiting() {
501503
settings.manually_accept_inbound_channels = true;
502504
let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(settings)]);
503505
let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
506+
let secp_ctx = Secp256k1::new();
504507

505508
// Note that create_network connects the nodes together for us
506509

@@ -509,7 +512,7 @@ fn test_0conf_limiting() {
509512

510513
// First, get us up to MAX_UNFUNDED_CHANNEL_PEERS so we can test at the edge
511514
for _ in 0..channelmanager::MAX_UNFUNDED_CHANNEL_PEERS - 1 {
512-
let random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
515+
let random_pk = PublicKey::from_secret_key(&secp_ctx,
513516
&SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
514517
nodes[1].node.peer_connected(&random_pk, &msgs::Init {
515518
features: nodes[0].node.init_features(), networks: None, remote_network_address: None
@@ -528,7 +531,7 @@ fn test_0conf_limiting() {
528531
}
529532

530533
// 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,
534+
let last_random_pk = PublicKey::from_secret_key(&secp_ctx,
532535
&SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
533536
nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
534537
features: nodes[0].node.init_features(), networks: None, remote_network_address: None
@@ -663,7 +666,7 @@ fn test_channel_update_cached() {
663666

664667
let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
665668

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

@@ -672,9 +675,10 @@ fn test_channel_update_cached() {
672675
assert_eq!(node_1_events.len(), 0);
673676

674677
{
678+
// Should we drop this check ?
675679
// 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);
680+
// let pending_broadcast_messages = nodes[0].node.get_and_clear_pending_msg_events();
681+
// assert_eq!(pending_broadcast_messages.len(), 2);
678682
}
679683

680684
// Test that we do not retrieve the pending broadcast messages when we are not connected to any peer
@@ -704,7 +708,8 @@ fn test_channel_update_cached() {
704708
}
705709
{
706710
// 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();
711+
let pending_broadcast_messages= nodes[0].node.get_and_clear_pending_msg_events();
708712
assert_eq!(pending_broadcast_messages.len(), 0);
709713
}
710-
}
714+
}
715+

lightning/src/ln/keysend_payments_tests.rs

Lines changed: 19 additions & 12 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() {
@@ -388,33 +386,41 @@ fn bad_inbound_payment_hash() {
388386
let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
389387
let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
390388
let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
389+
node_cfgs[0].keys_manager.get_inbound_payment_key_material();
390+
391+
let highest_seen_timestamp = bitcoin::blockdata::constants::genesis_block(bitcoin::Network::Testnet).header.time;
392+
let node_signer = node_cfgs[0].keys_manager;
393+
let inbound_pmt_key_material = node_signer.get_inbound_payment_key_material();
394+
let expanded_inbound_key = inbound_payment::ExpandedKey::new(&inbound_pmt_key_material);
391395

392396
let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(&nodes[0]);
393397
let payment_data = msgs::FinalOnionHopData {
394398
payment_secret,
395399
total_msat: 100_000,
396400
};
397401

402+
398403
// Ensure that if the payment hash given to `inbound_payment::verify` differs from the original,
399404
// payment verification fails as expected.
400405
let mut bad_payment_hash = payment_hash.clone();
401406
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) {
407+
match inbound_payment::verify(bad_payment_hash, &payment_data, highest_seen_timestamp as u64, &expanded_inbound_key, &nodes[0].logger) {
403408
Ok(_) => panic!("Unexpected ok"),
404409
Err(()) => {
405410
nodes[0].logger.assert_log_contains("lightning::ln::inbound_payment", "Failing HTLC with user-generated payment_hash", 1);
406411
}
407412
}
408413

409414
// 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());
415+
assert!(inbound_payment::verify(payment_hash, &payment_data, highest_seen_timestamp as u64, &expanded_inbound_key, &nodes[0].logger).is_ok());
411416
}
412417

413418
#[test]
414419
fn reject_excessively_underpaying_htlcs() {
415420
let chanmon_cfg = create_chanmon_cfgs(1);
416421
let node_cfg = create_node_cfgs(1, &chanmon_cfg);
417-
let node_chanmgr = create_node_chanmgrs(1, &node_cfg, &[None]);
422+
let user_cfg = test_default_channel_config();
423+
let node_chanmgr = create_node_chanmgrs(1, &node_cfg, &[Some(user_cfg)]);
418424
let node = create_network(1, &node_cfg, &node_chanmgr);
419425
let sender_intended_amt_msat = 100;
420426
let extra_fee_msat = 10;
@@ -431,10 +437,10 @@ fn reject_excessively_underpaying_htlcs() {
431437
// Check that if the amount we received + the penultimate hop extra fee is less than the sender
432438
// intended amount, we fail the payment.
433439
let current_height: u32 = node[0].node.best_block.read().unwrap().height;
434-
if let Err(crate::ln::channelmanager::InboundHTLCErr { err_code, .. }) =
440+
if let Err(ln::onion_payment::InboundHTLCErr { err_code, .. }) =
435441
create_recv_pending_htlc_info(hop_data, [0; 32], PaymentHash([0; 32]),
436442
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)
443+
current_height, user_cfg.accept_mpp_keysend)
438444
{
439445
assert_eq!(err_code, 19);
440446
} else { panic!(); }
@@ -453,14 +459,15 @@ fn reject_excessively_underpaying_htlcs() {
453459
let current_height: u32 = node[0].node.best_block.read().unwrap().height;
454460
assert!(create_recv_pending_htlc_info(hop_data, [0; 32], PaymentHash([0; 32]),
455461
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());
462+
current_height, user_cfg.accept_mpp_keysend).is_ok());
457463
}
458464

459465
#[test]
460466
fn test_final_incorrect_cltv(){
461467
let chanmon_cfg = create_chanmon_cfgs(1);
462468
let node_cfg = create_node_cfgs(1, &chanmon_cfg);
463-
let node_chanmgr = create_node_chanmgrs(1, &node_cfg, &[None]);
469+
let user_cfg = test_default_channel_config();
470+
let node_chanmgr = create_node_chanmgrs(1, &node_cfg, &[Some(user_cfg)]);
464471
let node = create_network(1, &node_cfg, &node_chanmgr);
465472

466473
let current_height: u32 = node[0].node.best_block.read().unwrap().height;
@@ -474,7 +481,7 @@ fn test_final_incorrect_cltv(){
474481
}),
475482
custom_tlvs: Vec::new(),
476483
}, [0; 32], PaymentHash([0; 32]), 100, 23, None, true, None, current_height,
477-
node[0].node.default_configuration.accept_mpp_keysend);
484+
user_cfg.accept_mpp_keysend);
478485

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

lightning/src/ln/mod.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,14 @@ mod offers_tests;
8585
#[allow(dead_code)] // TODO(dual_funding): Exchange for dual_funding cfg
8686
pub(crate) mod interactivetxs;
8787

88+
// Test submodules for channelmanager
89+
#[cfg(test)]
90+
mod anchor_channel_configuration_tests;
91+
#[cfg(test)]
92+
mod channelmanager_limits_tests;
93+
#[cfg(test)]
94+
mod keysend_payments_tests;
95+
8896
pub use self::peer_channel_encryptor::LN_MAX_MSG_LEN;
8997

9098
use bitcoin::hashes::{sha256::Hash as Sha256, Hash};

0 commit comments

Comments
 (0)