use chain::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
use chain::transaction::OutPoint;
use chain::keysinterface::{KeysInterface, BaseSign};
+use ln::{PaymentPreimage, PaymentSecret, PaymentHash};
use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
-use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, RAACommitmentOrder, PaymentPreimage, PaymentSecret, PaymentHash, PaymentSendFailure, BREAKDOWN_TIMEOUT};
+use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, RAACommitmentOrder, PaymentSendFailure, BREAKDOWN_TIMEOUT};
use ln::channel::{Channel, ChannelError};
use ln::{chan_utils, onion_utils};
use routing::router::{Route, RouteHop, get_route};
use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler,HTLCFailChannelUpdate, ErrorAction};
use util::enforcing_trait_impls::EnforcingSigner;
use util::{byte_utils, test_utils};
-use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
+use util::events::{Event, MessageSendEvent, MessageSendEventsProvider};
use util::errors::APIError;
use util::ser::{Writeable, ReadableArgs};
use util::config::UserConfig;
use regex;
use std::collections::{BTreeSet, HashMap, HashSet};
-use std::default::Default;
+use core::default::Default;
use std::sync::Mutex;
use ln::functional_test_utils::*;
// transaction fee with 0 HTLCs (183 sats)).
create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98817000, InitFeatures::known(), InitFeatures::known());
- let dust_amt = 546000; // Dust amount
+ let dust_amt = 329000; // Dust amount
// In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
// reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
// commitment transaction fee.
check_spends!(node_txn[0], tx);
}
+#[test]
+fn test_dup_events_on_peer_disconnect() {
+ // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
+ // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
+ // as we used to generate the event immediately upon receipt of the payment preimage in the
+ // update_fulfill_htlc message.
+
+ let chanmon_cfgs = create_chanmon_cfgs(2);
+ let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
+ let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
+ let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
+ create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
+
+ let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 1000000).0;
+
+ assert!(nodes[1].node.claim_funds(payment_preimage));
+ check_added_monitors!(nodes[1], 1);
+ let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
+ nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
+ expect_payment_sent!(nodes[0], payment_preimage);
+
+ nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
+ nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
+
+ reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
+ assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
+}
+
#[test]
fn test_simple_peer_disconnect() {
// Test that we can reconnect when there are no lost messages
nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
if messages_delivered < 2 {
reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
- //TODO: Deduplicate PaymentSent events, then enable this if:
- //if messages_delivered < 1 {
+ if messages_delivered < 1 {
let events_4 = nodes[0].node.get_and_clear_pending_events();
assert_eq!(events_4.len(), 1);
match events_4[0] {
},
_ => panic!("Unexpected event"),
}
- //}
+ } else {
+ assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
+ }
} else if messages_delivered == 2 {
// nodes[0] still wants its RAA + commitment_signed
reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
};
connect_block(&nodes[0], &block);
connect_block(&nodes[1], &block);
- for _ in CHAN_CONFIRM_DEPTH + 2 ..TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
+ let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
+ for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
block.header.prev_blockhash = block.block_hash();
connect_block(&nodes[0], &block);
connect_block(&nodes[1], &block);
nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
- // 100_000 msat as u64, followed by a height of TEST_FINAL_CLTV + 2 as u32
+ // 100_000 msat as u64, followed by the height at which we failed back above
let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
- expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(TEST_FINAL_CLTV + 2));
+ expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
}
send_payment(&nodes[0], &[&nodes[1]], 1000000);
}
+#[test]
+fn test_dup_htlc_onchain_fails_on_reload() {
+ // When a Channel is closed, any outbound HTLCs which were relayed through it are simply
+ // dropped when the Channel is. From there, the ChannelManager relies on the ChannelMonitor
+ // having a copy of the relevant fail-/claim-back data and processes the HTLC fail/claim when
+ // the ChannelMonitor tells it to.
+ //
+ // If, due to an on-chain event, an HTLC is failed/claimed, and then we serialize the
+ // ChannelManager, we generally expect there not to be a duplicate HTLC fail/claim (eg via a
+ // PaymentFailed event appearing). However, because we may not serialize the relevant
+ // ChannelMonitor at the same time, this isn't strictly guaranteed. In order to provide this
+ // consistency, the ChannelManager explicitly tracks pending-onchain-resolution outbound HTLCs
+ // and de-duplicates ChannelMonitor events.
+ //
+ // This tests that explicit tracking behavior.
+ let chanmon_cfgs = create_chanmon_cfgs(2);
+ let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
+ let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
+ let persister: test_utils::TestPersister;
+ let new_chain_monitor: test_utils::TestChainMonitor;
+ let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
+ let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
+
+ create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
+
+ // Route a payment, but force-close the channel before the HTLC fulfill message arrives at
+ // nodes[0].
+ let (payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 10000000);
+ nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
+ check_closed_broadcast!(nodes[0], true);
+ check_added_monitors!(nodes[0], 1);
+
+ nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
+ nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
+
+ let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
+ assert_eq!(node_txn.len(), 2);
+
+ assert!(nodes[1].node.claim_funds(payment_preimage));
+ check_added_monitors!(nodes[1], 1);
+
+ let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
+ connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
+ check_closed_broadcast!(nodes[1], true);
+ check_added_monitors!(nodes[1], 1);
+ let claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
+
+ connect_block(&nodes[0], &Block { header, txdata: node_txn});
+
+ // Serialize out the ChannelMonitor before connecting the on-chain claim transactions. This is
+ // fairly normal behavior as ChannelMonitor(s) are often not re-serialized when on-chain events
+ // happen, unlike ChannelManager which tends to be re-serialized after any relevant event(s).
+ let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
+ nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
+
+ header.prev_blockhash = header.block_hash();
+ let claim_block = Block { header, txdata: claim_txn};
+ connect_block(&nodes[0], &claim_block);
+ expect_payment_sent!(nodes[0], payment_preimage);
+
+ // ChannelManagers generally get re-serialized after any relevant event(s). Since we just
+ // connected a highly-relevant block, it likely gets serialized out now.
+ let mut chan_manager_serialized = test_utils::TestVecWriter(Vec::new());
+ nodes[0].node.write(&mut chan_manager_serialized).unwrap();
+
+ // Now reload nodes[0]...
+ persister = test_utils::TestPersister::new();
+ let keys_manager = &chanmon_cfgs[0].keys_manager;
+ new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), nodes[0].logger, node_cfgs[0].fee_estimator, &persister, keys_manager);
+ nodes[0].chain_monitor = &new_chain_monitor;
+ let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
+ let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
+ &mut chan_0_monitor_read, keys_manager).unwrap();
+ assert!(chan_0_monitor_read.is_empty());
+
+ let (_, nodes_0_deserialized_tmp) = {
+ let mut channel_monitors = HashMap::new();
+ channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
+ <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>
+ ::read(&mut std::io::Cursor::new(&chan_manager_serialized.0[..]), ChannelManagerReadArgs {
+ default_config: Default::default(),
+ keys_manager,
+ fee_estimator: node_cfgs[0].fee_estimator,
+ chain_monitor: nodes[0].chain_monitor,
+ tx_broadcaster: nodes[0].tx_broadcaster.clone(),
+ logger: nodes[0].logger,
+ channel_monitors,
+ }).unwrap()
+ };
+ nodes_0_deserialized = nodes_0_deserialized_tmp;
+
+ assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
+ check_added_monitors!(nodes[0], 1);
+ nodes[0].node = &nodes_0_deserialized;
+
+ // Note that if we re-connect the block which exposed nodes[0] to the payment preimage (but
+ // which the current ChannelMonitor has not seen), the ChannelManager's de-duplication of
+ // payment events should kick in, leaving us with no pending events here.
+ nodes[0].chain_monitor.chain_monitor.block_connected(&claim_block, nodes[0].blocks.borrow().len() as u32 - 1);
+ assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
+}
+
#[test]
fn test_manager_serialize_deserialize_events() {
// This test makes sure the events field in ChannelManager survives de/serialization
let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
assert!(htlc_updates.update_add_htlcs.is_empty());
assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
- assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
+ let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
assert!(htlc_updates.update_fulfill_htlcs.is_empty());
assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
check_added_monitors!(nodes[1], 1);
assert!(updates.update_add_htlcs.is_empty());
assert!(updates.update_fail_htlcs.is_empty());
assert_eq!(updates.update_fulfill_htlcs.len(), 1);
- assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
+ assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
assert!(updates.update_fail_malformed_htlcs.is_empty());
check_added_monitors!(nodes[1], 1);
assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
}
+#[test]
+fn bolt2_open_channel_sane_dust_limit() {
+ let chanmon_cfgs = create_chanmon_cfgs(2);
+ let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
+ let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
+ let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
+
+ let channel_value_satoshis=1000000;
+ let push_msat=10001;
+ nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
+ let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
+ node0_to_1_send_open_channel.dust_limit_satoshis = 661;
+ node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
+
+ nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
+ let events = nodes[1].node.get_and_clear_pending_msg_events();
+ let err_msg = match events[0] {
+ MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
+ msg.clone()
+ },
+ _ => panic!("Unexpected event"),
+ };
+ assert_eq!(err_msg.data, "dust_limit_satoshis (661) is greater than the implementation limit (660)");
+}
+
// Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
// originated from our node, its failure is surfaced to the user. We trigger this failure to
// free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
- nodes[0].node.timer_tick_occurred(); // dirty -> stagged
- nodes[0].node.timer_tick_occurred(); // staged -> fresh
+ nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
+ nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
assert_eq!(msg_events.len(), 3);
+ let mut chans_disabled: HashSet<u64> = [short_id_1, short_id_2, short_id_3].iter().map(|a| *a).collect();
for e in msg_events {
match e {
MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
- let short_id = msg.contents.short_channel_id;
- // Check generated channel_update match list in PendingChannelUpdate
- if short_id != short_id_1 && short_id != short_id_2 && short_id != short_id_3 {
+ assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
+ // Check that each channel gets updated exactly once
+ if !chans_disabled.remove(&msg.contents.short_channel_id) {
panic!("Generated ChannelUpdate for wrong chan!");
}
},
nodes[0].node.timer_tick_occurred();
assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
+ nodes[0].node.timer_tick_occurred();
+ let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
+ assert_eq!(msg_events.len(), 3);
+ chans_disabled = [short_id_1, short_id_2, short_id_3].iter().map(|a| *a).collect();
+ for e in msg_events {
+ match e {
+ MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
+ assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
+ // Check that each channel gets updated exactly once
+ if !chans_disabled.remove(&msg.contents.short_channel_id) {
+ panic!("Generated ChannelUpdate for wrong chan!");
+ }
+ },
+ _ => panic!("Unexpected event"),
+ }
+ }
}
#[test]
let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
- // Lock HTLC in both directions
- let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3_000_000).0;
- route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
+ // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
+ let route = get_route(&nodes[0].node.get_our_node_id(), &nodes[0].net_graph_msg_handler.network_graph.read().unwrap(),
+ &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 3_000_000, 50, nodes[0].logger).unwrap();
+ let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
+ let route = get_route(&nodes[1].node.get_our_node_id(), &nodes[1].net_graph_msg_handler.network_graph.read().unwrap(),
+ &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 3_000_000, 50, nodes[0].logger).unwrap();
+ send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
assert_eq!(revoked_local_txn[0].input.len(), 1);
claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
// Broadcast set of revoked txn on A
- connect_blocks(&nodes[0], 52 - CHAN_CONFIRM_DEPTH);
+ connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
expect_pending_htlcs_forwardable_ignore!(nodes[0]);
assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);